Agent工具系统——Tool Calling & Schema

目录

[一.Tool Calling 概念与 API 设计](#一.Tool Calling 概念与 API 设计)

[二.JSON Schema 设计基础(结构化参数)](#二.JSON Schema 设计基础(结构化参数))

[三.JSON Schema 现代化生成(Pydantic自动生成)](#三.JSON Schema 现代化生成(Pydantic自动生成))

四.参数验证策略与现代实践


一.Tool Calling 概念与 API 设计

本节理解 Tool Calling 的基本概念、 API 设计原则和应用场景
1. Tool Calling 基本概念
Tool Calling(原名Function Calling)是指 ⼤语⾔模型(LLM)能够理解⽤⼾意图并调⽤外部函数或⼯具的能⼒ 。这种能⼒让LLM从单纯的⽂本⽣成⼯具转变为可以执⾏实际任务的智能代理。
概念演变 :

  • OpenAI最初将此功能命名为"Function Calling"
  • 后来扩展为更通用的"Tools"概念,涵盖函数调用之外的更多功能

核心特点 :

  • 意图识别:LLM能理解用户的工具使用需求
  • 参数提取:自动从对话中提取函数参数
  • 函数执行:调用实际的代码函数
  • 结果整合:将函数结果整合到回复中

2. API 设计模式
OpenAI Tool Calling API 设计:

python 复制代码
{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "获取指定城市的天气信息",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "城市名称"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "温度单位"
        }
      },
      "required": ["city"]    必须要传入的参数
    }
  }
}

核心 API 组件 :
tools :工具定义列表
tool_choice :指定要调用的工具("auto" 、 "none" 或具体工具名)
messages :对话历史

提⽰
OpenAI 只是举例,⽬的是讲清楚概念和模式
OpenAI 是最早系统化提出并推⼴ Function Calling 范式的主流⼤模型⼚商
3. 应用场景分析
典型应用场景 :
1
信息查询 :天气、股票、新闻等实时数据
2
数据操作 :数据库查询、文件处理
3
外部服务调用 : API 接口、第三方服务
4
计算任务 :数学计算、数据分析
4. 工作流程


代码示例
先做一个简单了解即可,主要知道三个步骤:
1.定义一个工具类
2.写一个api范式
3.让大模型调用、理解、返回响应

uv init

uv venv .venv

python 复制代码
import json
import os

import openai
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


# 初始化OpenAI客户端
api_key = os.getenv("OPENAI_API_KEY")
base_url = os.getenv("OPENAI_API_BASE")

client = openai.OpenAI(api_key=api_key,base_url=base_url)

def get_weather(city: str, unit: str = "celsius") -> dict:
    """模拟天气查询函数"""
    # 这里应该是实际的天气API调用
    return {"temperature": 22, "condition": "sunny", "city": city}

# 工具定义(新版Tool格式)
weather_tool = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取指定城市的天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["city"]
        }
    }
}

