You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

一、概念

function Calling 是一种机制,允许大语言模型动态调用外部函数或API以完成特定任务。例如当用户提问“今天的天气如何”时模型可以通过调用天气API获取实时数据并返回结果。这种方式不仅提升了模型的实用性还使其能够处理复杂的多步骤任务。

流程如下: !Pasted image 20250317180245.png

  1. 用户输入问题或指令。
  2. 模型分析输入,生成 JSON 格式的函数调用请求。
  3. 后端解析请求调用对应函数或API。
  4. 将函数返回的结果传递回模型。
  5. 模型基于结果生成最终回答。

二、Deepseek function calling

  1. tools定义 deepseek 官方定义的格式(最多支持 128 个 function参考 https://api-docs.deepseek.com/zh-cn/guides/function_calling
{  
    "type": "function",  
    "function": {  
        "name": "get_current_weather",  
        "description": "Get weather of an location, the user shoud supply a location first",  
        "parameters": {  
            "type": "object",  
            "properties": {  
                "location": {  
                    "type": "string",  
                    "description": "The city and state, e.g. San Francisco, CA",  
                }  
            },  
            "required": ["location"]  
        },  
    }  
}
  1. 函数绑定及调用
模型初始化
llm = ChatOpenAI(  
    model='deepseek-r1-250120', api_key='4eefc827-187f-4756-9637-7e0153c93d81',  
    base_url='https://ark.cn-beijing.volces.com/api/v3/', max_tokens=4096, temperature=0.5, streaming=True  
)


@staticmethod  
def invoke_with_tool(user_input: str):  
    """  
    工具链调用,function calling时system prompt不会生效  
    :param user_input:    :return: 这里返回的是LLM推理出的tool信息格式如下  
        [{'name': 'get_current_weather', 'args': {'location': 'Beijing, China'}, 'id': 'call_xeeq4q52fw9x61lkrqwy9cr6', 'type': 'tool_call'}]    """    llm_with_tools = llm.bind_tools(TOOLS)  
    return llm_with_tools.invoke(user_input).tool_calls
  1. 返回样例,包含函数名和参数
[{'name': 'get_current_weather', 'args': {'location': 'Beijing, China'}, 'id': 'call_xeeq4q52fw9x61lkrqwy9cr6', 'type': 'tool_call'}]