自行实现一个Eino工具
2026年1月12日 · 153 字 · 1 分钟
自行实现一个Eino工具用来获取现在的时间
自行实现一个Eino工具
这里面举一个获取时间的tool示例
需要的包
"github.com/cloudwego/eino/components/tool"
"github.com/cloudwego/eino/components/tool/utils"
创建函数
type TimeRequest struct {
TimeZone string `json:"time_zone" jsonschema:"required,description=当地时区"`
//required代表必传,如果不是必须的,就把required,删掉
}
// 必须传入结构体,因为eino工具的参数是结构体
func GetTime(ctx context.Context, request *TimeRequest) (string, error) {
if len(request.TimeZone) == 0 {
request.TimeZone = "Asia/Shanghai"
}
loc, err := time.LoadLocation(request.TimeZone)
if err != nil {
return "", fmt.Errorf("failed to load location: %w", err)
}
now := time.Now().In(loc)
return now.Format("2006-01-02 15:04:05"), nil
}
将函数转为工具
func CreateTimeTool() tool.InvokableTool {
timetool, err := utils.InferTool("time_tool", "获取当前时间", GetTime)//名称,描述,函数
if err != nil {
log.Fatal(fmt.Errorf("failed to infer tool: %w", err))
}
return timetool
}
调用工具的函数
func UseTimeTool(TimeZone string) {
ctx := context.Background()
//创建工具
timetool := CreateTimeTool()
//创建请求参数
request := &TimeRequest{
TimeZone: TimeZone,
}
//json序列化
jsonRequest, err := sonic.Marshal(request)
if err != nil {
log.Fatal(fmt.Errorf("failed to marshal request: %w", err))
}
//调用工具
response, err := timetool.InvokableRun(ctx, string(jsonRequest))
if err != nil {
log.Fatal(fmt.Errorf("failed to invoke tool: %w", err))
}
fmt.Println(response)
}
最后调用
func main() {
UseTimeTool("Asia/Shanghai")
}
调用结果
2026-01-12 10:31:38