第二章:Go语言大模型调用框架 - Eino自定义工具调用
·
1. 自定义工具
1.1 模拟调用天气API获取数据
package tool
import "context"
// WeatherRequest 工具的参数
type WeatherRequest struct {
City string `json:"city"`
}
// WeatherResponse 工具的返回集
type WeatherResponse struct {
City string `json:"city"`
Temp string `json:"temp"`
Weather string `json:"weather"`
}
// GetWeather 工具的执行逻辑
func GetWeather(ctx context.Context, req *WeatherRequest) (*WeatherResponse, error) {
// 模拟天气的API返回结果
mockData := map[string]WeatherResponse{
"北京": {City: "北京", Temp: "22°C", Weather: "晴"},
"上海": {City: "上海", Temp: "26°C", Weather: "多云"},
"深圳": {City: "深圳", Temp: "30°C", Weather: "阵雨"},
}
if data, ok := mockData[req.City]; ok {
return &data, nil
}
return &WeatherResponse{City: req.City, Temp: "未知", Weather: "未知"}, nil
}
1.2 集成工具进行回复
package main
import (
"context"
myTool "day03/tool"
"fmt"
"github.com/cloudwego/eino-ext/components/model/openai"
"github.com/cloudwego/eino/components/tool"
"github.com/cloudwego/eino/components/tool/utils"
"github.com/cloudwego/eino/compose"
"github.com/cloudwego/eino/flow/agent/react"
"github.com/cloudwego/eino/schema"
"log"
)
// 自定义工具
func main() {
ctx := context.Background()
// 调用LLM
model, err := openai.NewChatModel(ctx, &openai.ChatModelConfig{
BaseURL: "https://api-inference.modelscope.cn/v1/",
APIKey: "xxx",
Model: "Qwen/Qwen3.5-35B-A3B",
})
if err != nil {
log.Fatalf("创建 ChatModel 失败: %v", err)
}
// 创建工具
weatherTool := utils.NewTool(
&schema.ToolInfo{
Name: "get_weather",
Desc: "查询指定城市的实时天气信息,包括温度和天气状况",
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
"city": {
Type: schema.String,
Desc: "要查询天气的城市名称,如:北京、上海、深圳",
Required: true,
},
}),
},
myTool.GetWeather,
)
// 验证工具信息
/*info, _ := weatherTool.Info(ctx)
fmt.Printf("工具名: %s\n", info.Name)
fmt.Printf("工具描述: %s\n", info.Desc)*/
// 创建ReAct Agent
agent, err := react.NewAgent(ctx, &react.AgentConfig{
ToolCallingModel: model,
ToolsConfig: compose.ToolsNodeConfig{
Tools: []tool.BaseTool{weatherTool},
},
})
if err != nil {
log.Fatalf("创建 Agent 失败: %v", err)
}
// 模拟参数
// args := `{"city": "深圳"}`
// 执行工具
/*result, err := weatherTool.InvokableRun(ctx, args)
if err != nil {
log.Fatal(err)
}
fmt.Printf("执行结果: %s\n", result)*/
// 解析结果
/* var resp myTool.WeatherResponse
json.Unmarshal([]byte(result), &resp)
fmt.Printf("城市: %s, 温度: %s, 天气: %s\n", resp.City, resp.Temp, resp.Weather)*/
// 向agent 提问
answer, err := agent.Generate(ctx, []*schema.Message{
schema.UserMessage("上海今天天气怎么样?"),
})
if err != nil {
log.Fatalf("Agent 执行失败: %v", err)
}
fmt.Printf("Agent 执行结果: %s\n", answer.Content)
}
输出结果:
更多推荐



所有评论(0)