核心内容摘要
加州大学团队推出了效率、成功率最优越的策略!4层网络,成功复现了复杂双臂操作
六 流式传输 (Streaming)需要注意的是流式输出依赖于整个程序链路都支持“逐块处理”。
如果程序中的某个环节必须等待完整输出如需一次性写入数据库则无法直接使用 StreamingLangChain
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#
构建最简单的 Prompt LLMpromptChatPromptTemplate.from_messages([(system,你是一个专业的 AI 助手。
),(human,{question})])#
初始化 ChatOpenAI 实例指定使用 gpt-
5-turbo 模型llmChatOpenAI(modelgpt-
5-turbo,)#
使用管道符将 prompt 模板与 llm 连接构建可运行的链chainprompt|llm#
使用 astream_events() 监听所有语义事件eventschain.astream_events({question:请用一句话介绍一下 LangChain
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#
定义期望的输出结构 (Pydantic 模型)classPerson(BaseModel):Information about a person.name:strField(description人的姓名)age:intField(description人的年龄)high:intField(description人的身高)hobbies:List[str]Field(description人的爱好列表)#
初始化模型并绑定结构化输出格式llmChatOpenAI(modelgpt-4o,temperature
structured_llmllm.with_structured_output(Person)#
调用模型并获取 Pydantic 对象构造提示要求提取约翰·多伊的姓名、年龄和兴趣爱好prompt提取名为约翰·多伊的人的信息提取不到的数据就为空值。
他30岁喜欢阅读、远足和弹吉他.resultstructured_llm.invoke(prompt)#
验证结果print(fType of result:{type(result)})print(fResult object:{result})#
判断result是否属于Person类assertisinstance(result,Person)Type of result: class __main__.Person Result object: name约翰·多伊 age30 high0 hobbies[阅读, 远足, 弹吉他]而如果想要获得模型的完整回复则可以设置include_rawTrue#
配置结构化输出指定返回 Pydantic 模型 Person并保留原始响应structured_llmllm.with_structured_output(Person,include_rawTrue)agent中结构化输出frompydanticimportBaseModel,Field,field_validatorfromtypingimportLiteralfromlangchain.agentsimportcreate_agentfromlangchain_openaiimportChatOpenAI#
定义天气结构化输出模型classWeatherForecast(BaseModel):天气预报结构化输出city:strField(description城市名称)temperature:intField(description温度(摄氏度))condition:Literal[晴,雨,多云,雪]Field(description天气状况)#
加载模型modelChatOpenAI(modeldeepseek-ai/DeepSeek-V
2,temperature
5,# 温度参数用于控制模型的随机性值越小则随机性越小max_tokens512,# 最大生成token数timeout30,# 超时时间单位秒base_urlhttps://api.siliconflow.cn/v1,api_keysk-xxx)#
创建智能体agentcreate_agent(modelmodel,# 加载的模型tools[],# 工具列表这里为空response_formatWeatherForecast# 指定结构化输出格式)#
调用智能体解析天气描述resultagent.invoke({messages:[{role:user,content:北京今天阳光明媚温度10度}]})#
提取并打印结果forecastresult[structured_response]print(f{forecast.city}天气:{forecast.condition},{forecast.temperature}°C)北京天气: 晴, 10°C带判断的结构frompydanticimportBaseModelfromlangchain_openaiimportChatOpenAI#
定义年龄模型限制范围
classAgeProfile(BaseModel):name:strage:intField(ge0,le
# 年龄必须在
之间#
定义模型modelChatOpenAI(modeldeepseek-ai/DeepSeek-V
2,temperature
5,# 温度参数用于控制模型的随机性值越小则随机性越小max_tokens512,# 最大生成token数timeout30,# 超时时间单位秒base_urlhttps://api.siliconflow.cn/v1,api_keysk-xxx)#
创建智能体agentagentcreate_agent(modelmodel,tools[],response_formatAgeProfile)#
模型返回age999非法值resultagent.invoke({messages:[{role:user,content:张三的年龄是999岁# 明显不合理的数据}]})# LangChain会自动#
捕获ValidationError#
在ToolMessage中反馈错误详情#
让模型重新生成# 最终返回合法值print(result[structured_response])name张三 age150JsonOutputParserfromlangchain_core.output_parsersimportJsonOutputParserimportjsonfrompydanticimportBaseModel,Fieldfromlangchain_openaiimportChatOpenAI#
定义输出结构classWeatherInfo(BaseModel):天气信息city:strField(description城市名称)temperature:intField(description温度摄氏度)condition:strField(description天气状况)#
创建 JSON 输出解析器json_parserJsonOutputParser(pydantic_objectWeatherInfo)#
创建提示模板关键必须包含 json 这个词promptChatPromptTemplate.from_template(请根据以下信息提取天气数据并以 JSON 格式返回。
信息{weather_info} 请返回包含以下字段的 JSON - city: 城市名称 - temperature: 温度摄氏度 - condition: 天气状况 必须返回以下 JSON 格式不要包含任何其他文本 例如 JSON 格式 )#