Prompts and structured output

Topic 4 of 5 in Generative AI & LLMs25 min readBeginnerFree course

Overview

In the previous lesson, you learned how to initialize a language model, send messages from Python, and receive an AIMessage response.

Calling a model is straightforward. Getting it to behave consistently enough for a production application is a different engineering problem.

Consider a customer support application that must categorize incoming requests. If you simply ask a model to classify a message, it might return any of these responses:

  • This appears to be a billing issue.
  • Category: Billing.
  • The customer needs help with their payment.
  • BILLING

A human understands that these responses communicate approximately the same information. However, a Python application needs a predictable value to select the appropriate workflow.

Two complementary techniques solve this problem:

  1. Prompt engineering: Communicating what the model should do, what information it should use, and which rules it should follow.
  2. Structured output: Defining the shape and types of the data that the model must return.

Prompt engineering governs behavior. Structured output governs the response contract.

Together, they allow us to transform probabilistic language generation into a component that conventional software can consume, validate, and act upon.

This distinction is foundational to agentic AI engineering. An agent frequently needs to classify requests, extract information, make routing decisions, and pass results between workflow components.

The following diagram illustrates how a prompt and a schema work together.

Overview diagram: User Input to Model Request; System Instructions to Model Request; Output Schema to Model Request; Model Request to Language Model; Language Model to Response Validation; Response Validation to Valid Response?; Valid Response? to Python Object (Yes); Valid Response? to Error Handling (No); Python Object to Application Logic.

By the end of this lesson, you will be able to build model calls whose responses behave more like conventional Python function results than unpredictable chat messages.

Environment setup

Install the packages used throughout this lesson.

Terminal
pip install -U "langchain>=1,<2" "langgraph>=1,<2" langchain-openai "pydantic>=2,<3"

Configure your OpenAI API key as an environment variable.

On macOS or Linux:

Terminal
export OPENAI_API_KEY="your-api-key"

On Windows PowerShell:

Terminal
$env:OPENAI_API_KEY="your-api-key"

Never commit API keys to source control.

All examples use Python 3.11 or later and the course’s OpenAI model, gpt-5.4-mini. Each example is independently runnable with the installed dependencies, valid credentials, and access to the model. The displayed model responses are illustrative expected results rather than captured live API executions.

Prompt engineering basics

What is a prompt?

A prompt is the input provided to a language model to influence its generated response.

In a chat-based application, a prompt is typically represented as a collection of messages rather than a single string.

These messages can contain application instructions, conversation history, examples, user requests, and information retrieved from external systems.

Language models generate responses based on learned patterns and the supplied context. A prompt does not permanently modify the model’s parameters. Instead, it changes the information available to the model during inference.

Prompt engineering is therefore the practice of designing, testing, and improving these inputs to obtain useful and consistent behavior.

Anatomy of an effective prompt

A practical application prompt generally contains the following components.

Component Purpose Example
Role Establishes the model’s responsibility You are a support assistant
Task Defines the operation Classify the customer request
Context Provides relevant information Company refund policy
Constraints Specifies behavioral rules Do not invent policies
Examples Demonstrates desired behavior Sample classifications
Output requirements Defines the expected response Return one category
Fallback behavior Handles missing information Return unknown

Not every prompt requires every component. A translation task might need only a clear instruction, while a customer support assistant requires stronger constraints and explicit uncertainty handling.

Compare these two prompts:

Weak prompt:

Text
Analyze this customer message.

Improved prompt:

Text
You are a customer support classification assistant.

Classify the customer message into exactly one category:
billing, technical, shipping, or other.

Use billing for charges, refunds, and payment issues.
Use technical for application errors and account access.
Use shipping for delivery and package tracking.
Use other when none of the categories apply.

Return only the category.
Do not invent additional categories.

The improved prompt defines an explicit classification policy. It reduces ambiguity and gives the model concrete decision boundaries.

However, even this prompt cannot guarantee that the model will return exactly the requested format. Structured output will address that limitation later.

System messages and human messages

LangChain provides message classes that represent different roles in a conversation.

Message Responsibility
SystemMessage Application instructions and behavioral policies
HumanMessage User requests and task-specific inputs
AIMessage Model responses or example assistant responses
ToolMessage Results from executed tools

System messages are appropriate for instructions controlled by the application developer. Human messages contain the actual customer request or other task input.

The following example demonstrates a simple support classifier using separate messages.

Python
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage

model = init_chat_model("openai:gpt-5.4-mini")

SYSTEM_PROMPT = """
You are a customer support classifier.

Choose exactly one category:

- billing: payments, charges, refunds
- technical: application errors, login problems
- shipping: delivery, package tracking
- other: anything else

Return only the category in lowercase.
"""

