package tool import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "time" "example.com/ueino/pkg/model" ) // Weather 查询 wttr.in 当前天气或 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", geocodingURL: "https://geocoding-api.open-meteo.com/v1/search", forecastURL: "https://api.open-meteo.com/v1/forecast", } } func (w *Weather) Definition() model.ToolDefinition { return model.ToolDefinition{ Type: "function", Function: model.ToolFunctionDefinition{ Name: "get_weather", 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;不传则查当前天气"}, "end_date": map[string]string{"type": "string", "description": "预报结束日期,YYYY-MM-DD,含当天;不传则只查开始日期,不能单独提供"}, }, "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("请提供要查询的地点") } 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 }