尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

swarm 智能体函数如何自动转换为 Chat Completions tools 的 JSON Schema

swarm 智能体函数如何自动转换为 Chat Completions tools 的 JSON Schema swarm 智能体函数如何自动转换为 Chat Completions tools 的 JSON Schema【免费下载链接】swarmEducational framework exploring ergonomic, lightweight multi-agent orchestration. Managed by OpenAI Solution team.项目地址: https://gitcode.com/GitHub_Trending/swarm6/swarm在 Swarm 中给Agent挂载 Python 函数后模型能直接调用它们但你并不需要自己手写 Chat Completions 的tools参数——Swarm 会把每个函数自动转换成一段 JSON Schema随每次chat.completions.create()请求发给模型。本文的目标是搞清楚这次转换的完整规则docstring、类型注解、默认值各变成什么并给出两条验证路径不依赖 API 直接检查生成的 Schema以及用execute_toolsFalse观察模型实际发出的tool_calls。前提是 Python 3.10并从源码安装框架pip install githttps://github.com/openai/swarm.git转换规则function_to_json 做了什么转换逻辑集中在 function_to_json它读取函数的签名和文档字符串返回 Chat Completionstools要求的那种字典结构。README 的 Function Schemas 一节给出了四条规则与源码一一对应函数名func.__name__成为function.name函数的 docstring 整体成为function.description没有 docstring 时是空字符串没有默认值的参数进入parameters.required类型注解映射到参数的type未标注或标注了未知类型的参数一律按string处理。源码中的类型映射表swarm/util.py为Python 类型JSON Schema typestrstringintintegerfloatnumberboolbooleanlistarraydictobjectNoneTypenullREADME 同时说明单参数级的description目前不支持显式声明但如果把说明写进 docstring例如Args:小节这些文字会随整个 docstring 一起进入description模型同样能读到。完整示例从函数到 tools 结构下面这段代码来自 README.md 的 Function Schemas 一节定义了带 docstring 的greet函数并调用function_to_jsonimport json from swarm.util import function_to_json def greet(name, age: int, location: str New York): Greets the user. Make sure to get their name and age before calling. Args: name: Name of the user. age: Age of the user. location: Best place on earth. print(fHello {name}, glad you are {age} in {location}!) print(json.dumps(function_to_json(greet), indent2, ensure_asciiFalse))README 给出的对应输出文档示例{ type: function, function: { name: greet, description: Greets the user. Make sure to get their name and age before calling.\n\nArgs:\n name: Name of the user.\n age: Age of the user.\n location: Best place on earth., parameters: { type: object, properties: { name: {type: string}, age: {type: integer}, location: {type: string} }, required: [name, age] } } }注意三个细节未标注类型的name落到string有默认值的location不在required里Args:小节没有被单独解析而是原样留在description文本中。context_variables 参数会被隐藏如果函数定义了context_variables参数Swarm 会在调用时把client.run()传入的context_variables注入进去README Functions 一节但这个参数不会暴露给模型。swarm/core.py 的get_chat_completion在把每个函数转成 JSON 后执行了剥离tools [function_to_json(f) for f in agent.functions] # hide context_variables from model for tool in tools: params tool[function][parameters] params[properties].pop(__CTX_VARS_NAME__, None) if __CTX_VARS_NAME__ in params[required]: params[required].remove(__CTX_VARS_NAME__)也就是说最终发给 Chat Completions 的 Schema 里既没有context_variables属性也不会要求模型提供它执行阶段再按函数代码里的形参名补上handle_tool_calls检查func.__code__.co_varnames。另外两点来自源码的事实Agent 没有任何函数时tools会以None发送存在 tools 时会附带parallel_tool_calls参数默认值为True见 swarm/types.py 中Agent的字段定义。验证一不调用 API 直接检查 Schema仓库自带了不需要 OpenAI 凭据的断言式测试 tests/test_util.py可以直接照抄它的最小用例来核对转换结果from swarm.util import function_to_json def basic_function(arg1, arg2): return arg1 arg2 print(function_to_json(basic_function))该测试断言的期望结果是{ type: function, function: { name: basic_function, description: , parameters: { type: object, properties: { arg1: {type: string}, arg2: {type: string}, }, required: [arg1, arg2], }, }, }两点核对无 docstring 时description为空字符串无注解的两个参数都是string且都在required中。同文件里还有带注解的用例断言int/str/float/bool分别映射为integer/string/number/boolean且有默认值的参数不进required。如果你改写了函数签名运行 tests/test_util.py 的断言仓库测试入口为 pytest就能立刻发现 Schema 不符合预期。验证二让模型按 Schema 发起调用想看模型是否真的按这份 Schema 调用函数用execute_toolsFalse最干净README 的参数表说明设为False时 Agent 一旦尝试调用函数就立即中断并返回tool_calls消息。下面基于 examples/basic/function_calling.py 改写需要配置好 openai SDK 可用的 API 环境Swarm()内部即实例化OpenAI()客户端见 README.md Running Swarm 一节from swarm import Swarm, Agent client Swarm() def get_weather(location) - str: return {temp:67, unit:F} agent Agent( nameAgent, instructionsYou are a helpful agent., functions[get_weather], ) response client.run( agentagent, messages[{role: user, content: Whats the weather in NYC?}], execute_toolsFalse, ) print(response.messages[-1].get(tool_calls))判断方式与 tests/test_core.py 中test_execute_tools_false的断言一致最后一条消息的tool_calls非空其中function.name等于get_weatherfunction.arguments可被json.loads解析为{location: San Francisco}这类由模型填参得到的字典。这证明模型读到的正是转换后的 tools Schema并且能按required约定把必填参数传全。边界与排查函数调用出错会回传错误消息模型调用了不存在的工具名、参数不匹配或函数抛错时Swarm 会把Error: Tool {name} not found.等错误响应追加进对话见 swarm/core.pyhandle_tool_calls让 Agent 有机会自行恢复而不是直接崩溃。类型注解不是越多越好映射表之外例如Optional[str]、自定义类的注解按string处理required判断只依赖有无默认值与注解无关。返回值约定README 要求函数通常返回str其他值会尝试str()强转返回Agent表示 handoff返回Result可同时携带value、agent和context_variables更新。这些发生在 Schema 之后的执行阶段但写函数签名时应一并考虑。项目定位README 顶部声明 Swarm 是 experimental/educational 项目生产用途推荐迁移到 OpenAI Agents SDK本文描述的转换行为以当前仓库源码为准。如果转换结果符合预期下一步可以参照 examples/basic/ 下的context_variables.py、function_calling.py组合多函数 Agent或用run_demo_loopswarm/repl/repl.py在命令行 REPL 中反复触发调用。【免费下载链接】swarmEducational framework exploring ergonomic, lightweight multi-agent orchestration. Managed by OpenAI Solution team.项目地址: https://gitcode.com/GitHub_Trending/swarm6/swarm创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表