def call_function_with_llm(user_query: str):
    """使用LLM进行函数调用的完整流程"""
    # 第一次调用大模型:让LLM根据用户问题判断是否需要调用工具
    '''
    你传 tools=[weather_tool] 是在告诉模型"你现在可以调用这些工具",
    这是一个集合,不是有先后顺序的流水线。模型拿到后,自己决定:
    *** 调不调用工具
    *** 调哪个工具
    *** 以什么顺序调
    '''
    response = client.chat.completions.create(
        model="GLM-5.3",  # 指定使用的大模型名称
        messages=[{"role": "user", "content": user_query}],  # 传入用户的问题
        tools=[weather_tool],  # 提供给LLM可用的工具列表
        tool_choice="auto"  # 让LLM自动决定是否调用工具
    )

    # tool_calls代表调用,stop代表没调用
    print(response.choices[0].finish_reason)

    # 检查是否需要调用工具:finish_reason 如果等于 tool_calls 说明LLM决定调用工具
    if response.choices[0].finish_reason == "tool_calls":
        # 取出LLM返回的所有工具调用请求
        tool_calls = response.choices[0].message.tool_calls

        # 用于保存每个工具调用的结果
        tool_call_results = []
        # 遍历每一个工具调用请求
        for tool_call in tool_calls:
            # 获取要调用的工具名称
            tool_name = tool_call.function.name
            # 解析LLM生成的参数(JSON字符串转字典)
            arguments = json.loads(tool_call.function.arguments)

            # 执行工具:根据工具名称分发到对应的函数
            '''
            当工具多时,不需要写的很多if,直接利用字典映射根据工具名称分发到对应的函数即可。
            '''
            if tool_name == "get_weather":
                # 调用天气函数,**arguments 将参数字典解包为关键字参数
                result = get_weather(**arguments)

            # 将工具执行结果追加到结果列表中
            tool_call_results.append({
                "tool_call_id": tool_call.id,  # 工具调用的唯一ID,用于关联响应
                "role": "tool",  # 消息角色标记为 tool
                "name": tool_name,  # 记录工具名称
                "content": json.dumps(result)  # 将结果序列化为JSON字符串作为内容
            })

        # 第二次调用大模型:将工具结果发送回LLM,让它生成最终的自然语言回复
        final_response = client.chat.completions.create(
            model="GLM-5.3",  # 指定使用的大模型名称
            messages=[
                {"role": "user", "content": user_query},  # 原始用户问题
                response.choices[0].message,  # 第一次LLM返回的(含工具调用请求的)消息
                *tool_call_results  # 解包并追加所有工具执行结果
            ]
        )
        # 返回最终回复的文本内容
        return final_response.choices[0].message.content

    # 如果LLM没有调用工具,直接返回第一次回复的文本内容
    return response.choices[0].message.content

if __name__ == "__main__":
    user_query = "北京今天的天气怎么样?"
    result = call_function_with_llm(user_query)
    print(result)

函数返回:

tool_calls
北京今天的天气情况如下:

**- **城市**:北京

  • **温度**:22°C
  • **天气状况**:晴 ☀️**

今天北京天气晴朗,温度适宜,非常适合外出活动!

未调用工具bug:

前几次执行的时候发现 print(response.choices0.finish_reason) 输出stop,即未调用我们自己编写的天气工具函数,后来换了几个不同的模型,发现这是模型的问题,之前用的模型是更适合处理视觉问题的模型,所以我更换了智谱最新推出的旗舰模型GLM-5.3,这时候模型就自动决定调用我自己写的天气函数了。所以要想让模型自己决策要调用哪些工具,还要选取合适模型。

二.JSON Schema 设计基础(结构化参数)

本节掌握 JSON Schema 的设计原则和参数结构化方法
1. JSON Schema 基础概念
JSON Schema是⽤于定义JSON数据结构的规范,它描述了数据的格式、类型和约束条件 。在Tool Calling中,JSON Schema⽤于定义⼯具参数的结构。
2. 核心数据类型
基本类型 :

  • string :字符串
  • number :数字(整数或浮点数)
  • integer :整数
  • boolean :布尔值
  • object :对象
  • array :数组
  • null :空值

3. 参数定义结构
完整的参数 Schema 结构 :

python 复制代码
{
  "type": "object",
  "properties": {
    "参数名": {
      "type": "数据类型",
      "description": "参数描述",
      "其他约束": "约束值"
    }
  },
  "required": ["必需参数列表"]
}

4. 约束条件详解
字符串约束 :

python 复制代码
{
    "type": "string",
    "minLength": 1,
    "maxLength": 100,
    "pattern": "^[a-zA-Z]+$",   #正则约束
    "enum": ["选项1", "选项2", "选项3"]
}

数值约束 :

python 复制代码
{
    "type": "number",
    "minimum": 0,
    "maximum": 100,
    "multipleOf": 0.5  #该数字除以 `0.5` 必须得到整数
}

数组约束 :

python 复制代码
{
    "type": "array",
    "items": {
       "type": "string"
    },
    "minItems": 1,
    "maxItems": 10,
    "uniqueItems": true  #元素唯一
}

