ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

【LangChain组件00:Models】—— LangChain Chat Model 详解:从常用参数到 bind_tools 与结构化输出

【LangChain组件00:Models】—— LangChain Chat Model 详解:从常用参数到 bind_tools 与结构化输出 LangChain Chat Model 详解从常用参数到 bind_tools 与结构化输出Chat Model 是 LangChain 里一切 Agent 的地基——没有模型工具、提示词、循环都无从谈起。理解init_chat_model()怎么配置模型行为参数temperature、max_tokens、timeout 等以及bind_tools()/with_structured_output()这两个高级能力是写出可控、可靠、可复用的 Agent 的起点。本文基于 LangChain 官方文档Python与菜鸟教程 LangChain 系列沿材料分类组件00Models的路径组织覆盖常用参数与高级用法两大部分。一、先厘清Chat Model 在 LangChain 里的角色一句话结论Chat Model 就是负责说话的模型它接受消息列表、返回回复而bind_tools()让它能返回工具调用请求with_structured_output()让它直接返回结构化数据——这两个能力是 Agent 和结构化提取的基石。普通模型只能生成纯文本。但模型的能力不止于此bind_tools()模型知道有哪些工具可用能在回复中返回tool_call告诉程序我需要在此时调用这个工具。with_structured_output()模型按你指定的 Schema 直接返回结构化数据Pydantic 对象 / 字典而不是让你去解析文本。这两个方法把模型从文本生成器升级成能干活、能交付结构的智能体组件。二、常用参数逐个拆解2.1 temperature——控制创造性与确定性temperature是最常用的参数取值范围 0 到 2控制模型输出的随机程度。fromlangchain.chat_modelsimportinit_chat_model question用一句话介绍菜鸟教程 RUNOOB# temperature0输出非常确定几乎每次结果一样model_lowinit_chat_model(deepseek:deepseek-v4-flash,temperature0)resp1model_low.invoke(question)resp2model_low.invoke(question)print(f两次结果相同:{resp1.contentresp2.content})# True# temperature1.5输出多样化每次可能不同model_highinit_chat_model(deepseek:deepseek-v4-flash,temperature1.5)print(f第1次:{model_high.invoke(question).content})print(f第2次:{model_high.invoke(question).content})temperature 值效果适用场景0 ~ 0.3输出稳定、确定每次结果几乎一致数据提取、分类、代码生成、翻译0.5 ~ 0.7适度的创造性输出自然但不偏离主题日常对话、内容总结0.8 ~ 1.2输出多样化有较多发挥空间创意写作、头脑风暴1.3 ~ 2.0输出非常随机可能出现意外内容探索性生成不太推荐用于生产temperature0 不等于完全相同。由于模型内部浮点精度差异极端情况下仍可能有微小差异。如果需要绝对的确定性有些模型提供了seed参数。2.2 max_tokens——控制输出长度与成本max_tokens限制模型输出的最大 Token 数。一个 Token 大约相当于 0.75 个英文单词或 0.5 个中文字。fromlangchain.chat_modelsimportinit_chat_model modelinit_chat_model(deepseek:deepseek-v4-flash,temperature0)# max_tokens30限制输出在 30 个 Token 以内response_shortmodel.invoke(详细介绍一下菜鸟教程 RUNOOB 平台,max_tokens30)print(f限制 30 tokens ({len(response_short.content)}字符):)print(response_short.content)⚠️ 避坑max_tokens是对输出长度的硬限制。如果设置过低模型的回答可能在句中突然截断。一般建议 100-2000一句话回答类场景 30-100 就够详细解释类建议 500-2000。2.3 timeout 与 max_retries——网络可靠性在生产环境中网络请求可能失败。这两个参数控制请求行为fromlangchain.chat_modelsimportinit_chat_model# 生产环境推荐配置modelinit_chat_model(deepseek:deepseek-v4-flash,timeout30,# 单次请求最多等待 30 秒max_retries3,# 失败后最多重试 3 次总共 4 次请求机会)参数说明建议值timeout单次请求的最大等待时间秒。None 表示不限制30~60太短易超时太长体验差max_retries失败后的重试次数。0 表示不重试2~3足够处理偶发网络问题2.4 base_url——自定义 API 地址base_url在你需要通过代理、中转服务或私有部署访问模型时非常有用fromlangchain.chat_modelsimportinit_chat_model# 场景 1通过代理访问modelinit_chat_model(deepseek:deepseek-v4-flash,base_urlhttps://your-proxy-domain.com/v1)# 场景 2使用兼容 OpenAI 接口的第三方服务modelinit_chat_model(deepseek:deepseek-v4-flash,base_urlhttps://api.third-party.com/v1,api_keyyour-third-party-key,)# 场景 3连接本地模型如 vLLM、Ollamamodelinit_chat_model(openai:qwen2.5,base_urlhttp://localhost:8000/v1,api_keynot-needed,# 本地通常不需要 Key)base_url改变的是 API 端点地址但provider参数决定行为模式。比如provideropenai会用 OpenAI 消息格式即使 base_url 指向的是别的服务。确保目标服务兼容你指定的 provider 格式。2.5 其他常用参数top_p核采样另一种控制随机性的方式模型只从累积概率达到 top_p 的词中采样。一般建议只调temperature或top_p中的一个不要同时调否则行为难预测。modelinit_chat_model(deepseek:deepseek-v4-flash,top_p0.9)# 只考虑累积概率前 90% 的词stop停止序列模型遇到这些词会立即停止生成。responsemodel.invoke(列出五个编程学习网站每个一行,stop[\n])# 遇到换行就停止seed可重复性部分模型支持相同 seed 相同输入 相同输出。modelinit_chat_model(deepseek:deepseek-v4-flash,seed42,temperature0)参数速查表参数类型默认值何时使用temperaturefloat因模型而异任务需稳定性时 0~0.3需创造性时 0.7~1.0max_tokensint模型上限输出长度需要控制时timeoutint/floatNone生产环境建议始终设置max_retriesint因模型而异网络不稳定时建议 2~3base_urlstr官方地址使用代理、中转或本地服务时top_pfloat1.0需要核采样控制时替代 temperaturestoplist[str]无需要精确控制输出结尾时三、高级用法bind_tools()——让模型知道有哪些工具普通模型只能生成文本。调用bind_tools()后模型能在回复中返回tool_call告诉程序我需要调用这个工具.fromdotenvimportload_dotenv load_dotenv()fromlangchain.chat_modelsimportinit_chat_model modelinit_chat_model(deepseek:deepseek-v4-flash,temperature0)# 用字典描述工具OpenAI function calling 格式tools[{type:function,function:{name:get_weather,description:查询指定城市的天气,parameters:{type:object,properties:{city:{type:string,description:城市名称如 杭州、北京}},required:[city],},},}]# bind_tools() 将工具绑定到模型model_with_toolsmodel.bind_tools(tools)# 问一个需要工具的问题responsemodel_with_tools.invoke(杭州今天天气怎么样)ifresponse.tool_calls:print(模型请求调用以下工具)fortcinresponse.tool_calls:print(f 工具名:{tc[name]})print(f 参数:{tc[args]})print(f 调用ID:{tc[id]})运行结果模型请求调用以下工具 工具名: get_weather 参数: {city: 杭州} 调用ID: call_abc123def456⚠️ 重点bind_tools()只是告诉模型你有一个工具可以用模型返回的是工具调用的请求。真正的执行由 Agent 或你自己的代码来完成。3.1 用 Pydantic 模型描述工具对于复杂工具用 Pydantic 模型定义参数结构比手写字典更清晰frompydanticimportBaseModel,Fieldfromlangchain.chat_modelsimportinit_chat_modelclassWeatherInput(BaseModel):查询指定城市的天气情况city:strField(description城市名称如 杭州、北京)unit:strField(defaultcelsius,description温度单位celsius摄氏度或 fahrenheit华氏度)classCalculatorInput(BaseModel):执行数学计算expression:strField(description要计算的数学表达式如 (3 5) * 2)modelinit_chat_model(deepseek:deepseek-v4-flash,temperature0)model_with_toolsmodel.bind_tools([WeatherInput,CalculatorInput])responsemodel_with_tools.invoke(北京今天多少度顺便帮我算一下 123 * 456)print(f模型请求了{len(response.tool_calls)}个工具调用)fortcinresponse.tool_calls:print(f{tc[name]}({tc[args]}))使用 Pydantic 定义工具参数是推荐做法——类型安全、自动校验LangChain 会自动从类名和 Field 描述生成工具描述。四、高级用法with_structured_output()——让模型返回结构化数据with_structured_output()是比 tool_calling 更直接的方式。它让模型按你指定的 Schema 返回数据而不是返回 tool_call。frompydanticimportBaseModel,Fieldfromlangchain.chat_modelsimportinit_chat_modelclassPersonInfo(BaseModel):从文本中提取的人物信息name:strField(description人物姓名)age:intField(description年龄)occupation:strField(description职业)skills:list[str]Field(description技能列表)modelinit_chat_model(deepseek:deepseek-v4-flash,temperature0)structured_modelmodel.with_structured_output(PersonInfo)text张三今年28岁是一名全栈工程师精通 Python、React 和 Dockerresultstructured_model.invoke(text)print(f姓名:{result.name})print(f年龄:{result.age})print(f类型:{type(result)})# PersonInfo 实例返回值直接是 Pydantic 模型实例可用.name、.age等属性访问。4.1 with_structured_output() vs bind_tools() 对比这两个方法看起来相似但用途不同对比维度with_structured_output()bind_tools()用途从文本中提取结构化数据让模型知道可用的工具列表返回格式直接返回 Pydantic 对象返回 AIMessage其中包含 tool_calls适用场景信息提取、数据解析Agent 工具调用、需要外部执行的场景模型支持需模型支持原生 structured output所有支持 function calling 的模型4.2 嵌套结构化输出with_structured_output()支持复杂的嵌套结构frompydanticimportBaseModel,Fieldfromlangchain.chat_modelsimportinit_chat_modelclassIngredient(BaseModel):食材信息name:strField(description食材名称)amount:strField(description用量如 200g、2个)classCookingStep(BaseModel):烹饪步骤step_number:intField(description步骤编号)description:strField(description步骤描述)duration_minutes:intField(description此步骤需要的时间分钟)classRecipe(BaseModel):菜谱dish_name:strField(description菜名)difficulty:strField(description难度简单、中等、困难)ingredients:list[Ingredient]Field(description食材列表)steps:list[CookingStep]Field(description烹饪步骤)modelinit_chat_model(deepseek:deepseek-v4-flash,temperature0)structured_modelmodel.with_structured_output(Recipe)recipe_text今天来教大家做一道经典的番茄炒蛋......resultstructured_model.invoke(recipe_text)print(f菜名:{result.dish_name})print(f食材 ({len(result.ingredients)}种):)foringinresult.ingredients:print(f -{ing.name}:{ing.amount})print(f步骤 ({len(result.steps)}步):)forstepinresult.steps:print(f{step.step_number}.{step.description}({step.duration_minutes}分钟))4.3 JSON Schema 模式除了 Pydantic 模型也可以直接传入 JSON Schemajson_schema{title:SentimentAnalysis,description:情感分析结果,type:object,properties:{sentiment:{type:string,enum:[positive,negative,neutral],description:情感倾向},confidence:{type:number,description:置信度0~1},keywords:{type:array,items:{type:string},description:关键情感词},},required:[sentiment,confidence],}structured_modelmodel.with_structured_output(json_schema)resultstructured_model.invoke(菜鸟教程 RUNOOB 真的太棒了强烈推荐给所有编程新手)print(f情感:{result[sentiment]}| 置信度:{result[confidence]}| 关键词:{result[keywords]})JSON Schema 需要包含顶层title和description键返回的是字典而非 Pydantic 对象。五、总结你真正需要记住的 N 件事Chat Model 是 Agent 的地基model 负责说话bind_tools()/with_structured_output()是它的两个高级能力。temperature 控制随机度稳定任务用 0~0.3创意任务用 0.7~1.2但别同时调 temperature 和 top_p。max_tokens 是硬限制设置过低会句中截断按场景设 100-2000。生产环境必设 timeout max_retries推荐 30s 2~3 次重试。base_url 改端点、provider 定行为用代理/兼容接口/本地模型都靠它。bind_tools() 只是告知模型返回的是工具调用请求真正执行在 Agent 或你的代码里。with_structured_output() 直接给结构信息提取别绕弯从文本直接拿 Pydantic 对象。优先用 Pydantic 定义参数类型安全、自动校验、自动生成描述。验证清单我为任务选对了 temperature稳定用低值、创意用高值我设置了 max_tokens 控制输出长度且没设过低导致截断生产环境我设了 timeout 和 max_retries用代理/本地模型时我配了 base_url并确认 provider 兼容需要工具调用时我用 bind_tools()并清楚真正执行在我这边信息提取我用 with_structured_output()能拿到 Pydantic 对象或字典复杂结构我用嵌套 Pydantic 模型 / JSON Schema 定义参考资源LangChain 官方文档Models——https://docs.langchain.com/oss/python/langchain/modelsLangChain Referenceinit_chat_model——https://reference.langchain.com/python/langchain/chat_models菜鸟教程 LangChain 系列——https://www.runoob.com/langchain/
返回列表