给链加默认参数:.bind()
🎉摘要:本文介绍 LangChain Runnable 的 bind() 方法:为当前 Runnable 绑定固定运行参数并生成新 Runnable,后续 invoke/stream/batch 自动携带这些参数,调用方无需反复传入。常用于给 ChatModel 绑定模型参数、response_format 强制 JSON、工具、温度、top_p 等,并给出基础语法与 response_format 为 json_object 的示例。
所有 Runnable 都有的一个 bind() 方法,该方法用来给当前这个 Runnable 绑定固定的运行参数,生成一个新的 Runnable。后续每次对新 Runnable 调用 invoke /stream/batch 时,自动带上这些绑定好的参数,调用方不用反复传。
经常用来给 ChatModel 绑定模型参数、格式约束(response_format 强制 JSON)、工具、温度、top_p 等。
基础语法
new_runnable = runnable.bind(**kwargs)调用后返回一个全新的 Runnable,不会修改原来的对象,调用时使用全新的 Runnable 对象,不要使用旧对象。调用时如果传了同名参数,传入的会覆盖 bind 里绑定的参数。
简单示例
使用 bind() 设置模型 response_format 为 json_object:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
# 创建模型
llm = ChatOllama(model="qwen2:0.5b", temperature=0)
json_llm = llm.bind(response_format={"type": "json_object"})
# 提示词模板
prompt = ChatPromptTemplate.from_template("提取用户信息:{user}")
# 将上面模型、提示词、输出解析器三个 Runnable 串起来
chain = prompt | json_llm | StrOutputParser()
# 调用链
response = chain.invoke({"user": "张三 男 28岁,工作是程序员"})
print(response)运行结果:
{"user": "张三", "age": 28, "job": "程序员"}注意,bind 常用于给 ChatModel 绑定 stop、response_format、甚至绑定要调用的函数(function calling,第 6 章)。
说说我的看法
还可使用 Gitee / GitHub 账号一键登录,与大家分享你的观点
立即登录
全部评论()
没有评论