5. 嵌套对象设计

python 复制代码
{
  "type": "object",
  "properties": {
    "user": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer", "minimum": 0 },
        "email": { "type": "string", "format": "email" }
      },
      "required": ["name", "email"]
    },
    "preferences": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": ["sports", "music", "reading"]
      }
    }
  },
  "required": ["user"]
}

上面的json scehma里有两个属性,分别是usre和preferences,其中user是必填项
代码示例

数据库查询函数的Schema设计

python 复制代码
# 数据库查询函数的Schema设计

database_query_schema = {
    "name": "query_database",
    "description": "执行数据库查询操作",
    "parameters": {
        "type": "object",
        "properties": {
            "table": {
                "type": "string",
                "description": "要查询的表名",
                "enum": ["users", "products", "orders"]
            },
            "columns": {
                "type": "array",
                "description": "要查询的列名列表",
                "items": {"type": "string"},
                "minItems": 1
            },
            "conditions": {
                "type": "object",
                "description": "查询条件",
                "properties": {
                    "column": {"type": "string"},
                    "operator": {
                        "type": "string",
                        "enum": ["=", ">", "<", ">=", "<=", "LIKE", "IN"]
                    },
                    "value": {
                        "oneOf": [
                            {"type": "string"},
                            {"type": "number"},
                            {"type": "boolean"}
                        ]
                    }
                }
            },
            "limit": {
                "type": "integer",
                "description": "查询结果限制数量",
                "minimum": 1,
                "maximum": 1000,
                "default": 100
            }
        },
        "required": ["table", "columns"]
    }
}

文件处理函数的Schema设计

python 复制代码
# 文件处理函数的Schema设计

file_operation_schema = {
    "name": "file_operation",
    "description": "执行文件操作",
    "parameters": {
        "type": "object",
        "properties": {
            "operation": {
                "type": "string",
                "enum": ["read", "write", "delete", "move"],
                "description": "文件操作类型"
            },
            "file_path": {
                "type": "string",
                "description": "文件路径",
                "pattern": "^(/[^/]+)+$"
            },
            "content": {
                "type": "string",
                "description": "写入的文件内容(write操作时必需)"
            },
            "encoding": {
                "type": "string",
                "enum": ["utf-8", "ascii", "latin-1"],
                "default": "utf-8",
                "description": "文件编码"
            }
        },
        "required": ["operation", "file_path"],
        "allOf": [
            {
                "if": {"properties": {"operation": {"const": "write"}}},
                "then": {"required": ["content"]}
            }
        ]
    }
}

三.JSON Schema 现代化生成(Pydantic自动生成)

本节 掌握使用 Pydantic 等现代工具自动生成 JSON Schema 的方法 ,理解类型驱动的开发方式

1. 为什么需要自动生成?
传统方式的局限性 :

  • 手动编写容易出错
  • 代码和Schema分离维护困难(因为代码和Schema是对应的,如果代码修改了,schema也要修改)
  • 类型不一致风险高
  • 开发效率低

现代化方案的优势 :

  • 类型安全:从Python类型注解自动生成
  • 代码即文档:类型定义同时提供验证和文档
  • 维护简单:修改类型自动更新Schema
  • 错误减少:编译时类型检查

2. Pydantic 基础回顾
官网: https://docs.pydantic.dev/2.12/
Pydantic 的核心特性 :

  • 基于类型注解的数据验证
  • 自动类型转换
  • 丰富的验证器支持
  • JSON Schema自动生成
    代码示例:
python 复制代码
import json
from enum import Enum
from typing import List, Optional  # noqa: UP035

from pydantic import BaseModel, Field, field_validator

