08F.6 Prompts, Output Parsers and Structured Output
Lesson 08F.5 gave you a chat model that takes messages in and returns an AIMessage. Almost nothing useful is built from that call alone. Before the model runs, something has to turn your variables (a ticket, a customer name, a date, the last six turns of a conversation) into the right list of messages. After it runs, something has to turn the reply into the thing your program wanted in the first place: a string, a list, a validated object with a category that is one of four allowed values. In LangChain those two jobs are done by prompt templates and by structured output (with the older output parsers underneath it). This lesson covers every piece: string and chat templates, MessagesPlaceholder, partials, few-shot templates and example selectors, the parser classes and what each one is for, with_structured_output on the model, the strategies each provider uses, response_format inside create_agent, what to do when the output is wrong, and how to store and version prompts, including the LangSmith prompt hub. It also tells you which of the tutorials you will find online are out of date, and why their imports fail. Most of the samples run on your laptop with no API key, using a fake chat model, and the lesson shows their real output.
Versions (current at time of writing, verified 14 November 2026): langchain-core 1.8.0, langchain 1.5.0, langchain-classic 1.0.8, langsmith 0.14.17, langchain-openai 1.8.0, langchain-anthropic 1.7.10, langchain-google-genai 4.5.0, langchain-openrouter 0.2.9, pydantic 2.14. The course floor is Python 3.11 (langchain and langchain-core require it). These are fast-moving packages: when a name or default in this lesson does not match what you see, trust the API reference and the changelog, and see 1.2 for why the usual docs site cannot settle prompt questions.
What you'll learn
- How a prompt template behaves as an object: it is a
Runnable, its output is aPromptValue, andinvoke,format,format_messagesandpartialeach return something different PromptTemplatefor strings andChatPromptTemplatefor messages: every message form and role name, the three template formats (f-string,mustache,jinja2), the brace-escaping gotcha, composition with+, and multimodal contentMessagesPlaceholderfor history: required versus optional,n_messages, the("placeholder", "{var}")shorthand, and where history lives now that agents carry it in state- Partial application with static and callable values, and the traps (
from_messagesdoes not takepartial_variables; a misspelt partial name is ignored) - Few-shot prompts:
FewShotPromptTemplate,FewShotChatMessagePromptTemplate, and example selectors (length-based, semantic similarity, max marginal relevance), including the wrong import paths in the source docstrings - Output parsers:
StrOutputParser,JsonOutputParser(including streaming partial JSON),PydanticOutputParserand its format instructions, list and XML parsers, tool-call parsers, writing your own (including the streaming base classes),OutputParserException, and the classic parsers that still exist inlangchain-classic with_structured_output: Pydantic versusTypedDictversus JSON Schema,methodandinclude_raw, refusals, what it does underneath, what.stream()yields for each schema type, and the per-provider defaults and quirks for OpenAI, Anthropic, Gemini and OpenRouter as of November 2026 (including the Claude models that reject forced tool choice)create_agent(response_format=...):ToolStrategy,ProviderStrategy,AutoStrategy,handle_errors, unions, refusals, and the unvalidated JSON Schema caveat- Error handling you build yourself (chains have no built-in retry):
with_retry,with_fallbacks, a repair loop with feedback, and the classicOutputFixingParserandRetryOutputParser - Prompt hubs and versioning: LangSmith
push_promptandpull_prompt, commit hashes and tags, caching,StructuredPrompt, the public-prompt security change, and when git beats a hub - Legacy patterns and how to read old tutorials:
LLMChain,StructuredOutputParser,hub.pull,langchain.promptsimports, and what replaced each - A complete, tested triage chain with a few-shot prompt, partials, structured output, retries and a fallback, whose tests need no key
What you don't need
- An API key for most of the lesson. Parts 2 to 7, 8.3, 8.8, 10.2, 11, 12.3 (the identifier parser), 12.6, the import check in Part 13 and the tests in Part 14 run keyless (fake chat models such as
GenericFakeChatModel, or no model at all) and show real output. The provider and hub samples (8.5, 8.7, 9.2, 10.5, 12.2, 12.3 pull, the "current equivalent" in Part 13 and 14.3) are labelled illustrative and written against the official documentation and package source. - Prior LangChain experience beyond 08F.4 and 08F.5. Pydantic is explained where it first appears (7.4); the schema design questions behind it are lesson 03.4.
- The agent loop or LangGraph.
create_agentappears once, in Part 10; it is the subject of 08F.8.
Setup
Python 3.11 or newer and uv. If you have not created a project yet, run the first line (or follow lesson 03.1, Part 4):
uv init lc-prompts --bare --python 3.13 && cd lc-prompts # first time only
uv add langchain langchain-classic pydantic python-dotenv pytest jinja2 defusedxml numpy
# or: pip install langchain langchain-classic pydantic python-dotenv pytest jinja2 defusedxml numpylangchain brings langchain-core (where prompts and parsers live), langgraph and langsmith with it. langchain-classic holds the legacy parsers used in 11.6 and 13. jinja2 is needed only for the jinja2 template format, defusedxml only for XMLOutputParser, and numpy only for the fake embeddings in 6.3. To run the provider samples add the integration packages you need, by name only:
uv add "langchain[openai]" "langchain[anthropic]" "langchain[google-genai]" # pick the ones you use (google-genai is optional)
uv add langchain-openrouter # optional: OpenRouter has its own packageThe provider samples read keys from a .env file (never commit it), the same one used across Modules 03 and 08A:
# .env
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=... # optional
OPENROUTER_API_KEY=... # optional gateway
LANGSMITH_API_KEY=... # only for Part 12The Gemini integration documents GOOGLE_API_KEY; the samples pass GEMINI_API_KEY explicitly with api_key= so one .env serves the whole course. Every sample here was written against the package versions above; the keyless samples were also run against them, and their output is pasted unedited.
What you must be able to do after this lesson#
- Build and invoke a prompt template and explain what it returns
- Keep conversation history in a prompt with MessagesPlaceholder
- Parse model output with an output parser
- Get structured output with with_structured_output
- Compose a prompt, model and parser into a tested chain
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Pass the PromptValue to the model." |
1.1 The three-stage pipeline |
"Why does it say I'm missing a variable called \"label\"?" |
2.3 The brace gotcha |
| "How do I keep chat history in a prompt?" | Part 4 |
| "Inject today's date without passing it every call." | Part 5 |
| "Pick the three most similar examples for each ticket." | 6.3 Dynamic selection |
| "Do we still need output parsers?" | 7.1 Do you still need a parser? |
"with_structured_output or response_format?" |
Part 8 and Part 10 |
| "It works on OpenAI and fails on Claude." | Part 9 |
| "Can I stream a structured result to a UI?" | 8.8 Streaming structured output |
"The model returned urgency: 9 and the schema says 1 to 5." |
Part 11 |
| "Where do we store prompts: git or LangSmith?" | 12.5 Git, the hub, or both |
"This tutorial's from langchain.prompts import ... fails." |
Part 13 |
| "How do we unit-test the prompt and the chain?" | Part 14 |
Part 1: Prompts, parsers and structured output as objects#
1.1 The three-stage pipeline#
Every LangChain call that is not an agent has the same three stages:
flowchart LR
vars["dict of variables<br/>(ticket, company, history)"] --> prompt["Prompt template<br/>PromptTemplate or ChatPromptTemplate"]
prompt -->|"PromptValue"| model["Chat model"]
model -->|"AIMessage"| parser["Output parser<br/>or structured output"]
parser --> result["str, list, dict<br/>or Pydantic object"]Each stage is a Runnable (the common interface covered in 08F.7): it has invoke, stream, batch and async twins, and stages join with |. For this lesson you need only three facts about that interface:
- A template's
invoketakes a dict of variables and returns aPromptValue. A string template returns aStringPromptValue; a chat template returns aChatPromptValue. APromptValuehasto_string()andto_messages(), and chat models accept it directly, which is whyprompt | modelworks with no glue code. - A template also has plain methods:
format(**kwargs)returns astr,format_messages(**kwargs)returns alist[BaseMessage], andpartial(...)returns a new template with some variables already filled. - Templates validate. The set of variables is inferred from the text, and a missing variable raises a
KeyErroratinvoketime, before any model is called and before any money is spent.
Without any model at all, the first stage looks like this. Save it as s01_string_prompt.py:
from langchain_core.prompts import PromptTemplate
prompt = PromptTemplate.from_template(
"Summarize this {doc_type} in {n} bullet points:\n\n{text}"
)
print(prompt.input_variables) # inferred from the template text
value = prompt.invoke({"doc_type": "invoice", "n": 3, "text": "Acme Ltd, 12 widgets, due in 30 days"})
print(repr(value)) # a PromptValue, not a str
print(value.to_string())
print(prompt.format(doc_type="contract", n=2, text="...")) # plain str
# Extra keys are ignored; missing keys raise KeyError at invoke time.
print(prompt.format(doc_type="a", n=1, text="b", unused="ignored"))
try:
prompt.invoke({"doc_type": "invoice"})
except KeyError as err:
print("KeyError:", err.args[0].split("\n")[0])Output (real, from langchain-core 1.8.0; the order of names inside the {...} set of the error message can vary between runs):
['doc_type', 'n', 'text']
StringPromptValue(text='Summarize this invoice in 3 bullet points:\n\nAcme Ltd, 12 widgets, due in 30 days')
Summarize this invoice in 3 bullet points:
Acme Ltd, 12 widgets, due in 30 days
Summarize this contract in 2 bullet points:
...
Summarize this a in 1 bullet points:
b
KeyError: Input to PromptTemplate is missing variables {'text', 'n'}. Expected: ['doc_type', 'n', 'text'] Received: ['doc_type']Three things to notice. input_variables was inferred from the template text, not declared. invoke returned a StringPromptValue, a wrapper, while format returned the plain string. And the KeyError message tells you the variables it expected, the ones it received and, helpfully, how to escape braces, which is the subject of 2.3.
1.2 What the official docs cover, and what they do not#
This is the first lesson in the module where the official documentation cannot be your only reference, and you should know that before you go looking. As of 14 November 2026 the current docs site (docs.langchain.com) no longer has conceptual pages for prompt templates, few-shot prompts or output parsers; searching its full index finds them only in the API reference. What the site does cover well is structured output (the Structured output page and the model pages) and, in the LangSmith section, prompt management. So:
| Topic | Where the truth lives |
|---|---|
PromptTemplate, ChatPromptTemplate, MessagesPlaceholder, few-shot classes, parsers |
The API reference at reference.langchain.com/python/langchain-core/prompts/... and .../output_parsers, and the docstrings in the langchain-core source (libs/core/langchain_core/prompts on GitHub) |
with_structured_output |
Each integration page (OpenAI, Anthropic, Google) plus the provider package source; the model pages |
create_agent(response_format=...), ToolStrategy, ProviderStrategy |
The Structured output page |
Prompt hub, push_prompt, pull_prompt |
The LangSmith pages on prompt engineering and managing prompts programmatically, plus the langsmith source |
1.3 Where this lesson stops and others start#
You already own most of the ideas here; this lesson is about the LangChain objects that implement them.
| Question | Owner |
|---|---|
| What to write in a prompt, how to choose and order few-shot examples, system prompt design | Module 04, especially 04.2 and 04.5 |
Templating in plain Python (f-strings, str.format, Jinja2), where prompts live, versioning and pinning, a prompt library |
04.10 |
| JSON Schema subsets per provider, schema design, validation layers, refusal and truncation as non-answers | 03.4 |
Messages, content blocks, init_chat_model, the model-level retry layers, fake models, and the first look at with_structured_output defaults and refusals (10.2, 10.3) |
08F.5 |
The Runnable protocol, ` |
, RunnableLambda, RunnableParallel, streaming events, and the full treatment of with_retryandwith_fallbacks` (defaults, composition, retry the smallest unit) |
create_agent, tools, middleware |
08F.8 |
| Tracing, datasets, evaluating prompts | 11A.5 and Module 10A |
Because this is the structured-output lesson, it keeps the per-class default table and the refusal detail in full (8.5 and 9.2), even though 08F.5 gives a first pass at both. It uses with_retry and with_fallbacks only for the failure shapes structured output produces (Part 11) and sends you to 08F.7 for how they work.
Part 2: String templates with PromptTemplate#
2.1 Creating and invoking a template#
PromptTemplate builds a single string. Import it from langchain_core.prompts (the langchain package itself no longer re-exports it; see Part 13). The recommended constructor is the class method:
PromptTemplate.from_template(
template: str,
*,
template_format: Literal["f-string", "mustache", "jinja2"] = "f-string",
partial_variables: dict[str, Any] | None = None,
**kwargs,
) -> PromptTemplatefrom_template infers the variable names from the text, so you never write input_variables=[...] by hand (the explicit constructor still works and old tutorials use it). When you need a plain string, call format; when you want a pipeline stage, call invoke.
When do you use a string template at all, now that nearly every current model is a chat model? Three cases: a fragment you will embed in a larger message (a formatted example block, a reusable instruction paragraph), an input to a legacy text-completion model, and the example template inside FewShotPromptTemplate (6.1). For anything you send to a chat model as a conversation, use ChatPromptTemplate (Part 3).
2.2 Three template formats#
template_format |
Syntax | Notes |
|---|---|---|
"f-string" (default) |
{name} |
Python str.format rules. Literal braces must be doubled: {{ and }}. Recommended unless you have a reason not to |
"mustache" |
{{name}} |
Handy when the prompt is full of single braces (JSON, code). Needs no extra package |
"jinja2" |
{{ name }}, {% for x in xs %} |
Loops and conditionals in the template. Needs uv add jinja2. Runs in Jinja2's SandboxedEnvironment (since langchain-core 0.0.329), but the source docstring is explicit that this is best effort and not a guarantee |
2.3 The brace gotcha#
The f-string format treats every {...} as a variable. A prompt that shows the model a JSON example is the classic way to hit this, and the failure is silent at creation time. Save as s02_braces_and_formats.py:
from langchain_core.prompts import PromptTemplate
# Gotcha: literal braces in an f-string template are treated as variables.
bad = PromptTemplate.from_template('Reply as JSON like {"label": "billing"} for: {text}')
print(bad.input_variables) # no error yet: a variable named '"label"' was invented
try:
bad.invoke({"text": "refund please"})
except KeyError as err:
print("KeyError:", err.args[0].split("\n")[0])
# Fix: double the braces.
good = PromptTemplate.from_template('Reply as JSON like {{"label": "billing"}} for: {text}')
print(good.input_variables)
print(good.format(text="refund please"))
# Braces inside VALUES are never re-interpreted.
print(good.format(text="{not_a_variable} and {{also not}}"))
# The other two formats.
mustache = PromptTemplate.from_template(
"Hello {{name}}, you have {{count}} open tickets", template_format="mustache"
)
print(mustache.input_variables, "->", mustache.format(name="Asha", count=3))
jinja = PromptTemplate.from_template(
"{% for t in tickets %}- {{ t }}\n{% endfor %}", template_format="jinja2"
)
print(jinja.input_variables, "->", repr(jinja.format(tickets=["refund", "login bug"])))['"label"', 'text']
KeyError: Input to PromptTemplate is missing variables {'"label"'}. Expected: ['"label"', 'text'] Received: ['text']
['text']
Reply as JSON like {"label": "billing"} for: refund please
Reply as JSON like {"label": "billing"} for: {not_a_variable} and {{also not}}
['count', 'name'] -> Hello Asha, you have 3 open tickets
['tickets'] -> '- refund\n- login bug\n'Read the first two lines carefully. Creating the template raised nothing; it invented a variable named "label" (quotes included), and the error appears only when you invoke, complaining about a variable you never meant to have. The cure is to double the braces ({{"label": "billing"}} renders as {"label": "billing"}) or to switch to mustache. Also note the fifth line: braces inside the values you pass in are never re-interpreted, so a customer who types {secret} into a ticket cannot make the template look anything up. Templates are single-pass; the f-string is not evaluated again on its own output.
2.4 Templates in files#
A prompt that is longer than a paragraph belongs in its own file, not inside a Python string, so that it can be reviewed, diffed and versioned (04.10, Part 3). The class method for that is PromptTemplate.from_file(template_file, encoding=None, **kwargs); load_prompt(path, encoding=None, *, allow_dangerous_paths=False) loads a prompt that was saved in LangChain's serialized form (12.6). Part 3 shows from_file in a runnable sample next to the roles and mustache chat template.
Part 3: Chat prompt templates#
3.1 Building a ChatPromptTemplate#
A ChatPromptTemplate is an ordered list of message templates. It is what you will use for nearly every prompt. Its constructor and the more common class method are:
ChatPromptTemplate(messages, *, template_format="f-string", **kwargs)
ChatPromptTemplate.from_messages(messages, template_format="f-string")Save the following as s03_chat_prompt.py and run it:
from langchain_core.messages import SystemMessage
from langchain_core.prompts import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a support triage assistant for {company}. Answer in {language}."),
("human", "{ticket}"),
])
print(prompt.input_variables)
value = prompt.invoke({"company": "Acme", "language": "English", "ticket": "My invoice is wrong"})
print(type(value).__name__)
for message in value.to_messages():
print(type(message).__name__, repr(message.content))
print(value.to_string())
# format_messages() returns the list directly (no PromptValue wrapper)
print(prompt.format_messages(company="Acme", language="French", ticket="x")[0].content)
# A one-variable template accepts a bare string
quick = ChatPromptTemplate([("system", "Be brief."), ("human", "{user_input}")])
print(quick.invoke("Hello there").to_messages()[1].content)
# A plain string is shorthand for a human message
print(ChatPromptTemplate.from_messages(["Translate to French: {text}"]).invoke({"text": "hi"}).to_messages())
# Message OBJECTS are used as-is: their braces are NOT templated
fixed = ChatPromptTemplate.from_messages([SystemMessage(content="Literal {braces} stay"), ("human", "{q}")])
print(fixed.input_variables, "|", fixed.invoke({"q": "x"}).to_messages()[0].content)
# Message-level templates (the older, more verbose spelling)
verbose = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("Role: {role}"),
HumanMessagePromptTemplate.from_template("{q}"),
])
print(verbose.input_variables)
# Templates compose with +
persona = ChatPromptTemplate.from_messages([("system", "You are {role}.")])
question = ChatPromptTemplate.from_messages([("human", "{q}")])
combined = persona + question
print(combined.input_variables, len(combined.messages))
combined.pretty_print()['company', 'language', 'ticket']
ChatPromptValue
SystemMessage 'You are a support triage assistant for Acme. Answer in English.'
HumanMessage 'My invoice is wrong'
System: You are a support triage assistant for Acme. Answer in English.
Human: My invoice is wrong
You are a support triage assistant for Acme. Answer in French.
Hello there
[HumanMessage(content='Translate to French: hi', additional_kwargs={}, response_metadata={})]
['q'] | Literal {braces} stay
['q', 'role']
['q', 'role'] 2
================================ System Message ================================
You are {role}.
================================ Human Message =================================
{q}What each part shows:
invokereturns aChatPromptValue;to_messages()gives the list ofSystemMessage,HumanMessageobjects you met in 08F.5, andto_string()gives a readable transcript withSystem:andHuman:prefixes (useful in logs; it is not what is sent to a chat model).format_messages(**kwargs)skips the wrapper and returns the list directly. Use it in tests and when you want to hand messages to the raw provider SDK.- If the template has exactly one input variable,
invokeaccepts a bare string and maps it to that variable. That is convenient in demos and a trap in real code, because adding a second variable later breaks every caller. Pass a dict. - Message objects (
SystemMessage(content="Literal {braces} stay")) are inserted as they are. Their text is never templated, so the braces survive and no variable is created. That is the right tool for a fixed message that contains JSON. +concatenates templates, andpretty_print()renders a template with its placeholders visible, which is the quickest way to see what a composed prompt will contain.
3.2 Message forms and roles#
from_messages accepts a list whose items can each be one of five forms:
| Form | Example | Meaning |
|---|---|---|
2-tuple of (role, template) |
("system", "You are {role}.") |
The usual form. The text is templated |
| A plain string | "Translate to French: {text}" |
Shorthand for ("human", template) |
| A message object | SystemMessage(content="...") |
Used as-is, not templated |
| A message template object | SystemMessagePromptTemplate.from_template("...") |
The older, verbose spelling of the tuple form; also HumanMessagePromptTemplate and AIMessagePromptTemplate |
| A placeholder | MessagesPlaceholder("history") |
A slot for a whole list of messages (Part 4) |
Role names in the tuple form: "system", "human", "ai", and "placeholder" are the canonical ones. OpenAI-style "user" and "assistant" also work as aliases (the official structured-output page itself writes ("user", "{review}")), and the next sample proves it. Pick one vocabulary per codebase; human/ai matches the message class names, user/assistant matches what you see on the wire.
The same sample shows the other two knobs you will want: template_format for a whole chat template, and from_file (see 2.4). Save as s19_roles_files_mustache.py:
import tempfile
from pathlib import Path
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
# OpenAI-style role names work as aliases
aliased = ChatPromptTemplate.from_messages([("user", "hi {x}"), ("assistant", "yo"), ("human", "{y}")])
print([type(m).__name__ for m in aliased.invoke({"x": 1, "y": 2}).to_messages()])
# template_format applies to every message of a chat template
mustache = ChatPromptTemplate.from_messages(
[("system", "Hello {{name}}"), ("human", "{{q}}")], template_format="mustache"
)
print(mustache.input_variables, "|", mustache.invoke({"name": "Asha", "q": "hi"}).to_messages()[0].content)
# Prompt text kept in a file (a file per prompt is the layout recommended in lesson 04.10)
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "triage.v1.txt"
path.write_text("Classify this {channel} ticket:\n{ticket}\n", encoding="utf-8")
from_disk = PromptTemplate.from_file(path)
print(from_disk.input_variables, "|", repr(from_disk.format(channel="email", ticket="refund please")))['HumanMessage', 'AIMessage', 'HumanMessage']
['name', 'q'] | Hello Asha
['channel', 'ticket'] | 'Classify this email ticket:\nrefund please\n'3.3 Composition, inspection and multimodal content#
A human message's content does not have to be a string. Give the tuple a list of content blocks and each block is templated. This is how you template an image or a PDF reference (the blocks follow the standard format from 08F.5; the sending side is 03.6). Save as s04_multimodal_prompt.py:
from langchain_core.prompts import ChatPromptTemplate
# A human message whose content is a list of blocks; each block is templated.
prompt = ChatPromptTemplate.from_messages([
("human", [
{"type": "text", "text": "Extract the total from this {document}."},
{"type": "image", "url": "{image_url}"},
])
])
print(prompt.input_variables)
message = prompt.invoke({"document": "receipt", "image_url": "https://example.com/receipt.png"}).to_messages()[0]
print(message.content)['document', 'image_url']
[{'type': 'text', 'text': 'Extract the total from this receipt.'}, {'type': 'image', 'url': 'https://example.com/receipt.png'}]HumanMessagePromptTemplate.from_template also accepts a list of text and image template dicts, if you prefer the explicit class. For base64 data the standard block needs a mime_type, and not every model accepts every file type, so keep the template to the references (URLs or provider file ids) and put large payloads in at call time as message objects rather than template variables.
For composing prompts out of reusable parts, three tools are enough:
a + bjoins two chat templates, or a template and a message tuple, and merges their variables. Keep apersonatemplate, asafety_rulestemplate and a task template, and add them.partial(Part 5) freezes the variables that do not change per call.- A
MessagesPlaceholder(Part 4) leaves a slot for a list.
Four more exports of langchain_core.prompts complete the picture (all four checked in 1.8.0):
| Export | What it is for |
|---|---|
ChatMessagePromptTemplate |
A message template with an arbitrary role string (ChatMessagePromptTemplate.from_template("hi {x}", role="critic") renders a ChatMessage whose role is critic). Needed only for providers or models that define their own roles |
DictPromptTemplate |
A template written as a dict ({"type": "text", "text": "hi {x}"}) whose string values are templated. It is the building block behind templated content blocks like the multimodal sample above |
format_document(doc, prompt) |
Renders a Document through a PromptTemplate that may use {page_content} and any metadata key, and returns a str. It is the usual way to turn retrieved chunks into a context block (Module 07) |
StringPromptTemplate |
The abstract base of PromptTemplate. Subclass it and implement format when you need a custom prompt type, for example one that renders a list of objects with its own logic. Most code never needs this |
3.4 Prompt design that plays well with caching#
Provider prompt caching (03.7, 02.7) matches on the prefix of the prompt, so the order of your template matters for cost: put everything that is the same on every call at the top (system instructions, tool descriptions, the few-shot block) and everything that changes at the bottom (the ticket, the history, a timestamp). A partial that injects today's date into the system message changes the prefix once a day, which is fine. A partial that injects a timestamp or a request id into the first message changes the prefix on every call and silently disables caching. The template does nothing to protect you from this; read the rendered prompt (pretty_print() or to_string()) with the cache in mind.
Part 4: Conversation history with MessagesPlaceholder#
4.1 Required, optional and capped#
MessagesPlaceholder marks a place where a whole list of messages is inserted. Its signature is MessagesPlaceholder(variable_name, *, optional=False, **kwargs), and it has one more field, n_messages. Save the sample as s05_placeholder.py:
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
required = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
MessagesPlaceholder("history"),
("human", "{question}"),
])
print(required.input_variables, required.optional_variables)
history = [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")]
for message in required.invoke({"history": history, "question": "now multiply that by 4"}).to_messages():
print(type(message).__name__, "|", message.content)
try:
required.invoke({"question": "first turn"}) # forgot history
except KeyError as err:
print("KeyError:", err.args[0].split("\n")[0])
print(len(required.invoke({"history": [], "question": "empty list is fine"}).to_messages()))
optional = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
MessagesPlaceholder("history", optional=True),
("human", "{question}"),
])
print(optional.input_variables, optional.optional_variables)
print(len(optional.invoke({"question": "first turn"}).to_messages()))
# The string shorthand is the optional form
shorthand = ChatPromptTemplate.from_messages([("system", "s"), ("placeholder", "{conversation}")])
print(shorthand.input_variables, shorthand.optional_variables, len(shorthand.invoke({}).to_messages()))
# n_messages keeps only the LAST n
capped = ChatPromptTemplate.from_messages([MessagesPlaceholder("history", n_messages=2), ("human", "{q}")])
turns = [HumanMessage("m1"), AIMessage("m2"), HumanMessage("m3"), AIMessage("m4")]
print([m.content for m in capped.invoke({"history": turns, "q": "now"}).to_messages()])
# A single message is rejected: pass a list
try:
required.invoke({"history": HumanMessage("solo"), "question": "q"})
except ValueError as err:
print("ValueError:", str(err)[:70])['history', 'question'] []
SystemMessage | You are a helpful assistant.
HumanMessage | what's 5 + 2
AIMessage | 5 + 2 is 7
HumanMessage | now multiply that by 4
KeyError: Input to ChatPromptTemplate is missing variables {'history'}. Expected: ['history', 'question'] Received: ['question']
2
['question'] ['history']
2
[] ['conversation'] 1
['m3', 'm4', 'now']
ValueError: variable history should be a list of base messages, got content='solo'The behaviours, from that output and from the source docstring:
| Setting | What happens | Appears in |
|---|---|---|
optional=False (default) |
The variable is required; omitting it raises KeyError, even though an empty list [] is accepted |
input_variables |
optional=True |
Omitting the variable yields no messages | optional_variables |
("placeholder", "{conversation}") |
Shorthand, equal to MessagesPlaceholder("conversation", optional=True) |
optional_variables |
n_messages=2 |
Keeps only the last two messages of whatever you pass |
Values can be message objects or the same tuples the template accepts (("human", "...")), and they must be a list: a single HumanMessage is rejected with a ValueError. Use optional=True for the first turn of a conversation; leave it required when forgetting the history would be a bug you want to catch loudly.
4.2 History in v1: where it really lives#
In pre-1.0 LangChain, conversation memory was a class (ConversationBufferMemory and relatives) that wrote into a MessagesPlaceholder("history") slot of an LLMChain. Both halves are legacy now. In v1 an agent carries its messages in its own state, and a checkpointer persists them per thread (08F.8, 08F.11). You do not template history into an agent's prompt at all.
MessagesPlaceholder is still the right tool when you hand-build a chain (prompt | model | parser) and own the history yourself: a support bot that keeps its turns in your database, a summariser that wants the previous three summaries, a classifier that should see the thread so far. The pattern is simply "load the list, trim it, pass it as history". The lesson on agent memory (08B.2) covers what is worth remembering; this part only covers the slot.
4.3 Trimming before you inject#
A placeholder inserts whatever you give it, so a long conversation overflows the context window unless you cut it first (02.7, 04.7). n_messages is the crude version (last N, regardless of size). trim_messages from langchain_core.messages (08F.5) is the token-aware one. token_counter="approximate" counts without a model or network call, strategy="last" keeps the most recent turns, and start_on="human" makes sure the kept slice does not begin with an orphaned AI reply. Save as s20_trim_into_placeholder.py:
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, trim_messages
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages([
("system", "You are a support assistant."),
MessagesPlaceholder("history", optional=True),
("human", "{question}"),
])
history = [
HumanMessage("My order A-1042 has not arrived."),
AIMessage("Sorry to hear that. Can you confirm the email on the order?"),
HumanMessage("It is asha@example.com."),
AIMessage("Thanks, I can see the order. It shipped on Monday."),
HumanMessage("Can I change the delivery address?"),
AIMessage("Not once it has shipped, but I can open a redirect request."),
]
# Keep the most recent turns that fit, never starting on an AI message.
# "approximate" counts tokens without a model or a network call.
recent = trim_messages(
history,
max_tokens=60,
token_counter="approximate",
strategy="last",
start_on="human",
)
print(len(history), "->", len(recent), "messages kept")
for message in recent:
print(f"{type(message).__name__:13}| {message.content}")
rendered = prompt.invoke({"history": recent, "question": "Please do the redirect."}).to_messages()
print([type(m).__name__ for m in rendered])6 -> 2 messages kept
HumanMessage | Can I change the delivery address?
AIMessage | Not once it has shipped, but I can open a redirect request.
['SystemMessage', 'HumanMessage', 'AIMessage', 'HumanMessage']With a budget of 60 approximate tokens, six messages shrank to the last two (a human question and the AI answer), and the rendered prompt is the system message, those two, and the new question. The same trim_messages can sit as a stage in a chain (it works as a Runnable), which is how you will meet it in 08F.7. Trimming drops information; summarising old turns instead of dropping them is covered in 08B.2, 08F.8 (summarization middleware) and 08F.11.
Part 5: Partial application#
Deep-dive
A partial binds some of a template's variables ahead of time and returns a new template that needs fewer inputs. The method is partial(**kwargs) on every template; each value can be a string (or, in practice, any value the variable accepts) or a zero-argument callable that is evaluated every time the prompt is formatted. That makes partials the natural home for three kinds of value:
- constants for one deployment (company name, tone, a fixed policy paragraph);
- values that change over time but not per request (today's date, the current release name), via a callable;
- machinery you want to hide from callers, such as the
format_instructionsof an output parser (7.4).
Save as s06_partials.py:
from datetime import date
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
prompt = PromptTemplate.from_template("Today is {today}. Question: {q}")
print(prompt.input_variables)
fixed = prompt.partial(today="2026-11-14") # returns a NEW template
print(fixed.input_variables, "->", fixed.format(q="when is it due?"))
dynamic = prompt.partial(today=lambda: date.today().isoformat()) # evaluated at format time
print(dynamic.input_variables, "->", dynamic.format(q="x") == f"Today is {date.today().isoformat()}. Question: x")
# The constructor takes partial_variables (from_messages does not)
chat = ChatPromptTemplate(
[("system", "Tone: {tone}. Today: {today}"), ("human", "{q}")],
partial_variables={"tone": "formal"},
)
print(chat.input_variables, chat.partial_variables)
more = chat.partial(today="Monday")
print(more.input_variables, [m.content for m in more.invoke({"q": "hi"}).to_messages()])
# A value passed at invoke time wins over the partial
print([m.content for m in more.invoke({"q": "hi", "tone": "playful"}).to_messages()])
# A misspelt partial name is silently ignored
print(PromptTemplate.from_template("Hi {name}").partial(nme="x").input_variables)
# Partials work for a MessagesPlaceholder variable too
seeded = ChatPromptTemplate.from_messages([
("placeholder", "{history}"), ("human", "{q}"),
]).partial(history=[("human", "earlier"), ("ai", "reply")])
print(seeded.input_variables, len(seeded.invoke({"q": "x"}).to_messages()))['q', 'today']
['q'] -> Today is 2026-11-14. Question: when is it due?
['q'] -> True
['q', 'today'] {'tone': 'formal'}
['q'] ['Tone: formal. Today: Monday', 'hi']
['Tone: playful. Today: Monday', 'hi']
['name']
['q'] 3The details worth remembering:
partialreturns a new object; the original template is unchanged. Partial variables disappear frominput_variables.- A callable is evaluated at format time, so
lambda: date.today().isoformat()gives today's date on each call, not the date the process started. That is what you want for a long-running service. The sample's second line shows the comparison against the real date printingTrue. - The constructor takes
partial_variables;from_messagesdoes not.ChatPromptTemplate.from_messages(..., partial_variables=...)raises aTypeError. Either call.partial(...)afterwards or build withChatPromptTemplate([...], partial_variables={...}).PromptTemplate.from_template(..., partial_variables=...)does accept it. - A value passed at invoke time wins over the partial of the same name. That is useful for per-request overrides and a quiet source of surprises if two layers set the same name.
- A misspelt partial name is silently ignored: the fourth output line shows
['name']still required afterpartial(nme="x"). Checkinput_variablesafter you partial, and put one assertion about it in a test (Part 14 does). - Partials work for a placeholder variable, so a conversation template can be seeded with earlier turns.
A chain-level alternative exists for values you compute per call from the input (look up the customer's plan from the ticket's account id, then inject it): put a RunnableLambda or a dict of runnables in front of the prompt. That belongs to 08F.7. Rule of thumb: static or time-based → partial; derived from this request's input → a step before the prompt.
Part 6: Few-shot prompts and example selectors#
Deep-dive
The craft of few-shot prompting (how many examples, which ones, in what order, how to avoid over-copying, what they cost) is lesson 04.2, and the dynamic-selection theory is 04.2, Part 6. This part is only how LangChain represents examples, so a template can render them for you. There are two template classes and a family of selectors. Everything is imported from langchain_core.prompts (and langchain_core.example_selectors for selectors).
6.1 Text few-shot#
FewShotPromptTemplate renders each example through a string example_prompt, joins them with example_separator (default two newlines), and wraps them with a prefix and a suffix. Its fields, read from the 1.8.0 source, are examples or example_selector (one of the two), example_prompt (a PromptTemplate), suffix (required), prefix (default empty), input_variables, example_separator and template_format (f-string or jinja2). Save as s07_fewshot.py (it also contains the chat flavour from 6.2):
from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
FewShotPromptTemplate,
PromptTemplate,
)
examples = [
{"ticket": "I was charged twice this month", "label": "billing"},
{"ticket": "The app crashes when I upload a PDF", "label": "bug"},
{"ticket": "How do I export my data?", "label": "how_to"},
]
# 1. String flavour: examples are rendered into ONE block of text.
example_prompt = PromptTemplate.from_template("Ticket: {ticket}\nLabel: {label}")
text_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="Classify each support ticket as billing, bug or how_to.",
suffix="Ticket: {ticket}\nLabel:",
input_variables=["ticket"],
)
print(text_prompt.format(ticket="Where is my invoice PDF?"))
print("-----")
# 2. Chat flavour: each example becomes a human/ai message pair.
pair = ChatPromptTemplate.from_messages([("human", "{ticket}"), ("ai", "{label}")])
shots = FewShotChatMessagePromptTemplate(examples=examples, example_prompt=pair)
chat_prompt = ChatPromptTemplate.from_messages([
("system", "Classify each support ticket as billing, bug or how_to. Reply with the label only."),
shots,
("human", "{ticket}"),
])
print(chat_prompt.input_variables)
for message in chat_prompt.invoke({"ticket": "Where is my invoice PDF?"}).to_messages():
print(f"{type(message).__name__:13}| {message.content}")
# 3. JSON inside example VALUES is safe: values are not re-templated.
json_pair = ChatPromptTemplate.from_messages([("human", "{ticket}"), ("ai", "{out}")])
json_shots = FewShotChatMessagePromptTemplate(
examples=[{"ticket": "charged twice", "out": '{"label": "billing"}'}],
example_prompt=json_pair,
)
print([m.content for m in json_shots.format_messages()])Classify each support ticket as billing, bug or how_to.
Ticket: I was charged twice this month
Label: billing
Ticket: The app crashes when I upload a PDF
Label: bug
Ticket: How do I export my data?
Label: how_to
Ticket: Where is my invoice PDF?
Label:
-----
['ticket']
SystemMessage| Classify each support ticket as billing, bug or how_to. Reply with the label only.
HumanMessage | I was charged twice this month
AIMessage | billing
HumanMessage | The app crashes when I upload a PDF
AIMessage | bug
HumanMessage | How do I export my data?
AIMessage | how_to
HumanMessage | Where is my invoice PDF?
['charged twice', '{"label": "billing"}']The first block is the text flavour: the prefix, three rendered examples, then the suffix holding the live input and a trailing Label: cue for the model to complete. input_variables in the constructor lists only the variables of the suffix and prefix (here ticket), not the example fields. Use this flavour when the target is a text-completion model or when the examples belong inside one message as a formatted block.
6.2 Chat few-shot#
FewShotChatMessagePromptTemplate renders every example through a chat example_prompt into real messages, so each example becomes a human/AI pair in the conversation. You then embed it in a ChatPromptTemplate between the system message and the live question. That is the second block of the output above: system message, three human/AI pairs, the live ticket. It is the layout most chat models follow best for short, label-style outputs, and 04.2, Part 3 compares it with putting the examples in one message.
The last line of the output shows a safety property you will rely on: the example's out value was {"label": "billing"}, JSON with braces, and it rendered intact. Braces inside values are never templated, so JSON examples are safe as example data. Only braces in template text need doubling (2.3).
Three cautions:
- The AI side of an example is plain text. If you will later call
with_structured_output(Part 8), a free-text example likebilling, urgency 4teaches the model a format the structured path will not use, and it leaves out fields the schema requires. Write the AI side as a JSON string that mirrors the whole schema (the Part 14 triage chain does exactly this). It is still plain text, but it shows the model the shape it will be asked to return. A tool-call-shaped example (anAIMessagewithtool_calls, then aToolMessage) is the other option for thefunction_callingpath; this lesson did not test how each provider treats tool calls in the history when no tools are bound, so it keeps to JSON text. 04.2, Part 8 discusses the trade-off. - Examples cost tokens on every call and sit at the front of the prompt, which is good for caching only while they stay constant (3.4).
- A third class,
FewShotPromptWithTemplates, makes theprefixandsuffixthemselves templates. Its fields, read from the 1.8.0 source, areexamplesorexample_selector,example_prompt(aPromptTemplate),suffix(aStringPromptTemplate, required),prefix(aStringPromptTemplate, optional),example_separator(default two newlines),template_format(f-string,mustacheorjinja2) andvalidate_template(defaultFalse).FewShotPromptTemplatetakesprefixandsuffixas plain strings; this class takes template objects, so use it when the prefix or suffix is a prompt template you already built and want to reuse as it is, for example a per-tenant policy paragraph template with its own variables and format. Most code never needs it: strings are enough for a fixed instruction.
6.3 Dynamic selection#
Pass example_selector= (and input_variables=) instead of examples= and the template asks the selector, at format time, which examples to include for this input. A selector is any object with select_examples(input_variables) -> list[dict] and add_example(example) (the BaseExampleSelector interface). Three selectors ship in langchain_core.example_selectors (length-based, semantic similarity and max marginal relevance), plus the BaseExampleSelector interface for your own:
| Selector | Picks examples by | Needs |
|---|---|---|
LengthBasedExampleSelector |
Fitting as many as a word budget (max_length, default 2048) allows; shorter inputs get more examples. "Words" means pieces split on single spaces and newlines, not tokens: pass your own get_text_length function to count something else |
nothing |
SemanticSimilarityExampleSelector |
The k stored examples nearest to the input by embedding similarity |
an Embeddings object and a vector store class |
MaxMarginalRelevanceExampleSelector |
Nearness and diversity (avoids returning five near-duplicates): it fetches fetch_k candidates (default 20), then keeps k diverse ones |
same as above, and a store that supports MMR |
BaseExampleSelector |
Your own rule (tenant, language, label balance) | you implement two methods |
Save as s08_selectors.py:
from langchain_core.embeddings import DeterministicFakeEmbedding
from langchain_core.example_selectors import (
LengthBasedExampleSelector,
SemanticSimilarityExampleSelector,
)
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.vectorstores import InMemoryVectorStore
examples = [
{"ticket": "I was charged twice this month", "label": "billing"},
{"ticket": "The app crashes when I upload a PDF", "label": "bug"},
{"ticket": "How do I export my data?", "label": "how_to"},
]
example_prompt = PromptTemplate.from_template("Ticket: {ticket}\nLabel: {label}")
# Length-based: fit as many examples as the word budget allows.
by_length = LengthBasedExampleSelector(examples=examples, example_prompt=example_prompt, max_length=25)
print("short input ->", len(by_length.select_examples({"ticket": "short"})), "examples")
print("long input ->", len(by_length.select_examples({"ticket": "a very long incoming ticket " * 5})), "examples")
dynamic = FewShotPromptTemplate(
example_selector=by_length, # instead of examples=
example_prompt=example_prompt,
prefix="Classify each support ticket.",
suffix="Ticket: {ticket}\nLabel:",
input_variables=["ticket"],
)
print(dynamic.format(ticket="short").count("Label:") - 1, "examples rendered")
# Semantic: embed the examples once, retrieve the k nearest to each new input.
# DeterministicFakeEmbedding gives meaningless similarity: this shows the PLUMBING only.
# In real code pass OpenAIEmbeddings() etc. and a real vector store class.
semantic = SemanticSimilarityExampleSelector.from_examples(
examples, DeterministicFakeEmbedding(size=64), InMemoryVectorStore, k=2
)
picked = semantic.select_examples({"ticket": "I was charged twice this month"})
print(len(picked), "examples picked, keys:", sorted(picked[0].keys()))
semantic.add_example({"ticket": "Cancel my plan", "label": "billing"}) # grows the storeshort input -> 2 examples
long input -> 0 examples
2 examples rendered
2 examples picked, keys: ['label', 'ticket']The length-based selector kept two of three examples for a one-word input and none for a long one: when there is no budget it quietly sends no examples, a behaviour worth knowing before you rely on it. The semantic selector used DeterministicFakeEmbedding and an in-memory store, so its ranking is meaningless (the fake embedding does not encode meaning). The sample shows only the plumbing: examples are embedded once at construction (from_examples), the k nearest are retrieved per call, and add_example grows the store as you collect good production cases. In real code replace the fake embedding with a real one (for example OpenAIEmbeddings from langchain-openai, embedding choices are Module 06) and use a real store class.
6.4 Choosing, and where the theory lives#
| Situation | Use |
|---|---|
| A chat model, a handful of fixed examples | FewShotChatMessagePromptTemplate with examples= inside a ChatPromptTemplate |
| One formatted block of examples inside a single message, or a completion model | FewShotPromptTemplate |
| Many labels or domains, examples vary a lot with the input | A selector (SemanticSimilarityExampleSelector, or a custom BaseExampleSelector) |
| A hard token budget and variable input length | LengthBasedExampleSelector |
| Examples must not leak between tenants | A custom selector that filters by tenant before similarity |
Part 7: Output parsers#
An output parser takes the model's reply (an AIMessage, or just its text) and returns a Python value. Parsers are Runnables, so prompt | model | parser is a valid chain, and they live in langchain_core.output_parsers. The full public list in 1.8.0 is: StrOutputParser, JsonOutputParser, SimpleJsonOutputParser, PydanticOutputParser, CommaSeparatedListOutputParser, NumberedListOutputParser, MarkdownListOutputParser, ListOutputParser, XMLOutputParser, JsonOutputToolsParser, JsonOutputKeyToolsParser, PydanticToolsParser, and the base classes BaseOutputParser, BaseLLMOutputParser, BaseGenerationOutputParser, BaseTransformOutputParser and BaseCumulativeTransformOutputParser. A second, older set (enum, datetime, boolean, YAML, regex and others) lives in langchain-classic; 7.9 lists it.
7.1 Do you still need a parser?#
For structured output, mostly no. The rule for current code:
If the model supports structured output, use
with_structured_output(Part 8) orcreate_agent(response_format=...)(Part 10) instead of prompting for JSON and parsing it. The provider constrains or validates the output, and LangChain parses it for you.
The official structured-output page says the same thing in its own terms: chains built with | "have no built-in retry mechanism for output parsing failures", and it points you to with_structured_output first. You still meet parsers in four situations:
| Situation | Why a parser |
|---|---|
You want plain text out of an AIMessage |
StrOutputParser is the end of nearly every text chain |
| The model has no native structured output (a small local model, an exotic endpoint) | Prompt for JSON and parse it |
| You need to stream partial structured data to a UI | JsonOutputParser yields growing partial dicts. Some structured-output paths stream partials too and some do not: see 8.8 |
| You are reading code, or one of LangChain's own structured-output paths, which are built from these classes | The tool-call parsers in 7.6 are exactly what with_structured_output(method="function_calling") uses underneath |
Every sample in this part uses a fake chat model so you can run it with no key. Our helper fake(text) is GenericFakeChatModel(messages=iter([AIMessage(content=text)])): it returns the scripted message once. Real models differ in what they return; the parser's behaviour on the text is the same.
7.2 StrOutputParser, JsonOutputParser and streaming#
StrOutputParser turns an AIMessage or AIMessageChunk into a str and streams text chunks. JsonOutputParser parses JSON out of the reply text, and while streaming it yields the object as it grows, which is the feature that makes it still worth knowing. Save as s09_str_json_parsers.py:
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import JsonOutputParser, StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
def fake(text: str) -> GenericFakeChatModel:
"""A keyless stand-in for a chat model: returns the given text once."""
return GenericFakeChatModel(messages=iter([AIMessage(content=text)]))
prompt = ChatPromptTemplate.from_messages([("human", "{q}")])
# StrOutputParser: AIMessage -> str, and it streams text chunks
chain = prompt | fake("Paris is the capital of France.") | StrOutputParser()
print(repr(chain.invoke({"q": "capital?"})))
chain = prompt | fake("Paris is the capital of France.") | StrOutputParser()
print(list(chain.stream({"q": "capital?"})))
# It keeps text blocks and drops reasoning blocks
blocks = AIMessage(content=[
{"type": "reasoning", "reasoning": "thinking..."},
{"type": "text", "text": "Hello "},
{"type": "text", "text": "world"},
])
print(repr(StrOutputParser().invoke(blocks)))
# JsonOutputParser: text -> dict, and it streams PARTIAL objects
reply = '{"label": "billing", "confidence": 0.9, "tags": ["refund", "double-charge"]}'
print((prompt | fake(reply) | JsonOutputParser()).invoke({"q": "x"}))
print("-- streamed partial objects")
for partial in (prompt | fake(reply) | JsonOutputParser()).stream({"q": "x"}):
print(partial)
print("-- diff=True streams JSON Patch operations")
for patch in (prompt | fake(reply) | JsonOutputParser(diff=True)).stream({"q": "x"}):
print(patch)
# It tolerates a Markdown fence and chatter around the JSON...
fenced = 'Sure! Here you go:\n```json\n{"label": "bug"}\n```\nHope that helps.'
print(JsonOutputParser().parse(fenced))
# ...but not a non-JSON answer
try:
JsonOutputParser().parse("not json at all")
except Exception as err:
print(type(err).__name__, "|", str(err).split("\n")[0])'Paris is the capital of France.'
['Paris', ' ', 'is', ' ', 'the', ' ', 'capital', ' ', 'of', ' ', 'France.']
'Hello world'
{'label': 'billing', 'confidence': 0.9, 'tags': ['refund', 'double-charge']}
-- streamed partial objects
{}
{'label': 'billing'}
{'label': 'billing', 'confidence': 0.9}
{'label': 'billing', 'confidence': 0.9, 'tags': ['refund']}
{'label': 'billing', 'confidence': 0.9, 'tags': ['refund', 'double-charge']}
-- diff=True streams JSON Patch operations
[{'op': 'replace', 'path': '', 'value': {}}]
[{'op': 'add', 'path': '/label', 'value': 'billing'}]
[{'op': 'add', 'path': '/confidence', 'value': 0.9}]
[{'op': 'add', 'path': '/tags', 'value': ['refund']}]
[{'op': 'add', 'path': '/tags/1', 'value': 'double-charge'}]
{'label': 'bug'}
OutputParserException | Invalid json output: not json at allWhat this shows:
StrOutputParseraccepted a message whosecontentwas a list of blocks and returned only the text blocks, dropping the reasoning block. Reasoning models (02.8) return such lists, and this is why.invoke(...).contenton a reasoning model can be a list whileStrOutputParserstill gives you a clean string. The fake streams word by word; a real provider streams in its own chunk sizes.JsonOutputParserstreamed{}, then{'label': 'billing'}, then added keys, then grew thetagslist: each yielded value is a complete, valid Python object that is "everything so far". A UI can render the fields as they arrive. Withdiff=Trueit yields JSON Patch operations instead (it needs thejsonpatchpackage, whichlangchain-coreinstalls), which is cheaper to transmit when the object is large.- It strips a Markdown code fence and the chatter around it (
Sure! Here you go:...Hope that helps.) before parsing, which is why its docstring calls it "probably the most reliable output parser for getting structured data that does not use function calling". A non-JSON reply raisesOutputParserException(7.8).
7.3 JsonOutputParser has no schema checking#
JsonOutputParser(pydantic_object=SomeModel) uses the Pydantic class only to produce format instructions. The docstring says so: with pydantic_object=None, "no validation is performed", and passing a class does not change that. The sample in 7.4 proves it: its last lines feed {"category": "weird", "urgency": "high"} through a JsonOutputParser configured with a model that forbids both values, and it parses without complaint. If you want validation you need PydanticOutputParser, next.
7.4 PydanticOutputParser and format instructions#
PydanticOutputParser(pydantic_object=Model) subclasses JsonOutputParser, parses the JSON and calls model_validate, so it returns a validated instance and raises OutputParserException when the JSON is wrong or when validation fails. It also supports pydantic.v1 models. Its second job is get_format_instructions(), a ready-made paragraph telling the model to emit JSON that conforms to the schema, which you inject into the prompt (best through a partial, Part 5).
Save as s10_pydantic_parser.py:
from typing import Literal
from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import JsonOutputParser, PydanticOutputParser
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"] = Field(description="Best-fitting category")
urgency: int = Field(description="1 (low) to 5 (critical)", ge=1, le=5)
summary: str = Field(description="One sentence summary")
parser = PydanticOutputParser(pydantic_object=TicketTriage)
print(parser.get_format_instructions())
print("=====")
good = '{"category": "billing", "urgency": 4, "summary": "Customer was charged twice."}'
print(repr(parser.parse(good)))
bad_replies = [
'{"category": "billing", "urgency": 9, "summary": "x"}', # violates le=5
'{"category": "refund", "urgency": 2, "summary": "x"}', # not in the Literal
"category: billing", # not JSON at all
]
for bad in bad_replies:
try:
parser.parse(bad)
except OutputParserException as err:
print(type(err).__name__, "|", str(err).split("\n")[0][:110])
print(" llm_output kept for repair:", repr(err.llm_output)[:50])
# JsonOutputParser(pydantic_object=...) only uses the model for instructions: no validation.
loose = JsonOutputParser(pydantic_object=TicketTriage)
print(loose.parse('{"category": "weird", "urgency": "high"}'))
print(loose.get_format_instructions().splitlines()[0])The output should be formatted as a JSON instance that conforms to the JSON schema below.
As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.
Here is the output schema:{"description": "Triage decision for one support ticket.", "properties": {"category": {"description": "Best-fitting category", "enum": ["billing", "bug", "how_to", "other"], "title": "Category", "type": "string"}, "urgency": {"description": "1 (low) to 5 (critical)", "maximum": 5, "minimum": 1, "title": "Urgency", "type": "integer"}, "summary": {"description": "One sentence summary", "title": "Summary", "type": "string"}}, "required": ["category", "urgency", "summary"]}
=====
TicketTriage(category='billing', urgency=4, summary='Customer was charged twice.')
OutputParserException | Failed to parse TicketTriage from completion {"category": "billing", "urgency": 9, "summary": "x"}. Got: 1 val
llm_output kept for repair: '{"category": "billing", "urgency": 9, "summary":
OutputParserException | Failed to parse TicketTriage from completion {"category": "refund", "urgency": 2, "summary": "x"}. Got: 1 vali
llm_output kept for repair: '{"category": "refund", "urgency": 2, "summary": "
OutputParserException | Invalid json output: category: billing
llm_output kept for repair: 'category: billing'
{'category': 'weird', 'urgency': 'high'}
STRICT OUTPUT FORMAT:Read the failures: urgency: 9 broke le=5, "refund" is not in the Literal, and category: billing is not JSON at all. All three arrive as the same OutputParserException, and each carries the offending text in llm_output, which is what the repair tools in Part 11 feed back to a model.
Two details of the format instructions matter in practice:
- They are input tokens on every call: the example, the explanation and your whole JSON Schema. A big schema makes them long. When the provider supports native structured output you pay no such prompt tax, because the schema travels in a dedicated request field.
- The wording is not a stable contract. In 1.8.0
PydanticOutputParserproduces the plain text printed above, whileJsonOutputParser(pydantic_object=...)prepends a "STRICT OUTPUT FORMAT" block that forbids code fences and chatter (the last line of the sample prints its first line). Do not assert on instruction text in tests, and re-read the output when you upgrade, because instructions are part of your prompt and a change in them is a prompt change.
7.5 List and XML parsers#
The list parsers parse a text format into list[str] and stream items as each one completes: CommaSeparatedListOutputParser, NumberedListOutputParser (lines starting 1.) and MarkdownListOutputParser (lines starting -). XMLOutputParser parses XML into nested dicts and can take a tags=[...] list for its format instructions; its default engine is defusedxml, which you must install separately. Save as s11_list_and_xml_parsers.py:
from langchain_core.output_parsers import (
CommaSeparatedListOutputParser,
MarkdownListOutputParser,
NumberedListOutputParser,
XMLOutputParser,
)
print(CommaSeparatedListOutputParser().parse("billing, bug, how_to"))
print(NumberedListOutputParser().parse("1. alpha\n2. beta\n3. gamma"))
print(MarkdownListOutputParser().parse("- alpha\n- beta"))
print(CommaSeparatedListOutputParser().get_format_instructions())
# XML needs the defusedxml package (uv add defusedxml)
xml = XMLOutputParser(tags=["invoice", "line", "sku", "qty"])
reply = "<invoice><line><sku>A1</sku><qty>2</qty></line><line><sku>B2</sku><qty>5</qty></line></invoice>"
print(xml.parse(reply)) # nested lists of single-key dicts; every leaf value is a str
print(XMLOutputParser().parse("```xml\n<a><b>1</b></a>\n```")) # fences are stripped['billing', 'bug', 'how_to']
['alpha', 'beta', 'gamma']
['alpha', 'beta']
Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`
{'invoice': [{'line': [{'sku': 'A1'}, {'qty': '2'}]}, {'line': [{'sku': 'B2'}, {'qty': '5'}]}]}
{'a': [{'b': '1'}]}Note the XML result shape: a list of single-key dicts, with every leaf as a str ('qty': '2', not 2). That is awkward to consume and does no type conversion, so for typed nested data prefer JSON through with_structured_output. XML earns its place when your prompt already uses XML-style tags to structure its content (04.4, 2.6 lists what each provider documents about them) or when a downstream system already speaks XML.
7.6 Tool-call parsers#
The next family does not read text; it reads the tool calls of an AIMessage (08F.5). JsonOutputToolsParser returns every call as a dict, JsonOutputKeyToolsParser(key_name=..., first_tool_only=...) returns the arguments of the calls to one named tool, and PydanticToolsParser(tools=[...], first_tool_only=...) validates the arguments into Pydantic instances. These are the parsers with_structured_output(method="function_calling") attaches (confirmed in the ChatAnthropic source), so seeing them in a stack trace tells you which path ran. The sample below also contains a custom parser; save the whole file as s12_custom_and_tool_parsers.py:
import re
from typing import Literal
from langchain_core.exceptions import OutputParserException
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, ToolCall
from langchain_core.output_parsers import (
BaseOutputParser,
JsonOutputKeyToolsParser,
JsonOutputToolsParser,
PydanticToolsParser,
)
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel
class ScoreParser(BaseOutputParser[int]):
"""Parse a trailing 'Score: N' line, N in 1..10."""
def parse(self, text: str) -> int:
match = re.search(r"Score:\s*(\d+)", text)
if not match:
raise OutputParserException(f"No score found in: {text!r}", llm_output=text)
value = int(match.group(1))
if not 1 <= value <= 10:
raise OutputParserException(f"Score {value} outside 1..10", llm_output=text)
return value
def get_format_instructions(self) -> str:
return "End your answer with a line 'Score: N' where N is an integer from 1 to 10."
@property
def _type(self) -> str:
return "score"
scorer = ScoreParser()
print(scorer.parse("Score: 3"))
print(scorer.invoke(AIMessage(content="Fine reply.\nScore: 7"))) # also accepts a message
try:
scorer.parse("Score: 42")
except OutputParserException as err:
print("OutputParserException:", str(err).split("\n")[0])
reply = AIMessage(content="ok\nScore: 9")
chain = ChatPromptTemplate.from_messages([("human", "{q}")]) | GenericFakeChatModel(messages=iter([reply])) | scorer
print(chain.invoke({"q": "rate it"}))
# Tool-call parsers read message.tool_calls instead of the text
class Triage(BaseModel):
category: Literal["billing", "bug"]
urgency: int
message = AIMessage(content="", tool_calls=[
ToolCall(name="Triage", args={"category": "bug", "urgency": 2}, id="c1"),
ToolCall(name="Triage", args={"category": "billing", "urgency": 5}, id="c2"),
])
print(JsonOutputToolsParser().invoke(message))
print(JsonOutputToolsParser(first_tool_only=True).invoke(message))
print(JsonOutputKeyToolsParser(key_name="Triage", first_tool_only=True).invoke(message))
print(PydanticToolsParser(tools=[Triage], first_tool_only=True).invoke(message))
print(PydanticToolsParser(tools=[Triage]).invoke(message))3
7
OutputParserException: Score 42 outside 1..10
9
[{'args': {'category': 'bug', 'urgency': 2}, 'type': 'Triage'}, {'args': {'category': 'billing', 'urgency': 5}, 'type': 'Triage'}]
{'args': {'category': 'bug', 'urgency': 2}, 'type': 'Triage'}
{'category': 'bug', 'urgency': 2}
category='bug' urgency=2
[Triage(category='bug', urgency=2), Triage(category='billing', urgency=5)]The tool-parser lines show a quirk: JsonOutputToolsParser labels the tool name with the key type, not name ({'args': {...}, 'type': 'Triage'}). With first_tool_only=True you get one dict instead of a list, and JsonOutputKeyToolsParser skips the envelope and returns just the arguments.
7.7 Writing your own parser#
The sample's ScoreParser shows the whole recipe, and it is short:
- Subclass
BaseOutputParser[T], whereTis whatparsereturns. - Implement
parse(text) -> T. On bad input raiseOutputParserException(message, llm_output=text), not a bareValueError, so retry and repair code can recognise it and read the offending text. - Optionally implement
get_format_instructions()(the text you will inject into the prompt) and the_typeproperty (a short name used in serialization and traces). - Use it like any parser:
.parse(text),.invoke(message_or_text)(it accepts either), or as the last stage of a chain, as the last two output lines do.
For a one-off transformation you do not need a class at all: any plain function can be a chain stage (prompt | model | StrOutputParser() | str.strip, or wrapped in RunnableLambda, 08F.7). Write a class when the parser needs format instructions, is reused, or should stream.
For streaming there are two base classes, read from the 1.8.0 source. BaseTransformOutputParser overrides _transform (and _atransform): it calls parse_result on each chunk on its own and yields the result, which suits parsers whose pieces are independent (the list parsers work this way). BaseCumulativeTransformOutputParser adds a diff flag and a _diff(prev, next) hook: it accumulates the chunks, calls parse_result(..., partial=True) on everything so far, and yields the parsed value only when it changed (or, with diff=True, the result of _diff, which raises NotImplementedError unless you implement it). JsonOutputParser and the tool-call parsers are built on the cumulative one, which is why they stream growing objects (8.8 shows what that looks like). To stream a custom parser, subclass the cumulative base and make parse_result tolerate partial input when partial=True (return None while there is nothing usable yet).
7.8 OutputParserException#
OutputParserException (in langchain_core.exceptions) subclasses both ValueError and LangChainException. Its constructor is (error, observation=None, llm_output=None, send_to_llm=False). The two optional pieces exist for the repair parsers: llm_output carries the text that failed (the samples above print it), and send_to_llm says whether the observation may be fed back to the model (default False). Two practical rules:
- Catch it narrowly.
except Exceptionaround a chain also swallows authentication errors and rate limits, which are not parsing problems and must not be "repaired". - It is not the only exception you will see. On the tool-calling path a bad value raises a Pydantic
ValidationErrordirectly (Part 8),ChatOpenAI's default path can raise a plainValueErrorwhen a reply carries no parsed object (8.3), andcreate_agentraises its ownStructuredOutputValidationError(Part 10). A retry rule that names onlyOutputParserExceptionwill miss the others (11.3 names all of them).
7.9 Classic parsers that still exist#
langchain_classic.output_parsers (uv add langchain-classic) still exports the parsers that pre-1.0 tutorials use. They work, they are legacy, and each has a simpler modern answer. Use one only when you cannot use structured output (a text-only model, or old code you are keeping alive). The list below was read from langchain-classic 1.0.8:
| Classic parser | What it returns | What to use today |
|---|---|---|
EnumOutputParser(enum=MyEnum) |
The Enum member whose value equals the stripped reply; anything else raises OutputParserException |
A Literal[...] or Enum field in a Pydantic schema |
BooleanOutputParser(true_val="YES", false_val="NO") |
True or False from a yes/no reply |
A bool field |
DatetimeOutputParser(format=...) |
A datetime parsed with a strptime format |
A datetime or date field (Pydantic parses ISO 8601) |
YamlOutputParser(pydantic_object=Model) |
A validated Pydantic instance from a YAML reply | with_structured_output(Model); YAML is worth it only for a model that writes YAML more reliably than JSON |
RegexParser(regex=..., output_keys=[...]) and RegexDictParser |
A dict of regex capture groups (all values are strings) | A custom parser (7.7), or a schema |
StructuredOutputParser.from_response_schemas([ResponseSchema(...), ...]) |
A dict with the named keys, from a fenced JSON block; types are not validated | with_structured_output(Model) (Part 13) |
CombiningOutputParser(parsers=[...]) |
One merged dict from several parsers run over sections of one reply | One schema with all the fields |
PandasDataFrameOutputParser(dataframe=df) |
The result of a small column or row query language over a DataFrame (needs pandas) |
A tool the model calls (08F.8) |
OutputFixingParser, RetryOutputParser, RetryWithErrorOutputParser |
A repaired parse, after an extra model call | 11.6 covers them |
The module also re-exports the langchain_core parsers from this part, so an old import of PydanticOutputParser from there keeps working. Save as s25_classic_parsers.py:
from enum import Enum
from langchain_classic.output_parsers import (
BooleanOutputParser,
DatetimeOutputParser,
EnumOutputParser,
RegexParser,
YamlOutputParser,
)
from langchain_core.exceptions import OutputParserException
from pydantic import BaseModel
class Category(Enum):
BILLING = "billing"
BUG = "bug"
class Triage(BaseModel):
category: str
urgency: int
print(repr(EnumOutputParser(enum=Category).parse(" billing\n")))
print(repr(BooleanOutputParser().parse("YES")))
print(repr(DatetimeOutputParser(format="%Y-%m-%d").parse("2026-11-14")))
print(repr(YamlOutputParser(pydantic_object=Triage).parse("category: bug\nurgency: 3")))
print(RegexParser(regex=r"Score: (\d+)", output_keys=["score"]).parse("Score: 7"))
try:
EnumOutputParser(enum=Category).parse("refund")
except OutputParserException as err:
print("OutputParserException:", str(err).splitlines()[0])<Category.BILLING: 'billing'>
True
datetime.datetime(2026, 11, 14, 0, 0)
Triage(category='bug', urgency=3)
{'score': '7'}
OutputParserException: Response 'refund' is not one of the expected values: ['billing', 'bug']Note the RegexParser result: '7' is a string, because nothing here knows about types. That is the general weakness of this family, and the reason a schema replaced it.
Part 8: Structured output on the model#
8.1 with_structured_output in one picture#
model.with_structured_output(schema) returns a new runnable that wraps the model: it binds your schema to the request in whichever way the provider supports, calls the model, and attaches the right parser, so you get a Python object back. The base signature on every chat model is:
BaseChatModel.with_structured_output(
schema: dict | type,
*,
include_raw: bool = False,
**kwargs,
) -> Runnable[LanguageModelInput, dict | BaseModel]Provider classes override it and add a method argument (and strict for OpenAI). Part 9 has the exact signatures and defaults.
flowchart LR
schema["Schema<br/>Pydantic, TypedDict or JSON Schema"] --> wso["model.with_structured_output(schema)"]
wso --> bind["Bind to the request<br/>a forced tool, response_format or JSON mode"]
bind --> llm["Chat model call"]
llm --> prs["Parser attached by LangChain"]
prs --> out["Pydantic instance or dict"]What this buys you over 03.4's raw-SDK versions is one spelling for four vendors: the same with_structured_output(TicketTriage) call works on OpenAI, Anthropic, Gemini and others, and LangChain picks the vendor mechanism. What it costs you is the same as any abstraction (08F.1, 1.2): the exact request is one layer further away, and provider defaults differ in ways Part 9 spells out.
8.2 Schemas: Pydantic, TypedDict and JSON Schema#
| Schema you pass | You get back | Validated by LangChain? |
|---|---|---|
A Pydantic BaseModel class |
An instance of the class | Yes: field types, Literal, ge/le, validators, all run |
A TypedDict class |
A plain dict |
No (the type hints are only used to build the schema) |
A JSON Schema dict |
A plain dict |
No |
An OpenAI function or tool schema dict |
A plain dict |
No |
Pydantic is the right default: it is the only option where "the object you hold has passed your rules" is true, including rules JSON Schema cannot express (03.4, 6.3). Choose TypedDict when you want a dict and the model is trusted to follow the shape, and a JSON Schema dict when the schema is generated or stored as data. A JSON Schema dict should carry a top-level title and description (the title becomes the tool or schema name, the description is the instruction the model reads).
# The three schema spellings for the same triage record (no model needed to define them)
from typing import Annotated, Literal
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
class TicketTriage(BaseModel):
"""Triage decision for one support ticket.""" # the docstring is sent to the model
category: Literal["billing", "bug", "how_to", "other"] = Field(description="Best-fitting category")
urgency: int = Field(description="1 (low) to 5 (critical)", ge=1, le=5)
class TriageDict(TypedDict):
"""Triage decision for one support ticket."""
category: Annotated[str, ..., "One of billing, bug, how_to, other"] # Annotated adds the description
urgency: Annotated[int, ..., "1 (low) to 5 (critical)"]
triage_json_schema = {
"title": "TicketTriage",
"description": "Triage decision for one support ticket.",
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "bug", "how_to", "other"]},
"urgency": {"type": "integer", "minimum": 1, "maximum": 5},
},
"required": ["category", "urgency"],
}The docstring and the field descriptions are part of the prompt. For a Pydantic class the class docstring becomes the schema description, and each Field(description=...) becomes a property description. The model reads them. Treat them as prompt text and iterate on them (03.4, 2.2 and Part 5). Nested models, lists of models and Literal enums all work; the provider's schema subset limits what is enforced (03.4, Part 4).
8.3 What happens underneath (run it without a key)#
The base-class implementation, used by every model that does not override it, is a three-step recipe, read from the 1.8.0 source:
- Call
bind_tools([schema], tool_choice="any"), so the model must call the schema as if it were a tool. - For a Pydantic class, attach
PydanticToolsParser(tools=[schema], first_tool_only=True); otherwiseJsonOutputKeyToolsParserkeyed on the tool name. - With
include_raw=True, run the model, then the parser inside a fallback that turns an exception intoparsing_errorinstead of raising.
The base-class version also ignores method and strict: it pops them from kwargs and always uses the forced tool. The provider classes override it with their native paths (Part 9).
You can watch the recipe run with no key if you give a fake model a bind_tools stub. GenericFakeChatModel does not implement bind_tools, so with_structured_output on it raises; the little subclass below records what is bound and replays scripted tool calls. It is a test double for the mechanism, not a model of any provider. Sibling lessons build the same helper under other names (ScriptedChat in 08F.5, ToolFakeChatModel in 08F.7, FakeToolCallingModel in 08F.8 and 08F.15); it is the same idea each time: a scripted fake plus a bind_tools stub. Save as s13_structured_mechanism.py:
from typing import Literal
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, ToolCall
from pydantic import BaseModel, Field
from typing_extensions import TypedDict
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"] = Field(description="Best-fitting category")
urgency: int = Field(description="1 (low) to 5 (critical)", ge=1, le=5)
summary: str = Field(description="One sentence summary")
class FakeToolModel(GenericFakeChatModel):
"""A test double. GenericFakeChatModel has no bind_tools, so with_structured_output
would raise; this stub records what LangChain binds and returns scripted tool calls."""
bound: list = []
last_kwargs: dict = {}
def bind_tools(self, tools, *, tool_choice=None, **kwargs):
self.bound = list(tools)
self.last_kwargs = {"tool_choice": tool_choice}
return self
def tool_call(args: dict, name: str = "TicketTriage") -> AIMessage:
return AIMessage(content="", tool_calls=[ToolCall(name=name, args=args, id="call_1")])
GOOD = {"category": "billing", "urgency": 4, "summary": "Charged twice."}
# 1. Pydantic schema: you get a validated instance back
model = FakeToolModel(messages=iter([tool_call(GOOD)]))
print(repr(model.with_structured_output(TicketTriage).invoke("My card was charged twice")))
print("bound with:", model.last_kwargs)
# 2. include_raw=True returns the raw message next to the parsed object
model = FakeToolModel(messages=iter([tool_call(GOOD)]))
result = model.with_structured_output(TicketTriage, include_raw=True).invoke("x")
print(sorted(result), "| parsing_error:", result["parsing_error"])
print(result["raw"].tool_calls[0]["args"])
# 3. Invalid arguments: raises a pydantic ValidationError...
bad = {"category": "billing", "urgency": 9, "summary": "x"}
model = FakeToolModel(messages=iter([tool_call(bad)]))
try:
model.with_structured_output(TicketTriage).invoke("x")
except Exception as err:
print(type(err).__name__, "|", str(err).split("\n")[0])
# ...or, with include_raw=True, hands the error back instead of raising
model = FakeToolModel(messages=iter([tool_call(bad)]))
result = model.with_structured_output(TicketTriage, include_raw=True).invoke("x")
print("parsed:", result["parsed"], "| error:", type(result["parsing_error"]).__name__)
# 4. TypedDict: you get a plain dict and NOTHING is validated
class TriageDict(TypedDict):
"""Triage decision."""
category: str
urgency: int
model = FakeToolModel(messages=iter([tool_call({"category": "bug", "urgency": 9}, name="TriageDict")]))
print(model.with_structured_output(TriageDict).invoke("x"))
# 5. JSON Schema dict: also a plain dict, and a title is needed for the tool name
schema = {
"title": "TicketTriage",
"description": "Triage decision",
"type": "object",
"properties": {"category": {"type": "string"}, "urgency": {"type": "integer"}},
"required": ["category", "urgency"],
}
model = FakeToolModel(messages=iter([tool_call({"category": "bug", "urgency": 3})]))
print(model.with_structured_output(schema).invoke("x"))TicketTriage(category='billing', urgency=4, summary='Charged twice.')
bound with: {'tool_choice': 'any'}
['parsed', 'parsing_error', 'raw'] | parsing_error: None
{'category': 'billing', 'urgency': 4, 'summary': 'Charged twice.'}
ValidationError | 1 validation error for TicketTriage
parsed: None | error: ValidationError
{'category': 'bug', 'urgency': 9}
{'category': 'bug', 'urgency': 3}Reading it line by line:
- Case 1: a validated
TicketTriageinstance, andtool_choice='any'confirms step 1. - Case 2 (
include_raw=True): the result dict has exactly three keys:raw(theAIMessage, with itstool_callsand, on a real model,usage_metadata),parsedandparsing_error. - Case 3:
urgency: 9violatesle=5, so the Pydantic path raises aValidationErrorfrompydantic; withinclude_raw=Trueyou getparsed=Noneand the error object inparsing_errorinstead of an exception. Note the type: on the tool-calling path it is a PydanticValidationError, not anOutputParserException. On the JSON-text paths (aPydanticOutputParserunderneath, as in Anthropic'sjson_schemamode) it isOutputParserException. And the path most readers use has a third type:ChatOpenAI's defaultjson_schemamethod with a Pydantic schema raises a plainValueError("Structured Output response does not have a 'parsed' field nor a 'refusal' field") when the reply carries no parsed object, which is what a cut-off or malformed reply looks like there. A bad value on that path is still a PydanticValidationError. (Both types were confirmed by calling the package's own parser function on a hand-built message, with no provider call; how often a truncated reply from the live API ends in theValueErrorbranch was not measured.) Your handler must expect all three; 11.3 shows how to name them. - Case 4: the
TypedDictacceptedurgency: 9because nothing validates it. - Case 5: a JSON Schema dict comes back as a dict.
8.4 include_raw and the three outcomes#
include_raw=True is the production setting, for three reasons. You can read token usage (result["raw"].usage_metadata) next to the parsed object, which is otherwise lost. You can log the raw reply when parsing fails. And a parsing failure becomes a value you handle, not an exception that can unwind through your pipeline. The result is always the same three-key dict, with three outcomes:
| Outcome | parsed |
parsing_error |
Typical cause |
|---|---|---|---|
| Success | the object | None |
|
| Parse or validation failure | None |
the exception (ValidationError, OutputParserException, or a plain ValueError on ChatOpenAI's default path) |
bad JSON, wrong type, rule violation, truncated output |
| (Refusal, on current versions) | None |
ModelRefusalError |
the model declined (8.5) |
A network or authentication error is a fourth thing: it is not captured here, it raises, because it happened before there was anything to parse. 08F.5 covers those exceptions and the model-level retries for them.
8.5 Refusals#
The provider signals for refusal, truncation and safety blocks, and why they must not be retried blindly, are in 03.4 §6.4. This section is only what LangChain raises for a refusal.
When a model refuses (a safety refusal, not a failed parse), the provider returns a refusal marker instead of your object. On current packages LangChain detects that for OpenAI, Anthropic and Gemini and raises ModelRefusalError (from langchain_core.exceptions, with the original message in .raw_message) instead of a confusing parse error; with include_raw=True it arrives as parsing_error. This needs langchain-core>=1.7.5, langchain-openai>=1.7.4 and langchain-google-genai>=4.4.3. The docs describe what earlier versions do for one case only: for refusals of structured output on OpenAI's Responses API, earlier langchain-openai versions raise a generic ValueError instead of a refusal error. Do not read that as "every provider raised ValueError before": on older packages, check what you get. ModelRefusalError derives from ModelError, not from ValueError, which matters for retry rules (11.3). The refusal content block itself is in 08F.5.
# s_refusal.py (illustrative: calls a hosted model, needs OPENAI_API_KEY)
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.exceptions import ModelRefusalError
from pydantic import BaseModel
load_dotenv()
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: str
urgency: int
structured = init_chat_model("openai:gpt-6-luna").with_structured_output(TicketTriage)
ticket_text = "(a ticket whose text the model declines to process)"
try:
triage = structured.invoke(ticket_text)
except ModelRefusalError as refusal:
# Do NOT retry the same request in a loop: a refusal tends to repeat.
# Log refusal.raw_message, then route the ticket to a human queue.
triage = NoneThe snippet is illustrative (it needs a provider call, and whether a given text is refused is the model's decision). This is a handled outcome, not an error: a support-ticket classifier meets refusals when customers paste abusive or self-harm text, and the right behaviour is a human queue. 03.4, 6.4 covers refusal, truncation and safety blocks together, and Module 12 covers what to do with them.
8.6 Constraints, descriptions and tools together#
Which JSON Schema keywords each provider enforces is in 03.4 Part 4. This section is what LangChain does with those constraints.
Three practical points that bite in real projects:
Field(ge=..., le=...)and similar constraint keywords are not always enforced by the provider. Each provider supports a subset of JSON Schema in its native mode (03.4, Part 4), and some ignore or reject numeric bounds. LangChain's Pydantic validation then runs on the result, so a violation still surfaces, but as a failure after the model call (cost spent) rather than as a prevented one. Keep the constraints (they document intent and catch violations), and assume the failure path in Part 11 will run.- A tool and a schema can be combined on OpenAI.
ChatOpenAI.with_structured_output(..., method="json_schema", tools=[...])binds extra tools next to the response format (thetoolsargument exists in the 1.8.0 signature and is applied in thejson_schemapath). The OpenAI integration page also documentsllm.bind_tools([tool], response_format=OutputSchema, strict=True), with the parsed value then atadditional_kwargs["parsed"]. Whether a given model can do both at once is a provider question; check the integration page. Inside an agent, this combination is whatcreate_agenthandles for you (Part 10). strict(OpenAI's strict schema adherence) is a keyword onChatOpenAI.with_structured_output. It makes the provider reject schemas it cannot enforce, which is why 03.4 lists OpenAI's rules aboutrequiredandadditionalProperties(03.4, 4.2). It is not supported together withmethod="json_mode"(LangChain raises aValueError), and the Gemini method ignores it.
8.7 The same call on every provider#
The sample below runs the same extraction on the four providers in the course's usual order. It is illustrative: it calls hosted models. Notice that only the model construction differs; the schema, the call and the result handling are identical. It uses the default method of each class; Part 9 explains what that default is and when to override it.
# s_structured_four_providers.py (needs OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY,
# OPENROUTER_API_KEY and the integration packages from Setup)
import os
from typing import Literal
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field
load_dotenv()
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"] = Field(description="Best-fitting category")
urgency: int = Field(description="1 (low) to 5 (critical)", ge=1, le=5)
summary: str = Field(description="One sentence summary, at most 200 characters")
TICKET = "I was charged twice for May and nobody has replied in three days."
MODELS = {
"openai": init_chat_model("openai:gpt-6-luna"),
"anthropic": init_chat_model("anthropic:claude-haiku-5-5"),
# The Gemini integration documents GOOGLE_API_KEY; pass the course's key explicitly
"gemini": init_chat_model("google_genai:gemini-3.8-flash", api_key=os.environ["GEMINI_API_KEY"]),
# OpenRouter has its own package (langchain-openrouter). Its default method is
# function_calling (a forced tool call); 9.2 says when to pass method="json_schema".
"openrouter": init_chat_model("openrouter:openai/gpt-6-luna"),
}
for name, model in MODELS.items():
structured = model.with_structured_output(TicketTriage, include_raw=True)
result = structured.invoke(TICKET)
if result["parsing_error"] is not None:
print(f"{name:11} FAILED: {type(result['parsing_error']).__name__}")
print(f"{'':11} raw content: {result['raw'].content!r}"[:200])
continue
usage = result["raw"].usage_metadata or {}
print(f"{name:11} {result['parsed']!r} tokens={usage.get('total_tokens')}")openai TicketTriage(category='billing', urgency=4, summary='Customer was charged twice for May and has had no reply for three days.') tokens=212
anthropic TicketTriage(category='billing', urgency=4, summary='Double charge for May with no response in three days.') tokens=287
gemini TicketTriage(category='billing', urgency=4, summary='Customer charged twice in May; no reply for three days.') tokens=198
openrouter TicketTriage(category='billing', urgency=4, summary='Duplicate May charge, three days without a reply.') tokens=214Model IDs change; check each provider's models page and the table in 02.9 for current ones. No sampling parameters appear in the sample on purpose: several current models reject non-default temperature, top_p and top_k (02.5, Part 6).
8.8 Streaming structured output#
How partial objects are streamed and which fields are settled, on the raw SDKs, is in 03.4 Part 8. This section covers only what LangChain's .stream() yields.
structured.stream(...) runs on every path, but what it yields depends on the last step LangChain attached, and that step depends on the provider class, the method and the schema type. The rule from 7.7 decides it: a parser built on the cumulative base re-parses everything received so far and yields each time the result grows, while a plain function step waits for the whole message and yields once.
Which last step each call gets (read by building each runnable on the installed packages with a dummy key, so no request was sent; langchain-openai 1.8.0, langchain-anthropic 1.7.10, langchain-google-genai 4.5.0, langchain-openrouter 0.2.9):
| Class and method | Pydantic schema | TypedDict or JSON Schema dict |
|---|---|---|
ChatOpenAI, default json_schema |
A plain function (_oai_structured_outputs_parser): one final object, no partials |
JsonOutputParser: growing dicts |
ChatOpenAI, function_calling |
PydanticToolsParser |
JsonOutputKeyToolsParser: growing dicts |
ChatAnthropic, default function_calling |
PydanticToolsParser |
JsonOutputKeyToolsParser: growing dicts |
ChatAnthropic, json_schema |
PydanticOutputParser |
JsonOutputParser: growing dicts |
ChatGoogleGenerativeAI, default json_schema |
PydanticOutputParser |
JsonOutputParser: growing dicts |
ChatOpenRouter, default function_calling |
PydanticToolsParser |
JsonOutputKeyToolsParser: growing dicts |
What those parsers yield can be shown without a provider, by feeding each one the chunks a streaming model would produce. Save as s23_stream_structured.py:
from collections.abc import Iterator
from langchain_core.messages import AIMessageChunk
from langchain_core.output_parsers import (
JsonOutputKeyToolsParser,
JsonOutputParser,
PydanticOutputParser,
PydanticToolsParser,
)
from langchain_core.runnables import RunnableLambda
from pydantic import BaseModel
class Triage(BaseModel):
"""Triage decision."""
urgency: int
summary: str
PIECES = ['{"urgency"', ': 4, "summary"', ': "Charged tw', 'ice."}']
def text_chunks() -> Iterator[AIMessageChunk]:
"""What a JSON-text path streams: pieces of the reply text."""
for piece in PIECES:
yield AIMessageChunk(content=piece)
def tool_chunks() -> Iterator[AIMessageChunk]:
"""What a tool-calling path streams: pieces of the tool call's JSON arguments."""
yield AIMessageChunk(
content="", tool_call_chunks=[{"name": "Triage", "args": PIECES[0], "id": "c1", "index": 0}]
)
for piece in PIECES[1:]:
yield AIMessageChunk(
content="", tool_call_chunks=[{"name": None, "args": piece, "id": None, "index": 0}]
)
print("JsonOutputParser (dict schema, JSON text):")
for item in JsonOutputParser().transform(text_chunks()):
print(" ", item)
print("PydanticOutputParser (Pydantic schema, JSON text):")
for item in PydanticOutputParser(pydantic_object=Triage).transform(text_chunks()):
print(" ", item)
print("JsonOutputKeyToolsParser (dict schema, forced tool):")
for item in JsonOutputKeyToolsParser(key_name="Triage", first_tool_only=True).transform(tool_chunks()):
print(" ", item)
print("PydanticToolsParser (Pydantic schema, forced tool):")
for item in PydanticToolsParser(tools=[Triage], first_tool_only=True).transform(tool_chunks()):
print(" ", item)
# A RunnableLambda (what ChatOpenAI puts after a Pydantic json_schema call) waits for the whole input.
print("RunnableLambda over the same chunks:")
for item in RunnableLambda(lambda message: message.content).transform(text_chunks()):
print(" ", item)JsonOutputParser (dict schema, JSON text):
{}
{'urgency': 4}
{'urgency': 4, 'summary': 'Charged tw'}
{'urgency': 4, 'summary': 'Charged twice.'}
PydanticOutputParser (Pydantic schema, JSON text):
urgency=4 summary='Charged tw'
urgency=4 summary='Charged twice.'
JsonOutputKeyToolsParser (dict schema, forced tool):
{}
{'urgency': 4}
{'urgency': 4, 'summary': 'Charged tw'}
{'urgency': 4, 'summary': 'Charged twice.'}
PydanticToolsParser (Pydantic schema, forced tool):
urgency=4 summary='Charged tw'
urgency=4 summary='Charged twice.'
RunnableLambda over the same chunks:
{"urgency": 4, "summary": "Charged twice."}What this shows:
- Dict schemas stream partial objects. Both dict-returning parsers yield a growing dict, starting with
{}, and a string value arrives in pieces ('Charged tw', then'Charged twice.'). - Pydantic schemas stream only what validates. The two Pydantic parsers yielded nothing while
summarywas missing (a partial dict without a required field fails validation, and the parser skips it), then yielded instances once every required field had a value. The first instance still holds a half-finished string. So a Pydantic schema gives you few, late updates, and "validated" does not mean "finished". - A plain function yields once. The last block is the shape of
ChatOpenAI's default path with a Pydantic schema: one item, at the end. include_raw=Truedoes not stream partials. Run through the base-class recipe of 8.3 with a scripted streaming fake, the same chunks produced three items:{'raw': ...}, then{'parsed': <the final object>}, then{'parsing_error': None}. If you need partial objects, do not combine the two.
What was not verified: no .stream() call was made against a provider, so the table says which step is attached and the sample says what that step does with chunks; how each provider cuts its stream into chunks is theirs to decide. The Gemini class's own docstring agrees with the table: its stream "emits fully-parsed objects of the specified schema type (not incremental JSON strings)". ChatAnthropic with function_calling on a model where it does not force the tool (9.2) inserts a check function before the parser; its streaming behaviour was not checked.
The rule to take away: for partial objects in a UI, use a dict schema (a TypedDict or JSON Schema) on a path that ends in JsonOutputParser or JsonOutputKeyToolsParser, or put an explicit JsonOutputParser after the model; a Pydantic schema delivers the final object, or a few late instances. Validate the finished dict yourself at the end (Model.model_validate(final)). Render only fields that have settled, never a half-written value as if it were final; 03.4, Part 8 gives that rule and the raw-SDK versions.
Streaming is for one reply shown to a person. For classifying many tickets, use structured.batch(tickets, config={"max_concurrency": 5}) or its async twin abatch, so you control how many calls run at once and stay under the provider's rate limit; 08F.7, 2.3 and 2.4 own those mechanics.
Part 9: Strategies per provider#
Deep-dive
9.1 The three methods#
The ladder of approaches on the raw APIs (prompt and parse, JSON mode, schema-constrained output, strict tools) is in 03.4 Part 1. The table below shows which request LangChain builds for each method.
The provider classes accept method= with up to three values. They mean different things on the wire:
method |
What it asks the provider for | What LangChain binds (from source) |
|---|---|---|
"json_schema" |
The provider's dedicated structured-output feature, which constrains decoding to your schema where the provider can | OpenAI: response_format with a JSON schema. Anthropic: output_config={"format": ...}. Gemini: response_mime_type="application/json" plus response_json_schema. Ollama: its format field |
"function_calling" |
A forced tool call whose arguments follow your schema | OpenAI: the tool plus tool_choice=<name> and parallel_tool_calls=False. Anthropic: the tool plus a forced tool_choice (see the caveat below) |
"json_mode" |
Valid JSON only; the schema is not enforced, so you must describe it in the prompt | OpenAI: response_format={"type": "json_object"}. Anthropic: not a method (warns, then uses json_schema). Gemini: an alias of json_schema, kept for backward compatibility |
json_schema is the strongest guarantee where it exists, function_calling is the portable fallback that works on any model with tool calling, and json_mode is the weakest: it guarantees valid JSON, not your shape. 02.5, Part 9 and 03.4, Part 1 explain the same ladder on the raw APIs.
9.2 Defaults and quirks by provider#
How each provider's native structured output works on its own SDK is in 03.4 Part 3. This section covers only the LangChain classes, their defaults and their quirks.
Signatures and defaults below were read from the package source on 14 November 2026 (langchain-openai 1.8.0, langchain-anthropic 1.7.10, langchain-google-genai 4.5.0, langchain-openrouter 0.2.9) and confirmed by inspecting the installed classes. 08F.5, 10.2 gives a first pass at the same defaults; this section is the full version.
| Class | Signature, relevant part | Default method |
|---|---|---|
ChatOpenAI |
(schema=None, *, method="json_schema", include_raw=False, strict=None, tools=None, **kwargs), method in function_calling, json_mode, json_schema |
json_schema |
AzureChatOpenAI |
the same, without tools |
json_schema |
BaseChatOpenAI (the parent of OpenAI-compatible partner classes) |
the same as ChatOpenAI |
function_calling |
ChatAnthropic |
(schema, *, include_raw=False, method="function_calling", **kwargs), method in function_calling, json_schema; no strict keyword |
function_calling |
ChatGoogleGenerativeAI |
(schema, method="json_schema", *, include_raw=False, **kwargs), method in function_calling, json_mode, json_schema (or None) |
json_schema |
ChatOllama |
(schema, *, method="json_schema", include_raw=False, **kwargs) |
json_schema |
ChatOpenRouter |
(schema=None, *, method="function_calling", include_raw=False, strict=None, **kwargs), method in function_calling, json_schema |
function_calling |
Provider by provider, in the course's order:
OpenAI. The default json_schema uses OpenAI's native structured outputs. The source adds three safety nets: a Pydantic v1 schema falls back to function_calling with a warning (json_schema needs Pydantic v2 or a JSON Schema), and model names starting gpt-3 or gpt-4- (or equal to gpt-4), which predate structured outputs, also fall back with a warning. strict raises a ValueError with json_mode. A refusal check runs on each streamed chunk, so streaming does not hide a refusal; but with a Pydantic schema this default path delivers one final object, not partial ones (8.8).
Anthropic. The default is the forced-tool path (function_calling); a code comment in the source says json_schema is meant to become the default in a future release, so pass method explicitly if you care. Two things the docs do not warn you about:
- Most current Claude models reject forced tool choice, and LangChain knows about only some of them. Anthropic's API returns a 400 for
tool_choiceofanyor a named tool on Claude Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1 (03.4, 1.5). Haiku 5.5 is the one current Claude that accepts it, so the default works there. The source (langchain-anthropic1.7.10) excludes only three name prefixes:claude-fable-5-1,claude-opus-5-5andclaude-sonnet-5-5. For those three, and whenever extended or adaptive thinking is enabled, LangChain warns and binds the tool without forcing it, then raisesOutputParserExceptionif the model did not call it. Forclaude-fable-5-2and the Mythos models, which this version does not exclude, the default path still sends the forced tool choice: a request those models reject, according to Anthropic's list. (This lesson made no provider call, so the 400 rests on 03.4's citation of Anthropic's documentation; what LangChain sends was read from the source.) The fix is the same for all of them, the native path, which uses Anthropic'soutput_configformat and aPydanticOutputParser(orJsonOutputParserfor dict schemas):with_structured_output(Schema, method="json_schema"). Treat every Fable, Mythos, Opus 5.5 and Sonnet 5.5 model as needing it, and expect the package's list to lag each new model: read the changelog, and run the check below against your installed version. json_modeis not an Anthropic method. Passing it warns "Unrecognized structured output method 'json_mode'" and silently usesjson_schema.
You can see what your installed version will do without a key, because constructing a model sends nothing. Save as s26_claude_forced_tool_check.py:
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.chat_models import _supports_forced_tool_choice # private: inspection only
for name in [
"claude-haiku-5-5",
"claude-sonnet-5-5",
"claude-opus-5-5",
"claude-fable-5-1",
"claude-fable-5-2",
"claude-mythos-5-2",
]:
model = ChatAnthropic(model=name, api_key="not-a-real-key") # constructing a model calls nothing
profile = model.profile
native = "no profile" if profile is None else profile.get("structured_output")
print(f"{name:18} LangChain will force the tool: {_supports_forced_tool_choice(name)!s:5} profile says native: {native}")claude-haiku-5-5 LangChain will force the tool: True profile says native: False
claude-sonnet-5-5 LangChain will force the tool: False profile says native: True
claude-opus-5-5 LangChain will force the tool: False profile says native: True
claude-fable-5-1 LangChain will force the tool: False profile says native: True
claude-fable-5-2 LangChain will force the tool: True profile says native: no profile
claude-mythos-5-2 LangChain will force the tool: True profile says native: no profileRead the two columns together. The three excluded models are not forced (LangChain warns and hopes the model calls the tool). claude-fable-5-2 and claude-mythos-5-2 say True: this version will force the tool on models Anthropic says reject it, and it has no profile for them at all, which also matters inside agents (10.1). claude-haiku-5-5 is forced, which its API accepts; its profile in this version reports no native structured output, so keep the default function_calling for Haiku 5.5 and check Anthropic's documentation before choosing json_schema there. The helper _supports_forced_tool_choice is private (the leading underscore), so use it to inspect, never in application code.
The call that works on the affected models:
# s_anthropic_native.py (needs ANTHROPIC_API_KEY)
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field
load_dotenv()
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: str = Field(description="One of billing, bug, how_to, other")
urgency: int = Field(description="1 (low) to 5 (critical)")
# Sonnet 5.5 rejects a forced tool_choice (so do Opus 5.5, Fable and Mythos): use the native path
sonnet = init_chat_model("anthropic:claude-sonnet-5-5")
structured = sonnet.with_structured_output(TicketTriage, method="json_schema")
print(structured.invoke("The export button does nothing since Tuesday."))category='bug' urgency=3Gemini (optional provider). json_schema (and the legacy alias json_mode) bind response_mime_type="application/json" with a response_json_schema; the Google GenAI SDK inlines $defs and resolves $ref itself, so nested models and unions work. function_calling is available but the source comments call it discouraged. strict is accepted and ignored. Google's integration page has sections on its structured-output methods and on combining structured output with Google Search; read them before mixing the two.
Ollama (optional, local models). json_schema sends the schema in Ollama's format field. The model must support structured output or tool calling, and small local models miss schema adherence more often than hosted ones (an inference; the docs do not quantify it), so validate and retry (Part 11). Lesson 03.1, Part 12 describes the course's free local stand-in.
OpenRouter (optional gateway). ChatOpenRouter comes from its own package, langchain-openrouter (0.2.9; marked Beta on PyPI). There is no langchain[openrouter] extra, so install it by name, and init_chat_model("openrouter:...") resolves to it. Read from its source:
- The default is
function_calling: a forced tool call, withtool_choiceset to the schema's name. The Pydantic path ends inPydanticToolsParser, so a bad value is a PydanticValidationError(8.3). method="json_schema"sendsresponse_format={"type": "json_schema", "json_schema": {"name": ..., "schema": ...}}(plusstrictwhen you pass it) and ends inPydanticOutputParser, so failures areOutputParserException.json_modeis not a method. As on Anthropic, it warns "Unrecognized structured output method 'json_mode'. Defaulting to 'json_schema' method." and usesjson_schema.strict=Trueis accepted with both real methods.
What is actually enforced depends on the model OpenRouter routes to and whether that endpoint supports response_format or tools (03.4, 4.5). So pass method="json_schema" only for models whose OpenRouter endpoint lists response_format (structured outputs) support, and keep the default function_calling otherwise. One trap follows from the Anthropic section above: the default forces a tool call, so routing to a Claude model that rejects forced tool choice needs method="json_schema" here too (not run against OpenRouter; it follows from the request the source builds). The ChatOpenRouter integration page documents the same methods and shows create_agent with ProviderStrategy on an OpenRouter model. Using ChatOpenAI(base_url=...) against OpenRouter is discouraged by the docs because non-standard fields are lost; use ChatOpenRouter.
9.3 Choosing a method#
flowchart TD
start["You need typed output from a chat model"] --> agent{"Inside create_agent?"}
agent -->|"yes"| rf["Use response_format<br/>(Part 10)"]
agent -->|"no"| native{"Native structured output<br/>on this model?"}
native -->|"yes"| js["with_structured_output(Schema,<br/>method='json_schema')"]
native -->|"no, but tool calling works"| fc["method='function_calling'"]
native -->|"neither"| pj["Prompt for JSON and use<br/>PydanticOutputParser (Part 7)"]
js --> wrap["Add include_raw=True, validate,<br/>retry and fall back (Part 11)"]
fc --> wrap
pj --> wrap| Use | When |
|---|---|
method="json_schema" (pass it explicitly) |
Any OpenAI, Gemini or Ollama model that supports native structured output; every Claude model on Anthropic's forced-tool-choice list (Fable, Mythos, Opus 5.5, Sonnet 5.5) and any Claude run with thinking; on OpenRouter, routed models whose endpoint lists response_format support. The strongest guarantee, and it makes your code independent of which default the class has this month |
method="function_calling" |
Models without native structured output but with tool calling, older OpenAI models, OpenAI-compatible servers that implement tools but not response_format json_schema, OpenRouter models without response_format support (it is ChatOpenRouter's default), and claude-haiku-5-5, the one current Claude that accepts forced tool choice |
method="json_mode" |
Almost never: valid JSON without your shape. Reach for it only when nothing else exists, and describe the schema in the prompt |
PydanticOutputParser and a prompt |
The endpoint supports neither tools nor schemas (7.4) |
9.4 Model profiles and OpenAI-compatible servers#
Start with what the OpenAI integration page says: ChatOpenAI targets the official OpenAI API specification only, non-standard fields from third-party endpoints are not extracted, and for OpenRouter, LiteLLM, vLLM or DeepSeek you should use the provider-specific package (ChatOpenRouter, for example). So ChatOpenAI(base_url=...) is not the normal route to another server. It does work for a server that is strictly OpenAI-compatible, and it loses fields or fails on one that is not. If you do point it at such a server (a self-hosted model, an internal gateway), the default json_schema method only works if that server implements OpenAI's response_format with a JSON schema; many implement tools but not that. If the call fails with a request error, try method="function_calling", and check the server's documentation (that last step is a recommendation, not something the LangChain docs state).
LangChain also tracks what each model can do in a model profile (model.profile, beta since langchain 1.1): a dict including a structured_output flag. create_agent reads that flag to decide whether native structured output is available (10.1). A missing or wrong profile can break that automatic choice, and you can override it: init_chat_model("...", profile={"structured_output": True, ...}). 08F.5 covers profiles in general.
Part 10: Structured output inside create_agent#
Deep-dive
10.1 response_format and the three strategies#
An agent (08F.8) is a loop: the model calls tools until it is ready to answer. If you also want the final answer as a typed object, you do not call with_structured_output (the agent owns the model calls). You pass response_format to create_agent, and the object appears in result["structured_response"]. The official reference is the Structured output page.
from langchain.agents.structured_output import ToolStrategy, ProviderStrategy, AutoStrategyWhat you pass as response_format |
Strategy | How the object is produced |
|---|---|---|
A schema type (Pydantic class, dataclass, TypedDict) |
Chosen automatically (AutoStrategy internally) |
ProviderStrategy if the model's profile says it supports native structured output, otherwise ToolStrategy |
ProviderStrategy(schema, *, strict=None) |
Provider-native | The provider's own structured-output feature produces the final reply. strict needs langchain>=1.2 and is supported by some providers (for example OpenAI and xAI) |
ToolStrategy(schema, *, tool_message_content=None, handle_errors=True) |
Tool calling | The schema is exposed as an extra tool; the model "calls" it to give its final answer, and the agent forces tool use (tool_choice="any") |
AutoStrategy(schema) |
Explicit auto-detect | In the 1.5.0 source and exported, but not described in the docs; passing a bare type already does this |
Results by schema kind: a Pydantic class gives a validated instance; a dataclass or TypedDict gives a dict; a JSON Schema gives a dict. Native support is read dynamically from model.profile["structured_output"] (since langchain>=1.1), and the 1.5.0 source adds an exception: Gemini models older than the 3-series cannot combine native structured output with tool use, so they fall back to the tool strategy when the agent has tools. Using tools and structured output together needs a model that supports both at once.
10.2 ToolStrategy error handling, run keyless#
The big difference from with_structured_output is what happens on a failure. Because the schema is a tool and the agent is a loop, a validation error need not end the run: the agent can send the error back to the model as a ToolMessage and let it try again. That is what handle_errors controls. The sample runs a real create_agent over a scripted model (the same bind_tools stub as in 8.3), so the retry messages below are what the real agent produces. Save as s16_agent_toolstrategy.py:
from typing import Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import (
MultipleStructuredOutputsError,
StructuredOutputValidationError,
ToolStrategy,
)
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, ToolCall
from pydantic import BaseModel, Field
class Review(BaseModel):
"""Analysis of a product review."""
rating: int = Field(description="Stars, 1-5", ge=1, le=5)
sentiment: Literal["positive", "negative"]
class FakeToolModel(GenericFakeChatModel):
"""Scripted model; create_agent binds tools, so the stub needs bind_tools."""
def bind_tools(self, tools, **kwargs):
return self
def call(name: str = "Review", call_id: str = "call_1", **args) -> AIMessage:
return AIMessage(content="", tool_calls=[ToolCall(name=name, args=args, id=call_id)])
def run(strategy, replies):
agent = create_agent(model=FakeToolModel(messages=iter(replies)), tools=[], response_format=strategy)
return agent.invoke({"messages": [{"role": "user", "content": "Review: 5 stars, fast shipping"}]})
print(StructuredOutputValidationError.__mro__[1].__name__, "<-", StructuredOutputValidationError.__name__)
# 1. Default handle_errors=True: the error goes back to the model as a ToolMessage
result = run(ToolStrategy(Review), [call(rating=9, sentiment="positive"), call(call_id="call_2", rating=5, sentiment="positive")])
print([type(m).__name__ for m in result["messages"]])
print(result["messages"][2].content)
print("->", repr(result["structured_response"]))
print("final ToolMessage:", result["messages"][-1].content)
# 2. handle_errors=False: the error is raised to you
try:
run(ToolStrategy(Review, handle_errors=False), [call(rating=9, sentiment="positive")])
except Exception as err:
print("raised:", type(err).__name__)
# 3. A fixed message instead of the generated one
result = run(
ToolStrategy(Review, handle_errors="Rating must be an integer from 1 to 5. Try again."),
[call(rating=9, sentiment="positive"), call(call_id="call_2", rating=4, sentiment="negative")],
)
print(result["messages"][2].content)
# 4. A callable builds the message from the exception
def explain(err: Exception) -> str:
return f"Fix this and call the tool again: {type(err).__name__}"
result = run(ToolStrategy(Review, handle_errors=explain), [call(rating=0, sentiment="positive"), call(call_id="call_2", rating=3, sentiment="negative")])
print(result["messages"][2].content)
# 5. Exception types: only those are retried, anything else is raised
try:
run(ToolStrategy(Review, handle_errors=(MultipleStructuredOutputsError,)), [call(rating=9, sentiment="positive")])
except Exception as err:
print("raised (type not in the tuple):", type(err).__name__)
# 6. A union lets the model choose the shape
class Bug(BaseModel):
"""A bug report."""
title: str
class Question(BaseModel):
"""A how-to question."""
topic: str
result = run(ToolStrategy(Bug | Question), [call(name="Question", topic="exports")])
print(repr(result["structured_response"]))
# 7. Two structured calls in one turn is an error the model is told about
both = AIMessage(content="", tool_calls=[
ToolCall(name="Bug", args={"title": "a"}, id="c1"),
ToolCall(name="Question", args={"topic": "b"}, id="c2"),
])
result = run(ToolStrategy(Bug | Question), [both, call(name="Bug", call_id="c3", title="only one")])
print(result["messages"][2].content.splitlines()[0])
print("->", repr(result["structured_response"]))
# 8. A raw JSON Schema dict is NOT validated: the arguments come back as-is
schema = {
"title": "Review", "description": "Analysis of a review", "type": "object",
"properties": {"rating": {"type": "integer", "minimum": 1, "maximum": 5}},
"required": ["rating"],
}
print(run(ToolStrategy(schema), [call(rating=99)])["structured_response"])StructuredOutputError <- StructuredOutputValidationError
['HumanMessage', 'AIMessage', 'ToolMessage', 'AIMessage', 'ToolMessage']
Error: Failed to parse structured output for tool 'Review': Failed to parse data to Review: 1 validation error for Review
rating
Input should be less than or equal to 5 [type=less_than_equal, input_value=9, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/less_than_equal.
Please fix your mistakes.
-> Review(rating=5, sentiment='positive')
final ToolMessage: Returning structured response: rating=5 sentiment='positive'
raised: StructuredOutputValidationError
Rating must be an integer from 1 to 5. Try again.
Fix this and call the tool again: StructuredOutputValidationError
raised (type not in the tuple): StructuredOutputValidationError
Question(topic='exports')
Error: Model incorrectly returned multiple structured responses (Bug, Question) when only one is expected.
-> Bug(title='only one')
{'rating': 99}Reading the cases:
- Default (
handle_errors=True). The first reply hadrating=9. The message list showsHuman, AI, Tool, AI, Tool: the agent answered the bad "tool call" with aToolMessagethat startsError: Failed to parse structured output for tool 'Review', includes the Pydantic error text, and endsPlease fix your mistakes.The model corrected itself on the second reply, and the finalToolMessagesaysReturning structured response: ...(the defaulttool_message_content; override it withtool_message_content="..."). handle_errors=False. The error is raised to your code asStructuredOutputValidationError.- A string. Every error produces that fixed message, which is useful when you want the feedback in your own words.
- A callable receives the exception and returns the message: build the feedback from the error.
- An exception type, or a tuple of types. Only those errors are retried; any other exception is raised. Here the validation error is not in the tuple, so it raised.
- A union (
Bug | Question) lets the model choose the shape; the call's tool name selects which class is instantiated. A JSON SchemaoneOfworks the same way. - Two structured calls in one turn is an error the model is told about (
MultipleStructuredOutputsError), and it retries with a single call. - A JSON Schema dict is not validated. The reply
{"rating": 99}violated the schema'smaximum: 5and came back untouched.
The two exceptions subclass StructuredOutputError (which carries the offending ai_message): StructuredOutputValidationError for a bad value, MultipleStructuredOutputsError for several structured answers at once.
10.3 Unions, refusals and JSON Schema caveats#
- JSON Schema dicts must be wrapped in an explicit strategy (they are not auto-detected, per the docs) and should carry a top-level
titleanddescription. As case 8 showed, withToolStrategythe arguments come back as-is, unvalidated, sohandle_errorscan never fire. To get validation and retries, use a Pydantic class, a dataclass or aTypedDict. (This caveat comes from reading the source and running it; the docs do not state it.) - Refusals. With
ProviderStrategya refusal makes the agent raiseStructuredOutputValidationError; withToolStrategythe agent simply ends without astructured_response, so check"structured_response" in resultbefore reading it. AddModelRefusalMiddleware()(from langchain.agents.middleware import ModelRefusalMiddleware, needslangchain>=1.4.9) to raiseModelRefusalErrorinstead, as in 8.5. The middleware's own docstring says to list it afterModelFallbackMiddleware, so a fallback can catch the error, and that it only reacts to standard refusal blocks (it does not infer refusals from text or retry). - Pre-bound models. A model you already called
bind_toolson is not supported with structured output according to the docs. The 1.5.0factory.pyhas no explicit check, and a pre-bound fake went throughcreate_agent(..., response_format=ToolStrategy(...))without an exception in a test, so what you get is unpredictable (an error, or a silent double bind) rather than a clean rejection. Pass the plain model and let the agent bind. - Retries are bounded only by the loop. Each failed structured answer is another model call inside the agent loop. The recursion limit is a very high safety backstop (10,007 in
langgraph1.1.4 and later, 08F.8, 7.5), not a budget; cap model calls explicitly withModelCallLimitMiddleware(08F.8, 08F.10).
10.4 What changed from v0#
In pre-1.0 LangGraph, create_react_agent(response_format=Schema) added a separate node and an extra model call after the loop, and the form response_format=("prompt", Schema) asked the model to emit JSON from a prompt. Both are gone from langchain.agents.create_agent. The v1 migration notes say prompted output "has not proven to be particularly reliable", and that structured output now happens inside the main loop with no extra node, which reduces cost and latency. If an old tutorial uses create_react_agent or the ("prompt", ...) form, translate it to ToolStrategy or ProviderStrategy (Part 13).
10.5 An agent sample (illustrative)#
# s_agent_structured.py (needs OPENAI_API_KEY and langchain[openai])
from typing import Literal
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.agents.middleware import ModelRefusalMiddleware
from langchain.agents.structured_output import ProviderStrategy
from langchain.tools import tool
from pydantic import BaseModel, Field
load_dotenv()
class RefundDecision(BaseModel):
"""The agent's final answer about one refund request."""
order_id: str
decision: Literal["approve", "deny", "needs_human"] = Field(description="Outcome of the review")
reason: str = Field(description="One sentence the customer can be shown")
@tool
def lookup_order(order_id: str) -> str:
"""Return the status and age in days of an order, e.g. 'delivered, 12 days ago'."""
return {"A-1042": "delivered, 12 days ago"}.get(order_id, "not found")
agent = create_agent(
model="openai:gpt-6-luna",
tools=[lookup_order],
# ProviderStrategy uses the provider's native structured output for the FINAL reply
response_format=ProviderStrategy(RefundDecision),
middleware=[ModelRefusalMiddleware()], # refusal -> ModelRefusalError, not a missing field
)
result = agent.invoke({"messages": [{"role": "user", "content": "Refund order A-1042, it arrived broken."}]})
print(result["structured_response"])order_id='A-1042' decision='needs_human' reason='The order was delivered 12 days ago and reports damage, so a person will confirm the refund.'Tools, middleware and create_agent's other arguments are 08F.8; the policy that decides whether an agent may issue a refund at all is 08A.14.
Part 11: Error handling and reliability#
Deep-dive
11.1 What can go wrong, and what you see#
A chain prompt | model | parser has no built-in retry for parse failures; the official docs say so explicitly. Structured output makes failures rarer, not impossible. Know which failure shows up as which exception, because each needs a different response:
| Failure | What you see in LangChain | Right response |
|---|---|---|
| Network error, 429, 5xx, timeout | A model exception (ModelRateLimitError, ModelTimeoutError, ...) or the provider SDK's own error |
The model's max_retries and with_retry (08F.5, 03.8); not a parsing concern |
| Authentication, invalid request, context overflow | ModelAuthenticationError, ModelInvalidRequestError, ContextOverflowError |
Never retry; fix the request |
| The model refuses | ModelRefusalError (or parsing_error with include_raw) |
Do not loop; route to a human (8.5) |
| The reply is cut off by the output limit | A parse failure, an invalid_tool_call, or on ChatOpenAI's default path a plain ValueError ("does not have a 'parsed' field") |
Raise the limit (reasoning models spend output tokens on thinking, 02.8); retrying at the same limit fails the same way |
| The text is not valid JSON | OutputParserException |
Retry, repair or fall back |
| JSON is valid but breaks the schema or a validator | Pydantic ValidationError (tool-calling path), OutputParserException (parser paths), StructuredOutputValidationError (agent) |
Retry with feedback, or fall back |
| Everything validates and the answer is wrong | Nothing | Evals (Module 10A), not exceptions |
The first two rows are transport and request errors: they happen before there is anything to parse, and a repair loop must never swallow them. 03.4, Part 6 and 7 develop the same layers for raw SDKs, including why a truncated or refused reply must not be retried blindly.
11.2 The ladder#
Climb only as far as you need; each rung costs more latency and tokens than the one before.
flowchart TD
prevent["1. Prevent<br/>native json_schema, clear descriptions,<br/>small closed schemas"] --> fail{"Output invalid?"}
fail -->|"no"| done["Use it"]
fail -->|"yes"| same["2. Retry the same call<br/>with_retry on the whole chain"]
same --> fail2{"Still invalid?"}
fail2 -->|"no"| done
fail2 -->|"yes"| fb["3. Retry WITH feedback<br/>error message back to the model"]
fb --> fail3{"Still invalid?"}
fail3 -->|"no"| done
fail3 -->|"yes"| other["4. Fall back to another model"]
other --> fail4{"Still invalid?"}
fail4 -->|"no"| done
fail4 -->|"yes"| human["5. Degrade: typed failure,<br/>human queue, log the raw output"]11.3 Retry the whole chain#
Runnable.with_retry(...) wraps any runnable (a model, a chain) so it re-runs on failure. The documented signature is with_retry(*, retry_if_exception_type=(Exception,), wait_exponential_jitter=True, exponential_jitter_params=None, stop_after_attempt=3). Wrapped around the whole sequence, every attempt is a fresh model call, which is what you want for a parse failure: the model is non-deterministic, so asking again may produce valid output. Save as s14_retry_and_fallback.py (it also holds the fallback from 11.4):
from typing import Literal
from langchain_core.exceptions import OutputParserException
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"]
urgency: int = Field(ge=1, le=5)
summary: str
parser = PydanticOutputParser(pydantic_object=TicketTriage)
prompt = ChatPromptTemplate.from_messages([
("system", "Triage the ticket.\n{format_instructions}"),
("human", "{ticket}"),
]).partial(format_instructions=parser.get_format_instructions())
def fake(*texts: str) -> GenericFakeChatModel:
return GenericFakeChatModel(messages=iter([AIMessage(content=t) for t in texts]))
# 1. with_retry re-runs the WHOLE chain, so each attempt is a fresh model call.
model = fake(
"Sure! category=billing, urgency=high", # not JSON
'{"category": "billing", "urgency": 9, "summary": "Charged twice."}', # urgency out of range
'{"category": "billing", "urgency": 4, "summary": "Charged twice."}', # valid
)
chain = (prompt | model | parser).with_retry(
retry_if_exception_type=(OutputParserException,),
stop_after_attempt=3,
wait_exponential_jitter=False, # no sleeping in a demo; keep jitter on in production
)
print(chain.invoke({"ticket": "I was charged twice"}))
# 2. ...and when every attempt fails, the last exception propagates.
chain = (prompt | fake("nope", "nope") | parser).with_retry(
retry_if_exception_type=(OutputParserException,), stop_after_attempt=2, wait_exponential_jitter=False
)
try:
chain.invoke({"ticket": "x"})
except OutputParserException as err:
print("gave up:", type(err).__name__)
# 3. Fall back to a different model (here: a stronger one) when parsing fails.
cheap = fake("I think it is billing")
strong = fake('{"category": "bug", "urgency": 2, "summary": "Crash on upload."}')
chain = (prompt | cheap | parser).with_fallbacks(
[prompt | strong | parser], exceptions_to_handle=(OutputParserException,)
)
print(chain.invoke({"ticket": "The app crashes on upload"}))category='billing' urgency=4 summary='Charged twice.'
gave up: OutputParserException
category='bug' urgency=2 summary='Crash on upload.'The first line is the retry: the scripted model returned prose, then out-of-range JSON, then valid JSON, and the third attempt succeeded. The second shows the end state: after stop_after_attempt failures the last exception propagates. Three rules:
- Always narrow
retry_if_exception_type. The default is(Exception,), which retries authentication errors and programming bugs too. For structured output name the parse exceptions:(OutputParserException, ValidationError)whereValidationErrorispydantic.ValidationError(the tool-calling path), plusStructuredOutputErrorif you wrap an agent, plus the plainValueErrorthatChatOpenAI's defaultjson_schemapath raises when a reply has no parsed object (8.3). The last one is awkward: both parse exceptions areValueErrorsubclasses too, so addingValueErroralso retries every unrelatedValueErrorin your chain.retry_if_exception_typealso accepts a predicate (a function from exception tobool), which gives the narrower rule. Save ass24_retry_predicate.py:
from langchain_core.exceptions import ModelRefusalError, OutputParserException
from langchain_core.runnables import RunnableLambda
from pydantic import BaseModel, ValidationError
class Score(BaseModel):
value: int
def bad_value() -> ValidationError:
try:
Score(value="high") # type: ignore[arg-type]
except ValidationError as err:
return err
raise AssertionError("unreachable")
# The failures a structured-output call can produce, and what each one is
failures = {
"pydantic ValidationError": bad_value(),
"OutputParserException": OutputParserException("not json"),
"bare ValueError (ChatOpenAI json_schema path)": ValueError(
"Structured Output response does not have a 'parsed' field nor a 'refusal' field."
),
"unrelated ValueError (a bug)": ValueError("negative temperature"),
"ModelRefusalError": ModelRefusalError(),
}
for name, err in failures.items():
print(f"{name:48} is a ValueError: {isinstance(err, ValueError)}")
def is_parse_failure(exc: BaseException) -> bool:
"""A narrower rule than (ValueError,): parse and validation failures only."""
if isinstance(exc, (ValidationError, OutputParserException)):
return True
return isinstance(exc, ValueError) and "'parsed' field" in str(exc)
calls = {"n": 0}
def flaky(_: str) -> str:
calls["n"] += 1
if calls["n"] == 1:
raise failures["bare ValueError (ChatOpenAI json_schema path)"]
return "ok"
chain = RunnableLambda(flaky).with_retry(
retry_if_exception_type=is_parse_failure, stop_after_attempt=3, wait_exponential_jitter=False
)
print(chain.invoke("x"), "after", calls["n"], "calls")
def buggy(_: str) -> str:
raise failures["unrelated ValueError (a bug)"]
bug_chain = RunnableLambda(buggy).with_retry(
retry_if_exception_type=is_parse_failure, stop_after_attempt=3, wait_exponential_jitter=False
)
try:
bug_chain.invoke("x")
except ValueError as err:
print("an unrelated ValueError is raised at once:", err)pydantic ValidationError is a ValueError: True
OutputParserException is a ValueError: True
bare ValueError (ChatOpenAI json_schema path) is a ValueError: True
unrelated ValueError (a bug) is a ValueError: True
ModelRefusalError is a ValueError: False
ok after 2 calls
an unrelated ValueError is raised at once: negative temperatureThe first five lines settle the inventory: all three parse failures are ValueErrors, and ModelRefusalError is not, so a retry rule built on ValueError never retries a refusal (which is right: a refusal should reach a human, 8.5). The predicate retries the bare ValueError that carries the 'parsed' field text and lets an unrelated one through at once. Matching on message text is brittle, so treat the predicate as a pragmatic filter and pin your langchain-openai version when you rely on it.
- Wrap the
prompt | model | parserunit, not just the parser. Retrying only the parser re-parses the same bad text and fails identically; the model call is the step that must repeat. In the retry above the prompt and model re-run each attempt. Keep any step with a side effect outside the retried section (08F.7, 6.3). - The whole-chain parse retry is
invoke-only. When you stream the chain (stream,astreamorastream_events),with_retryis skipped, so a parse failure surfaces as a plain exception on the first try (08F.7, 6.2). For streamed output, validate at the end yourself and re-invoke, or use a repair loop (11.5). - Remember what a retry costs. Every attempt bills input and output tokens again (03.7), and
wait_exponential_jitter=Trueadds sleep. The sample turns jitter off only so the demo does not wait; keep it on in production.
11.4 Fall back to another model#
with_fallbacks([...], exceptions_to_handle=(Exception,), exception_key=None) runs the alternatives in order when the main runnable raises. The sample's third case sends a parse failure from a "cheap" model to a "strong" one. Combine the two tools: retry the cheap model a couple of times (cheap), and only then pay for the strong one. Agent-level equivalents of both are the retry and fallback middleware in 08F.8. Fallbacks also cover the provider is down case, a different failure from content, so name the exceptions you intend: a fallback that catches Exception hides bugs.
11.5 Repair with feedback#
The provider-native version of this loop (bounded retries, escalation to a stronger model, no retry for refusals or truncation) is in 03.4 Part 7. This section builds the LangChain chain version.
A plain retry gives the model no new information. Retry with feedback appends the model's bad answer and the error to the conversation and asks it to fix it. That is what the agent's ToolStrategy does for you (10.2), and it is short to write for a chain. The one provider rule to respect: an assistant message that contains a tool call must be followed by a ToolMessage answering it, so the feedback has to be a tool result when the failed output was a tool call. Save as s21_repair_loop.py:
from typing import Literal
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langchain_core.runnables import Runnable
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"]
urgency: int = Field(ge=1, le=5)
def extract_with_repair(structured: Runnable, messages: list, max_attempts: int = 3):
"""Retry WITH feedback. `structured` must be built with include_raw=True.
Returns (parsed_object, conversation_so_far). Raises after max_attempts.
"""
history = list(messages)
for attempt in range(1, max_attempts + 1):
result = structured.invoke(history)
error = result["parsing_error"]
if error is None:
return result["parsed"], history
raw: AIMessage = result["raw"]
feedback = f"Your output was invalid: {str(error)[:300]}\nCall the tool again with corrected arguments."
history.append(raw)
if raw.tool_calls:
# Providers reject an assistant tool call that has no matching tool result
history.extend(
ToolMessage(content=feedback, tool_call_id=call["id"], status="error")
for call in raw.tool_calls
)
else:
history.append(HumanMessage(feedback))
raise ValueError(f"no valid output after {max_attempts} attempts")
# --- keyless demonstration -------------------------------------------------------------
class FakeToolModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
def reply(call_id: str, **args) -> AIMessage:
return AIMessage(content="", tool_calls=[ToolCall(name="TicketTriage", args=args, id=call_id)])
model = FakeToolModel(messages=iter([
reply("call_1", category="billing", urgency=9), # invalid
reply("call_2", category="refund", urgency=3), # invalid
reply("call_3", category="billing", urgency=4), # valid
]))
structured = model.with_structured_output(TicketTriage, include_raw=True)
parsed, history = extract_with_repair(structured, [HumanMessage("I was charged twice")])
print(parsed)
print([type(m).__name__ for m in history])
print(history[2].content.splitlines()[0])category='billing' urgency=4
['HumanMessage', 'AIMessage', 'ToolMessage', 'AIMessage', 'ToolMessage']
Your output was invalid: 1 validation error for TicketTriageThe scripted model failed twice (urgency 9, then a category outside the Literal) before a valid third answer. The conversation grew as Human, AI, Tool, AI, Tool (the final good answer is returned separately), and the first feedback line is the Pydantic error summary. In a real run the model sees its own mistake and the error and usually corrects it. Two details: the feedback is truncated ([:300]) to bound tokens, and the function raises after max_attempts rather than looping forever.
11.6 The classic fixing parsers#
Two parsers from langchain-classic automate repair for text-based chains (uv add langchain-classic; they are not in langchain-core):
| Class | What it sends to a model | Call it with |
|---|---|---|
OutputFixingParser.from_llm(parser=..., llm=..., max_retries=...) |
The malformed output, the parser's format instructions and the error. Not the original prompt | .parse(text), or as the last stage of a chain |
RetryOutputParser.from_llm(parser=..., llm=..., max_retries=1) and RetryWithErrorOutputParser |
The original prompt as well as the bad completion (the first adds nothing else, as its template shows; the second also includes the error text, as a Details: {error} line, read from its source) |
.parse_with_prompt(completion, prompt_value) only: it needs the prompt value, so it cannot be the final piped step |
Save as s15_classic_fixers.py:
from typing import Literal
from langchain_classic.output_parsers import OutputFixingParser, RetryOutputParser
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.prompt_values import StringPromptValue
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"]
urgency: int = Field(ge=1, le=5)
summary: str
base = PydanticOutputParser(pydantic_object=TicketTriage)
# OutputFixingParser: send the bad text + error to a model and parse its answer.
fixer_model = GenericFakeChatModel(messages=iter([
AIMessage(content='{"category": "billing", "urgency": 4, "summary": "Charged twice."}'),
]))
fixing = OutputFixingParser.from_llm(parser=base, llm=fixer_model, max_retries=2)
print(fixing.parse("category: billing, urgency 4, summary: Charged twice"))
# RetryOutputParser: also sends the ORIGINAL PROMPT, so it needs parse_with_prompt().
retry_model = GenericFakeChatModel(messages=iter([
AIMessage(content='{"category": "bug", "urgency": 2, "summary": "Crash."}'),
]))
retrying = RetryOutputParser.from_llm(parser=base, llm=retry_model, max_retries=1)
prompt_value = StringPromptValue(text="Triage this ticket: the app crashes on upload")
print(retrying.parse_with_prompt("not json", prompt_value))category='billing' urgency=4 summary='Charged twice.'
category='bug' urgency=2 summary='Crash.'These are legacy tools in a legacy package. They exist for chains that use text parsers because the model has no native structured output. When with_structured_output is available, prefer it; when you need repair, the loop above (or ToolStrategy) is explicit about what is sent and easier to bound and test. Also note both fixers make an extra model call per failure with no cap beyond max_retries.
11.7 When to stop#
- Decide the failure value up front. What does your system do when three attempts and a fallback all fail? For triage: a typed
TriageFailedresult routed to a human queue, with the raw output logged. Never return a half-valid object. - Log every failure with the raw text (
include_raw=Trueor the exception'sllm_output), the prompt version (Part 12) and the model ID. Repeated failures usually point at a prompt, schema or model change, and the log is how you notice (11A.5 for traces, Module 11A). - Track two rates: first-try validity and eventual validity. A rising retry rate is a cost increase you will not see on the invoice until it is large.
- Validate beyond the shape. Schema validity says the fields exist; it does not say
urgencymatches the ticket. Add semantic validators (03.4, 6.3), as Part 14 does, and offline evals (Module 10A).
Part 12: Prompt hubs and versioning#
Reference
Where prompts live, how to version, pin, alias and roll them back, and how to test and review a prompt change is lesson 04.10 (especially Part 3 and Part 4). This part is the LangChain-specific piece: the LangSmith prompt hub, the SDK calls that talk to it, and the security change you must know about. The hub needs a LangSmith account and LANGSMITH_API_KEY (the SDK also falls back to the older LANGCHAIN_API_KEY); tracing, datasets and evaluation in LangSmith are 11A.5. The samples in this part that touch the hub are illustrative: they need an account.
12.1 What the prompt hub is#
LangSmith's Prompt and Context Hub stores prompts as versioned objects: every change is a commit with a hash, you can attach tags, and a Playground in the UI lets people edit and try prompts without touching code. The docs call it a way to "update prompts and contexts without redeploying", and it also stores context bundles (versioned collections of instructions and tools promoted through environments). Terminology has shifted: prompts used to be called "repos", the public collection was "LangChain Hub", and the old langchainhub package is deprecated; the docs say all functionality now lives in the langsmith package (Client.push_prompt and Client.pull_prompt). Commits can trigger webhooks, and a prompt can be public or private.
12.2 Push a prompt#
push_prompt uploads a prompt object (creating the prompt if the name is new) and returns its URL. The verified signature in langsmith 0.14.17:
Client.push_prompt(
prompt_identifier: str, *, object=None, parent_commit_hash="latest",
is_public=None, description=None, readme=None, tags=None,
commit_tags=None, commit_description=None,
) -> str# s_hub_push.py (illustrative: needs a LangSmith account and LANGSMITH_API_KEY)
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
from langsmith import Client
load_dotenv()
prompt = ChatPromptTemplate.from_messages([
("system", "You triage support tickets for {company}. Reply with the category only."),
("human", "{ticket}"),
])
client = Client()
url = client.push_prompt(
"ticket-triage",
object=prompt,
description="Support ticket triage prompt",
tags=["support"],
commit_tags=["staging"], # a readable name for this commit
commit_description="Add company variable",
)
print(url)https://smith.langchain.com/prompts/ticket-triage/3f2a9c1b?organizationId=...Beyond a bare template you can push a prompt plus a model (a RunnableSequence), which stores the model configuration too (the provider must be supported by the Playground), and a StructuredPrompt, which bundles the template with its output schema. StructuredPrompt.from_messages_and_schema(messages, schema=...) lives in langchain_core.prompts.structured; 12.6 runs one without a key. A structured prompt piped into a model produces structured output, so the schema and the wording version together, which fixes a classic drift where someone edits the prompt and the Pydantic class separately.
12.3 Pull, pin and cache#
pull_prompt fetches a prompt and returns a LangChain object ready to use:
Client.pull_prompt(
prompt_identifier: str, *, include_model=False, secrets=None,
secrets_from_env=False, skip_cache=False, dangerously_pull_public_prompt=False,
) -> AnyThe identifier decides which version you get. The next sample parses the identifier forms with the SDK's own helper (no network). Save as s18_hub_identifiers.py:
from langsmith.utils import parse_prompt_identifier # pure string parsing, no network
for identifier in [
"triage-prompt",
"triage-prompt:3f2a9c1b",
"triage-prompt:prod",
"acme/triage-prompt:abc123",
]:
owner, name, commit = parse_prompt_identifier(identifier)
print(f"{identifier:28} owner={owner!r:9} name={name!r:16} commit_or_tag={commit!r}")triage-prompt owner='-' name='triage-prompt' commit_or_tag='latest'
triage-prompt:3f2a9c1b owner='-' name='triage-prompt' commit_or_tag='3f2a9c1b'
triage-prompt:prod owner='-' name='triage-prompt' commit_or_tag='prod'
acme/triage-prompt:abc123 owner='acme' name='triage-prompt' commit_or_tag='abc123'| Identifier | Meaning | Use it for |
|---|---|---|
"ticket-triage" |
Your own prompt, latest commit | Development only: the "version" changes under you |
"ticket-triage:3f2a9c1b" |
A specific commit hash | Production pinning: immutable |
"ticket-triage:prod" |
A commit tag | Environments: you move the tag to promote or roll back, and the code stays unchanged |
"acme/ticket-triage:abc123" |
Another owner's (public) prompt at a commit | Third-party prompts (12.4) |
# s_hub_pull.py (illustrative: needs LANGSMITH_API_KEY and a prompt named ticket-triage)
import os
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langsmith import Client
load_dotenv()
client = Client()
# Production pins a tag (or a commit hash) taken from config, never "latest"
prompt = client.pull_prompt(os.environ.get("TRIAGE_PROMPT", "ticket-triage:prod"))
chain = prompt | init_chat_model("openai:gpt-6-luna")
print(chain.invoke({"company": "Acme Cloud", "ticket": "I was charged twice"}).text)billingCaching. Per the LangSmith docs the Python SDK keeps an in-memory prompt cache, enabled by default: max_size=100 prompts, ttl_seconds=300, refresh_interval_seconds=60, with stale-while-revalidate behaviour (a stale entry is served while it refreshes in the background). The cache is a global singleton (from langsmith.prompt_cache import prompt_cache_singleton), needs langsmith>=0.7.0 for Python, and pull_prompt(..., skip_cache=True) bypasses it. The consequences: pulling per request is cheap, a tag you move can take a few minutes to reach every process, and a short hub outage will not break a warm process (a cold start still needs the hub, so keep a bundled fallback, 12.5). pull_prompt_commit and list_prompt_commits also exist on the client.
include_model=True returns the prompt with its saved model configuration as a runnable sequence. It is convenient and it is the riskiest option for the reasons in 12.4. The docs also describe an LLM Gateway option: setting LANGSMITH_GATEWAY="true" routes pulled prompts' model calls through the LangSmith gateway, with LANGSMITH_GATEWAY_API_KEY as the override key; read the LangSmith pages before depending on it.
12.4 The security model#
- Public prompts are refused by default. The official docs still show
client.pull_prompt("efriis/my-first-prompt"). Inlangsmith0.14.17 the code in_validate_public_prompt_pullraises aValueErrorfor any identifier whose owner is not-(your own prompts) unless you passdangerously_pull_public_prompt=True: "Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects." The docs example therefore fails on a current SDK. The name of the flag is the warning; treat it as one. - Pin a commit SHA for anything not yours, especially with
include_model=True. A mutable "latest" lets the author change what your service runs. - Secrets from the environment are off by default. Since
langsmith0.5.1,secrets_from_envdefaults toFalse, a remediation for an advisory inlangchain-core(GHSA-c67j-w6g6-q2cm): serialized secret references in a manifest are not resolved from your environment unless you opt in. Note the limit in the docstring: a deserialized model class may still read its own default environment credential (such asOPENAI_API_KEY) when it is constructed, so "secrets off" does not make an untrusted manifest safe. - The same applies to
langchain_core.load.load. Its docstring: do not use it with untrusted input; for untrusted data passallowed_objects="messages"or an explicit list of classes. The default allowlist ("core") is described as unsafe for untrusted manifests. - The legacy
hubmodule carries the same warning.from langchain_classic import hubhashub.pullandhub.pushmarked deprecated sincelangchain-classic1.0.6 ("Use the LangSmith SDK instead"), and its pull docstring begins "Hub manifests are untrusted input".
For a broader view of prompt and supply-chain risks see 04.10, Part 9 and Module 12.
12.5 Git, the hub, or both#
| Question | Prompts in git (files plus a loader, as in 04.10) | LangSmith hub |
|---|---|---|
| Who can change a prompt? | Anyone who can open a pull request | Anyone with hub access, including non-engineers in the Playground |
| Review and history | Code review, blame, atomic with the code and the tests that depend on it | Commits and diffs in the UI; review is whatever process you build |
| Roll back | Redeploy, or flip a config alias | Move a tag to an earlier commit, no deploy |
| Runtime dependency | None | The hub must be reachable on cold start; mitigate with the cache and a bundled fallback |
| Trace and eval linkage | You add it | Built in with LangSmith traces, datasets and the Playground |
| Security | Your repo's controls | Manifests are executable configuration (12.4) |
| Best for | Prompts coupled to schemas and tests; regulated review | Fast iteration, prompt owners outside engineering, A/B and playground work |
A hybrid that many teams use: git is the source of truth, CI pushes a prompt to the hub on release with the git commit SHA as a commit tag, and the service pins that tag or hash from config, keeping a copy of the same prompt in the repository as a fallback when the hub is unreachable. Whatever you choose, the version of the prompt must appear in your logs and traces next to the model ID, because "which prompt produced this answer" is the first question in every incident (Part 11).
12.6 Local serialization and load_prompt#
Without the hub, LangChain can still serialize prompts to its JSON format and back. The sample prints a StructuredPrompt (template plus output schema), then dumps a normal prompt with dumpd and loads it back. Save as s17_structured_prompt_and_serialization.py:
import json
from langchain_core.load import dumpd, load
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts.structured import StructuredPrompt
from pydantic import BaseModel
class Triage(BaseModel):
"""Triage decision."""
category: str
urgency: int
# A prompt that carries its output schema (this is what the hub stores)
prompt = StructuredPrompt.from_messages_and_schema(
[("system", "Triage the ticket."), ("human", "{ticket}")],
schema=Triage,
)
print(type(prompt).__name__, prompt.input_variables, prompt.schema_.__name__)
# Serialize a plain prompt to the LangChain JSON format and load it back
plain = ChatPromptTemplate.from_messages([("system", "Hi {name}"), ("human", "{q}")])
manifest = dumpd(plain)
print(json.dumps(manifest)[:150] + "...")
restored = load(manifest, allowed_objects="core") # only load manifests you wrote or reviewed
print(type(restored).__name__, restored.input_variables)Output (real; load also prints a LangChainBetaWarning to stderr that this capture suppressed):
StructuredPrompt ['ticket'] Triage
{"lc": 1, "type": "constructor", "id": ["langchain", "prompts", "chat", "ChatPromptTemplate"], "kwargs": {"input_variables": ["name", "q"], "messages"...
ChatPromptTemplate ['name', 'q']The manifest is {"lc": 1, "type": "constructor", "id": [...], "kwargs": {...}}: a recipe for constructing objects, which is exactly why loading one is a trust decision. load is in beta, and without allowed_objects it warns that the default will change; pass an explicit allowlist. Only load manifests that you wrote or reviewed. For prompts saved as files, load_prompt(path, encoding=None, *, allow_dangerous_paths=False) is the loader; the keyword name tells you that path handling is a security surface too.
Part 13: Legacy patterns and how to read old tutorials#
Reference
Most LangChain tutorials, blog posts and Stack Overflow answers predate v1. Their code does not run today, and the failure is usually an import error. This part keeps the rows that concern prompts, parsers, the hub and structured output, then the proof. The complete legacy-to-current table (agents, memory, every import path) is in 08F.4, Part 4 and the migration playbook is 08F.15, Part 3.
| Legacy (pre-1.0) | Status as of November 2026 | Current replacement |
|---|---|---|
from langchain.prompts import ..., langchain.output_parsers, langchain.chains, langchain.schema, langchain.hub, langchain.memory |
Gone from the langchain package; the code lives in langchain-classic |
langchain_core.prompts, langchain_core.output_parsers, langchain_core.messages |
LLMChain(prompt=..., llm=...) |
Deprecated since 0.1.17, removal planned for 2.0.0; only in langchain_classic.chains |
prompt | model | parser |
PromptTemplate(template=..., input_variables=[...]) explicit constructor |
Still works | PromptTemplate.from_template(...) infers the variables |
StructuredOutputParser with ResponseSchema |
langchain-classic only; predates native structured output |
with_structured_output(PydanticModel) |
create_structured_output_runnable, create_openai_functions_chain |
langchain-classic only |
with_structured_output |
from langchain import hub; hub.pull(...) / hub.push(...) |
Deprecated since langchain-classic 1.0.6, removal planned for 2.0.0 |
langsmith.Client().pull_prompt / push_prompt (Part 12) |
ConversationBufferMemory plus MessagesPlaceholder("history"), and RunnableWithMessageHistory |
Deprecated or superseded | Agent state plus a checkpointer (4.2, 08F.11, 08F.15, 3.7) |
langgraph.prebuilt.create_react_agent and its response_format=("prompt", Schema) form |
The prompted form was removed in v1 ("has not proven to be particularly reliable"); create_react_agent is replaced by create_agent |
create_agent with ToolStrategy or ProviderStrategy (Part 10) |
Agents (AgentExecutor) and text LLM classes (llm.predict, from langchain.llms import OpenAI) |
Legacy runtimes | create_agent and model.invoke(...) on a chat model: 08F.4, Part 4, 08F.5, 08F.8 |
Verify the first row yourself; this sample tries the old import paths against the current packages. Save as s22_old_tutorial_imports.py:
import importlib
# Import paths that pre-1.0 tutorials use, tried against the current langchain package
# and against langchain-classic (the home of the legacy code).
for module in [
"langchain.prompts",
"langchain.output_parsers",
"langchain.chains",
"langchain.schema",
"langchain.hub",
"langchain.memory",
"langchain_classic.prompts",
"langchain_classic.output_parsers",
"langchain_classic.chains",
"langchain_classic.hub",
"langchain_classic.memory",
]:
try:
importlib.import_module(module)
print(f"ok {module}")
except ModuleNotFoundError:
print(f"missing {module}")missing langchain.prompts
missing langchain.output_parsers
missing langchain.chains
missing langchain.schema
missing langchain.hub
missing langchain.memory
ok langchain_classic.prompts
ok langchain_classic.output_parsers
ok langchain_classic.chains
ok langchain_classic.hub
ok langchain_classic.memorySo the quick-and-dirty fix for an old tutorial, uv add langchain-classic and change langchain. to langchain_classic., works for reading and for a short migration, but it keeps you on code with a removal date. A typical translation:
# LEGACY tutorial style: does not run on current langchain (the imports below are gone)
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
llm = OpenAI(temperature=0)
prompt = PromptTemplate(input_variables=["ticket"], template="Classify this ticket: {ticket}")
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run("I was charged twice"))# CURRENT equivalent (illustrative: calls a hosted model, needs OPENAI_API_KEY)
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
load_dotenv()
prompt = PromptTemplate.from_template("Classify this ticket: {ticket}")
chain = prompt | init_chat_model("openai:gpt-6-luna") | StrOutputParser()
print(chain.invoke({"ticket": "I was charged twice"}))billingWhat changed: the model is a chat model from init_chat_model, the prompt infers its variables, the three pieces compose with |, the parser is explicit, and .run(...) became .invoke({...}) with a dict.
Part 14: Putting it together: a tested triage chain#
Everything above in one small module: a few-shot chat prompt with partials and an optional history slot, a Pydantic schema with a semantic validator, with_structured_output, a retry on the whole chain and an optional fallback model. The model is injected, so the same code runs against a real provider in production and against a scripted fake in tests (the pattern from 03.10 and 08A.2).
14.1 The module#
Save as triage.py:
# triage.py: a prompt + structured-output chain with the model injected, so tests need no key.
import json
from collections.abc import Callable
from datetime import date
from typing import Literal
from langchain_core.exceptions import OutputParserException
from langchain_core.language_models import BaseChatModel
from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
MessagesPlaceholder,
)
from langchain_core.runnables import Runnable
from pydantic import BaseModel, Field, ValidationError, model_validator
class TicketTriage(BaseModel):
"""Triage decision for one support ticket."""
category: Literal["billing", "bug", "how_to", "other"] = Field(
description="Best-fitting category. Use 'other' only if nothing fits."
)
urgency: int = Field(description="1 (can wait) to 5 (outage or money lost)", ge=1, le=5)
needs_human: bool = Field(description="True if an agent must read this before any reply")
summary: str = Field(description="One sentence, max 200 characters", max_length=200)
@model_validator(mode="after")
def critical_needs_human(self) -> "TicketTriage":
# A semantic rule no JSON Schema keyword can express.
if self.urgency == 5 and not self.needs_human:
raise ValueError("urgency 5 tickets must set needs_human to true")
return self
# The AI side of each example is a JSON string that mirrors the FULL schema (summary included).
# It is still plain text, but it teaches the same shape the structured-output call will return.
EXAMPLES = [
{
"ticket": "I was charged twice for May",
"decision": json.dumps(
{"category": "billing", "urgency": 4, "needs_human": True,
"summary": "Customer was charged twice for May."}
),
},
{
"ticket": "How do I export my invoices?",
"decision": json.dumps(
{"category": "how_to", "urgency": 1, "needs_human": False,
"summary": "Customer asks how to export invoices."}
),
},
]
def build_prompt(today: Callable[[], str] = lambda: date.today().isoformat()) -> ChatPromptTemplate:
# Braces inside example VALUES (the JSON above) are never templated, so no escaping is needed.
example_prompt = ChatPromptTemplate.from_messages([("human", "{ticket}"), ("ai", "{decision}")])
shots = FewShotChatMessagePromptTemplate(examples=EXAMPLES, example_prompt=example_prompt)
return ChatPromptTemplate.from_messages(
[
("system", "You triage support tickets for {company}. Today is {today}."),
shots,
MessagesPlaceholder("history", optional=True), # earlier turns, if any
("human", "{ticket}"),
]
).partial(company="Acme Cloud", today=today)
def build_triage_chain(
model: BaseChatModel, *, fallback: BaseChatModel | None = None
) -> Runnable[dict, TicketTriage]:
prompt = build_prompt()
# Everything below is a ValueError: pydantic.ValidationError and OutputParserException both
# subclass it, and so does the bare ValueError that ChatOpenAI's default json_schema path
# raises when a reply has no parsed object (for example when it was cut off). The first two
# are listed to document intent. ModelRefusalError is NOT a ValueError, so a refusal is not
# retried: it propagates to the caller, which should route it to a human.
retryable = (ValidationError, OutputParserException, ValueError)
def attempt(m: BaseChatModel) -> Runnable:
# with_retry re-runs the WHOLE prompt | model | parser unit: a fresh model call each time.
# There is no side-effecting step inside it, so repeating it is safe (08F.7, 6.3).
return (prompt | m.with_structured_output(TicketTriage)).with_retry(
retry_if_exception_type=retryable,
stop_after_attempt=3,
wait_exponential_jitter=False,
)
chain = attempt(model)
if fallback is not None:
chain = chain.with_fallbacks([attempt(fallback)], exceptions_to_handle=retryable)
return chainPoints worth noticing:
- The system message holds the constants (
company,today) as partials, andtodayis a callable, so it is evaluated per call.build_prompt(today=...)lets a test freeze the date. - The few-shot block sits before the volatile parts (history, then the ticket), friendly to prompt caching (3.4). The AI side of each example is a JSON string that mirrors the whole schema,
summaryincluded, which is the advice of 6.2 for a chain that ends inwith_structured_output. It is still plain text:json.dumpswrites the string, and the braces inside an example value are never treated as template variables, so no escaping is needed. MessagesPlaceholder("history", optional=True)makes the first turn work with no history and follow-ups with it.- The schema carries a rule JSON Schema cannot express (urgency 5 must set
needs_human), enforced by a Pydanticmodel_validator. When the model breaks it, theValidationErrortriggers a retry. retryablenames the exception families from 7.8 and 8.3, including the bareValueErrorthatChatOpenAI's default path raises. Because the first two are themselvesValueErrorsubclasses, the tuple is effectively "anyValueError", which is broad on purpose here; 11.3 shows a narrower predicate.ModelRefusalErroris not aValueError, so a refusal is not retried: it reaches the caller, who should route it to a human.with_retrywraps the wholeprompt | model | parserunit (nothing in it has a side effect, so repeating it is safe, 08F.7, 6.3); the fallback gets its own retries first.- It calls
with_structured_output(TicketTriage)with the class default, to keep the fake-model test simple. In production passmethod=explicitly (9.3), and useinclude_raw=Trueif you need token usage per call (8.4).
To see what the model would receive, render the prompt (save as show.py):
from triage import build_prompt
print(build_prompt(today=lambda: "2026-11-14").invoke({"ticket": "Where is my invoice?"}).to_string())System: You triage support tickets for Acme Cloud. Today is 2026-11-14.
Human: I was charged twice for May
AI: {"category": "billing", "urgency": 4, "needs_human": true, "summary": "Customer was charged twice for May."}
Human: How do I export my invoices?
AI: {"category": "how_to", "urgency": 1, "needs_human": false, "summary": "Customer asks how to export invoices."}
Human: Where is my invoice?14.2 The tests#
Save as test_triage.py and run uv run pytest -v. There is no network and no key. The fake needs the bind_tools stub from 8.3 (a minimal version of it: here nothing needs to record tool_choice), because with_structured_output binds the schema as a tool. RaisingToolModel adds one thing: a scripted item that is an exception is raised instead of returned, which lets two tests simulate failures a reply cannot carry.
import pytest
from langchain_core.exceptions import ModelRefusalError
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, ToolCall
from pydantic import ValidationError
from triage import TicketTriage, build_prompt, build_triage_chain
class FakeToolModel(GenericFakeChatModel):
"""GenericFakeChatModel with a bind_tools stub, so with_structured_output works."""
def bind_tools(self, tools, **kwargs):
return self
class RaisingToolModel(FakeToolModel):
"""Scripted replies where an item that is an exception is raised instead of returned."""
script: list = []
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
item = self.script.pop(0)
if isinstance(item, Exception):
raise item
return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
def reply(**args) -> AIMessage:
return AIMessage(content="", tool_calls=[ToolCall(name="TicketTriage", args=args, id="call_1")])
GOOD = dict(category="billing", urgency=4, needs_human=True, summary="Charged twice for May.")
BAD = dict(category="billing", urgency=5, needs_human=False, summary="Outage.") # breaks the rule
def test_prompt_renders_examples_partials_and_history():
prompt = build_prompt(today=lambda: "2026-11-14")
assert prompt.input_variables == ["ticket"] # catches a misspelt partial
messages = prompt.invoke({"ticket": "Where is my invoice?"}).messages
assert "Acme Cloud" in messages[0].content and "2026-11-14" in messages[0].content
assert [type(m).__name__ for m in messages] == [
"SystemMessage", "HumanMessage", "AIMessage", "HumanMessage", "AIMessage", "HumanMessage",
]
# The example answers mirror the schema, so they validate against it
for message in messages:
if type(message).__name__ == "AIMessage":
TicketTriage.model_validate_json(message.content)
with_history = prompt.invoke({"ticket": "And now?", "history": [("human", "hi"), ("ai", "hello")]})
assert len(with_history.messages) == len(messages) + 2
def test_happy_path_returns_validated_object():
chain = build_triage_chain(FakeToolModel(messages=iter([reply(**GOOD)])))
result = chain.invoke({"ticket": "charged twice"})
assert isinstance(result, TicketTriage) and result.urgency == 4
def test_semantic_validator_failure_is_retried():
chain = build_triage_chain(FakeToolModel(messages=iter([reply(**BAD), reply(**GOOD)])))
assert chain.invoke({"ticket": "x"}).needs_human is True
def test_gives_up_after_three_attempts():
chain = build_triage_chain(FakeToolModel(messages=iter([reply(**BAD)] * 3)))
with pytest.raises(ValidationError):
chain.invoke({"ticket": "x"})
def test_fallback_model_takes_over():
weak = FakeToolModel(messages=iter([reply(**BAD)] * 3))
strong = FakeToolModel(messages=iter([reply(**GOOD)]))
assert build_triage_chain(weak, fallback=strong).invoke({"ticket": "x"}).category == "billing"
def test_bare_value_error_is_retried():
# What ChatOpenAI's default path raises for a reply with no parsed object
flaky = RaisingToolModel(
messages=iter([reply(**GOOD)]),
script=[ValueError("Structured Output response does not have a 'parsed' field"), None],
)
assert build_triage_chain(flaky).invoke({"ticket": "x"}).category == "billing"
def test_refusal_is_not_retried():
refused = RaisingToolModel(
messages=iter([reply(**GOOD)]),
script=[ModelRefusalError(raw_message=AIMessage("I can't help with that.")), None],
)
with pytest.raises(ModelRefusalError):
build_triage_chain(refused).invoke({"ticket": "x"})
assert len(refused.script) == 1 # the second scripted item was never consumed: no retry============================= test session starts ==============================
collecting ... collected 7 items
test_triage.py::test_prompt_renders_examples_partials_and_history PASSED [ 14%]
test_triage.py::test_happy_path_returns_validated_object PASSED [ 28%]
test_triage.py::test_semantic_validator_failure_is_retried PASSED [ 42%]
test_triage.py::test_gives_up_after_three_attempts PASSED [ 57%]
test_triage.py::test_fallback_model_takes_over PASSED [ 71%]
test_triage.py::test_bare_value_error_is_retried PASSED [ 85%]
test_triage.py::test_refusal_is_not_retried PASSED [100%]
============================== 7 passed in 0.12s ===============================The seven tests pin the behaviour that matters: the rendered prompt (the examples, which must validate against the schema, the partials, the optional history, and input_variables == ["ticket"], which catches a misspelt partial, Part 5), the happy path, a retry after a semantic-validator failure, giving up after three attempts (ValidationError propagates), the fallback taking over after the primary exhausts its retries, a retry after the bare ValueError, and a refusal that is not retried (the second scripted item is never consumed). Notice what they do not test: whether a real model classifies tickets correctly. That is an eval question, with a dataset and metrics (Module 10A, 11A.5); fakes only prove your plumbing and failure handling.
14.3 Running it against real providers#
# run_triage.py (illustrative: needs OPENAI_API_KEY and ANTHROPIC_API_KEY; assumes triage.py beside it)
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from triage import build_triage_chain
load_dotenv()
primary = init_chat_model("openai:gpt-6-luna")
fallback = init_chat_model("anthropic:claude-haiku-5-5") # OpenAI primary, Claude fallback; swap them to go the other way
chain = build_triage_chain(primary, fallback=fallback)
result = chain.invoke({"ticket": "The checkout page has been down for an hour and we are losing orders."})
print(result)category='bug' urgency=5 needs_human=True summary='Checkout page has been down for an hour and is losing orders.'14.4 Decision guide#
| You need | Use | Part |
|---|---|---|
| Fill variables into a chat prompt | ChatPromptTemplate.from_messages([...]) |
3 |
| Include prior turns | MessagesPlaceholder("history", optional=True), trimmed first; agents carry history in state |
4 |
| Constants or today's date | .partial(...), a callable for time |
5 |
| Examples in the prompt | FewShotChatMessagePromptTemplate; a selector for large label sets |
6 |
| Plain text out | StrOutputParser |
7.2 |
| Stream partial JSON to a UI | JsonOutputParser |
7.2 |
| A typed object, model supports it | with_structured_output(Schema, method=..., include_raw=True) |
8, 9 |
| A typed final answer from an agent | create_agent(response_format=...) |
10 |
| Retry on invalid output | with_retry on the whole chain, narrow exceptions |
11.3 |
| Feedback to the model on failure | A repair loop, or ToolStrategy |
11.5, 10.2 |
| Another model on failure | with_fallbacks |
11.4 |
| Shared, versioned prompts | Git first; hub for fast iteration, pinned | 12 |
| Making sense of an old tutorial | langchain-classic, then translate |
13 |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A prompt template returns a string." | format returns a string; invoke returns a PromptValue (a ChatPromptValue for chat templates) that chat models accept directly (1.1). |
| "A missing-variable error means I forgot a variable." | If the name contains quotes or spaces it is a JSON example with single braces; double them or use mustache (2.3). |
"MessagesPlaceholder is optional." |
It is required by default; an empty list is fine, an absent key is a KeyError. Use optional=True or the ("placeholder", ...) shorthand (4.1). |
| "I should put history into my agent's prompt." | Agents carry messages in state and a checkpointer; MessagesPlaceholder is for hand-built chains (4.2). |
| "A misspelt partial raises an error." | It is silently ignored and the variable stays required (Part 5). |
"JsonOutputParser(pydantic_object=...) validates the output." |
It only builds format instructions; use PydanticOutputParser or structured output to validate (7.3). |
| "I need an output parser for structured output." | Prefer with_structured_output or response_format; parsers are for text, streaming partial JSON and old models (7.1). |
"with_structured_output always uses native structured output." |
The default method differs by class: json_schema for OpenAI, Gemini and Ollama, function_calling for Anthropic. Pass method= explicitly (9.2). |
"A TypedDict schema gives me validated output." |
It gives a dict and no validation; only Pydantic validates (8.2). |
"A validation error is an OutputParserException." |
On the tool-calling path it is a Pydantic ValidationError; in agents it is StructuredOutputValidationError; and ChatOpenAI's default path can raise a plain ValueError for a reply with no parsed object. Name all of them in a retry rule (7.8, 11.3). |
| "Claude supports forced tool choice like the others." | Not on the models Anthropic lists (Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, Mythos 5.2 and 5.1), which is more than LangChain currently excludes, nor with thinking enabled; use method="json_schema" (9.2). |
"with_retry fixes bad output." |
It repeats the call; it does not tell the model what was wrong. Retry with feedback needs a repair loop or ToolStrategy (11.5). |
"ToolStrategy with a JSON Schema dict retries invalid output." |
A raw schema is not validated, so handle_errors never fires (10.2). |
| "The hub prompt I pulled is just text." | It is executable configuration; public pulls are refused unless you pass dangerously_pull_public_prompt=True, and you should pin a commit (12.4). |
"Old tutorials only need pip install langchain-classic." |
That reads them; it keeps you on code with a removal date. Translate to the current patterns (Part 13). |
Key takeaways#
- Prompts are objects: a template is a
Runnabletaking a dict and returning aPromptValue.invoke,format,format_messagesandpartialreturn different things, and variables are inferred and validated before any model runs. - Use
ChatPromptTemplatefor chat models, with("system" | "human" | "ai" | "placeholder", text)tuples. Message objects are not templated. Double the braces (or use mustache) around JSON examples; never accept ajinja2template from an untrusted source. MessagesPlaceholderis required by default, takesoptional=Trueandn_messages, and is for hand-built chains. Trim history first withtrim_messages; never split a tool call from its result.- Partials bind constants and callables (dates) ahead of time. Use
.partial(...)or the constructor'spartial_variables;from_messagesdoes not take them, and a misspelt name is ignored. - Few-shot:
FewShotChatMessagePromptTemplatefor chat models,FewShotPromptTemplatefor text, selectors for large or varied example sets. Selectors add an embedding call per prompt and defeat caching on the example block. - Parsers are mostly the pre-structured-output tools:
StrOutputParserfor text,JsonOutputParserfor streaming partial JSON,PydanticOutputParserwhen you must parse text. RaiseOutputParserException(withllm_output) from your own parsers. with_structured_output(Schema, method=..., include_raw=True)is the default for typed output. Pydantic validates,TypedDictand JSON Schema do not. Defaults differ by provider, so passmethodexplicitly; the OpenAI docs line on the default is stale.- Provider traps (as of November 2026): the Claude models Anthropic lists as rejecting forced tool choice (more than
langchain-anthropicexcludes today, including Fable 5.2), and any run with thinking enabled, needmethod="json_schema"; Anthropic and OpenRouter have nojson_mode; Gemini's function calling is discouraged;ChatOpenRouterdefaults tofunction_calling. - Streaming a structured result: partial objects come from a dict schema or an explicit
JsonOutputParser; a Pydantic schema onChatOpenAI's default path delivers one final object (8.8). - In agents,
response_formatwithToolStrategyorProviderStrategyreturnsstructured_response;handle_errorsfeeds validation errors back to the model; a JSON Schema dict is unvalidated; addModelRefusalMiddlewarefor refusals. - Chains have no built-in retry. Wrap the whole
prompt | model | parserunit inwith_retry(invoke only: it is skipped when streaming) with narrow exception types, including the bareValueErroron OpenAI's default path, addwith_fallbacks, repair with feedback when a plain retry is not enough, and decide the final failure value before you ship. - The hub is a dependency: pull by commit hash or tag, treat manifests as executable configuration, keep a fallback, and put the prompt version in your logs. Git remains the best home for prompts coupled to schemas and tests.
- Old tutorials fail on imports because
langchain.prompts,langchain.chainsand friends moved tolangchain-classic; translate toprompt | model | parser,with_structured_outputandcreate_agent.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
PromptTemplate |
A string template whose variables are inferred from the text; format returns a str, invoke a StringPromptValue |
ChatPromptTemplate |
An ordered list of message templates; invoke returns a ChatPromptValue that chat models accept |
PromptValue |
The wrapper a template produces; to_string() and to_messages() convert it for text or chat models |
| Template format | f-string (default), mustache or jinja2; selected with template_format |
MessagesPlaceholder |
A slot for a list of messages (history); required unless optional=True, n_messages keeps the last N |
Partial (partial) |
A template with some variables pre-bound, by value or by a zero-argument callable evaluated at format time |
FewShotPromptTemplate |
A string template that renders examples between a prefix and a suffix |
FewShotChatMessagePromptTemplate |
A template that renders each example as chat messages (human/AI pairs) |
| Example selector | An object that chooses which examples to include per input (LengthBased, SemanticSimilarity, MaxMarginalRelevance, or custom) |
| Output parser | A Runnable that turns a model reply into a Python value (StrOutputParser, JsonOutputParser, PydanticOutputParser, list and XML parsers) |
| Format instructions | Text from get_format_instructions() that tells the model how to shape its reply; part of your prompt and its token cost |
| Tool-call parser | A parser that reads an AIMessage's tool_calls (JsonOutputToolsParser, JsonOutputKeyToolsParser, PydanticToolsParser) |
OutputParserException |
The exception parsers raise; carries llm_output and send_to_llm for repair tools |
with_structured_output |
A chat-model method that returns a runnable producing a Pydantic instance or dict from a schema |
method (structured output) |
json_schema (native), function_calling (forced tool) or json_mode (valid JSON only); defaults differ per provider class |
include_raw |
Makes with_structured_output return {"raw", "parsed", "parsing_error"} so failures become values |
ModelRefusalError |
The standard exception for a refused structured-output request (langchain-core 1.7.5 and later) |
response_format |
The create_agent argument that makes the final reply a typed object in structured_response |
ToolStrategy |
Agent structured output via a schema exposed as a tool; handle_errors controls retry feedback |
ProviderStrategy |
Agent structured output via the provider's native feature; strict optional |
AutoStrategy |
Picks ProviderStrategy or ToolStrategy from the model profile |
handle_errors |
ToolStrategy option: True, a message string, exception type(s), a callable or False |
StructuredOutputValidationError |
The agent error for a value that violates the schema; subclass of StructuredOutputError |
| Retry with feedback | Repair that appends the bad output and the error to the conversation before asking again |
OutputFixingParser / RetryOutputParser |
Legacy langchain-classic parsers that ask a model to repair malformed output |
| Prompt hub | LangSmith's store of versioned prompts, with commits, tags and a Playground |
push_prompt / pull_prompt |
langsmith.Client methods to store and fetch prompts, by name, commit hash or commit tag |
| Commit tag | A readable name (for example prod) attached to a prompt commit, used to promote and roll back |
StructuredPrompt |
A prompt bundled with its output schema (langchain_core.prompts.structured) |
dangerously_pull_public_prompt |
The flag required to pull another owner's prompt; marks that the manifest is untrusted |
langchain-classic |
The package holding legacy LangChain code (LLMChain, OutputFixingParser, the old hub) |
All terms are also collected in the glossary.
Exercises#
- Brace hunt: build a
PromptTemplatethat includes a JSON example without escaping, printinput_variables, and explain the name you see. Fix it three ways: doubled braces,mustache, and aSystemMessageobject in a chat template. - Placeholder drill: write a chat prompt with a required
historyplaceholder and call it withouthistory, with[], and with a singleHumanMessage. Record each result. Then switch tooptional=Trueandn_messages=2and show the difference with six messages. - Date partial: create a template with
todayas a callable partial. Show that the date is evaluated per call by monkeypatching the callable to return a counter. Then misspell the partial name and write an assertion oninput_variablesthat catches it. - Few-shot to selector: convert the triage few-shot block to use
LengthBasedExampleSelectorwithmax_lengthsmall enough that long tickets get zero examples. Print how many examples a 5-word and a 60-word ticket receive, and decide whether that behaviour is acceptable for your task. - Parser autopsy: feed
PydanticOutputParserthese replies: valid JSON; JSON inside a code fence with chatter; JSON with an out-of-range value; prose. Record which raise and whaterr.llm_outputholds. Then do the same withJsonOutputParserand explain the differences. - Custom parser: write a
BaseOutputParserthat extracts aVerdict: PASS|FAILline and returns abool, raisesOutputParserExceptionwithllm_outputotherwise, and has format instructions. Test it withGenericFakeChatModelin a chain. - Mechanism check: using the
FakeToolModelfrom 8.3, show that aTypedDictschema acceptsurgency: 9, a Pydantic schema rejects it, andinclude_raw=Truereturns the error as a value. Then add amodel_validatorand show it also fires. - Exception inventory: list every exception type a bad structured answer can produce across
PydanticOutputParser,with_structured_output(tool-calling path andChatOpenAI's default path) andcreate_agentwithToolStrategy. Write oneretry_if_exception_typetuple that covers all of them, then a predicate that is narrower than a blanketValueError. - Repair loop variants: extend
extract_with_repairto (a) log each failure with the attempt number, (b) stop immediately onModelRefusalError, and (c) cap total feedback characters. Test with a fake whose second call refuses. - Agent errors: using the
create_agentfake from 10.2, comparehandle_errors=True, a fixed string and a callable. For each, print theToolMessagethe model sees. Which would you choose for a customer-facing refund agent, and why? - Strategy table: for each of OpenAI, Anthropic (
claude-haiku-5-5andclaude-sonnet-5-5), Gemini, Ollama and OpenRouter, write down themethodyou would pass for a Pydantic schema and the evidence (source or docs page) for your choice. Mark anything you could not verify. - Hub policy: write a one-page policy for your team: which prompts live in git, which in the hub, how a hub prompt is promoted (tag moves), what gets pinned, what the fallback is if the hub is down, and which review gate guards a tag move.
- Old tutorial translation: take any pre-1.0 tutorial using
LLMChainandStructuredOutputParserand translate it toprompt | model.with_structured_output(...). List every import you changed and where each class lives now.
Hints and answers
- The variable is named
"label"including its quotes, because{"label": "billing"}looks like a placeholder. Doubled braces:{{"label": "billing"}}. Mustache:template_format="mustache"with{{name}}for real variables (and single braces left alone). ASystemMessage(content=...)object is never templated. - Without
history:KeyError. With[]: works, no messages added. With a singleHumanMessage:ValueError(must be a list). Withoptional=Truethe key may be absent;n_messages=2keeps the last two of six. - Pass
lambda: next(counter)or similar and callformattwice; the values differ, so evaluation is per call. A misspelt partial leaves the original name ininput_variables, soassert prompt.input_variables == ["q"]fails. - A 5-word ticket gets examples that fit the word budget; a 60-word one may get zero. Acceptable only if the task works zero-shot; otherwise use a semantic selector or raise the budget.
PydanticOutputParserandJsonOutputParserboth strip a fence and chatter. The out-of-range value passesJsonOutputParserand failsPydanticOutputParser; prose fails both withOutputParserExceptionandllm_outputset.- Subclass
BaseOutputParser[bool], implementparseandget_format_instructions, returnTrueforPASS. Chain it after a fake model returningAIMessage(content="...\nVerdict: PASS"). - The
TypedDictreturns the dict untouched. The Pydantic class raisesValidationError(or givesparsing_errorwithinclude_raw). Amodel_validator(mode="after")raisingValueErrorsurfaces as aValidationErrortoo. OutputParserException(parsers),pydantic.ValidationError(tool-calling path), a plainValueError("does not have a 'parsed' field",ChatOpenAI's defaultjson_schemapath),StructuredOutputValidationErrorandMultipleStructuredOutputsError(agents; both subclassStructuredOutputError). A tuple:(OutputParserException, ValidationError, StructuredOutputError, ValueError). The last is broad, because the first two areValueErrors as well and it also catches unrelated bugs; the narrower rule is the predicate ofs24in 11.3 (aValueErrorwhose text contains'parsed' field).ModelRefusalErroris not aValueError, so none of this retries a refusal.- Check
isinstance(error, ModelRefusalError)before building feedback and re-raise. Truncate the accumulated feedback. To script the refusal, subclass theFakeToolModelfrom 8.3 so its second_generateraisesModelRefusalError(raw_message=AIMessage("I can't help with that."))(theRaisingToolModelin 14.2 does this), or call your function with a hand-built{"raw": ..., "parsed": None, "parsing_error": ModelRefusalError(raw_message=AIMessage("I can't help with that."))}and assert it re-raises. Trueshows the Pydantic error text; the string hides detail but is predictable; the callable can map the error to your own wording. For customer-facing use a fixed or callable message that never echoes raw model output.- Evidence is in 9.2 and 8.8: explicit
json_schemafor OpenAI,claude-sonnet-5-5(rejects forced tool choice), Gemini and Ollama;function_callingorjson_schemaforclaude-haiku-5-5(it accepts forced tool choice; keep the default); for OpenRouter theChatOpenRoutersource showsfunction_callingas the default andjson_schemaavailable, so passjson_schemaonly for a routed model whose endpoint listsresponse_formatsupport (and for a Claude that rejects forced tool choice), otherwise keep the default. Mark the routed-model behaviour unverified: no request was sent to OpenRouter. - Include: git for schema-coupled prompts; hub for experiment-stage prompts; promotion by moving a
prodtag only after the eval suite passes; pin commit hashes in production config; a bundled copy as fallback; review by the prompt owner plus one engineer. - Typical moves:
langchain.promptstolangchain_core.prompts;LLMChainremoved in favour of|;StructuredOutputParserandResponseSchemareplaced by a Pydantic class andwith_structured_output;chain.runtochain.invoke.
Check yourself#
- What does
ChatPromptTemplate.invokereturn, and how doformat_messagesandto_string()differ from it?AChatPromptValue, which chat models accept directly.to_messages()gives the list of message objects,to_string()a readable transcript for logs, andformat_messages(**kwargs)returns the list directly without the wrapper. - Why does
PromptTemplate.from_template('Reply like {"label": "x"}')raise only when you invoke it, and what is the fix?In an f-string template a single-brace{"label": "x"}creates a variable named"label", and the missing-variable check happens at invoke time. Double the braces ({{...}}), use mustache, or use a message object. - What is the difference between
MessagesPlaceholder("history")andMessagesPlaceholder("history", optional=True)?The first is required: omitting the key raisesKeyError(an empty list is fine) and it appears ininput_variables. The second is optional: omitting it yields no messages and it appears inoptional_variables. - Where does conversation history live for a
create_agentagent in v1, and when isMessagesPlaceholderstill the right tool?In the agent's own state, persisted by a checkpointer.MessagesPlaceholderis for hand-builtprompt | model | parserchains where you manage history yourself. - Which constructor accepts
partial_variables,from_messagesor theChatPromptTemplate(...)constructor? What happens to a misspelt partial name?TheChatPromptTemplate(...)constructor (andPromptTemplate.from_template);from_messagesraisesTypeErrorfor it. A misspelt partial name is silently ignored and the variable stays required. - When would you use
FewShotChatMessagePromptTemplateinstead ofFewShotPromptTemplate, and what does a semantic selector add to each call?The chat flavour for chat models, rendering examples as human/AI pairs; the text flavour for one block inside a message or a completion model. A semantic selector adds an embedding call and a vector search per prompt and makes the example block vary, which defeats caching. - Why is
JsonOutputParser(pydantic_object=Model)not validation, and which parser validates?It only uses the class to produce format instructions; the docstring says no validation is performed.PydanticOutputParser(and structured output with a Pydantic schema) validates. - What does
JsonOutputParseryield while streaming, and what doesdiff=Truechange?Growing partial objects (everything parsed so far). Withdiff=Trueit yields JSON Patch operations instead. - Name three situations where an output parser is still the right tool today.Plain text out (
StrOutputParser), streaming partial JSON, models without native structured output, and reading code or errors from LangChain's tool-call paths. Custom formats are a fourth. - What are the three shapes
with_structured_outputcan return, and which of them is validated?A Pydantic instance, aTypedDictdict, or a JSON Schema dict. Only the Pydantic instance is validated. - What does
include_raw=Truereturn, and why is it the production setting?{"raw": AIMessage, "parsed": ..., "parsing_error": ...}. It gives you token usage, the raw reply for logs, and turns a parse failure into a value rather than an exception. - What is the default
methodforChatOpenAIand forChatAnthropic, and which source disagrees with which docs?ChatOpenAIdefaults tojson_schemaandChatAnthropictofunction_calling. The OpenAI integration page still says OpenAI defaults to function calling; the 1.8.0 source saysjson_schema(only the parentBaseChatOpenAIdefaults to function calling). - Which Claude models reject forced tool choice, what does LangChain do about it by default, and what should you pass instead?Anthropic lists Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1 (03.4, 1.5), and any run with thinking enabled behaves the same way.
langchain-anthropic1.7.10 excludes onlyclaude-fable-5-1,claude-opus-5-5andclaude-sonnet-5-5: for those it warns, does not force the tool, and raisesOutputParserExceptionif the model did not call it; forclaude-fable-5-2and Mythos it still forces the tool. Passmethod="json_schema"for all of them. - In
create_agent, what doToolStrategyandProviderStrategydo differently, and what doeshandle_errorscontrol?ToolStrategyexposes the schema as a tool and forces tool use;ProviderStrategyuses the provider's native structured output.handle_errorsdecides whether and how validation errors are returned to the model as aToolMessagefor another attempt (True, a string, exception types, a callable, orFalseto raise). - Why does a raw JSON Schema dict give no validation or retries with
ToolStrategy?The tool-call arguments are returned as-is, so nothing raises andhandle_errorsnever fires. Use Pydantic, a dataclass or aTypedDictto get validation. - Why must
with_retrywrap the whole chain, why narrowretry_if_exception_type, and what happens to the retry when you stream?Every attempt must be a fresh model call; retrying only the parser re-parses the same bad text. The default retries anyException, including authentication errors and bugs, so name the parse exceptions (including the bareValueErroronChatOpenAI's default path, or a predicate). When you stream,with_retryis skipped, so validate at the end and re-invoke. - Why is
client.pull_prompt("owner/name")an error in currentlangsmith, and what should you pin for production?Public prompts (any owner other than your own) are refused unlessdangerously_pull_public_prompt=True, because manifests are executable configuration. Pin a commit hash (or a tag you control), especially withinclude_model=True. - Why does
from langchain.prompts import PromptTemplatefail in an old tutorial, and where does the code live now?Thelangchain1.x package no longer containslangchain.prompts,langchain.chains,langchain.huband similar; the current home islangchain_core.prompts, and legacy code is inlangchain-classic(langchain_classic.prompts).
Further resources#
Official sources first; where the official documentation is more complete than this lesson (it is, for every provider's own structured-output options), read it. Lesson 08F.17 is the closing lesson on learning the rest from the docs.
- Structured output: LangChain: Structured output, LangChain: Models (structured output section), v1 migration guide
- Provider pages: OpenAI, Anthropic, Google Generative AI, OpenRouter, all chat integrations
- Prompt and parser API reference:
ChatPromptTemplate,MessagesPlaceholder, output parsers, and the source inlangchain_core/prompts - Errors and testing: OUTPUT_PARSING_FAILURE, Unit testing
- Prompt hub: Prompt engineering, Manage prompts programmatically, Create a prompt, Prompt and context hub
- In this course: 03.4 Structured Output, 04.2 Examples and Few-Shot, 04.10 Prompt Templates and Versioning, 08F.1 Agent Frameworks
← 08F.5: Chat Models, Messages and Content Blocks | Module 08F overview | 08F.7: Runnables and LCEL →