Blades 为自定义工具提供便捷支持,可以自己定制函数式工具。
tools.NewFunc(...) 是创建一个基于函数的工具得核心方法,包含以下参数:
name:工具的名称,用于标识工具。
description:工具的描述,用于提示用户工具的功能。
handler:工具的处理函数,用于处理工具的请求并返回结果。在定义handler时需要使用包装器,将一个普通的go函数转换成blades可以识别的工具处理函数。
// WeatherReq represents a request for weather information.type WeatherReq struct { Location string `json:"location" jsonschema:"Get the current weather for a given city"`}
// WeatherRes represents a response containing weather information.type WeatherRes struct { Forecast string `json:"forecast" jsonschema:"The weather forecast"`}weatherTool, err := tools.NewFunc( "get_weather", "Get the current weather for a given city", weatherHandle,)// Configure OpenAI API key and base URL using environment variables:model := openai.NewModel("gpt-5", openai.Config{ APIKey: os.Getenv("OPENAI_API_KEY"),})agent, err := blades.NewAgent( "Weather Agent", blades.WithModel(model), blades.WithInstruction("You are a helpful assistant that provides weather information."), blades.WithTools(weatherTool),)if err != nil { log.Fatal(err)}input := blades.UserMessage("What is the weather in New York City?") session := blades.NewSession() runner := blades.NewRunner(agent, blades.WithSession(session)) ctx := context.Background() output, err := runner.Run(ctx, input) if err != nil { log.Fatal(err) } log.Println("state:", session.State()) log.Println("output:", output.Text())成功运行代码,将看到类似如下的输出:
2025/11/14 11:01:18 stream status: completed output: The weather in San Francisco is currently sunny with a temperature of 25°C.