Function Calling实战:让AI调用你的业务API
随着人工智能技术的飞速发展,如何让AI不仅能生成文本,还能主动调用外部业务API成为开发者关注的热点。BAYLLM AI 作为领先的 AI API 中转站服务商,支持多家主流模型(OpenAI、Anthropic Claude、Google Gemini),提供稳定、低延迟的接入环境,助力开发者实现复...

Function Calling实战:让AI调用你的业务API
随着人工智能技术的飞速发展,如何让AI不仅能生成文本,还能主动调用外部业务API成为开发者关注的热点。BAYLLM AI 作为领先的 AI API 中转站服务商,支持多家主流模型(OpenAI、Anthropic Claude、Google Gemini),提供稳定、低延迟的接入环境,助力开发者实现复杂的 Function Calling(函数调用)场景。
本文将围绕 Function Calling,结合 BAYLLM AI 的强大能力,深入讲解如何实现 AI 调用自定义业务API,涵盖天气查询、数据库查询和多工具并行调用示例,帮助你快速搭建智能、自动化的业务系统。
什么是 Function Calling?
Function Calling(函数调用)是指让 AI 模型在生成文本的同时,识别并调用外部的函数接口,以实现更丰富、更智能的交互。相比传统仅限于文本生成,Function Calling 使 AI 能够:
Function Calling 的优势
BAYLLM AI 上的 Function Calling 基础实现
BAYLLM AI 提供统一 API 接口,支持主流 AI 模型的 Function Calling 功能。下面以调用天气查询接口为例,演示如何通过 OpenAI 的函数调用标准实现。
1. 定义天气查询函数接口
import requests
API_BASE_URL = "https://bayllm.com/v1"
API_KEY = "sk-你的密钥"
def query_weather(city: str) -> dict:
"""
模拟天气查询API调用,返回指定城市的天气信息
"""
# 这里模拟业务API,实际可替换为真实天气API
payload = {"city": city}
headers = {"Authorization": f"Bearer {API_KEY}"}
response = requests.post(f"{API_BASE_URL}/weather", json=payload, headers=headers)
return response.json()
2. 发送带函数定义的请求给模型
利用 OpenAI 风格的函数调用接口,让模型知道可以调用 query_weather 函数。
import requests
import json
def call_openai_function_calling(city):
url = f"{API_BASE_URL}/chat/completions"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": f"请告诉我{city}的天气情况。"}
],
"functions": [
{
"name": "query_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
],
"function_call": "auto"
}
res = requests.post(url, headers=headers, json=data)
response_json = res.json()
# 检查模型是否调用了函数
message = response_json["choices"][0]["message"]
if message.get("function_call"):
# 提取函数调用参数
function_args = json.loads(message["function_call"]["arguments"])
weather_info = query_weather(function_args["city"])
return weather_info
else:
return message["content"]
# 示例调用
if __name__ == "__main__":
result = call_openai_function_calling("北京")
print("天气查询结果:", result)
以上示例展示了如何让模型在对话中自动识别调用天气查询函数,并返回具体结果。
多工具并行调用示例:天气 + 数据库查询
现实业务中,AI 可能需要调用多个工具或接口。BAYLLM AI 支持同时调用多个函数,下面以天气查询和数据库查询为例,展示多工具并行调用。
1. 模拟数据库查询函数
def query_user_info(user_id: str) -> dict:
"""
模拟数据库查询,返回用户信息
"""
payload = {"user_id": user_id}
headers = {"Authorization": f"Bearer {API_KEY}"}
response = requests.post(f"{API_BASE_URL}/userdb", json=payload, headers=headers)
return response.json()
2. 多函数定义与调用
def multi_tool_call(user_id, city):
url = f"{API_BASE_URL}/chat/completions"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": f"帮我查一下用户{user_id}的信息,并告诉我{city}的天气。"}
],
"functions": [
{
"name": "query_user_info",
"description": "查询用户数据库,获取用户详细信息",
"parameters": {
"type": "object",
"properties": {
"user_id": {"type": "string", "description": "用户ID"}
},
"required": ["user_id"]
}
},
{
"name": "query_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
],
"function_call": "auto"
}
res = requests.post(url, headers=headers, json=data)
response_json = res.json()
message = response_json["choices"][0]["message"]
results = {}
# 解析是否有函数调用
if message.get("function_call"):
func_call = message["function_call"]
func_name = func_call["name"]
func_args = json.loads(func_call["arguments"])
if func_name == "query_user_info":
results["user_info"] = query_user_info(func_args["user_id"])
elif func_name == "query_weather":
results["weather"] = query_weather(func_args["city"])
return results
# 示例调用
if __name__ == "__main__":
output = multi_tool_call("12345", "上海")
print("多工具调用结果:", output)
注意:BAYLLM AI 支持多轮对话和多函数调用,开发者可以基于此实现更复杂的业务逻辑与并行处理。
Claude 和 Gemini 的 Tool Use 支持
BAYLLM AI 不仅支持 OpenAI 的函数调用,还兼容 Anthropic Claude 和 Google Gemini 的 Tool Use 功能,帮助开发者无缝切换多模型环境。
Claude Tool Use 示例
def call_claude_tool_use(city):
url = f"{API_BASE_URL}/chat/completions"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "claude-2",
"messages": [
{"role": "user", "content": f"请告诉我{city}的天气情况。"}
],
"tools": [
{
"name": "query_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"city": city
}
}
],
"tool_use": True
}
res = requests.post(url, headers=headers, json=data)
return res.json()
# 示例调用
if __name__ == "__main__":
response = call_claude_tool_use("广州")
print("Claude Tool Use 调用结果:", response)
通过 BAYLLM AI,开发者可以在国内直连环境下,低延迟、高稳定地使用 Claude 和 Gemini 的 Tool Use 功能。
BAYLLM AI 的优势
| 指标 | OpenAI | Claude | Gemini |
| ------------- | ------------- | ------------- | ------------- |
| 在线率 | 98.2% | 98.3% | 98.4% |
| 平均延迟 | 1430ms | 1527ms | 1545ms |
| 支持模型数 | 17 | 17 | 17 |
| 国内直连支持 | ✔ | ✔ | ✔ |
总结
Function Calling 是提升 AI 应用智能化和自动化的重要手段。通过 BAYLLM AI 统一的 API 中转服务,开发者能够轻松实现 OpenAI 函数调用、Claude Tool Use 及 Gemini Tool Use,支持多工具并行调用,满足复杂业务需求。
本文通过天气查询、数据库查询及多工具调用示例,详解了 Function Calling 的完整实现流程。无论是构建智能客服、自动化办公还是行业垂直应用,BAYLLM AI 都是你不可或缺的强大助力。
相关文章
更多技术文章与示例,请访问我们的文章中心。
相关文章推荐
以下是 BAYLLM AI 文章中心的相关内容:
查看更多:[BAYLLM AI 文章中心](https://bayllm.com/articles)