Function Calling - MyTokenGate
1. 使用场景
Function Calling 功能让模型能够调用外部工具,来增强自身能力。该能力可以通过外部工具,通过大模型作为大脑调用外部工具(如搜索外部知识、查阅行程、或者某些特定领域工具),有效解决模型的幻觉、知识时效性等问题。
2. 使用方式
2.1 通过 REST API 添加 tools 请求参数
在请求体中添加
"tools": [
{
'type': 'function',
'function': {
'name': '函数名称',
'description': '函数描述',
'parameters': {
'type': 'object',
'properties': {...}
}
}
}
]比如完整的 payload 信息:
payload = {
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "中国大模型行业2025年将会迎来哪些机遇和挑战"}
],
"tools": [...]
}2.2 通过 OpenAI 库请求
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=[...]
)3. 支持模型列表
目前支持的模型:
gpt-4o- 支持 Function Callinggpt-4.1- 支持 Function Callinggpt-5系列 - 支持 Function Callingclaude-sonnet-4-6- 支持 Tool Useclaude-opus-4-6- 支持 Tool Usegemini-2.5-pro- 支持 Function Callinggemini-2.5-flash- 支持 Function Calling
4. 使用示例
4.1 示例 1:通过 function calling 来扩展大语言模型的数值计算能力
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://gateway.mytokengate.com/v1"
)
def add(a: float, b: float):
return a + b
def compare(a: float, b: float):
if a > b:
return f'{a} is greater than {b}'
elif a < b:
return f'{b} is greater than {a}'
else:
return f'{a} is equal to {b}'
tools = [
{
'type': 'function',
'function': {
'name': 'add',
'description': 'Compute the sum of two numbers',
'parameters': {
'type': 'object',
'properties': {
'a': {'type': 'number', 'description': 'First number'},
'b': {'type': 'number', 'description': 'Second number'},
},
'required': ['a', 'b'],
},
}
},
{
'type': 'function',
'function': {
'name': 'compare',
'description': 'Compare two numbers',
'parameters': {
'type': 'object',
'properties': {
'a': {'type': 'number', 'description': 'First number'},
'b': {'type': 'number', 'description': 'Second number'},
},
'required': ['a', 'b'],
},
}
}
]
messages = [{'role': 'user', 'content': '比较 9.11 和 9.9 哪个小?'}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
print(response.choices[0].message)4.2 示例 2:通过 function calling 来扩展大语言模型对外部环境的理解
import requests
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://gateway.mytokengate.com/v1"
)
def get_weather(city: str):
# 调用天气 API
response = requests.get(f"https://api.example.com/weather?city={city}")
if response.status_code == 200:
data = response.json()
return f"The weather in {city} is {data['weather']} with a temperature of {data['temp']}°C."
else:
return f"Could not retrieve weather for {city}."
tools = [
{
'type': 'function',
'function': {
'name': 'get_weather',
'description': 'Get the current weather for a given city.',
'parameters': {
'type': 'object',
'properties': {
'city': {'type': 'string', 'description': 'City name'},
},
'required': ['city'],
},
}
}
]
messages = [{'role': 'user', 'content': 'how is the weather today in beijing?'}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
print(response.choices[0].message)Last updated on