'''
`class Priority(str, Enum):` 括号里**不是调用传参**,是【多继承】,`str`、`Enum` 是两个父类(基类)
- 继承 `Enum`:把它做成枚举,只能取这几个固定值,适合业务里优先级常量。
- 继承 `str`:让枚举成员同时是字符串,能直接和普通字符串比较、序列化(FastAPI 很常用这个写法;
Python3.11+ 官方也有 `StrEnum` 等价方案)Python。
- 效果:`Priority.LOW == "low"` 会返回 `True`,而普通 `Enum` 直接和字符串相等比较一般不行。

这种 `(str, Enum)` 顺序有讲究,是老式手动实现字符串枚举;
新版本优先用 `from enum import StrEnum; class Priority(StrEnum):`。

'''
class Priority(str,Enum):
    LOW = 'low'
    MEDIUM = 'medium'
    HIGH = 'high'

class TaskCreate(BaseModel):
    title:str = Field(description='任务标题',min_length=1,max_length=200)
    description : Optional[str] = Field(default=None,description='任务描述',max_length=2000)  # noqa: UP045
    priority : Priority=Field(description='优先级')
    '''
    default_factory=list:如果前端不传这个字段,就调用 `list()` 新建一个空列表作为默认值
    为什么不用default,因为列表是可变对象。所有实例会共享同一个列表对象,改一个,其他全都跟着变。

    `default_factory` 每次创建模型实例时都会执行一次 `list()`,生成独立的新列表,避免共享可变对象。

    - `default=xxx`:直接放一个固定值(适合 `str`、`int` 这类不可变值)
    - `default_factory=函数`:需要动态生成默认值(`list`、`dict`、自定义对象)

    - 不可变:`str` / `int` / `float` / `bool` / `tuple` → `default` 放心用;
    - 可变:`list` / `dict` / 自定义类实例 → 优先 `default_factory`。
    '''
    # 列表里最多有10个元素(标题)
    tags:List[str]=Field(default_factory=list,description='标题列表',max_length=10)  # noqa: UP006

    '''
    `@field_validator('title')` 是 Pydantic 的**字段校验装饰器**,`title_not_empty` 是自定义校验函数,
    作用是:在 Pydantic 自带规则(`min_length=1`)之外,再额外校验标题不能全是空格,并且自动把标题前后空格去掉。
    '''
    @field_validator('title')
    def title_not_empty(cls,v): #使用cls,而不是self,说明这是一个类方法,不是实例方法,所以不能使用self
        # `v` 就是传入到 `title` 的原始值
        if not v.strip():
            raise ValueError('标题不能为空')
        return v.strip()

# 自动生成schema
schema = TaskCreate.model_json_schema()
print(type(schema))
print()
print(schema,end='\n\n')
print('************************************',end='\n\n')

# 转换为JSON字符串
'''
`indent=2`:格式化缩进输出
输出 JSON 时,每一层嵌套用 **2 个空格**缩进,换行展示,方便人阅读。
`indent=None`(默认):输出压缩成一整行,没有换行缩进。

`ensure_ascii=False`:控制中文等非 ASCII 字符

- `ensure_ascii=True`(默认):中文会被转成 `\\uXXXX` 这类 unicode 转义序列;
- `ensure_ascii=False`:直接原样输出中文、日文等字符。
'''
print(json.dumps(schema,indent=2,ensure_ascii=False))

输出:

bash 复制代码
<class 'dict'>

{'$defs': {'Priority': {'enum': ['low', 'medium', 'high'], 'title': 'Priority', 'type': 'string'}}, 'properties': {'title': {'description': '任务标题', 'maxLength': 200, 'minLength': 1, 'title': 'Title', 'type': 'string'}, 'description': {'anyOf': [{'maxLength': 2000, 'type': 'string'}, {'type': 'null'}], 'default': None, 'description': '任务描述', 'title': 'Description'}, 'priority': {'$ref': '#/$defs/Priority', 'description': '优先级'}, 'tags': {'description': '标题列表', 'items': {'type': 'string'}, 'maxItems': 10, 'title': 'Tags', 'type': 'array'}}, 'required': ['title', 'priority'], 'title': 'TaskCreate', 'type': 'object'}

************************************

