如何配置不同的LLM提供商
本指南将向您展示如何使用LangChainGo配置和使用不同的LLM提供商。
OpenAI
基本配置
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
import "github.com/tmc/langchaingo/llms/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
基本配置
import "github.com/tmc/langchaingo/llms/anthropic"
// 使用环境变量 ANTHROPIC_API_KEY
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)
基本配置
import "github.com/tmc/langchaingo/llms/googleai"
// 使用环境变量 GOOGLE_API_KEY
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
基本配置
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)
基本配置
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
基本配置
import "github.com/tmc/langchaingo/llms/huggingface"
// 使用环境变量 HF_TOKEN
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"),
)
环境变量
设置适当的API密钥:
# 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)
}
}
最佳实践
- 使用环境变量:将 API 密钥安全地存储在环境变量中
- 处理速率限制:实现带有指数退避的重试逻辑
- 模型选择:根据您的用例和预算选择合适的模型
- 错误处理:为不同的故障模式实现稳健的错误处理
- 资源管理:使用上下文进行超时和取消操作
- 测试:使用模拟提供程序进行测试(参见测试指南)
提供商比较
提供商 | 优势 | 使用场景 |
---|---|---|
OpenAI | 高质量,函数调用 | 通用目的,代理 |
Anthropic | 安全性,长上下文 | 研究,内容分析 |
Google AI | 免费层级,快速 | 实验,移动应用 |
Vertex AI | 企业功能 | 生产,合规 |
Ollama | 隐私,离线 | 局部开发,敏感数据 |
Hugging Face | 开源模型,多样性 | 研究,实验 |
请确保输出符合上述规则和示例。