feat: add progressive Eino examples and unify weather provider
This commit is contained in:
1 parent
73f6f0901e
commit
1373f0903f
18 files changed
+893
-380
No files matched your search
+5
-33
@@ -4,26 +4,23 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
// Weather 查询 wttr.in 当前天气或 Open-Meteo 日期预报。
|
||||
// Weather 通过 Open-Meteo 查询指定地点的逐日天气预报。
|
||||
type Weather struct {
|
||||
client *http.Client
|
||||
baseURL string
|
||||
geocodingURL string
|
||||
forecastURL string
|
||||
}
|
||||
|
||||
func NewWeather() *Weather {
|
||||
return &Weather{
|
||||
client: &http.Client{Timeout: 10 * time.Second}, baseURL: "https://wttr.in",
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
geocodingURL: "https://geocoding-api.open-meteo.com/v1/search",
|
||||
forecastURL: "https://api.open-meteo.com/v1/forecast",
|
||||
}
|
||||
@@ -34,12 +31,12 @@ func (w *Weather) Definition() model.ToolDefinition {
|
||||
Type: "function",
|
||||
Function: model.ToolFunctionDefinition{
|
||||
Name: "get_weather",
|
||||
Description: "查询指定地点天气。不传日期查询当前天气;传 start_date 查询该日,end_date 可指定结束日期(含)。预报支持北京时间今天起共16天,不支持历史天气。日期必须是 YYYY-MM-DD,明天、本周末等需根据系统当前日期换算。地点可从对话获取,缺少地点时先询问,不要猜测。",
|
||||
Description: "查询指定地点天气。不传日期查询北京时间今天的预报;传 start_date 查询该日,end_date 可指定结束日期(含)。预报支持北京时间今天起共16天,不支持历史天气。日期必须是 YYYY-MM-DD,明天、本周末等需根据系统当前日期换算。地点可从对话获取,缺少地点时先询问,不要猜测。",
|
||||
Parameters: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
|
||||
"start_date": map[string]string{"type": "string", "description": "预报开始日期,YYYY-MM-DD;不传则查当前天气"},
|
||||
"start_date": map[string]string{"type": "string", "description": "预报开始日期,YYYY-MM-DD;不传则查北京时间今天的预报"},
|
||||
"end_date": map[string]string{"type": "string", "description": "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"},
|
||||
},
|
||||
"required": []string{"location"},
|
||||
@@ -60,30 +57,5 @@ func (w *Weather) Execute(ctx context.Context, arguments string) (string, error)
|
||||
args.Location = location
|
||||
args.StartDate = strings.TrimSpace(args.StartDate)
|
||||
args.EndDate = strings.TrimSpace(args.EndDate)
|
||||
if args.StartDate != "" || args.EndDate != "" {
|
||||
return w.forecast(ctx, args)
|
||||
}
|
||||
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
|
||||
return w.forecast(ctx, args)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ func (w *Weather) Info(ctx context.Context) (*schema.ToolInfo, error) {
|
||||
Desc: definition.Description,
|
||||
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
|
||||
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
|
||||
"start_date": {Type: schema.String, Desc: "预报开始日期,YYYY-MM-DD;不传则查当前天气"},
|
||||
"start_date": {Type: schema.String, Desc: "预报开始日期,YYYY-MM-DD;不传则查北京时间今天的预报"},
|
||||
"end_date": {Type: schema.String, Desc: "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"},
|
||||
}),
|
||||
}, nil
|
||||
|
||||
@@ -16,9 +16,17 @@ import (
|
||||
|
||||
func forecastDates(args model.WeatherArguments, now time.Time) (time.Time, time.Time, error) {
|
||||
zone := time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
start, err := time.ParseInLocation(time.DateOnly, args.StartDate, zone)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("start_date 必须是 YYYY-MM-DD 格式的有效日期")
|
||||
now = now.In(zone)
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, zone)
|
||||
start := today
|
||||
var err error
|
||||
if args.StartDate != "" {
|
||||
start, err = time.ParseInLocation(time.DateOnly, args.StartDate, zone)
|
||||
if err != nil {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("start_date 必须是 YYYY-MM-DD 格式的有效日期")
|
||||
}
|
||||
} else if args.EndDate != "" {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("end_date 不能单独提供,请同时提供 start_date")
|
||||
}
|
||||
end := start
|
||||
if args.EndDate != "" {
|
||||
@@ -27,7 +35,6 @@ func forecastDates(args model.WeatherArguments, now time.Time) (time.Time, time.
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("end_date 必须是 YYYY-MM-DD 格式的有效日期")
|
||||
}
|
||||
}
|
||||
today, _ := time.ParseInLocation(time.DateOnly, now.In(zone).Format(time.DateOnly), zone)
|
||||
last := today.AddDate(0, 0, 15)
|
||||
if end.Before(start) {
|
||||
return time.Time{}, time.Time{}, fmt.Errorf("结束日期不能早于开始日期")
|
||||
|
||||
@@ -21,6 +21,7 @@ func TestForecastDates(t *testing.T) {
|
||||
name, start, end, wantEnd string
|
||||
invalid bool
|
||||
}{
|
||||
{name: "默认今天", wantEnd: "2027-01-01"},
|
||||
{name: "单日", start: "2027-01-02", wantEnd: "2027-01-02"},
|
||||
{name: "整个窗口", start: "2027-01-01", end: "2027-01-16", wantEnd: "2027-01-16"},
|
||||
{name: "缺少开始日期", end: "2027-01-02", invalid: true},
|
||||
@@ -39,7 +40,11 @@ func TestForecastDates(t *testing.T) {
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || start.Format(time.DateOnly) != tt.start || end.Format(time.DateOnly) != tt.wantEnd {
|
||||
wantStart := tt.start
|
||||
if wantStart == "" {
|
||||
wantStart = "2027-01-01"
|
||||
}
|
||||
if err != nil || start.Format(time.DateOnly) != wantStart || end.Format(time.DateOnly) != tt.wantEnd {
|
||||
t.Fatalf("日期范围 = %s 至 %s,错误 = %v", start, end, err)
|
||||
}
|
||||
})
|
||||
@@ -111,8 +116,9 @@ func TestForecastInvalidArguments(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ }))
|
||||
defer server.Close()
|
||||
weather := NewWeather()
|
||||
weather.baseURL, weather.geocodingURL = server.URL, server.URL
|
||||
weather.geocodingURL = server.URL
|
||||
for _, args := range []string{
|
||||
`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`,
|
||||
`{"location":"北京","end_date":"2026-11-20"}`,
|
||||
`{"location":"北京","start_date":"明天"}`,
|
||||
`{"location":"北京","start_date":"2000-01-01"}`,
|
||||
|
||||
+27
-62
@@ -2,84 +2,49 @@ package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"example.com/ueino/pkg/model"
|
||||
)
|
||||
|
||||
func TestWeatherExecute(t *testing.T) {
|
||||
location := "北京 海淀/?&"
|
||||
func TestWeatherDefaultsToToday(t *testing.T) {
|
||||
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
|
||||
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)
|
||||
if r.URL.Path == "/search" {
|
||||
if r.URL.Query().Get("name") != "北京" {
|
||||
t.Errorf("地点参数错误: %s", r.URL)
|
||||
}
|
||||
fmt.Fprint(w, `{"results":[{"name":"北京","country":"中国","latitude":39.9,"longitude":116.4}]}`)
|
||||
return
|
||||
}
|
||||
query := r.URL.Query()
|
||||
if query.Get("format") != "3" || query.Get("lang") != "zh" || !query.Has("m") {
|
||||
t.Errorf("查询参数不正确: %v", query)
|
||||
if r.URL.Path != "/forecast" || r.URL.Query().Get("start_date") != today || r.URL.Query().Get("end_date") != today {
|
||||
t.Errorf("未指定日期时应查询北京时间今天: %s", r.URL)
|
||||
}
|
||||
fmt.Fprint(w, "北京: 晴 +20°C\n")
|
||||
json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{
|
||||
"time": []string{today}, "weather_code": []int{0},
|
||||
"temperature_2m_min": []int{10}, "temperature_2m_max": []int{20},
|
||||
"precipitation_probability_max": []int{0},
|
||||
}})
|
||||
}))
|
||||
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)
|
||||
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
|
||||
result, err := weather.Execute(context.Background(), `{"location":" 北京 "}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, arguments := range []string{`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`} {
|
||||
if _, err := weather.Execute(context.Background(), arguments); err == nil {
|
||||
t.Fatalf("参数 %s 应报错", arguments)
|
||||
}
|
||||
var forecast model.WeatherForecast
|
||||
if err := json.Unmarshal([]byte(result), &forecast); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
if calls != 2 || len(forecast.Days) != 1 || forecast.Days[0].Date != today || forecast.Days[0].Condition != "晴" {
|
||||
t.Fatalf("默认查询结果不正确: %+v,请求次数=%d", forecast, calls)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user