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

+2 -1
View File
@@ -47,7 +47,8 @@ func New(ctx context.Context, cfg config.Config) (*Agent, error) {
mainAgent, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{
Name: mainAgentName, Instruction: instruction, Model: chat, MaxIterations: opt.MAX_TOOL_ROUND,
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}, EmitInternalEvents: true},
GenModelInput: genModelInput,
ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: tools}, EmitInternalEvents: true},
})
if err != nil {
+33
View File
@@ -0,0 +1,33 @@
package agent
import (
"context"
"fmt"
"time"
"github.com/cloudwego/eino/adk"
"github.com/cloudwego/eino/schema"
)
func genModelInput(_ context.Context, instruction string, input *adk.AgentInput) ([]adk.Message, error) {
messages := []adk.Message{schema.SystemMessage(timedInstruction(instruction, time.Now()))}
return append(messages, input.Messages...), nil
}
// timedInstruction 每轮生成时间信息,避免使用进程启动时的旧日期。
func timedInstruction(instruction string, now time.Time) string {
now = now.In(time.FixedZone("Asia/Shanghai", 8*60*60))
weekdays := [...]string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
// 按周一至周日确定当前周,给模型明确的日期参照。
weekday := (int(now.Weekday()) + 6) % 7
saturday := now.AddDate(0, 0, 5-weekday)
return instruction + fmt.Sprintf(`
当前日期:%s,%s,时区:Asia/Shanghai(UTC+08:00)。
明天:%s;本周六:%s;本周日:%s。
查询天气时将相对时间换算为 YYYY-MM-DD,日期参数只能是一个完整日期,不要把多个日期拼进同一个字段。
查询本周末两天时,日期参数示例:{"start_date":"%s","end_date":"%s"},location 使用用户指定的地点。日期存在歧义时先询问。
未提供查询地点且历史中也没有时,先询问,不要猜测。收到预报后直接根据结果回答,不重复查询相同日期;无法获取时如实说明,不用当前天气代替目标日期预报。`,
now.Format(time.DateOnly), weekdays[now.Weekday()], now.AddDate(0, 0, 1).Format(time.DateOnly),
saturday.Format(time.DateOnly), saturday.AddDate(0, 0, 1).Format(time.DateOnly),
saturday.Format(time.DateOnly), saturday.AddDate(0, 0, 1).Format(time.DateOnly))
}
+45
View File
@@ -0,0 +1,45 @@
package agent
import (
"context"
"strings"
"testing"
"time"
"github.com/cloudwego/eino/adk"
"github.com/cloudwego/eino/schema"
)
func TestTimedInstruction(t *testing.T) {
// 同一进程跨越北京时间午夜后,日期与星期都必须更新。
before := time.Date(2026, 11, 18, 15, 59, 0, 0, time.UTC)
after := before.Add(time.Minute)
for _, tt := range []struct {
now time.Time
date string
day string
}{
{before, "2026-11-18", "星期三"},
{after, "2026-11-19", "星期四"},
} {
prompt := timedInstruction("原有指令", tt.now)
for _, expected := range []string{"原有指令", tt.date, tt.day, "Asia/Shanghai", "YYYY-MM-DD", "先询问", `"start_date":"2026-11-21","end_date":"2026-11-22"`} {
if !strings.Contains(prompt, expected) {
t.Errorf("系统消息缺少 %q", expected)
}
}
}
}
func TestGenModelInput(t *testing.T) {
user := schema.UserMessage("明天北京的天气")
input := &adk.AgentInput{Messages: []adk.Message{user}}
messages, err := genModelInput(context.Background(), "原有指令", input)
if err != nil || len(messages) != 2 || messages[0].Role != schema.System || messages[1] != user || len(input.Messages) != 1 {
t.Fatalf("模型输入 = %+v,错误 = %v", messages, err)
}
date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly)
if !strings.Contains(messages[0].Content, date) {
t.Fatal("系统消息缺少当前日期")
}
}
+96
View File
@@ -0,0 +1,96 @@
package agent
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"example.com/ueino/adk/internal/config"
"example.com/ueino/pkg/model"
)
func TestChatForecast(t *testing.T) {
for _, days := range []int{1, 2} {
t.Run(fmt.Sprintf("预报%d天", days), func(t *testing.T) {
today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60))
start, end := today.AddDate(0, 0, 1).Format(time.DateOnly), today.AddDate(0, 0, days).Format(time.DateOnly)
previous := http.DefaultTransport
var weatherCalls atomic.Int32
http.DefaultTransport = roundTripperFunc(func(r *http.Request) (*http.Response, error) {
var response any
switch r.URL.Host {
case "geocoding-api.open-meteo.com":
if r.URL.Query().Get("name") != "北京" {
t.Errorf("城市提取错误: %s", r.URL)
}
response = map[string]any{"results": []map[string]any{{"name": "北京", "country": "中国", "latitude": 39.9, "longitude": 116.4}}}
case "api.open-meteo.com":
if r.URL.Query().Get("start_date") != start || r.URL.Query().Get("end_date") != end {
t.Errorf("日期传递错误: %s", r.URL)
}
dates, codes := []string{}, []int{}
maxTemps, minTemps, rain := []int{}, []int{}, []int{}
for i := 1; i <= days; i++ {
dates = append(dates, today.AddDate(0, 0, i).Format(time.DateOnly))
codes, maxTemps, minTemps, rain = append(codes, 61), append(maxTemps, 18), append(minTemps, 8), append(rain, 70)
}
response = map[string]any{"daily": map[string]any{"time": dates, "weather_code": codes, "temperature_2m_max": maxTemps, "temperature_2m_min": minTemps, "precipitation_probability_max": rain}}
default:
return previous.RoundTrip(r)
}
weatherCalls.Add(1)
data, _ := json.Marshal(response)
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: make(http.Header), Request: r}, nil
})
t.Cleanup(func() { http.DefaultTransport = previous })
var modelCalls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request model.ChatCompletionRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Error(err)
}
if !strings.Contains(request.Messages[0].Content.(string), today.Format(time.DateOnly)) || !strings.Contains(request.Messages[0].Content.(string), "Asia/Shanghai") {
t.Error("系统消息缺少当前日期或时区")
}
properties := request.Tools[0].Function.Parameters["properties"].(map[string]any)
if properties["start_date"] == nil || properties["end_date"] == nil {
t.Error("Eino 工具定义缺少日期参数")
}
if modelCalls.Add(1) == 1 {
arguments, _ := json.Marshal(model.WeatherArguments{Location: "北京", StartDate: start, EndDate: end})
writeCompletion(w, request.Stream, "", []model.ToolCall{{ID: "forecast-1", Type: "function", Function: model.ToolFunction{Name: "get_weather", Arguments: string(arguments)}}})
return
}
last := request.Messages[len(request.Messages)-1]
var forecast model.WeatherForecast
if last.Role != "tool" || last.ToolCallID != "forecast-1" {
t.Errorf("工具消息不正确: %+v", last)
} else if err := json.Unmarshal([]byte(last.Content.(string)), &forecast); err != nil || len(forecast.Days) != days || forecast.Days[0].Date != start || forecast.Days[0].Condition != "小雨" {
t.Errorf("预报没有正确回传: %+v,%v", forecast, err)
}
writeCompletion(w, request.Stream, start+" 北京小雨,记得带伞。", nil)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
chat, err := New(ctx, config.Config{Chat: config.ModelConfig{BaseURL: server.URL, Model: "test-model"}, MaxToken: 4096})
if err != nil {
t.Fatal(err)
}
var output strings.Builder
if err := chat.Chat(ctx, "查询北京的预报", func(s string) { output.WriteString(s) }, nil, nil); err != nil {
t.Fatal(err)
}
if modelCalls.Load() != 2 || weatherCalls.Load() != 2 || !strings.Contains(output.String(), start) || !strings.Contains(output.String(), "小雨") {
t.Fatalf("模型调用=%d,天气请求=%d,输出=%q", modelCalls.Load(), weatherCalls.Load(), output.String())
}
})
}
}