def classify(message: str) -> str:
    response = model.invoke([
        SystemMessage(content=SYSTEM_PROMPT),
        HumanMessage(content=message)
    ])

    return response.text.strip()

print(classify("My credit card was charged twice."))
print(classify("I cannot log into my account."))
print(classify("Where is my package?"))

Expected output:

Text
billing
technical
shipping

Notice that the classification rules remain constant while the customer message changes between calls.

This separation makes the prompt reusable and easier to maintain.

System instructions are not security boundaries, however. Malicious user content may attempt to override them, a technique known as prompt injection. Keep authorization and sensitive operations under application control rather than trusting model instructions alone.

Providing context and handling uncertainty

A model cannot reliably answer questions about private company policies that it has never received.

Suppose a customer asks whether international orders qualify for free shipping. Without the relevant policy, the model may generate a plausible but incorrect answer.

A better prompt explicitly supplies relevant information and defines what to do when it is insufficient.

Text
Answer using only the provided company policies.

If the policies do not contain enough information,
state that the answer is unavailable.

Do not invent policies, prices, dates, or eligibility rules.

Providing authoritative information in the model’s input is called grounding.

Grounding reduces hallucinations, but it does not eliminate them. The model may misunderstand, overlook, or misrepresent supplied information.

For our chapter’s question-answering application, grounding will be essential. Later, we will retrieve relevant documents automatically using retrieval-augmented generation, commonly called RAG.

Prompt length and context windows

Every instruction, example, document, and conversation message consumes part of the model’s context budget.

Longer prompts are not necessarily better prompts.

Unnecessary instructions increase processing costs and may introduce conflicting requirements. Excessive documents can make relevant facts harder to identify.

Prefer concise instructions, relevant context, and examples that address actual failure cases. Reserve sufficient context capacity for the model’s generated response.

Tip: Treat prompts as versioned application assets. When changing a prompt, evaluate it against the same representative test inputs before deploying the new version.

Few-shot examples

Zero-shot and few-shot prompting

A model can perform many tasks without receiving explicit demonstrations because it has learned general patterns during training.

This is called zero-shot prompting.

For example:

Text
Classify the sentiment of this review as positive,
negative, neutral, or mixed.

Review: The product arrived yesterday.

The task is clear, but the boundaries between categories may still be ambiguous.

Few-shot prompting adds demonstrations of the expected input-output behavior.

Technique Demonstrations Best suited for
Zero-shot 0 Straightforward tasks
One-shot 1 Demonstrating a specific pattern
Few-shot Several Ambiguous classifications and specialized behavior
Fine-tuning Training dataset Persistent behavior adaptation through training

Few-shot prompting does not train the model or update its weights. The demonstrations become temporary context that influences the current response.

This behavior is a form of in-context learning.

Implementing few-shot prompting

Suppose an e-commerce application must determine customer sentiment.

Positive and negative reviews are relatively easy to classify, but a review containing both praise and criticism requires a clear policy.

The following example uses alternating human and assistant messages as demonstrations.

Python
from langchain.chat_models import init_chat_model
from langchain.messages import (
    SystemMessage,
    HumanMessage,
    AIMessage
)

model = init_chat_model("openai:gpt-5.4-mini")

examples = [
    SystemMessage(content="""
    Classify customer reviews into one category:
    positive, negative, neutral, or mixed.

    Use mixed when the review contains both
    meaningful positive and negative opinions.

    Return only the category.
    """),
    HumanMessage(content="Excellent product and fast delivery."),
    AIMessage(content="positive"),
    HumanMessage(content="The item arrived damaged."),
    AIMessage(content="negative"),
    HumanMessage(content="The package arrived on Tuesday."),
    AIMessage(content="neutral"),
    HumanMessage(content="Great product, but terrible support."),
    AIMessage(content="mixed")
]

def classify_review(review: str) -> str:
    messages = examples + [HumanMessage(content=review)]
    return model.invoke(messages).text.strip()

print(classify_review(
    "The laptop is excellent, but the battery life is disappointing."
))

print(classify_review(
    "The order contains two items."
))

Expected output:

Text
mixed
neutral

The AIMessage objects are manually supplied demonstrations, not responses obtained through previous API calls.

The model sees the classification policy and several examples before processing the new review.

Choosing effective demonstrations

Effective demonstrations clarify decisions that instructions alone do not adequately explain.

For a customer support classifier, include ambiguous requests such as a shipping complaint that also mentions a refund. Specify which category takes priority.

