跳转到主要内容

LangChain

15 · Function Calling

让模型调用你的函数

  • LangChain
  • Python

本节速览

这一节的每一块内容,分别是干什么的:

内容是干什么的
tool() 定义工具把普通函数变成模型可调用的工具
响应结构与调用流程tool_call 怎么往返:模型要 → 代码执行 → 结果回传
tool_choice自动 / 强制指定 / 禁用三种控制模式
并行调用一次对话模型同时要多个工具的结果
with_structured_output借 function calling 做打标签、信息提取

Function Calling(OpenAI 已更名为 tools)让 LLM 在合适的时机返回「要调用哪个函数、传什么参数」,由应用层执行函数并回传结果,LLM 再据此生成回答。本章先讲 provider 层的协议(与 LangChain 版本无关),再讲 LangChain 的封装。

工具描述结构(原生 API)

没有它会怎样——模型只能输出文本:你说「查下北京天气」,它要么说「我查不了」,要么当场编一个「晴,15℃」——编得跟真的一样。

有了它——函数注册给模型后,模型不答题改发结构化 tool_call:「调 get_weather,参数 city=北京」,真假数据由你的代码说了算。

向 LLM 注册函数,按 OpenAI 兼容格式提供描述对象(智谱、DeepSeek、Kimi、各类中转站都遵循这套结构):

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

六个关键字段:type(目前只支持 "function")、function、name(执行时分发的依据)、description(模型判断「是否调用、何时调用」的唯一信息来源,必须写清效果)、parameters(JSON Schema)、required。description 用英文书写不影响中文提问的识别。

响应结构与完整调用流程

没有它会怎样——不看懂往返结构:拿不到 tool_calls 里的参数、回传格式不对,模型下一轮直接报「工具结果格式错误」,整条链卡死。

有了它——按「模型要 → 你执行 → 结果回传」三步循环,直到模型给出最终答复。

模型决定调用工具时,返回 finish_reason="tool_calls",意图在 message.tool_calls 里:

{
    "finish_reason": "tool_calls",
    "message": {
        "content": None,
        "tool_calls": [
            {
                "id": "call_xxxxx",          # 回传结果时要用
                "function": {
                    "name": "get_current_weather",
                    "arguments": '{\n  "location": "Beijing"\n}',
                },
            },
        ],
    },
}

最大的坑:arguments 是 JSON 字符串,不是对象。 执行前必须 json.loads。完整调用流程共四条消息,按序追加后再次请求:

import json   # 解析 arguments 字符串
import os   # 读取环境变量

from dotenv import load_dotenv   # 从 .env 读环境变量
from openai import OpenAI   # OpenAI SDK:智谱直连与中转站都是 OpenAI 兼容协议

load_dotenv()

client = OpenAI(
    base_url=os.environ["GLM_BASE_URL"],   # 智谱直连或中转站的接口地址
    api_key=os.environ["GLM_API_KEY"],
)
model_id = os.environ["GLM_MODEL_ID"]      # 服务方提供的模型名


def get_current_weather(location: str, unit: str = "fahrenheit") -> str:
    """真实项目里这里调天气 API,演示直接返回固定值。"""
    return json.dumps({"location": location, "temperature": "22", "unit": unit})


# 分发表:工具名 → 函数(tools 的 JSON 描述见上一节)
functions = {"get_current_weather": get_current_weather}

messages = [{"role": "user", "content": "北京的天气怎么样?"}]
result = client.chat.completions.create(
    model=model_id,
    messages=messages,
    tools=[{                       # 工具描述,结构见上一节
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }],
)

if result.choices[0].finish_reason != "tool_calls":
    print(result.choices[0].message.content)        # 分支:模型直接回答
else:
    messages.append(result.choices[0].message)       # 1. assistant(tool_calls) 先入列
    for tool_call in result.choices[0].message.tool_calls:
        args = json.loads(tool_call.function.arguments)   # 2. 关键:解析 JSON 字符串
        output = functions[tool_call.function.name](**args)
        messages.append({
            "tool_call_id": tool_call.id,            # 3. 必须与 tool_calls[].id 对应
            "role": "tool",
            "name": tool_call.function.name,
            "content": output,
        })
    response = client.chat.completions.create(       # 4. 带工具结果再请求一次
        model=model_id, messages=messages,
    )
    print(response.choices[0].message.content)       # 模型基于工具结果给出最终回答

