Prompt Templates, Structured Output and Parsers
Prompt templates turn inputs into prompt values (text or messages), and structured output turns model replies into typed data. Know what each template piece produces, how variables and braces are handled, how `with_structured_output` works and what each schema type returns, and when output parsers and fixing/retry parsers still earn their place.
Key points
- 1
ChatPromptTemplate.invokereturns aChatPromptValue(.to_messages()or.to_string()), andPromptTemplate.invokereturns aStringPromptValue. A template with a single variable accepts a bare string; with two or more you must pass a dict. Missing variables raiseKeyError, while extra keys are ignored. - 2
from_messagesaccepts role tuples (human/user,ai/assistant,system,placeholder), plain strings (human), message dicts, message objects and message prompt templates. Message objects are inserted literally and never formatted. Unknown roles such astoolraiseValueError. - 3
f-string is the default template format:
{x}is a variable,{{and}}are literal braces, and attribute access such as{user.name}is rejected. Mustache (template_format="mustache") supports nested lookups and sections but renders missing variables as empty text. Never accept Jinja2 templates from untrusted sources: the docs warn they can execute arbitrary code and that sandboxing is only best effort. - 4
MessagesPlaceholder("history")splices a list of messages in at its position. It is required by default, andoptional=True(or the("placeholder", "{history}")shorthand) lets callers leave it out. It accepts message objects, tuples or dicts, rejects a bare string, andn_messages=Nkeeps the last N. - 5
.partial(name=value)(orpartial_variables=) pre-fills variables and removes them frominput_variables. A zero-argument function partial is called on every format, which suits dates. A common use is putting a parser's format instructions into the prompt. - 6
FewShotChatMessagePromptTemplateformats each example withexample_promptinto human/AI messages inserted where the template sits. Pass eitherexamplesor anexample_selector, not both.SemanticSimilarityExampleSelectorpicks the k nearest examples via embeddings, whileLengthBasedExampleSelectoradds examples in order until a length budget is used up. - 7
model.with_structured_output(schema)returns a Runnable. A Pydantic class gives a validated instance (lax coercion, so"36"becomes36); a TypedDict or JSON schema gives an unvalidated dict. A JSON schema dict needs a top-leveltitle(and ideally adescription). The class name, docstring and field descriptions are all sent to the model. - 8
methoddepends on the provider:json_schemauses native structured output,function_callingforces a tool call, andjson_modeguarantees valid JSON only, so the schema must be described in the prompt.ChatOpenAIdefaults tojson_schema, and itsstrict=Trueguarantees schema conformance forjson_schema/function_calling.include_raw=Truereturns{raw, parsed, parsing_error}and catches parse errors instead of raising. - 9
langchain-core's default implementation binds the schema as a tool with
tool_choice="any"and parses only the first tool call. It needsbind_tools(otherwiseNotImplementedError) and accepts but ignoresmethod/strict. If the model makes no tool call,parsedisNonewith no error. - 10
Output parsers:
StrOutputParsergives text,JsonOutputParsergives dicts (fenced JSON is fine;pydantic_objectonly shapes format instructions and adds no validation),PydanticOutputParsergives validated instances or raisesOutputParserException, andCommaSeparatedListOutputParsergives a list. While streaming, JSON parsers yield growing partial dicts, and the Pydantic parser yields only objects that already validate. - 11
Fixing and retry parsers live in
langchain_classic.output_parsers.OutputFixingParserrepairs a bad completion from the instructions, completion and error, without the original prompt (max_retriesdefaults to 1).RetryOutputParser/RetryWithErrorOutputParseralso send the original prompt and must be called withparse_with_prompt.
Common traps
A JSON example inside an f-string template creates a bogus variable such as
"ok". Double the braces or use aSystemMessageobject.Building a template with an f-string from user text lets any
{...}in the data become a variable. Keep templates static and pass data as values; values are never re-parsed.model.bind_tools([search]).with_structured_output(Answer)silently dropssearch: only the forcedAnswertool is sent.with_structured_output(Person)returns one object. For many, wrap them:people: list[Person].Format instructions are just prompt text; they constrain nothing. Prefer native structured output when the model supports it.
Switching a schema from Pydantic to TypedDict to stop validation errors only hides bad data.
RetryOutputParser.parse()raisesNotImplementedError; it needsparse_with_prompt.
Read the source
Further reading
Suggest a resourceNo extra reading for Prompt Templates, Structured Output and Parsers yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Prompt Templates, Structured Output and Parsers
Ten questions, with the answer and explanation after each one.