76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
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
|
|
}
|