tool 消息的 tool_call_id 必须与 tool_calls[].id 一一对应;assistant(tool_calls) 消息必须先于 tool 消息入列,否则 API 报错。这套循环手写约 40 行,LangChain 的 agent 就是把它自动化。

tool_choice:三种控制模式

没有它会怎样——默认自动模式:做分类打标签时模型兴致来了直接回一段文字而不调工具,下游等着接结构化对象,接到的是 None,程序崩。

有了它——tool_choice="required" 或指定函数名,模型必须走工具,输出永远结构化。

tool_choice = "none"    # 禁止调用,只输出文本
tool_choice = "auto"    # 默认,模型自主决定
tool_choice = {"type": "function", "function": {"name": "get_current_weather"}}  # 强制调用

强制调用时,即使输入完全不相关,模型也会返回 tool_calls,代价是编造参数(凭空补出 "location": "上海")。这个「缺陷」正是结构化输出的基础:输入不需要包含函数所需信息,模型也会补全出完整的结构化参数。

三种模式的实际返回对比:

import os   # 读取环境变量
from dotenv import load_dotenv   # 从 .env 读环境变量
from langchain.tools import tool   # 工具定义装饰器
from langchain_openai import ChatOpenAI   # OpenAI 聊天模型

load_dotenv()

@tool
def get_current_weather(location: str) -> str:
    """Get the current weather in a given location."""
    return '{"temperature": "22", "unit": "celsius"}'

model = ChatOpenAI(
    base_url=os.environ["GLM_BASE_URL"],
    api_key=os.environ["GLM_API_KEY"],
    model=os.environ["GLM_MODEL_ID"],
    temperature=0,   # 工具调用要稳定,温度调低
)

tools = [get_current_weather]

# 默认 auto:模型自主决定,问天气就调工具
model.bind_tools(tools).invoke("北京的天气怎么样")
# tool_calls=[{"name": "get_current_weather", "args": {"location": "Beijing", ...}}]

# none:禁止调用,模型用文本反问
model.bind_tools(tools, tool_choice="none").invoke("北京的天气怎么样")
# content="请问您需要当前天气还是预报?"(finish_reason="stop")

# 强制调用:输入无关也会调,参数是模型补全的
model.bind_tools(tools, tool_choice="get_current_weather").invoke("你好")
# tool_calls=[{"name": "get_current_weather", "args": {"location": "上海"}}]  ← 参数编的

并行调用

没有它会怎样——要查三个城市天气,老老实实三轮对话,一轮 2 秒等 6 秒,轮次多 token 也多。

有了它——一次响应返回多个 tool_call,代码里并行执行、一遍回传,时间和轮次都省。

tools 支持一次返回多个调用(「同时告诉我时间和天气」可能返回两个 tool_calls)。工程结论:

  • 多函数之间的选择是稳定的,可以放心提供多个工具;
  • 一次返回多个调用并不稳定。按「一轮调用一个工具」兜底,批量需求靠函数参数设计(如接受城市数组)解决。

Tools:用 tool() 定义工具

没有它会怎样——原生写法手搓 JSON Schema:name / type / description / properties 一层套一层,十几行才能描述一个两参数函数,字段拼错模型就调不对。

有了它——@tool 装饰器 + 类型注解 + docstring,Schema 自动生成,定义工具就是写普通函数。

Tools 是 LangChain 的工具抽象:把函数、API、数据库、搜索等能力连同参数约束一起声明给模型或 Agent。function calling 是协议层,tool()(来自 langchain 包)是这套抽象在 1.x 的入口。pydantic 模型描述输入,类型、required、enum 全部由 pydantic 生成:

from langchain_openai import ChatOpenAI   # OpenAI 聊天模型
import os   # 读取环境变量
from dotenv import load_dotenv   # 从 .env 读环境变量
import json   # 序列化工具返回值
from typing import Literal   # 枚举类型注解
from pydantic import BaseModel, Field   # 数据模型与字段描述
from langchain.tools import tool   # 工具定义装饰器

load_dotenv()

llm = ChatOpenAI(
    base_url=os.environ["GLM_BASE_URL"],
    api_key=os.environ["GLM_API_KEY"],
    model=os.environ["GLM_MODEL_ID"],
)

class GetCurrentWeather(BaseModel):
    location: str = Field(description="The city and state, e.g. San Francisco, CA")
    unit: Literal["celsius", "fahrenheit"] = Field(description="The unit of temperature")

def _get_current_weather(location: str, unit: str = "fahrenheit") -> str:
    return json.dumps({"location": location, "temperature": "72", "unit": unit})

