(由SiliconCloud平台模型Flux.1生成)
Function Calling(函数调用)是大模型API的一个高级功能,允许开发者通过API调用外部函数或服务,从而增强模型的能力。
简单来说,当模型在处理用户输入时,如果需要执行某些特定的操作(如查询数据库、调用第三方API、执行计算等),模型可以通过Function Calling机制调用预定义的函数,并将函数返回的结果整合到生成的文本中。目前,SiliconCloud上的Qwen2.5、DeepSeek-V2.5、GLM4、InternLM2.5等模型已支持Function Calling。通过该功能,开发者接入SiliconCloud上的大模型API可以处理更复杂的任务,提高响应的准确性,简化开发流程,并增强用户体验。支持模型列表
Deepseek系列:
InternLM系列:
internlm/internlm2_5-7b-chat
Pro/internlm/internlm2_5-7b-chat
Qwen系列:
GLM系列:
(注:支持的模型名称会发生变化,请查阅SiliconCloud使用手册了解最新支持的模型列表。)
适用场景
场景描述1:用户询问“今天的天气如何?”Function Calling应用:模型通过Function Calling调用天气API,获取当前的天气信息,并将结果整合到生成的文本中。示例:
{ “user_input”: “今天的天气如何?”, “function_call”: { “name”: “get_weather”, “parameters”: {“location”: “北京”} } }
返回结果:
{“response”: “今天北京的天气是晴,最高温度25°C,最低温度15°C。”}
场景描述2:用户询问“苹果公司的股票价格是多少?”
Function Calling应用:模型通过Function Calling调用股票API,获取苹果公司的实时股票价格,并将结果整合到生成的文本中。
示例:
{ “user_input”: “苹果公司的股票价格是多少?”, “function_call”: { “name”: “get_stock_price”, “parameters”: {“symbol”: “AAPL”} }}
返回结果:
{“response”: “苹果公司(AAPL)的当前股票价格是226.37美元。”}
如何使用Function Calling
1.通过REST请求
在请求体中添加
“tools”: [ { ‘type’: ‘function’, ‘function’: { ‘name’: ‘对应到实际执行的函数名称’, ‘description’: ‘此处是函数相关描述’, ‘parameters’: { // 此处是函数参数相关描述 }, } }, { // 其他函数相关说明 }]
比如完整的payload信息:
payload = { “model”: “deepseek-ai/DeepSeek-V2-Chat”, “messages”: [ { “role”: “user”, “content”: “SiliconCloud推出分层速率方案与免费模型RPM提升10倍,对于整个大模型应用领域带来哪些改变?” } ], “tools”: [ { ‘type’: ‘function’, ‘function’: { ‘name’: ‘对应到实际执行的函数名称’, ‘description’: ‘此处是函数相关描述’, ‘parameters’: { // 此处是函数参数相关描述 }, } }, { // 其他函数相关说明 } ] // 其他参数}
2.通过OpenAI库请求
该功能和OpenAI兼容,在使用OpenAI的库时,对应的请求参数中添加 tools=[对应的 tools] 比如:
response = client.chat.completions.create( model=”deepseek-ai/DeepSeek-V2.5″, messages = messages, tools=[ { ‘type’: ‘function’, ‘function’: { ‘name’: ‘对应到实际执行的函数名称’, ‘description’: ‘此处是函数相关描述’, ‘parameters’: { // 此处是函数参数相关描述 }, } }, { // 其他函数相关说明 } ] // chat.completions 其他参数)
应用示例
1.通过Function Calling来扩展大语言模型的数值计算能力
本代码输入4个函数,分别是数值的加、减、比较大小、字符串中重复字母计数四个函数来演示通过Function Calling来解决大语言模型在Token预测不擅长的领域的执行问题。
from openai import OpenAI
client = OpenAI( api_key=”您的 APIKEY”, # 从https://cloud.siliconflow.cn/account/ak获取 base_url=”https://api.siliconflow.cn/v1″)
def add(a: float, b: float): return a + b
def mul(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}’
def count_letter_in_string(a: str, b: str): string = a.lower() letter = b.lower() count = string.count(letter) return(f”The letter ‘{letter}’ appears {count} times in the string.”)
tools = [{ ‘type’: ‘function’, ‘function’: { ‘name’: ‘add’, ‘description’: ‘Compute the sum of two numbers’, ‘parameters’: { ‘type’: ‘object’, ‘properties’: { ‘a’: { ‘type’: ‘int’, ‘description’: ‘A number’, }, ‘b’: { ‘type’: ‘int’, ‘description’: ‘A number’, }, }, ‘required’: [‘a’, ‘b’], }, }}, { ‘type’: ‘function’, ‘function’: { ‘name’: ‘mul’, ‘description’: ‘Calculate the product of two numbers’, ‘parameters’: { ‘type’: ‘object’, ‘properties’: { ‘a’: { ‘type’: ‘int’, ‘description’: ‘A number’, }, ‘b’: { ‘type’: ‘int’, ‘description’: ‘A number’, }, }, ‘required’: [‘a’, ‘b’], }, }},{ ‘type’: ‘function’, ‘function’: { ‘name’: ‘count_letter_in_string’, ‘description’: ‘Count letter number in a string’, ‘parameters’: { ‘type’: ‘object’, ‘properties’: { ‘a’: { ‘type’: ‘str’, ‘description’: ‘source string’, }, ‘b’: { ‘type’: ‘str’, ‘description’: ‘letter’, }, }, ‘required’: [‘a’, ‘b’], }, }},{ ‘type’: ‘function’, ‘function’: { ‘name’: ‘compare’, ‘description’: ‘Compare two number, which one is bigger’, ‘parameters’: { ‘type’: ‘object’, ‘properties’: { ‘a’: { ‘type’: ‘float’, ‘description’: ‘A number’, }, ‘b’: { ‘type’: ‘float’, ‘description’: ‘A number’, }, }, ‘required’: [‘a’, ‘b’], }, }}]
def function_call_playground(prompt): messages = [{‘role’: ‘user’, ‘content’: prompt}] response = client.chat.completions.create( model=”deepseek-ai/DeepSeek-V2.5″, messages = messages, temperature=0.01, top_p=0.95, stream=False, tools=tools)
# print(response) func1_name = response.choices[0].message.tool_calls[0].function.name func1_args = response.choices[0].message.tool_calls[0].function.arguments func1_out = eval(f'{func1_name}(**{func1_args})’) # print(func1_out)
messages.append(response.choices[0].message) messages.append({ ‘role’: ‘tool’, ‘content’: f'{func1_out}’, ‘tool_call_id’: response.choices[0].message.tool_calls[0].id }) # print(messages) response = client.chat.completions.create( model=”deepseek-ai/DeepSeek-V2.5″, messages=messages, temperature=0.01, top_p=0.95, stream=False, tools=tools) return response.choices[0].message.content prompts = [ “用中文回答:strawberry中有多少个r?”, “用中文回答:9.11和9.9,哪个小?”]
for prompt in prompts: print(function_call_playground(prompt))
模型将输出:
strawberry中有3个r。9.11 比 9.9 小。
2.通过Function Calling来扩展大语言模型对外部环境的理解
该例子输入1个函数,通过外部API来查询外部信息。
import requestsfrom openai import OpenAI
client = OpenAI( api_key=”您的 APIKEY”, # 从https://cloud.siliconflow.cn/account/ak获取 base_url=”https://api.siliconflow.cn/v1″)
# 使用 WeatherAPI 的天气查询函数def get_weather(city: str): # 使用 WeatherAPI 的 API 来获取天气信息 api_key = “您的WeatherAPI APIKEY” # 替换为你自己的 WeatherAPI APIKEY base_url = “http://api.weatherapi.com/v1/current.json” params = { ‘key’: api_key, ‘q’: city, ‘aqi’: ‘no’ # 不需要空气质量数据 } # 调用天气 API response = requests.get(base_url, params=params) if response.status_code == 200: data = response.json() weather = data[‘current’][‘condition’][‘text’] temperature = data[‘current’][‘temp_c’] return f”The weather in {city} is {weather} with a temperature of {temperature}°C.” else: return f”Could not retrieve weather information for {city}.”
# 定义 function calling toolstools = [ { ‘type’: ‘function’, ‘function’: { ‘name’: ‘get_weather’, ‘description’: ‘Get the current weather for a given city.’, ‘parameters’: { ‘type’: ‘object’, ‘properties’: { ‘city’: { ‘type’: ‘string’, ‘description’: ‘The name of the city to query weather for.’, }, }, ‘required’: [‘city’], }, } }]
# 发送请求并处理 function callingdef function_call_playground(prompt): messages = [{‘role’: ‘user’, ‘content’: prompt}] # 发送请求到 OpenAI API response = client.chat.completions.create( model=”deepseek-ai/DeepSeek-V2.5″, messages=messages, temperature=0.01, top_p=0.95, stream=False, tools=tools )
# 处理 API 返回的工具调用请求 func1_name = response.choices[0].message.tool_calls[0].function.name func1_args = response.choices[0].message.tool_calls[0].function.arguments func1_out = eval(f'{func1_name}(**{func1_args})’)
# 将结果添加到对话中并返回 messages.append(response.choices[0].message) messages.append({ ‘role’: ‘tool’, ‘content’: f'{func1_out}’, ‘tool_call_id’: response.choices[0].message.tool_calls[0].id }) # 返回模型响应 response = client.chat.completions.create( model=”deepseek-ai/DeepSeek-V2.5″, messages=messages, temperature=0.01, top_p=0.95, stream=False, tools=tools ) return response.choices[0].message.content # 示例使用prompt = “how is the weather today in beijing?”print(function_call_playground(prompt))
模型将输出:
The weather in Beijing today is sunny with a temperature of 21.4°C.
暂无评论内容