Search⌘ K
AI Features

Prompts as Code, Not Chat

Explore how to write task-shaped prompts treated as code rather than casual chat messages. Learn to define tasks, constrain outputs, specify formats, and handle ambiguous inputs to improve reliability in AI-powered backend integrations.

It’s easy to write a prompt as an informal natural language request: provide a rough, conversational description of the task and hope the resulting output is usable. That approach is fine for exploring an idea. For prompts used in backend services, however, it is often too underspecified. Unspecified details must be resolved during generation and can introduce behavior that the application did not define explicitly. A structured prompt defines those constraints up front, much like defining a function’s inputs, outputs, constraints, and expected behavior before implementation.

A prompt is a spec, not a message

A task-shaped prompt for a backend job typically needs four things a casual chat message usually skips: a clear statement of the task, the exact set of allowed outputs, an explicit output format, and instructions for what to do when the input doesn't cleanly fit. Let’s build one as a function, since treating prompt construction as code, with parameters, not hardcoded strings, is exactly the mindset this lesson is named after.

Python
def build_ticket_prompt(categories: list[str], ticket_text: str) -> str:
category_list = ", ".join(categories)
return (
"You are a support-ticket classifier.\n"
f"Allowed categories: {category_list}.\n"
"Instructions:\n"
"1. Read the ticket text below.\n"
"2. Choose exactly one category from the allowed list.\n"
"3. Respond with only the category name in lowercase, nothing else.\n"
"4. If the ticket does not clearly fit any category, respond with "
"exactly: unclear.\n\n"
f'Ticket: "{ticket_text}"'
)
categories = ["billing", "technical", "account_access"]
ticket_text = "The app crashes every time I try to open my saved documents."
prompt = build_ticket_prompt(categories, ticket_text)
print(prompt)
  • Lines 1–2: We define build_ticket_prompt, which accepts the permitted categories and ticket text. We then join the categories into one comma-separated string. ...