{
  "$defs": {
    "Priority": {
      "enum": [
        "low",
        "medium",
        "high"
      ],
      "title": "Priority",
      "type": "string"
    }
  },
  "properties": {
    "title": {
      "description": "任务标题",
      "maxLength": 200,
      "minLength": 1,
      "title": "Title",
      "type": "string"
    },
    "description": {
      "anyOf": [
        {
          "maxLength": 2000,
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "任务描述",
      "title": "Description"
    },
    "priority": {
      "$ref": "#/$defs/Priority",
      "description": "优先级"
    },
    "tags": {
      "description": "标题列表",
      "items": {
        "type": "string"
      },
      "maxItems": 10,
      "title": "Tags",
      "type": "array"
    }
  },
  "required": [
    "title",
    "priority"
  ],
  "title": "TaskCreate",
  "type": "object"
}

回头看看刚开始写的智能体调用天气工具的小demo,其中的天气工具的schema,其中的主要部分现在都可以自动生成了,如下图所示:

红框圈出的部分都可以自动生成,所以我们只需要将剩余部分补充完整即可。
4. 高级 Field 约束
数值约束 :

python 复制代码
from pydantic import BaseModel, Field
from decimal import Decimal

class ProductSearch(BaseModel):
    query: str = Field(description="搜索关键词")
    min_price: Optional[Decimal] = Field(default=None, description="最低价格", ge=0)
    max_price: Optional[Decimal] = Field(default=None, description="最高价格", ge=0)
    limit: int = Field(default=20, description="返回数量", ge=1, le=100)
    sort_by: str = Field(
        default="relevance",
        description="排序方式",
        # 只能取下面四个值
        pattern="^(relevance|price_asc|price_desc|rating)$"
        # 相关性|价格升序|价格降序|评分
    )

日期时间约束 :

python 复制代码
from datetime import datetime, date
from pydantic import BaseModel, Field
from typing import Optional

class EventQuery(BaseModel):
    start_date: date = Field(description="开始日期")
    end_date: Optional[date] = Field(default=None, description="结束日期")
    include_past: bool = Field(default=False, description="包含过去事件")

    def model_post_init(self, __context):
        if self.end_date and self.start_date > self.end_date:
            raise ValueError("开始日期不能晚于结束日期")

5. 嵌套模型设计
复杂嵌套结构 :

python 复制代码
from pydantic import BaseModel, Field
from typing import List, Optional


class Address(BaseModel):
    street: str = Field(description="街道地址")
    city: str = Field(description="城市")
    country: str = Field(description="国家", default="中国")
    postal_code: Optional[str] = Field(default=None, description="邮政编码")


class ContactInfo(BaseModel):
    email: str = Field(description="邮箱地址")
    phone: Optional[str] = Field(default=None, description="电话号码")
    address: Address = Field(description="地址信息")


class UserProfile(BaseModel):
    username: str = Field(description="用户名", min_length=3, max_length=50)
    full_name: str = Field(description="全名")
    age: Optional[int] = Field(default=None, description="年龄", ge=0, le=150)
    contacts: ContactInfo = Field(description="联系方式")
    preferences: List[str] = Field(default_factory=list, description="偏好设置")

6. 与 Function Calling 集成

现在我们只需要将不能生成的部分也创建一个工具使其自动生成即可,就能得到完整的schema了!
自动生成工具 Schema :

python 复制代码
import json
from typing import List, Optional  # noqa: UP035

from pydantic import BaseModel, Field


class DatabaseQuery(BaseModel):
    table: str = Field(description="要查询的表名", json_schema_extra=["users", "products", "orders"])
    columns: List[str] = Field(description="要查询的列名列表", min_length=1)  # noqa: UP006
    where_clause: Optional[str] = Field(default=None, description="WHERE条件")  # noqa: UP045
    limit: int = Field(default=100, description="返回记录数量", ge=1, le=1000)
    order_by: Optional[str] = Field(default=None, description="排序字段")  # noqa: UP045

def query_database(params: DatabaseQuery) -> dict:
    """执行数据库查询"""
    # 实现查询逻辑
    return {"status": "success", "data": []}

# 自动生成工具定义,这里可以比对之前写过的weather_tool
def create_tool_definition(func, param_model):
    return {
        "type": "function",
        "function": {
            "name": func.__name__,
            "description": func.__doc__ or f"Execute {func.__name__}",
            "parameters": param_model.model_json_schema()
        }
    }

# 使用示例,创建大模型实例时,传给大模型实例的tools参数
tools = [create_tool_definition(query_database, DatabaseQuery)]

print(json.dumps(create_tool_definition(query_database, DatabaseQuery),indent=2,ensure_ascii=False))

输出:

python 复制代码
{
  "type": "function",
  "function": {
    "name": "query_database",
    "description": "执行数据库查询",
    "parameters": {
      "properties": {
        "table": {
          "description": "要查询的表名",
          "title": "Table",
          "type": "string"
        },
        "columns": {
          "description": "要查询的列名列表",
          "items": {
            "type": "string"
          },
          "minItems": 1,
          "title": "Columns",
          "type": "array"
        },
        "where_clause": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "WHERE条件",
          "title": "Where Clause"
        },
        "limit": {
          "default": 100,
          "description": "返回记录数量",
          "maximum": 1000,
          "minimum": 1,
          "title": "Limit",
          "type": "integer"
        },
        "order_by": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "排序字段",
          "title": "Order By"
        }
      },
      "required": [
        "table",
        "columns"
      ],
      "title": "DatabaseQuery",
      "type": "object"
    }
  }
}

