DeepSeek + LangChain Go 智能工具调用示例
这个示例展示了如何使用 LangChain Go 接入 DeepSeek API 实现智能工具调用。
功能特点
- 🤖 智能代理自动分析用户请求
- 🔧 自动选择和调用合适的工具
- 💬 支持普通对话(不需要工具的情况)
- 🌐 支持中英文输入
- 🎯 交互式界面,实时测试
可用工具
- Weather - 查询城市天气
- LightControl - 控制灯光开关
- MusicPlayer - 播放音乐
使用方法
1. 设置环境变量
export DEEPSEEK_API_KEY="your-deepseek-api-key"
2. 安装依赖
go mod init learn-langchain-go
go get github.com/tmc/langchaingo
3. 运行程序
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/openai"
)
func main() {
// 设置 DeepSeek API 的配置
// 确保设置了环境变量 DEEPSEEK_API_KEY
apiKey := os.Getenv("DEEPSEEK_API_KEY")
if apiKey == "" {
log.Fatal("请设置环境变量 DEEPSEEK_API_KEY")
}
// https://api.deepseek.com
// 创建 OpenAI 兼容的客户端,指向 DeepSeek API
llm, err := openai.New(
openai.WithToken(apiKey),
openai.WithBaseURL("https://api.deepseek.com/v1"), // DeepSeek API 基础 URL
openai.WithModel("deepseek-chat"), // 使用 DeepSeek 模型
)
if err != nil {
log.Fatal("创建 LLM 客户端失败:", err)
}
// 创建上下文
ctx := context.Background()
// 示例1: 简单的文本生成
fmt.Println("=== 简单文本生成 ===")
simplePrompt := "请简单介绍一下人工智能的发展历史"
result, err := llms.GenerateFromSinglePrompt(ctx, llm, simplePrompt)
if err != nil {
log.Fatal("生成内容失败:", err)
}
fmt.Printf("提问: %s\n", simplePrompt)
fmt.Printf("回答: %s\n\n", result)
fmt.Println("\n\n程序运行完成!")
}
示例请求
工具调用示例
- "What's the weather in Shanghai?"
- "Turn on the lights"
- "Play some jazz music"
- "上海天气怎么样?"
- "开灯"
- "播放周杰伦的歌"
普通对话示例
- "Hello, how are you?"
- "What is AI?"
- "你好,请自我介绍一下"
工作原理
- 请求分析: 智能代理使用 DeepSeek LLM 分析用户输入
- 工具选择: 根据分析结果决定是否使用工具,以及使用哪个工具
- 参数提取: 从用户请求中提取工具所需的参数
- 工具执行: 调用相应的工具并获取结果
- 结果返回: 将工具执行结果或直接回复返回给用户
扩展工具
要添加新工具,只需:
- 实现
tools.Tool接口 - 定义
Name(),Description(), 和Call()方法 - 将新工具添加到工具列表中
示例:
type CalculatorTool struct{}
func (t CalculatorTool) Name() string {
return "Calculator"
}
func (t CalculatorTool) Description() string {
return "Useful for performing mathematical calculations. Input should be a math expression."
}
func (t CalculatorTool) Call(ctx context.Context, input string) (string, error) {
// 实现计算逻辑
return result, nil
}
注意事项
- 确保 DeepSeek API Key 有效
- 网络连接正常(需要访问 api.deepseek.com)
- 工具的描述要清晰,这有助于 LLM 做出正确的选择