如何在大模型API调用中实现function calling配合流式输出

在上一篇文章,MCP-HOST:简易版的Claude Code命令行工具中,虽然MCP-HOST实现了在与大模型交互中使用MCP server的功能,但是缺乏流式输出的能力,导致在处理稍微复杂的交互中,不能确定任务是否在进行中,还是响应超时了。所以我就在想如何让它的输出方式变为流式输出,这样就可以实时掌握输出的情况了,当然调用MCP server的场景还是需要等其处理完才能知道结果。


什么是Function Calling

简单来讲,Function Calling (函数调用) 让大模型(如DeepSeek、CHATGPT等)在对话过程中智能识别用户需求,并决定是否需要调用外部工具/函数来完成特定任务。从之前的几篇MCP的文章中,我们已经了解到 MCP-Client 和 MCP-Server 通过 List_Tools 和 Call_Tools 这两个接口来查看/使用工具。也就是说相对于 Function Calling 来说,MCP协议解耦了工具的使用,不像使用 Function Calling 那样,你需要在事先在你的Agent中定义好工具,如果后续需要使用新的工具,你需要重新定义Agent,这会带来很多麻烦。

有了上面的说明,你就可以理解,通过 MCP-ClientMCP-Server 来使用 Tools 和使用 Function Calling 其实本质上差不多,所以接下来我们就一起看看如何使用 Function Calling配合流式输出。


定义工具

下面是一段获取当前时间 Tool 的代码:

go 复制代码
// 示例工具函数
func handleToolCall(toolCall ToolCall) string {
	switch toolCall.Function.Name {
	case ToolNameGetTime:
		return time.Now().Format("2006-01-02 15:04:05")
	default:
		return "Tool not found"
	}
}

流式输出

下面是一段流式输出的代码,具体使用 Tool 的逻辑在 handleResponse 中。

go 复制代码
func (c *DeepSeekClient) ChatStream(messages []Message, tools []Tool, handleResponse func(StreamResponse)) error {
	requestBody := map[string]any{
		"model":    "deepseek-chat",
		"messages": messages,
		"stream":   true,
	}
	if len(tools) > 0 {
		requestBody["tools"] = tools
	}

	bodyBytes, _ := json.Marshal(requestBody)
	req, _ := http.NewRequest("POST", APIEndpoint, bytes.NewReader(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+c.apiKey)

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Bytes()
		if len(line) == 0 {
			continue
		}

		var response StreamResponse
		if err := json.Unmarshal(line[6:], &response); err != nil { // 跳过"data: "前缀
			continue
		}

		handleResponse(response)
	}

	return nil
}

调用 Tool

下面代码是每次流式响应的时候需要回调处理 Tool 的逻辑。

go 复制代码
	handleResponse := func(response StreamResponse) {
		if len(response.Choices) == 0 {
			return
		}

		delta := response.Choices[0].Delta

		// 处理工具调用
		if len(delta.ToolCalls) > 0 {
			for _, toolCall := range delta.ToolCalls {
                if toolCall.Type != "function" {
                    continue
                }
				result := handleToolCall(toolCall)
				fmt.Printf("\n[工具调用] 结果: %s\n", result)
			}
		}

		// 处理常规输出
		if delta.Content != "" {
			fmt.Print(delta.Content)
		}
	}

总结

本文简单的介绍了Function CallingMCP 之间的区别,实现了一个简单的在流式输出中回调工具的示例,完整代码在demo_for_ai中。

相关推荐
AI大模型顾潇1 小时前
[特殊字符] Milvus + LLM大模型:打造智能电影知识库系统
数据库·人工智能·机器学习·大模型·llm·llama·milvus
白总Server1 天前
Golang领域Beego框架的中间件开发实战
服务器·网络·websocket·网络协议·udp·go·ssl
yi念zhi间1 天前
如何把ASP.NET Core WebApi打造成Mcp Server
后端·ai·mcp
ん贤1 天前
GoWeb开发
开发语言·后端·tcp/ip·http·https·go·goweb
纪元A梦2 天前
华为OD机试真题——荒岛求生(2025A卷:200分)Java/python/JavaScript/C/C++/GO最佳实现
java·c语言·javascript·c++·python·华为od·go
Alfred king2 天前
华为昇腾910B通过vllm部署InternVL3-8B教程
llm·nlp·vllm部署
杨浦老苏2 天前
MCPHub:一站式MCP服务器聚合平台
人工智能·docker·ai·群晖·mcp
伊织code2 天前
AWS MCP Servers
服务器·python·ai·云计算·aws·mcp
Generalzy2 天前
Model Context Protocol (MCP)笔记
笔记·ai·mcp
CoderJia程序员甲2 天前
AI驱动的Kubernetes管理:kubectl-ai 如何简化你的云原生运维
运维·人工智能·云原生·kubernetes·llm