get_current_weather = tool(
    _get_current_weather,
    name="get_current_weather",
    description="Get the current weather in a given location",
    args_schema=GetCurrentWeather,
)

model_with_tools = llm.bind_tools([get_current_weather])

res = model_with_tools.invoke("北京的天气怎么样")
for tool_call in res.tool_calls or []:
    print(tool_call["name"])   # "get_current_weather"
    print(tool_call["args"])   # {"location": "Beijing", "unit": "celsius"}

与原生 API 的关键差异:tool_call["args"] 已经是对象,原生 arguments 是 JSON 字符串要手动解析的坑,框架已处理。工具名建议 snake_case(LLM 训练语料的惯例)。

调用行为的控制:

import os   # 读取环境变量
from dotenv import load_dotenv   # 从 .env 读环境变量
from langchain.tools import tool   # 工具定义装饰器
from langchain_openai import ChatOpenAI   # OpenAI 聊天模型

load_dotenv()

@tool
def tool_a(query: str) -> str:
    """Search the knowledge base."""
    return "知识库检索结果"

@tool
def tool_b(query: str) -> str:
    """Query the database."""
    return "数据库查询结果"

model = ChatOpenAI(
    base_url=os.environ["GLM_BASE_URL"],
    api_key=os.environ["GLM_API_KEY"],
    model=os.environ["GLM_MODEL_ID"],
    temperature=0,
)

model.bind_tools([tool_a, tool_b])               # 模型自主决定(默认)
model.bind_tools([tool_a], tool_choice="any")    # 强制调用任意一个
model.bind_tools([tool_a], tool_choice="tool_a") # 强制调用指定名字

bind_tools 返回新 Runnable,可直接 pipe 进任何 LCEL 链。

with_structured_output:打标签与信息提取

没有它会怎样——prompt 约束「输出 pos 或 neg」,模型回「积极(偏正面)」;你 split 不了,词表越维护越乱。

有了它——pydantic 的 Literal["pos", "neg"] 硬约束,输出只能是枚举之一,词表天然闭合。

打标签和提取不需要实现函数,要的就是模型输出的结构化参数本身。用 with_structured_output 一步完成:

from langchain_openai import ChatOpenAI   # OpenAI 聊天模型
import os   # 读取环境变量
from dotenv import load_dotenv   # 从 .env 读环境变量
from typing import Literal   # 枚举类型注解
from pydantic import BaseModel, Field   # 数据模型与字段描述
from langchain_core.prompts import ChatPromptTemplate   # 带角色的消息模板

load_dotenv()

llm = ChatOpenAI(
    base_url=os.environ["GLM_BASE_URL"],
    api_key=os.environ["GLM_API_KEY"],
    model=os.environ["GLM_MODEL_ID"],
)

class Tagging(BaseModel):
    emotion: Literal["pos", "neg", "neutral"] = Field(description="文本的情感")
    language: str = Field(description="文本的核心语言(ISO 639-1 代码)")

chain = ChatPromptTemplate.from_messages([
    {"role": "system", "content": "仔细思考,你有充足的时间进行严谨的思考,然后按照指示对文本进行标记"},
    {"role": "human", "content": "{input}"},
]).pipe(llm.with_structured_output(Tagging))

chain.invoke({"input": "我非常喜欢 AI,特别是 LLM"})
# Tagging(emotion='pos', language='zh')

信息提取与打标签同构,区别是 schema 更复杂:嵌套对象、数组、可选字段:

from pydantic import BaseModel, Field   # 数据模型与字段描述


class Person(BaseModel):
    """提取关于一个人的信息"""

    name: str = Field(description="人的名字")
    age: int | None = Field(default=None, description="人的年龄")


class Relation(BaseModel):
    people: list[Person] = Field(description="提取所有人")
    relation: str = Field(description="人之间的关系,尽量简洁")

要点:

  • 防幻觉靠两层:schema 层用 int | None 允许字段缺失,prompt 层写明「没有明确提供就不要猜测,可以只提取部分信息」。
  • 类的 docstring 会进入 JSON Schema 的 description,帮助模型理解嵌套对象语义。
  • system prompt 里「仔细思考」这类措辞是经验性技巧,对结构化输出任务值得保留。
  • 这是 zero-shot 能力:只靠 schema 描述即可完成,无需训练。

下一步:把工具调用的循环交给图自动执行——先手写(LangGraph 基础),再用 create_agent(Agent)。


上一节:记忆系统 · 下一节:LangGraph 基础