Good examples should represent realistic inputs, cover important categories, and remain consistent with the system instructions.

Avoid filling the context with dozens of nearly identical demonstrations. More examples consume more tokens and do not necessarily improve classification.

Start with zero-shot prompting. Identify recurring failures through testing, then introduce targeted examples addressing those failures.

Few-shot prompting improves behavioral consistency, but the resulting response is still generated by a language model. It is not a guaranteed enumeration value.

Structured output

Why free-text responses are problematic

Imagine that an invoice-processing application receives this model response:

Text
The invoice number is INV-1042, the total amount
is $249.99, and payment is due on December 15, 2026.

Extracting these values with regular expressions is fragile. The model might change punctuation, field order, date formatting, or wording.

Requesting JSON through prompting is an improvement, but problems remain. The model might produce Markdown code fences, omit required fields, or return an incorrect type.

Instead, define a schema and use the model’s structured-output capability.

A schema describes the expected data structure, including field names, data types, and permitted values.

Structured output makes the model response suitable for database operations, REST API responses, conditional logic, and graph state updates.

Defining schemas with Pydantic

Pydantic is a Python library for data validation.

Unlike ordinary Python type annotations, which do not automatically validate incoming values, Pydantic models validate data when constructing model instances.

Consider this schema:

Python
from typing import Literal
from pydantic import BaseModel

class Classification(BaseModel):
    category: Literal["billing", "technical", "shipping", "other"]
    summary: str
    requires_human: bool

The category field accepts only four values. The summary field contains text, and requires_human represents a Boolean decision.

A Pydantic model can also generate a JSON Schema representation through model_json_schema().

LangChain uses schema information to configure supported model integrations and interpret their responses.

Using with_structured_output()

LangChain chat models expose the with_structured_output() method for supported integrations.

The method creates a runnable wrapper around the underlying model.

The following example converts a customer support request into a typed Python object.

Python
from typing import Literal

from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from pydantic import BaseModel, Field, ConfigDict

class SupportTicket(BaseModel):
    """Structured information extracted from a support request."""

    model_config = ConfigDict(extra="forbid")

    category: Literal[
        "billing", "technical", "shipping", "other"
    ] = Field(description="The primary category of the request.")

    priority: Literal["low", "medium", "high"] = Field(
        description="Urgency based on the customer impact."
    )

    summary: str = Field(
        description="A concise description of the customer problem."
    )

    requires_human: bool = Field(
        description="Whether human review is necessary."
    )

model = init_chat_model("openai:gpt-5.4-mini")

structured_model = model.with_structured_output(
    SupportTicket,
    method="json_schema",
    strict=True
)

messages = [
    SystemMessage(content="""
    Analyze customer support requests.

    Use high priority for urgent financial or access problems.
    Use medium priority for ordinary unresolved problems.
    Use low priority for general questions.

    Require human review for disputed charges.
    Do not invent information.
    """),
    HumanMessage(
        content="I was charged twice for my subscription today."
    )
]

ticket = structured_model.invoke(messages)

print(type(ticket).__name__)
print(ticket.model_dump_json(indent=2))

if ticket.requires_human:
    print("Forwarding to human support.")

Possible output:

Text
SupportTicket
{
  "category": "billing",
  "priority": "high",
  "summary": "Customer was charged twice for a subscription.",
  "requires_human": true
}
Forwarding to human support.

The important distinction is that ticket is a SupportTicket instance, not an AIMessage or a raw JSON string.

You can directly access its attributes:

Python
ticket.category
ticket.priority
ticket.requires_human

Use model_dump() to obtain a dictionary and model_dump_json() to obtain a JSON string.

How structured output works internally

Depending on the selected method and provider, LangChain communicates the schema using native structured-output features, tool definitions, or JSON-generation instructions.

After receiving the response, the wrapper interprets the generated data. When a Pydantic schema is supplied, the resulting fields are validated against that model.

Provider-native schema enforcement can constrain the permitted response structure during generation.

This is stronger than simply requesting a format in natural language.

Three common approaches are available.

Method Mechanism Schema enforcement
json_schema Native provider structured output Strong when strict mode is supported
function_calling Schema represented as a tool definition Depends on provider capabilities
json_mode Provider JSON-generation mode JSON syntax, not the complete schema

For OpenAI models supporting native structured output, method="json_schema" with strict=True is a useful starting point.

With json_mode, the expected fields must also be described in the prompt. Client-side validation remains necessary.

The supported methods and parameters are provider-specific. Consult the LangChain chat model reference and OpenAI structured-output integration reference.

Handling parsing failures