**7.**最佳实践和注意事项
类型设计原则 :

  • 使用具体的类型而不是Any
  • 为所有字段添加description
  • 合理使用约束条件
  • 保持模型的单一职责

四.参数验证策略与现代实践

理解参数验证的重要性
如何选择合适的验证策略
参数验证流程

1. AI 平台的验证机制
理解 AI 平台的角色 :

  • OpenAI/Claude等平台内置JSON Schema验证
  • 参数格式错误时,AI会收到反馈并重新生成
  • 大多数简单场景下不需要额外验证
python 复制代码
# AI平台的工作流程
# 1. 用户请求 → AI生成参数 → 平台验证Schema → 调用工具
# 2. 如果验证失败 → AI收到错误 → 重新生成参数
# 开发者视角:参数通常已经是正确格式
def get_weather(city: str, unit: str = "celsius"):
   # 大多数情况下可以直接使用
   return call_weather_api(city, unit)

2. 选择验证策略
何时需要验证?何时不需要?
✅ 需要验证的场景 :

  • 关键业务系统:金融、医疗、交易系统
  • 外部API调用:参数需要符合第三方API规范
  • 复杂业务逻辑:涉及多重依赖的参数关系
  • 用户输入处理:直接来自用户的未经验证数据

❌ 不需要验证的场景 :

  • 简单工具调用:参数格式简单,相信AI生成
  • 内部服务:参数来自可信的内部系统
  • 原型开发:快速验证功能为主
    验证策略选择 :
python 复制代码
# 策略1:信任AI(最常见)
def simple_tool(params):
    return my_function(**params)


# 策略2:基本类型检查
def basic_validation(params):
    if not isinstance(params.get('city'), str):
        raise ValueError("city必须是字符串")
    return my_function(**params)


# 策略3:使用Pydantic(推荐)
class ToolParams(BaseModel):
    city: str
    limit: int = Field(ge=1, le=100)

def pydantic_validation(params_dict):
    params = ToolParams(**params_dict)
    return my_function(params.city, params.limit)


# 策略4:完整验证(关键系统)
def full_validation(params_dict):
    # 多层次验证 + 业务规则 + 安全检查,即传入一个专门的验证函数来验证
    validated = comprehensive_validator(params_dict)
    return my_function(**validated)

3. 现代工具与框架
Pydantic 集成 :

python 复制代码
from pydantic import BaseModel, Field, ValidationError
from typing import Optional


