feat: add date-based weather forecasts and dynamic time context

This commit is contained in:
loveuer committed 2026-11-18 11:30:38 +08:00
1 parent a394f22d77
commit 975352c7d6
12 files changed
+607 -15

No files matched your search

+20 -6
View File
@@ -13,14 +13,20 @@ import (
"example.com/ueino/pkg/model"
)
// Weather 通过 wttr.in 查询当前天气。
// Weather 查询 wttr.in 当前天气或 Open-Meteo 日期预报。
type Weather struct {
client *http.Client
baseURL string
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"}
return &Weather{
client: &http.Client{Timeout: 10 * time.Second}, baseURL: "https://wttr.in",
geocodingURL: "https://geocoding-api.open-meteo.com/v1/search",
forecastURL: "https://api.open-meteo.com/v1/forecast",
}
}
func (w *Weather) Definition() model.ToolDefinition {
@@ -28,11 +34,13 @@ func (w *Weather) Definition() model.ToolDefinition {
Type: "function",
Function: model.ToolFunctionDefinition{
Name: "get_weather",
Description: "查询指定地点的当前天气,不提供未来预报。地点可从当前对话中获取;如果未提供地点,先询问用户,不要猜测。",
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": "需要查询的城市或地点,例如北京、上海"},
"location": map[string]string{"type": "string", "description": "需要查询的城市或地点,例如北京、上海"},
"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"},
},
@@ -49,6 +57,12 @@ func (w *Weather) Execute(ctx context.Context, arguments string) (string, error)
if location == "" {
return "", fmt.Errorf("请提供要查询的地点")
}
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)
+3 -1
View File
@@ -14,7 +14,9 @@ func (w *Weather) Info(ctx context.Context) (*schema.ToolInfo, error) {
Name: definition.Name,
Desc: definition.Description,
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
"location": {Type: schema.String, Required: true, Desc: "需要查询的城市或地点,例如北京、上海"},
"start_date": {Type: schema.String, Desc: "预报开始日期,YYYY-MM-DD;不传则查当前天气"},
"end_date": {Type: schema.String, Desc: "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"},
}),
}, nil
}
+144
View File
@@ -0,0 +1,144 @@
package tool
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"time"
"example.com/ueino/pkg/model"
)
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 格式的有效日期")
}
end := start
if args.EndDate != "" {
end, err = time.ParseInLocation(time.DateOnly, args.EndDate, zone)
if err != nil {
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("结束日期不能早于开始日期")
}
if start.Before(today) || end.After(last) {
return time.Time{}, time.Time{}, fmt.Errorf("预报仅支持 %s 至 %s,不支持历史或更远日期", today.Format(time.DateOnly), last.Format(time.DateOnly))
}
return start, end, nil
}
func (w *Weather) forecast(ctx context.Context, args model.WeatherArguments) (string, error) {
start, end, err := forecastDates(args, time.Now())
if err != nil {
return "", err
}
search := url.Values{"name": {args.Location}, "count": {"1"}, "language": {"zh"}, "format": {"json"}}
var locations model.WeatherLocations
if err := w.getWeatherJSON(ctx, w.geocodingURL+"?"+search.Encode(), &locations); err != nil {
return "", err
}
if len(locations.Results) == 0 {
return "", fmt.Errorf("未找到地点 %q,请提供明确的城市名称", args.Location)
}
location := locations.Results[0]
query := url.Values{
"latitude": {strconv.FormatFloat(location.Latitude, 'f', -1, 64)},
"longitude": {strconv.FormatFloat(location.Longitude, 'f', -1, 64)},
"start_date": {start.Format(time.DateOnly)}, "end_date": {end.Format(time.DateOnly)},
"timezone": {"Asia/Shanghai"},
"daily": {"weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"},
}
var response model.WeatherDailyResponse
if err := w.getWeatherJSON(ctx, w.forecastURL+"?"+query.Encode(), &response); err != nil {
return "", err
}
result := model.WeatherForecast{
Location: strings.TrimSpace(location.Name + " " + location.Admin1 + " " + location.Country),
Timezone: "Asia/Shanghai",
}
daily := response.Daily
for date := start; !date.After(end); date = date.AddDate(0, 0, 1) {
day := date.Format(time.DateOnly)
index := slices.Index(daily.Dates, day)
if index < 0 || index >= len(daily.Codes) || index >= len(daily.MaxTemps) || index >= len(daily.MinTemps) || index >= len(daily.RainChances) {
return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day)
}
if daily.Codes[index] == nil || daily.MaxTemps[index] == nil || daily.MinTemps[index] == nil || daily.RainChances[index] == nil {
return "", fmt.Errorf("天气接口未提供 %s 的完整预报,无法查询该日期范围", day)
}
result.Days = append(result.Days, model.WeatherDay{
Date: day, Condition: weatherCondition(*daily.Codes[index]),
MinTemperatureC: *daily.MinTemps[index], MaxTemperatureC: *daily.MaxTemps[index],
PrecipitationChancePct: *daily.RainChances[index],
})
}
data, err := json.Marshal(result)
return string(data), err
}
func (w *Weather) getWeatherJSON(ctx context.Context, endpoint string, result any) error {
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)
}
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return fmt.Errorf("解析天气接口响应失败: %w", err)
}
return nil
}
func weatherCondition(code int) string {
switch code {
case 0:
return "晴"
case 1:
return "大部晴朗"
case 2:
return "多云"
case 3:
return "阴"
case 45, 48:
return "雾"
case 51, 53, 55:
return "毛毛雨"
case 56, 57, 66, 67:
return "冻雨"
case 61:
return "小雨"
case 63:
return "中雨"
case 65:
return "大雨"
case 71, 73, 75, 77:
return "雪"
case 80, 81, 82:
return "阵雨"
case 85, 86:
return "阵雪"
case 95:
return "雷暴"
case 96, 99:
return "雷暴伴冰雹"
default:
return fmt.Sprintf("未知天气(WMO %d)", code)
}
}
+201
View File
@@ -0,0 +1,201 @@
package tool
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"example.com/ueino/pkg/model"
)
func TestForecastDates(t *testing.T) {
// UTC 尚未跨年,北京时间已是下一年的第一天。
now := time.Date(2026, 12, 31, 16, 30, 0, 0, time.UTC)
for _, tt := range []struct {
name, start, end, wantEnd string
invalid bool
}{
{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},
{name: "相对日期", start: "明天", invalid: true},
{name: "无效日期", start: "2027-02-30", invalid: true},
{name: "无效结束", start: "2027-01-02", end: "周末", invalid: true},
{name: "过去日期", start: "2026-12-31", invalid: true},
{name: "超出窗口", start: "2027-01-16", end: "2027-01-17", invalid: true},
{name: "反向范围", start: "2027-01-02", end: "2027-01-01", invalid: true},
} {
t.Run(tt.name, func(t *testing.T) {
start, end, err := forecastDates(model.WeatherArguments{StartDate: tt.start, EndDate: tt.end}, now)
if tt.invalid {
if err == nil {
t.Fatal("预期参数错误")
}
return
}
if err != nil || start.Format(time.DateOnly) != tt.start || end.Format(time.DateOnly) != tt.wantEnd {
t.Fatalf("日期范围 = %s 至 %s,错误 = %v", start, end, err)
}
})
}
}
func TestWeatherForecast(t *testing.T) {
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
for _, days := range []int{1, 2} {
t.Run(fmt.Sprintf("%d天", days), func(t *testing.T) {
start := today.AddDate(0, 0, 1).Format(time.DateOnly)
end := today.AddDate(0, 0, days).Format(time.DateOnly)
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.Method != http.MethodGet {
t.Error("应使用 GET")
}
query := r.URL.Query()
if r.URL.Path == "/search" {
if query.Get("name") != "北京 海淀/?&" || query.Get("count") != "1" || query.Get("language") != "zh" {
t.Errorf("地点查询编码错误: %v", query)
}
fmt.Fprint(w, `{"results":[{"name":"北京","admin1":"北京市","country":"中国","latitude":39.9,"longitude":116.4}]}`)
return
}
if r.URL.Path != "/forecast" || query.Get("latitude") != "39.9" || query.Get("longitude") != "116.4" || query.Get("start_date") != start || query.Get("end_date") != end || query.Get("timezone") != "Asia/Shanghai" || query.Get("daily") != "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max" {
t.Errorf("预报请求错误: %s", r.URL)
}
// 返回乱序日期及额外日期,必须按请求范围提取排序。
json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{
"time": []string{today.AddDate(0, 0, 2).Format(time.DateOnly), start, today.Format(time.DateOnly)},
"weather_code": []int{61, 0, 3}, "temperature_2m_max": []float64{12, 18, 15},
"temperature_2m_min": []float64{3, 8, 6}, "precipitation_probability_max": []float64{80, 0, 30},
}})
}))
defer server.Close()
weather := NewWeather()
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
args := model.WeatherArguments{Location: " 北京 海淀/?& ", StartDate: start}
if days == 2 {
args.EndDate = end
}
arguments, _ := json.Marshal(args)
result, err := weather.Execute(context.Background(), string(arguments))
if err != nil {
t.Fatal(err)
}
var forecast model.WeatherForecast
if err := json.Unmarshal([]byte(result), &forecast); err != nil {
t.Fatal(err)
}
if calls != 2 || forecast.Location != "北京 北京市 中国" || forecast.Timezone != "Asia/Shanghai" || len(forecast.Days) != days {
t.Fatalf("预报结果 = %+v,调用次数 = %d", forecast, calls)
}
first := forecast.Days[0]
if first.Date != start || first.Condition != "晴" || first.MinTemperatureC != 8 || first.MaxTemperatureC != 18 || first.PrecipitationChancePct != 0 {
t.Fatalf("单日数据错误: %+v", first)
}
if days == 2 && (forecast.Days[1].Date != end || forecast.Days[1].Condition != "小雨") {
t.Fatalf("日期顺序错误: %+v", forecast.Days)
}
})
}
}
func TestForecastInvalidArguments(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ }))
defer server.Close()
weather := NewWeather()
weather.baseURL, weather.geocodingURL = server.URL, server.URL
for _, args := range []string{
`{"location":"北京","end_date":"2026-11-20"}`,
`{"location":"北京","start_date":"明天"}`,
`{"location":"北京","start_date":"2000-01-01"}`,
`{"location":"北京","start_date":"2999-01-01"}`,
`{"start_date":"2026-11-19"}`,
`{"location":"北京","start_date":123}`,
} {
if _, err := weather.Execute(context.Background(), args); err == nil {
t.Errorf("参数 %s 应返回错误", args)
}
}
if calls != 0 {
t.Fatalf("无效参数请求了接口 %d 次", calls)
}
}
func TestForecastResponseErrors(t *testing.T) {
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
for _, mode := range []string{"查无城市", "搜索失败", "预报失败", "错误JSON", "缺少日期", "缺少字段", "字段为空"} {
t.Run(mode, func(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.URL.Path == "/search" {
switch mode {
case "查无城市":
fmt.Fprint(w, `{}`)
case "搜索失败":
w.WriteHeader(http.StatusServiceUnavailable)
case "错误JSON":
fmt.Fprint(w, "{")
default:
fmt.Fprint(w, `{"results":[{"name":"北京","latitude":39.9,"longitude":116.4}]}`)
}
return
}
if mode == "预报失败" {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
daily := map[string]any{
"time": []string{date}, "weather_code": []int{0},
"temperature_2m_max": []float64{18}, "temperature_2m_min": []float64{8},
"precipitation_probability_max": []float64{0},
}
switch mode {
case "缺少日期":
daily["time"] = []string{}
case "缺少字段":
delete(daily, "temperature_2m_min")
case "字段为空":
daily["weather_code"] = []any{nil}
}
json.NewEncoder(w).Encode(map[string]any{"daily": daily})
}))
defer server.Close()
weather := NewWeather()
weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast"
args := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date)
if _, err := weather.Execute(context.Background(), args); err == nil {
t.Fatal("接口异常应返回错误")
}
if (mode == "查无城市" || mode == "搜索失败" || mode == "错误JSON") && calls != 1 {
t.Fatal("城市查询失败后不应请求预报")
}
})
}
}
func TestForecastCancellationAndTimeout(t *testing.T) {
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
arguments := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() }))
defer server.Close()
weather := NewWeather()
weather.geocodingURL = server.URL
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := weather.Execute(ctx, arguments); !errors.Is(err, context.Canceled) {
t.Fatalf("取消错误 = %v", err)
}
weather.client.Timeout = 20 * time.Millisecond
if _, err := weather.Execute(context.Background(), arguments); err == nil || !strings.Contains(err.Error(), "Client.Timeout") {
t.Fatalf("超时错误 = %v", err)
}
}