Logo 丙阅科技-加菲猫中转API使用文档

函数调用

下面是将普通调用改为**函数调用**的版本代码,结合你提供的接入方式。假设我们需要定义一个获取天气的函数 `get_weather`,模型将返回一个结构化的函数调用请求。

python代码

import requests
api_url = 'https://api.132999.xyz/v1/chat/completions'
api_key = 'sk-******'
headers = {
   'Content-Type': 'application/json',
   'Authorization': f'Bearer {api_key}'
}
# 定义函数调用的参数
functions = [
   {
       "name": "get_weather",
       "description": "Get the current weather information for a given location.",
       "parameters": {
           "type": "object",
           "properties": {
               "location": {
                   "type": "string",
                   "description": "The name of the city or location to get the weather for."
               }
           },
           "required": ["location"]
       }
   }
]
# 准备请求数据
request_data = {
   'messages': [
       {'role': 'system', 'content': 'You are a helpful assistant.'},
       {'role': 'user', 'content': 'What is the weather like in New York?'}
   ],
   'functions': functions,
   'function_call': 'auto',  # 自动触发函数调用
   'stream': False,
   'model': 'gpt-3.5-turbo-16k',
   'temperature': 0.5,
   'presence_penalty': 0,
   'frequency_penalty': 0,
   'top_p': 1
}
# 发送请求
response = requests.post(api_url, headers=headers, json=request_data)
data = response.json()
# 处理响应数据
if 'choices' in data and len(data['choices']) > 0:
   function_call = data['choices'][0].get('message', {}).get('function_call', {})
   if function_call:
       function_name = function_call.get('name', '')
       arguments = function_call.get('arguments', '{}')
       print(f"Function to call: {function_name}")
       print(f"Arguments: {arguments}")
   else:
       print("No function call returned.")
else:
   print("Error or empty response:", data)

关键点解释:
functions 字段:
定义了函数调用的具体参数规范,包括函数名称、功能描述和参数要求。
function_call:
设置为 "auto",表示模型会根据上下文判断是否需要调用函数。
如果需要更明确调用某个函数,可以直接写 { "name": "get_weather" }。
响应解析:
如果 function_call 存在,会返回函数名称和参数(以 JSON 格式)。
你可以根据返回的参数调用实际的后端逻辑(如获取天气数据)。
扩展性:
通过修改 functions 和 messages,可以支持多种任务类型或增加其他函数接口。
示例输出
用户输入 "What is the weather like in New York?",可能的响应结构如下:

{
   "choices": [
       {
           "message": {
               "function_call": {
                   "name": "get_weather",
                   "arguments": "{\"location\": \"New York\"}"
               }
           }
       }
   ]
}
# 你可以根据返回的 function_call 信息处理后续逻辑,例如调用真实的天气 API。