LangChainGo项目配置不同LLM提供商的完整指南
2025-07-07 05:07:12作者:伍希望
前言
在构建基于大语言模型(LLM)的应用时,选择合适的提供商并正确配置是至关重要的。LangChainGo作为一个强大的Go语言LLM集成框架,支持多种主流LLM提供商。本文将详细介绍如何配置和使用这些提供商。
核心概念
在开始配置前,我们需要了解几个关键概念:
- LLM提供商:提供大语言模型服务的平台,如OpenAI、Anthropic等
- API密钥:访问提供商服务的凭证
- 模型选择:不同提供商提供不同能力的模型
- 端点配置:自定义API端点地址
主流提供商配置详解
OpenAI配置
OpenAI是目前最流行的LLM提供商之一,提供GPT系列模型。
基础配置
import "github.com/tmc/langchaingo/llms/openai"
// 使用环境变量OPENAI_API_KEY
llm, err := openai.New()
// 显式指定API密钥
llm, err := openai.New(openai.WithToken("your-api-key"))
高级配置选项
llm, err := openai.New(
openai.WithToken("your-api-key"),
openai.WithModel("gpt-4"), // 指定模型版本
openai.WithBaseURL("https://custom-endpoint.com"), // 自定义端点
openai.WithOrganization("org-id"), // 组织ID
openai.WithAPIVersion("2023-12-01"), // API版本
)
Azure OpenAI服务
对于企业用户,可以使用Azure托管的OpenAI服务:
llm, err := openai.New(
openai.WithToken("your-azure-api-key"),
openai.WithBaseURL("https://your-resource.openai.azure.com"),
openai.WithAPIVersion("2023-12-01-preview"),
openai.WithAPIType(openai.APITypeAzure),
)
Anthropic配置
Anthropic以安全性和长上下文处理能力著称,提供Claude系列模型。
基础配置
import "github.com/tmc/langchaingo/llms/anthropic"
// 使用环境变量
llm, err := anthropic.New()
// 显式指定API密钥
llm, err := anthropic.New(anthropic.WithToken("your-api-key"))
模型选择
llm, err := anthropic.New(
anthropic.WithModel("claude-3-opus-20240229"),
anthropic.WithToken("your-api-key"),
)
Google AI (Gemini)配置
Google提供的Gemini模型具有优秀的性价比。
基础配置
import "github.com/tmc/langchaingo/llms/googleai"
// 使用环境变量
llm, err := googleai.New(context.Background())
// 显式指定API密钥
llm, err := googleai.New(
context.Background(),
googleai.WithAPIKey("your-api-key"),
)
模型配置
llm, err := googleai.New(
context.Background(),
googleai.WithDefaultModel("gemini-pro"),
googleai.WithAPIKey("your-api-key"),
)
Vertex AI配置
Vertex AI是Google的企业级AI平台服务。
基础配置
import "github.com/tmc/langchaingo/llms/vertexai"
llm, err := vertexai.New(
context.Background(),
vertexai.WithProjectID("your-project-id"),
vertexai.WithLocation("us-central1"),
)
使用服务账号
llm, err := vertexai.New(
context.Background(),
vertexai.WithProjectID("your-project-id"),
vertexai.WithLocation("us-central1"),
vertexai.WithCredentialsFile("path/to/service-account.json"),
)
本地模型(Ollama)配置
对于需要本地运行的场景,可以使用Ollama。
基础配置
import "github.com/tmc/langchaingo/llms/ollama"
// 默认配置(localhost:11434)
llm, err := ollama.New(ollama.WithModel("llama2"))
// 自定义服务器
llm, err := ollama.New(
ollama.WithServerURL("http://custom-server:11434"),
ollama.WithModel("codellama"),
)
Hugging Face配置
Hugging Face提供丰富的开源模型。
基础配置
import "github.com/tmc/langchaingo/llms/huggingface"
// 使用环境变量
llm, err := huggingface.New()
// 显式指定token
llm, err := huggingface.New(huggingface.WithToken("your-hf-token"))
模型选择
llm, err := huggingface.New(
huggingface.WithModel("microsoft/DialoGPT-medium"),
huggingface.WithToken("your-hf-token"),
)
环境变量配置
推荐使用环境变量管理敏感信息:
# OpenAI
export OPENAI_API_KEY="sk-..."
# Anthropic
export ANTHROPIC_API_KEY="sk-ant-..."
# Google AI
export GOOGLE_API_KEY="AI..."
# Hugging Face
export HF_TOKEN="hf_..."
# Vertex AI
export GOOGLE_APPLICATION_CREDENTIALS="path/to/service-account.json"
高级功能
OpenAI函数调用
tools := []openai.Tool{
{
Type: "function",
Function: openai.FunctionDefinition{
Name: "get_weather",
Description: "获取当前天气",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]any{
"type": "string",
"description": "城市名称",
},
},
"required": []string{"location"},
},
},
},
}
response, err := llm.GenerateContent(ctx, messages, llms.WithTools(tools))
Anthropic系统消息
messages := []llms.MessageContent{
llms.TextParts(llms.ChatMessageTypeSystem, "你是一个有帮助的助手。"),
llms.TextParts(llms.ChatMessageTypeHuman, "你好!"),
}
流式响应
// 大多数提供商都支持
response, err := llm.GenerateContent(
ctx,
messages,
llms.WithStreamingFunc(func(ctx context.Context, chunk []byte) error {
fmt.Print(string(chunk))
return nil
}),
)
错误处理最佳实践
response, err := llm.GenerateContent(ctx, messages)
if err != nil {
// 检查特定错误类型
if errors.Is(err, llms.ErrRateLimit) {
// 处理速率限制
time.Sleep(time.Second * 60)
// 重试...
} else if errors.Is(err, llms.ErrQuotaExceeded) {
// 处理配额超出
log.Fatal("API配额已用尽")
} else {
// 处理其他错误
log.Printf("LLM错误: %v", err)
}
}
提供商对比指南
提供商 | 优势 | 适用场景 |
---|---|---|
OpenAI | 高质量模型,函数调用支持 | 通用场景,智能体开发 |
Anthropic | 安全性高,长上下文处理 | 研究分析,内容审核 |
Google AI | 免费额度,响应快速 | 实验性项目,移动应用 |
Vertex AI | 企业级功能 | 生产环境,合规要求高的场景 |
Ollama | 隐私保护,离线运行 | 本地开发,敏感数据处理 |
Hugging Face | 开源模型丰富 | 研究实验,定制需求 |
配置建议
- 安全性:始终通过环境变量管理API密钥
- 容错设计:实现指数退避的重试机制
- 模型选择:根据预算和需求选择合适的模型
- 资源管理:使用context控制超时和取消
- 测试策略:开发阶段使用mock进行测试
结语
通过LangChainGo框架,我们可以轻松集成多种LLM提供商服务。本文详细介绍了各主流提供商的配置方法、高级功能使用技巧以及最佳实践建议。开发者可以根据具体需求选择合适的提供商和配置方式,构建强大的语言模型应用。