A production application needs to account for refusals, incomplete responses, validation errors, unsupported schemas, and network failures.

Setting include_raw=True preserves the original response alongside the parsing result.

The following example extracts a small contact record and checks for parsing errors before using it.

Python
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field

class Contact(BaseModel):
    name: str

    email: str | None = Field(
        description="Email address, or null if not supplied."
    )

model = init_chat_model("openai:gpt-5.4-mini")

extractor = model.with_structured_output(
    Contact,
    method="json_schema",
    strict=True,
    include_raw=True
)

result = extractor.invoke(
    "Extract contact information without guessing. "
    "My name is Priya Sharma. Please call me tomorrow."
)

if result["parsing_error"] is not None:
    print("Could not parse the model response.")
    print(type(result["parsing_error"]).__name__)

elif result["parsed"] is None:
    print("No structured result was available.")

else:
    contact = result["parsed"]

    print(contact.model_dump_json(indent=2))
    print("Token usage:", result["raw"].usage_metadata)

Expected parsed data:

JSON
{
  "name": "Priya Sharma",
  "email": null
}

Token usage varies between requests.

The returned dictionary contains raw, parsed, and parsing_error. Transport and authentication errors can still propagate from invoke() and require separate exception handling.

Note: A schema-valid response can still contain false information. Structured output improves format reliability, not factual correctness.

Tips for schemas

Design schemas around application decisions

A schema should represent information that downstream software actually needs.

Use Literal for fixed categories, Boolean fields for binary decisions, and lists for collections.

Use nullable fields when information might genuinely be absent.

For example, email: str | None allows a required field whose value can be null. Adding = None instead supplies a Python default, which some strict provider schemas do not accept.

Prefer simple, explicit field descriptions. A field named urgency should explain what urgency means in the business domain.

Avoid unnecessary nesting and excessively complicated schemas. Native structured-output providers support different subsets of JSON Schema, especially when strict enforcement is enabled.

Separate structural validation from business validation

Structural validation verifies that data matches the declared schema.

Business validation verifies that the data makes sense within the application.

For example, an extracted refund amount might be a valid number but exceed the original purchase amount.

Likewise, an answer might contain a correctly formatted document ID that does not exist.

Use ordinary Python code to check these conditions after parsing. Pydantic validators are also useful for application-level rules.

For strict provider compatibility, avoid assuming that every Pydantic constraint can be translated into a supported provider schema.

Common mistakes and best practices

Common mistake Better approach
Extracting fields using regular expressions Use structured output
Allowing arbitrary classification strings Use Literal or an enum
Requiring unavailable information Allow null or explicit unknown states
Treating model confidence as calibrated probability Evaluate reliability empirically
Trusting generated source IDs Verify them against supplied documents
Retrying indefinitely Use bounded retries and fallback behavior
Using generated decisions as authorization Enforce permissions in application code

Test schemas with ordinary inputs, missing information, ambiguous requests, conflicting context, and adversarial instructions.

Evaluate formatting success and semantic accuracy separately. A classifier can return valid categories on every request while choosing the wrong category frequently.

Working across model providers

The structured-output interface is shared across many LangChain integrations, but model capabilities are not identical.

Provider Integration package
OpenAI langchain-openai
Gemini langchain-google-genai
Anthropic langchain-anthropic
Ollama langchain-ollama

For supported models, the general pattern remains model.with_structured_output(MySchema).

However, verify native schema support, method parameters, strict-mode availability, and tool-calling capabilities before switching providers.

A locally hosted model through Ollama may also require different prompting and evaluation strategies from a hosted frontier model.

Where this shows up in LangGraph

LangGraph orchestrates workflows using nodes, edges, and shared state.

A node can call a model to classify a request, while a conditional edge selects the next node based on the returned classification.

Structured output makes these decisions easier to implement because routing functions operate on validated fields rather than interpreting prose.

The following workflow routes billing requests to billing support and everything else to general support.

Where this shows up in LangGraph diagram: START to Classify Request; Classify Request to Billing Request?; Billing Request? to Billing Handler (Yes); Billing Request? to General Handler (No); Billing Handler to END; General Handler to END.

Building a structured routing workflow

This complete example demonstrates how a structured model response becomes part of LangGraph state.

Python
from typing import TypedDict, Literal

from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
from pydantic import BaseModel

class RoutingDecision(BaseModel):
    category: Literal["billing", "general"]
    reason: str

class SupportState(TypedDict, total=False):
    request: str
    category: Literal["billing", "general"]
    reason: str
    response: str

model = init_chat_model("openai:gpt-5.4-mini")