class DatabaseQuery(BaseModel):
    table: str = Field(description="表名")
    limit: int = Field(default=10, ge=1, le=1000)
    filters: Optional[dict] = None

    def execute(self):
        # 参数已自动验证
        return db.query(self.table, self.limit, self.filters)


# 直接使用,异常会自动抛出
try:
    query = DatabaseQuery(table="users", limit=50)
    result = query.execute()
except ValidationError as e:
    print(f"参数错误:{e}")

LangChain 工具装饰器:

python 复制代码
from langchain.tools import tool
from langchain_core.tools import ToolException

@tool
def search_database(query: str, limit: int = 10) -> str:
    """搜索数据库

    Args:
        query: 搜索关键词
        limit: 返回数量 (1-100)
    """
    # LangChain会自动验证参数类型和范围
    if len(query) < 2:
        raise ToolException("搜索关键词太短")
    return db.search(query, limit)

**4.**实际项目案例
案例 1 :电商搜索工具

python 复制代码
# 简单场景:相信AI参数
@tool
def search_products(query: str, category: str = None) -> str:
   """搜索产品"""
   # AI通常会生成合理参数,直接使用
   return product_db.search(query, category)

案例 2 :金融交易工具

python 复制代码
from pydantic import BaseModel, Field, model_validator
from decimal import Decimal

# 关键场景:全方位验证
class TransferParams(BaseModel):
    from_account: str = Field(pattern=r'^\d{10}$')
    to_account: str = Field(pattern=r'^\d{10}$')
    amount: Decimal = Field(ge=0.01, le=1000000)
    description: str = Field(max_length=100)

    @model_validator(mode='after')
    def validate_accounts(self):
        if self.from_account == self.to_account:
            raise ValueError("转出和转入账户不能相同")
        return self


@tool
def transfer_money(params: TransferParams) -> str:
    """转账功能"""
    # 所有验证已完成,直接执行业务逻辑
    return banking_system.transfer(
        params.from_account,
        params.to_account,
        params.amount,
        params.description
    )

案例3:API代理工具

python 复制代码
# 中等场景:适度验证
def call_external_api(endpoint: str, params: dict) -> dict:
    """调用外部API"""

    # 基本验证
    if not endpoint.startswith('/api/'):
        raise ValueError("无效的API端点")

    # 转换参数格式(如果需要)
    api_params = convert_params_for_external_api(params)

    # 调用外部API
    return requests.post(f"https://api.example.com{endpoint}", json=api_params)

最佳实践

  • 从简单开始:先假设参数正确,逐步添加必要验证
  • 选择合适工具:Pydantic > 手动验证 > 无验证
  • 分层验证:输入验证 → 业务验证 → 安全验证
  • 性能考虑:避免过度验证影响响应速度
  • 错误友好:提供清晰、可操作的错误信息
相关推荐
深海鱼肝油ya12 分钟前
LangChain(一)概念&初识
langchain·大模型·llm·agent·思维链·智能体
雨中飘荡的记忆23 分钟前
一个人、两个 AI,我做出了一张可以点亮的中国美食地图
人工智能·后端
邂逅and回眸34 分钟前
TinyML 入门:KB 级内存里怎么跑神经网络
人工智能·深度学习·神经网络
tellmewhoisi42 分钟前
深度学习1番外篇:sigmoid为啥比Tanh收敛的慢
人工智能·深度学习
落羽的落羽1 小时前
【C++】现代容器: tuple、optional、variant、any、string_view
linux·开发语言·数据结构·c++·人工智能·计算机网络·算法
电科_银尘1 小时前
【大模型算法与工程 38】RLHF与奖励模型:偏好如何变成训练信号
人工智能·算法·机器学习
Microvision维视智造1 小时前
焊缝好不好,用数据说了算 | 激光焊接 3D 视觉检测方案
人工智能·计算机视觉·3d·机器人·视觉检测·机器视觉
MobotStone1 小时前
AI为什么会越来越聪明?
人工智能
AI创界者1 小时前
Python 进阶实战(六十二章):分布式定时任务、异步工作流与幂等补偿机制实战
人工智能·python·aigc