一文带你掌握LangChain中的bind,打造更聪明的智能应用

Bind

单一函数模式

bind 是 LangChain Expression Language(LCEL)中的一个关键方法,用于将模型与外部函数调用进行绑定

你可以把它理解为:我提前告诉模型「你可以调用这些函数,并且它们的功能和参数是这样的」,模型在生成回答时就可以按需触发函数调用,而不是只是给你一个文本答案。

我们还是拿前两节课Function Call里天气查询的例子进行演示:

functions = [
    {
      "name": "weather_search",
      "description": "Search for weather given an airport code",
      "parameters": {
        "type": "object",
        "properties": {
          "airport_code": {
            "type": "string",
            "description": "The airport code to get the weather for"
          },
        },
        "required": ["airport_code"]
      }
    }
  ]

假如我们想要指定大模型的任务是调查天气的话,我们就可以在设置的语言模型后面加上.bind(functions=functions)来告诉模型它可以使用这个函数(这里有一个前提就是model要使用ChatOpenAI的方式,而非前面使用的ChatTongyi,这是因为ChatTongyi并不支持OpenAI格式的Function Call,当然这个api_key写入的还是阿里云百炼大模型的api_key):

prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}")
    ]
)

# 初始化通义千问模型
model = ChatOpenAI(
    model="qwen-turbo",
    openai_api_key='你的api_key',
    openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1"
).bind(functions=functions)

runnable = prompt | model

response = runnable.invoke({"input": "广州"})

print(response)

模型会自动解析你的意图,并生成一个 function call,调用 weather_search。当然由于我们这里并没有真正写入这个函数,所以我们看到终端里并没有真正的显示结果。但是我们可以从输入内容中看到确实调用了Function Call且传入了关键词”CAN“。

content='' additional_kwargs={'function_call': {'arguments': '{"airport_code": "CAN"}', 'name': 'weather_search'}} response_metadata={'token_usage': {'completion_tokens': 18, 'prompt_tokens': 176, 'total_tokens': 194, 'completion_tokens_details': None}, 'model_name': 'qwen-turbo', 'system_fingerprint': None, 'finish_reason': 'function_call', 'logprobs': None} id='run-6cc1d1d8-aa12-4611-96ba-7c53570b9ce5-0'

多函数模式

当然我们也可以尝试使用多函数的模式,比如我们多写入一个sport_search的内容:

functions = [
    {
      "name": "weather_search",
      "description": "Search for weather given an airport code",
      "parameters": {
        "type": "object",
        "properties": {
          "airport_code": {
            "type": "string",
            "description": "The airport code to get the weather for"
          },
        },
        "required": ["airport_code"]
      }
    },
        {
      "name": "sports_search",
      "description": "Search for news of recent sport events",
      "parameters": {
        "type": "object",
        "properties": {
          "team_name": {
            "type": "string",
            "description": "The sports team to search for"
          },
        },
        "required": ["team_name"]
      }
    }
  ]

模型将会根据你的问题内容,智能选择调用哪个函数。例如:

  • 输入:“What’s the weather in LAX?” → 调用 weather_search
  • 输入:“How did the Lakers do yesterday?” → 调用 sports_search

这就是“工具智能体”(Tool-using Agent)的雏形。

我们使用类似的方法调用一下:

# 初始化通义千问模型
model = ChatOpenAI(
    model="qwen-turbo",
    openai_api_key='你的api_key',
    openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1"
).bind(functions=functions)

runnable = prompt | model

response = runnable.invoke({"input": "昨天中国队赢了吗?"})

print(response)

这个时候我们就能看到结果不单单是调用天气了,而是使用的是运动相关的搜索工具了。

content='' additional_kwargs={'function_call': {'arguments': '{"team_name": "China"}', 'name': 'sports_search'}} response_metadata={'token_usage': {'completion_tokens': 18, 'prompt_tokens': 248, 'total_tokens': 266, 'completion_tokens_details': None}, 'model_name': 'qwen-turbo', 'system_fingerprint': None, 'finish_reason': 'function_call', 'logprobs': None} id='run-d8379e2d-a8c0-4074-bffa-886d7e588926-0'

完整代码如下所示:

from langchain_community.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

functions = [
    {
      "name": "weather_search",
      "description": "Search for weather given an airport code",
      "parameters": {
        "type": "object",
        "properties": {
          "airport_code": {
            "type": "string",
            "description": "The airport code to get the weather for"
          },
        },
        "required": ["airport_code"]
      }
    },
        {
      "name": "sports_search",
      "description": "Search for news of recent sport events",
      "parameters": {
        "type": "object",
        "properties": {
          "team_name": {
            "type": "string",
            "description": "The sports team to search for"
          },
        },
        "required": ["team_name"]
      }
    }
  ]

prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}")
    ]
)
# 初始化通义千问模型
model = ChatOpenAI(
    model="qwen-turbo",
    openai_api_key='你的api_key',
    openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1"
).bind(functions=functions)

runnable = prompt | model

response = runnable.invoke({"input": "广州"})

print(response)

response = runnable.invoke({"input": "昨天中国队赢了吗?"})\

print(response)

小结

总的来说,使用 bind,你就可以轻松把模型变成“带工具的智能助手”:

  • 会听(理解输入)
  • 会说(自然语言生成)
  • 会做(函数调用)

无论你是在构建 AI 应用、聊天机器人,还是自动化助手,bind 都能帮你少写逻辑代码、多用大模型“自由发挥”。

下一步?你可以把这个能力接入你自己的搜索接口、数据库查询、系统操作,开启真正的智能化工作流!

– 完 –

机智流推荐阅读

\1. QCon 全球软件开发大会 | 与全球 140+ 顶尖工程师共同解构 AI 时代的技术浪潮

\2. 从零开始打造自己的Manus:学学如何使用 LangChain 快速构建 AI Agent

\3. LangChain 实战案例:使用 RAG 技术搭建商品快速查询系统

\4. 掌握如何搭建高效的大模型任务流(三):如何完成LangChain动态任务分发

欢迎在“机智流”公众号后台回复“cc”,加入机智流大模型交流群,与我们一起探索 AI 与人类潜能的未来,一起共赴 AI 浪潮!

img机智流共赴 AI 时代浪潮~587篇原创内容公众号

img

机智流科技

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

剑锋小课堂25

剑锋小课堂 · 目录

上一篇Manus等一众产品看得眼花缭乱?教你5行代码用LangChain构建AI工作流

阅读 134

写留言