feat: add weather tools to legacy and Eino chat
This commit is contained in:
1 parent
6e6171f481
commit
86e86bc9fa
18 files changed
+926
-77
No files matched your search
@@ -0,0 +1,13 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Tool 提供模型可见的定义和实际执行方法。
|
||||
type Tool interface {
|
||||
Definition() model.ToolDefinition
|
||||
Execute(ctx context.Context, arguments string) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Weather 通过 wttr.in 查询当前天气。
|
||||
type Weather struct {
|
||||
client *http.Client
|
||||
baseURL string
|
||||
}
|
||||
|
||||
func NewWeather() *Weather {
|
||||
return &Weather{client: &http.Client{Timeout: 10 * time.Second}, baseURL: "https://wttr.in"}
|
||||
}
|
||||
|
||||
func (w *Weather) Definition() model.ToolDefinition {
|
||||
return model.ToolDefinition{
|
||||
Type: "function",
|
||||
Function: model.ToolFunctionDefinition{
|
||||
Name: "get_weather",
|
||||
Description: "查询指定地点的当前天气,不提供未来预报。地点可从当前对话中获取;如果未提供地点,先询问用户,不要猜测。",
|
||||
Parameters: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
|
||||
},
|
||||
"required": []string{"location"},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Weather) Execute(ctx context.Context, arguments string) (string, error) {
|
||||
var args model.WeatherArguments
|
||||
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
|
||||
return "", fmt.Errorf("天气参数无效: %w", err)
|
||||
}
|
||||
location := strings.TrimSpace(args.Location)
|
||||
if location == "" {
|
||||
return "", fmt.Errorf("请提供要查询的地点")
|
||||
}
|
||||
query := url.Values{"format": {"3"}, "lang": {"zh"}, "m": {""}}
|
||||
endpoint := w.baseURL + "/" + url.PathEscape(location) + "?" + query.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := w.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("天气接口返回 %s", resp.Status)
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
result := strings.TrimSpace(string(body))
|
||||
if result == "" {
|
||||
return "", fmt.Errorf("天气接口返回空结果")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
einotool "github.com/cloudwego/eino/components/tool"
|
||||
"github.com/cloudwego/eino/schema"
|
||||
)
|
||||
|
||||
// Info 提供 Eino 所需的天气工具定义。
|
||||
func (w *Weather) Info(ctx context.Context) (*schema.ToolInfo, error) {
|
||||
definition := w.Definition().Function
|
||||
return &schema.ToolInfo{
|
||||
Name: definition.Name,
|
||||
Desc: definition.Description,
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// InvokableRun 直接复用天气查询,执行失败时把错误交回模型。
|
||||
func (w *Weather) InvokableRun(ctx context.Context, arguments string, _ ...einotool.Option) (string, error) {
|
||||
result, err := w.Execute(ctx, arguments)
|
||||
if err != nil {
|
||||
return "工具执行失败: " + err.Error(), nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWeatherExecute(t *testing.T) {
|
||||
location := "北京 海淀/?&"
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != http.MethodGet || r.URL.EscapedPath() != "/"+url.PathEscape(location) {
|
||||
t.Errorf("地点编码不正确: %s", r.URL)
|
||||
}
|
||||
query := r.URL.Query()
|
||||
if query.Get("format") != "3" || query.Get("lang") != "zh" || !query.Has("m") {
|
||||
t.Errorf("查询参数不正确: %v", query)
|
||||
}
|
||||
fmt.Fprint(w, "北京: 晴 +20°C\n")
|
||||
}))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL = server.URL
|
||||
got, err := weather.Execute(context.Background(), `{"location":" 北京 海淀/?& "}`)
|
||||
if err != nil || got != "北京: 晴 +20°C" {
|
||||
t.Fatalf("天气 = %q,错误 = %v", got, err)
|
||||
}
|
||||
for _, arguments := range []string{`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`} {
|
||||
if _, err := weather.Execute(context.Background(), arguments); err == nil {
|
||||
t.Fatalf("参数 %s 应报错", arguments)
|
||||
}
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("无效参数不应请求接口,实际请求 %d 次", calls)
|
||||
}
|
||||
definition := weather.Definition()
|
||||
if definition.Type != "function" || definition.Function.Name != "get_weather" {
|
||||
t.Fatalf("工具定义不正确: %+v", definition)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherResponseErrors(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{name: "接口错误", status: 503, body: "unavailable"},
|
||||
{name: "空结果", status: 200, body: " \n"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(tt.status); fmt.Fprint(w, tt.body) }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL = server.URL
|
||||
if _, err := weather.Execute(context.Background(), `{"location":"北京"}`); err == nil {
|
||||
t.Fatal("期望返回错误")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherCancellationAndTimeout(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL = server.URL
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := weather.Execute(ctx, `{"location":"北京"}`); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("取消错误 = %v", err)
|
||||
}
|
||||
weather.client.Timeout = 50 * time.Millisecond
|
||||
if _, err := weather.Execute(context.Background(), `{"location":"北京"}`); err == nil || !strings.Contains(err.Error(), "Client.Timeout") {
|
||||
t.Fatalf("超时错误 = %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user