router = model.with_structured_output(
    RoutingDecision,
    method="json_schema",
    strict=True
)

def classify_request(state: SupportState) -> dict:
    decision = router.invoke([
        SystemMessage(content="""
        Classify requests into billing or general.
        Payments, charges, invoices, and refunds are billing.
        Everything else is general.
        Provide a brief classification reason.
        """),
        HumanMessage(content=state["request"])
    ])

    return {
        "category": decision.category,
        "reason": decision.reason
    }

def choose_route(
    state: SupportState
) -> Literal["billing", "general"]:
    return state["category"]

def billing_handler(state: SupportState) -> dict:
    return {
        "response": "Your request has been routed to billing support."
    }

def general_handler(state: SupportState) -> dict:
    return {
        "response": "Your request has been routed to general support."
    }

builder = StateGraph(SupportState)

builder.add_node("classify", classify_request)
builder.add_node("billing", billing_handler)
builder.add_node("general", general_handler)

builder.add_edge(START, "classify")

builder.add_conditional_edges(
    "classify",
    choose_route,
    {
        "billing": "billing",
        "general": "general"
    }
)

builder.add_edge("billing", END)
builder.add_edge("general", END)

graph = builder.compile()

result = graph.invoke({
    "request": "Why was my credit card charged twice?"
})

print(result["category"])
print(result["reason"])
print(result["response"])

Possible output:

Text
billing
The customer is asking about a duplicate charge.
Your request has been routed to billing support.

Understanding the workflow

The RoutingDecision model defines what the LLM must produce.

The SupportState definition describes the data shared across the graph.

The classification node constructs the prompt, invokes the structured model, and returns selected fields as state updates.

The routing function reads the validated category and determines the next node.

Finally, the selected handler produces a response.

Notice that the LLM does not directly execute a billing operation. It proposes a classification, while ordinary Python and LangGraph control execution.

This separation becomes increasingly important when workflows interact with databases, external APIs, and sensitive business operations.

Applying this to the chapter project

Our question-answering application can combine a grounding prompt with a schema containing an answer, supporting source IDs, and an answerability flag.

A future LangGraph workflow could route answerable questions to a response node and unanswered questions to a retrieval or clarification node.

Instead of searching generated text for phrases such as “I don’t know,” the workflow can inspect an explicit Boolean field.

As the application grows, these structured contracts will allow model-based components to communicate with predictable software interfaces.

Connection to the next lesson

This lesson extended the model invocation techniques introduced in Calling models from Python by adding behavioral instructions and typed responses.

In the next lesson, Function and tool calling, we will explore how models generate structured requests for external operations, how Python executes those operations, and how the results return to the model.

Structured output describes what information a model should return. Tool calling enables a model to request an operation that can retrieve information or interact with an external system.

Understanding this distinction prepares you to build agents that not only generate useful responses but also participate in controlled, multi-step workflows.

Exercise

Build a Structured Question-Answering Assistant

Build an assistant that answers questions using only a supplied knowledge base. Define a Pydantic schema containing the answer, whether the question is answerable, the supporting source IDs, and a short explanation. Use structured output and verify that the model handles both answerable questions and questions for which information is unavailable.

Python
import json
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
from pydantic import BaseModel, Field

model = init_chat_model("openai:gpt-5.4-mini")

knowledge_base = {
    "DOC-1": "Customers can return products within 30 days of delivery.",
    "DOC-2": "Standard shipping takes 3 to 5 business days.",
    "DOC-3": "Refunds are processed within 7 business days."
}

# TODO: Define a Pydantic model named Answer.
# Include answer, answerable, sources, and explanation.

# TODO: Create a structured model using with_structured_output().

def ask(question: str):
    # TODO: Write a system prompt that restricts answers
    # to information in the knowledge base.

    # TODO: Invoke the structured model.

    # TODO: Validate that every source ID exists.

    raise NotImplementedError

questions = [
    "How long do I have to return a product?",
    "Do you offer international shipping?"
]

for question in questions:
    result = ask(question)
    print(result.model_dump_json(indent=2))

Summary

  • Prompt engineering defines the task, context, constraints, and expected behavior of a language model.
  • System messages communicate application instructions while human messages carry user requests and task-specific data.
  • Few-shot prompting provides demonstrations that help models recognize desired behavior and handle ambiguous inputs.
  • Structured output converts model responses into predictable data structures that applications can consume programmatically.
  • Pydantic schemas provide typed Python objects and runtime validation of model-generated fields.
  • Schema compliance does not guarantee factual accuracy, authorization, or business-rule correctness.
  • Structured model responses enable reliable conditional routing and state updates in LangGraph workflows.