六 流式传输 (Streaming)需要注意的是流式输出依赖于整个程序链路都支持“逐块处理”。如果程序中的某个环节必须等待完整输出如需一次性写入数据库则无法直接使用 StreamingLangChain 1.0 进一步优化了流式机制引入 自动流式模式Auto-streaming。例如在Agent中如果整体程序处于 streaming 模式即便节点中调用 model.invoke()LangChain 也会自动流式化模型调用。# 使用.stream()方法进行流式传输forchunkinmodel.stream(用一段话描述大海。):print(chunk.content,end,flushTrue)# 逐块打印astream_events()此外LangChain 还支持通过 astream_events() 对语义事件进行异步流式监听适合需要过滤不同事件类型的复杂场景。你能看到 完整语义生命周期事件,包括on_chain_starton_prompt_start / on_prompt_endon_llm_starton_llm_stream逐 Tokenon_llm_endon_chain_end非常适合调试 LLM 推理过程了解 LangChain pipeline 的执行顺序构建 UI如 web 前端的逐 token streaming实现日志、可观测性、监控系统importasynciofromlangchain_openaiimportChatOpenAIfromlangchain_core.promptsimportChatPromptTemplate# 1. 构建最简单的 Prompt LLMpromptChatPromptTemplate.from_messages([(system,你是一个专业的 AI 助手。),(human,{question})])# 2. 初始化 ChatOpenAI 实例指定使用 gpt-3.5-turbo 模型llmChatOpenAI(modelgpt-3.5-turbo,)# 3. 使用管道符将 prompt 模板与 llm 连接构建可运行的链chainprompt|llm# 4. 使用 astream_events() 监听所有语义事件eventschain.astream_events({question:请用一句话介绍一下 LangChain 1.0 的核心思想。},versionv1,# 必须指明版本v1 才有语义事件)asyncforeventinevents:# 打印事件类型print(f[Event] type{event[event]})# 展示关键字段ifdatainevent:print( data:,event[data])print(-----------------------------)七 结构化输出解析很多时候我们需要模型返回结构化的数据如JSON以便程序后续处理。输出解析器 (Output Parsers) 正是为此而生。最强大的是 StructuredOutputParser它可以与 ZodTypeScript或 PydanticPython等模式定义工具结合使用确保输出符合预定格式。目标让大模型返回可程序解析的数据任务学习Pydantic模型使用with_structured_output()产出一个信息抽取器提取电影信息/新闻摘要关键点ToolStrategy兼容所有模型ProviderStrategy更可靠with_structured_output()使用 Pydantic 的 BaseModel 定义一个严格的数据结构。每个字段都明确了类型如 str、int、float并用 Field(…, description“…”) 提供语义描述。据此模型回复时LangChain 会要求 LLM 的输出必须能填充这些字段。然后使用with_structured_output即可引导模型进行结构化输出。fromtypingimportListfromlangchain_core.utils.pydanticimportBaseModel,Fieldfromlangchain_openaiimportChatOpenAI# 1. 定义期望的输出结构 (Pydantic 模型)classPerson(BaseModel):Information about a person.name:strField(description人的姓名)age:intField(description人的年龄)high:intField(description人的身高)hobbies:List[str]Field(description人的爱好列表)# 2. 初始化模型并绑定结构化输出格式llmChatOpenAI(modelgpt-4o,temperature0)structured_llmllm.with_structured_output(Person)# 3. 调用模型并获取 Pydantic 对象构造提示要求提取约翰·多伊的姓名、年龄和兴趣爱好prompt提取名为约翰·多伊的人的信息提取不到的数据就为空值。他30岁喜欢阅读、远足和弹吉他.resultstructured_llm.invoke(prompt)# 4. 验证结果print(fType of result:{type(result)})print(fResult object:{result})# 5.判断result是否属于Person类assertisinstance(result,Person)Type of result: class __main__.Person Result object: name约翰·多伊 age30 high0 hobbies[阅读, 远足, 弹吉他]而如果想要获得模型的完整回复则可以设置include_rawTrue# 1. 配置结构化输出指定返回 Pydantic 模型 Person并保留原始响应structured_llmllm.with_structured_output(Person,include_rawTrue)agent中结构化输出frompydanticimportBaseModel,Field,field_validatorfromtypingimportLiteralfromlangchain.agentsimportcreate_agentfromlangchain_openaiimportChatOpenAI# 1. 定义天气结构化输出模型classWeatherForecast(BaseModel):天气预报结构化输出city:strField(description城市名称)temperature:intField(description温度(摄氏度))condition:Literal[晴,雨,多云,雪]Field(description天气状况)# 2. 加载模型modelChatOpenAI(modeldeepseek-ai/DeepSeek-V3.2,temperature0.5,# 温度参数用于控制模型的随机性值越小则随机性越小max_tokens512,# 最大生成token数timeout30,# 超时时间单位秒base_urlhttps://api.siliconflow.cn/v1,api_keysk-xxx)# 3. 创建智能体agentcreate_agent(modelmodel,# 加载的模型tools[],# 工具列表这里为空response_formatWeatherForecast# 指定结构化输出格式)# 4. 调用智能体解析天气描述resultagent.invoke({messages:[{role:user,content:北京今天阳光明媚温度10度}]})# 5. 提取并打印结果forecastresult[structured_response]print(f{forecast.city}天气:{forecast.condition},{forecast.temperature}°C)北京天气: 晴, 10°C带判断的结构frompydanticimportBaseModelfromlangchain_openaiimportChatOpenAI# 1. 定义年龄模型限制范围 0-150classAgeProfile(BaseModel):name:strage:intField(ge0,le150)# 年龄必须在0-150之间# 2. 定义模型modelChatOpenAI(modeldeepseek-ai/DeepSeek-V3.2,temperature0.5,# 温度参数用于控制模型的随机性值越小则随机性越小max_tokens512,# 最大生成token数timeout30,# 超时时间单位秒base_urlhttps://api.siliconflow.cn/v1,api_keysk-xxx)# 3. 创建智能体agentagentcreate_agent(modelmodel,tools[],response_formatAgeProfile)# 4. 模型返回age999非法值resultagent.invoke({messages:[{role:user,content:张三的年龄是999岁# 明显不合理的数据}]})# LangChain会自动# 1. 捕获ValidationError# 2. 在ToolMessage中反馈错误详情# 3. 让模型重新生成# 最终返回合法值print(result[structured_response])name张三 age150JsonOutputParserfromlangchain_core.output_parsersimportJsonOutputParserimportjsonfrompydanticimportBaseModel,Fieldfromlangchain_openaiimportChatOpenAI# 1. 定义输出结构classWeatherInfo(BaseModel):天气信息city:strField(description城市名称)temperature:intField(description温度摄氏度)condition:strField(description天气状况)# 2. 创建 JSON 输出解析器json_parserJsonOutputParser(pydantic_objectWeatherInfo)# 3. 创建提示模板关键必须包含 json 这个词promptChatPromptTemplate.from_template(请根据以下信息提取天气数据并以 JSON 格式返回。 信息{weather_info} 请返回包含以下字段的 JSON - city: 城市名称 - temperature: 温度摄氏度 - condition: 天气状况 必须返回以下 JSON 格式不要包含任何其他文本 {{city: 城市名称, temperature: 温度数字, condition: 天气状况}} 例如{{city: 北京, temperature: 25, condition: 晴}} JSON 格式 )# 4. 定义模型modelChatOpenAI(modeldeepseek-ai/DeepSeek-V3.2,temperature0.5,# 温度参数用于控制模型的随机性值越小则随机性越小max_tokens512,# 最大生成token数timeout30,# 超时时间单位秒base_urlhttps://api.siliconflow.cn/v1,api_keysk-xxx)# 5. 构建链runnableprompt|model|json_parser# 6. 调用resultrunnable.invoke({weather_info:北京今天晴温度25度})print(result)print(result[city]){city: 北京, temperature: 25, condition: 晴} 北京结构化输出关键要点输出json格式提示词必须包含 “json” 关键词有些大模型 要求提示词中包含 “json” 这个词否则会报错Prompt must contain the word json推荐方案对比方案 1 (JsonOutputParser)最简洁推荐使用方案 2 (with_structured_output)需要提示词包含 “json”方案 3 (可选手动 JSON 解析)最稳定适合关键应用配置建议设置temperature0.0获得更稳定的输出最好提供清晰的 JSON 格式示例常见错误提示词中没有 “json” 关键词没有设置低温度参数没有提供 JSON 格式示例没有处理解析异常简单问答机器人用标准接口实现一个支持多轮消息与流式输出的问答机器人fromlangchain_openaiimportChatOpenAIfromlangchain.messagesimportHumanMessage,SystemMessage,AIMessagefromlangchain_core.promptsimportChatPromptTemplate modelChatOpenAI(modeldeepseek-ai/DeepSeek-V3.2,temperature0.5,# 温度参数用于控制模型的随机性值越小则随机性越小max_tokens512,# 最大生成token数timeout30,# 超时时间单位秒base_urlhttps://api.siliconflow.cn/v1,api_keysk-xxxx)defchat():msgs[SystemMessage(content你是一个智能助手),]whileTrue:promptinput(请输入:)ifpromptexit:breakhumanHumanMessage(contentprompt)msgs.append(human)# retmodel.invoke(msgs)# msgs.append(AIMessage(contentret.content))# print(ret.content)full_replyforchunkinmodel.stream(msgs):print(chunk.content,end,flushTrue)full_replychunk.content msgs.append(AIMessage(contentfull_reply))print(\n-*40)# 分隔线if__name____main__:chat()