openai-cookbookOpenAPI:OpenAPI规范与函数调用集成
openai-cookbookOpenAPI:OpenAPI规范与函数调用集成
OpenAPI规范(OpenAPI Specification,OAS)是RESTful API的通用描述标准,而OpenAI函数调用(Function Calling)则赋予大语言模型(LLM)执行外部工具的能力。本文将通过examples/Function_calling_with_an_OpenAPI_spec.ipynb展示如何将两者结合,让AI自动解析API文档并生成可执行的函数调用逻辑。
OpenAPI与函数调用的协同价值
在传统开发中,API集成需要手动编写接口适配代码。而通过OpenAPI规范与函数调用的集成,可实现以下突破:
- 自动化接口对接:AI直接解析OpenAPI文档生成调用逻辑,减少人工编码
- 动态能力扩展:无需修改模型即可通过更新API规范扩展AI功能
- 多步骤任务编排:支持复杂业务流程的函数调用链执行
OpenAPI规范定义了API的端点、参数、请求/响应格式等元数据,函数调用则提供了AI与外部系统交互的标准协议。两者结合形成了"规范解析→函数生成→调用执行"的完整闭环。
从OpenAPI规范到函数定义的转换
规范解析核心步骤
转换过程主要包含三个关键环节:
- JSON引用解析:处理OpenAPI中的
$ref关键字,合并分散定义的schema - 操作映射:将API端点的
operationId映射为函数名称 - 参数提取:从
requestBody和parameters中提取函数入参定义
核心实现代码如下:
def openapi_to_functions(openapi_spec):
functions = []
for path, methods in openapi_spec["paths"].items():
for method, spec_with_ref in methods.items():
# 解析JSON引用
spec = jsonref.replace_refs(spec_with_ref)
# 提取函数名称和描述
function_name = spec.get("operationId")
desc = spec.get("description") or spec.get("summary", "")
# 构建参数schema
schema = {"type": "object", "properties": {}}
# 处理请求体
req_body = spec.get("requestBody", {}).get("content", {}).get("application/json", {}).get("schema")
if req_body:
schema["properties"]["requestBody"] = req_body
# 处理路径/查询参数
params = spec.get("parameters", [])
if params:
param_properties = {param["name"]: param["schema"] for param in params if "schema" in param}
schema["properties"]["parameters"] = {"type": "object", "properties": param_properties}
# 添加函数定义
functions.append({"type": "function", "function": {
"name": function_name,
"description": desc,
"parameters": schema
}})
return functions
转换效果示例
以事件管理API的OpenAPI规范为例,转换后生成的函数定义如下:
{
"type": "function",
"function": {
"name": "createEvent",
"description": "Create a new event",
"parameters": {
"type": "object",
"properties": {
"requestBody": {
"type": "object",
"properties": {
"name": {"type": "string"},
"date": {"type": "string", "format": "date-time"},
"location": {"type": "string"}
},
"required": ["name", "date", "location"]
}
}
}
}
}
多步骤函数调用的执行流程
核心执行逻辑
通过process_user_instruction函数实现多步骤任务的自动执行:
def process_user_instruction(functions, instruction):
messages = [
{"content": SYSTEM_MESSAGE, "role": "system"},
{"content": instruction, "role": "user"}
]
while num_calls < MAX_CALLS:
response = client.chat.completions.create(
model="gpt-3.5-turbo-16k",
tools=functions,
tool_choice="auto",
messages=messages
)
message = response.choices[0].message
if message.tool_calls:
# 处理函数调用结果
messages.append({
"role": "tool",
"content": "success",
"tool_call_id": message.tool_calls[0].id
})
num_calls += 1
else:
# 返回最终结果
print(message.content)
break
执行流程示意图
实际执行案例
当用户输入以下指令时:
1. 获取所有事件列表
2. 创建名为"AGI Party"的新事件
3. 删除ID为2456的事件
系统将自动生成三次函数调用,执行日志如下:
>> Function call #: 1
[ChatCompletionMessageToolCall(id='call_jmlvEyMRMvOtB80adX9RbqIV', function=Function(arguments='{}', name='listEvents'), type='function')]
>> Function call #: 2
[ChatCompletionMessageToolCall(id='call_OOPOY7IHMq3T7Ib71JozlUQJ', function=Function(arguments='{"requestBody":{"id":"1234","name":"AGI Party","date":"2022-12-31","location":"New York"}}', name='createEvent'), type='function')]
>> Function call #: 3
[ChatCompletionMessageToolCall(id='call_Kxluu3fJSOsZNNCn3JIlWAAM', function=Function(arguments='{"parameters":{"id":"2456"}}', name='deleteEvent'), type='function')]
Here are the actions I performed:
1. Retrieved all the events.
2. Created a new event named "AGI Party" with the ID "1234", scheduled for December 31, 2022, in New York.
3. Deleted the event with the ID "2456".
企业级应用与最佳实践
多场景适配案例
在openai-cookbook中,这种集成模式已广泛应用于各类业务场景:
- 数据库操作:examples/chatgpt/gpt_actions_library/gpt_action_snowflake_direct.ipynb展示了通过OpenAPI规范操作Snowflake数据仓库
- 项目管理:examples/chatgpt/gpt_actions_library/gpt_action_jira.ipynb实现JIRA任务的自动创建与更新
- 文档管理:examples/chatgpt/gpt_actions_library/gpt_action_confluence.ipynb提供Confluence文档的AI辅助编辑功能
关键技术挑战与解决方案
| 挑战 | 解决方案 | 相关资源 |
|---|---|---|
| 复杂schema处理 | 使用jsonref库解析嵌套引用 | examples/Function_calling_with_an_OpenAPI_spec.ipynb |
| 权限控制 | 通过中间层实现OAuth2授权 | examples/chatgpt/gpt_actions_library/gpt_action_google_drive.ipynb |
| 错误处理 | 添加try-catch块和重试机制 | examples/How_to_handle_rate_limits.ipynb |
性能优化建议
- 规范预解析:提前处理大型OpenAPI文档,缓存转换后的函数定义
- 调用结果缓存:对相同参数的函数调用结果进行缓存,减少重复执行
- 批量操作合并:将多个独立调用合并为批量操作,降低API调用次数
总结与未来展望
OpenAPI规范与函数调用的集成,构建了AI与外部系统通信的标准化桥梁。通过examples/Function_calling_with_an_OpenAPI_spec.ipynb提供的工具方法,开发者可以快速实现从API文档到AI能力的无缝转化。
未来,随着OpenAPI 3.1+规范的普及和函数调用能力的增强,我们将看到更多创新应用:
- 实时API适配:AI动态适配API版本变更
- 跨API协同:多系统API的自动编排与协同
- 自然语言接口:纯自然语言描述替代传统API调用
通过README.md可获取更多OpenAPI集成案例,建议结合examples/How_to_call_functions_with_chat_models.ipynb深入学习函数调用基础原理。
更多推荐



所有评论(0)