构建自定义输出解析器
使用自定义和内置的 LangChain 输出解析器,将原始 LLM 文本转换为可靠的结构化数据。
构建自定义输出解析器 是 CoddyKit 上的免费 LangChain / RAG / Vector DBs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 LangChain / RAG / Vector DBs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 LangChain / RAG / Vector DBs 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Parse Output?
LLMs return free-form text, but applications need structured data: objects, lists, enums. An output parser converts the raw string into something your code can use safely.
The Parser Interface
A LangChain output parser implements two key methods.
parse(text)turns the string into your typeget_format_instructions()tells the model how to format its reply
A Minimal Custom Parser
Subclass BaseOutputParser and implement parse. This one splits a comma-separated reply into a list.
from langchain_core.output_parsers import BaseOutputParser
class CommaListParser(BaseOutputParser):
def parse(self, text):
return [t.strip() for t in text.split(",")]
print(CommaListParser().parse("a, b, c")) # ["a", "b", "c"]Format Instructions
Override get_format_instructions so the prompt nudges the model toward a parseable shape. The instructions are injected into your prompt template.
def get_format_instructions(self):
return "Reply with items separated by commas, no numbering."Pydantic Output Parser
For rich objects, LangChain ships a PydanticOutputParser. You define a schema and it generates instructions plus validation automatically.
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
# parser = PydanticOutputParser(pydantic_object=Person)Wiring a Parser into a Chain
With LCEL you pipe the model output straight into the parser using the | operator.
chain = prompt | llm | CommaListParser()
result = chain.invoke({"topic": "fruits"})Handling Malformed Output
Models sometimes ignore the format. A robust parser validates and raises a clear error, or attempts a best-effort recovery, instead of crashing downstream.
def parse(self, text):
try:
return json.loads(text)
except json.JSONDecodeError:
raise ValueError("Model did not return valid JSON")The OutputFixingParser
Wrap any parser in an OutputFixingParser. When parsing fails, it sends the bad output and the error back to an LLM to repair it.
Streaming and Parsers
Some parsers support incremental parsing of streamed tokens. For structured types this is hard, so streaming parsers often emit partial objects as fields complete.
Validation Beyond Types
You can add business rules inside parse: ranges, allowed values, required combinations. Reject anything that would corrupt your application state.
def parse(self, text):
n = int(text.strip())
if not 1 <= n <= 5:
raise ValueError("Rating must be 1-5")
return nPutting It Together
Define the parser, expose format instructions, inject them into the prompt, and pipe everything in a chain. The result is reliable structured output.
prompt = template.partial(
format=parser.get_format_instructions()
)
chain = prompt | llm | parser
chain.invoke({"input": "..."})Quick Check
Test your understanding of output parsers.
Recap
You built custom output parsing:
- Implement
parseandget_format_instructions - Use
PydanticOutputParserfor rich schemas - Pipe parsers into chains with
| - Wrap with
OutputFixingParserfor resilience
用 AI 导师学习 LangChain / RAG / Vector DBs — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「构建自定义输出解析器」课时是免费的吗?
是的 — 「构建自定义输出解析器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 LangChain / RAG / Vector DBs 课程的其余内容,请升级到 CoddyKit PRO。 LangChain / RAG / Vector DBs 课程共包含 4 节课。
「构建自定义输出解析器」这节课中我会学到什么?
使用自定义和内置的 LangChain 输出解析器,将原始 LLM 文本转换为可靠的结构化数据。 你通过在浏览器中直接运行的动手代码来练习 LangChain / RAG / Vector DBs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 LangChain / RAG / Vector DBs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 LangChain / RAG / Vector DBs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「构建自定义输出解析器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 LangChain / RAG / Vector DBs 课中编写并运行代码吗?
能。每节 LangChain / RAG / Vector DBs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 开发自定义文档加载器
- 集成自定义嵌入模型
- 使用自定义逻辑扩展检索链
- 构建自定义输出解析器