From 1512f0516f81b411d0b2866569bd8cbcf04be821 Mon Sep 17 00:00:00 2001 From: "zhaoyupeng.elqb" Date: Thu, 19 Nov 2026 10:44:56 +0800 Subject: [PATCH] feat: add weather tracing and unify example system prompts Move shared prompt constants into pkg/opt and use them across examples. Add agent, model, and tool tracing to the weather example, with tests, and update weather argument descriptions and parse-error logging. Strip timestamp and speaker markers from final ADK voice transcripts, keeping normal bracketed text and treating marker-only results as empty. Co-authored-by: TRAE CLI --- adk/internal/agent/agent.go | 2 +- adk/internal/terminal/voice.go | 6 +- adk/internal/terminal/voice_test.go | 21 +++- legacy/main.go | 2 +- legacy/round/round.go | 2 +- {internal => pkg}/opt/const.go | 0 pkg/tool/weather.go | 2 + pkg/tool/weather_eino.go | 4 +- steps/asr/internal/chain.go | 3 +- steps/basic/main.go | 3 +- steps/interaction/main.go | 3 +- steps/trans/internal/chain.go | 6 +- steps/weather/internal/trace.go | 160 +++++++++++++++++++++++++++ steps/weather/internal/trace_test.go | 128 +++++++++++++++++++++ steps/weather/main.go | 7 +- 15 files changed, 332 insertions(+), 17 deletions(-) rename {internal => pkg}/opt/const.go (100%) create mode 100644 steps/weather/internal/trace.go create mode 100644 steps/weather/internal/trace_test.go diff --git a/adk/internal/agent/agent.go b/adk/internal/agent/agent.go index 3946efb..5544155 100644 --- a/adk/internal/agent/agent.go +++ b/adk/internal/agent/agent.go @@ -6,8 +6,8 @@ import ( "strings" "example.com/ueino/adk/internal/config" - "example.com/ueino/internal/opt" "example.com/ueino/pkg/memory" + "example.com/ueino/pkg/opt" "example.com/ueino/pkg/provider" "example.com/ueino/pkg/tool" diff --git a/adk/internal/terminal/voice.go b/adk/internal/terminal/voice.go index 5f39fa0..5e2ec30 100644 --- a/adk/internal/terminal/voice.go +++ b/adk/internal/terminal/voice.go @@ -8,6 +8,7 @@ import ( "io" "os" "os/exec" + "regexp" "runtime" "strings" @@ -15,6 +16,8 @@ import ( "example.com/ueino/pkg/provider" ) +var transcriptMarkers = regexp.MustCompile(`\[(?:[0-9]+(?:\.[0-9]+)?|S[0-9]+)\]`) + type voiceResult struct { text string err error @@ -112,7 +115,8 @@ func recordVoice(ctx context.Context, cmd *exec.Cmd, input *terminalInput, if result.err != nil { return "", fmt.Errorf("%w %s", result.err, strings.TrimSpace(stderr.String())) } - if strings.TrimSpace(result.text) == "" { + result.text = strings.TrimSpace(transcriptMarkers.ReplaceAllString(result.text, "")) + if result.text == "" { fmt.Println("未识别到文字,请重新输入。") return "", nil } diff --git a/adk/internal/terminal/voice_test.go b/adk/internal/terminal/voice_test.go index 274e786..53929f8 100644 --- a/adk/internal/terminal/voice_test.go +++ b/adk/internal/terminal/voice_test.go @@ -38,7 +38,7 @@ func TestRecordVoice(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("录音控制使用 Unix 信号") } - for _, mode := range []string{"automatic", "manual", "failure", "asr-failure", "empty", "cancel", "eof"} { + for _, mode := range []string{"automatic", "manual", "marked", "markers-only", "brackets", "failure", "asr-failure", "empty", "cancel", "eof"} { t.Run(mode, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -73,8 +73,15 @@ func TestRecordVoice(t *testing.T) { if _, err := io.ReadAll(audio); err != nil { return "", err } - if mode == "empty" { + switch mode { + case "empty": return "", nil + case "marked": + return " [0.00][S01]嗯,帮我查询一下成都后面[3.00]\n[0.00][S02]两天的天气。[0.98] ", nil + case "markers-only": + return " [0.00][S01][0.98] ", nil + case "brackets": + return "请保留[备注]和[123abc]。", nil } return "最终识别", nil }) @@ -94,12 +101,18 @@ func TestRecordVoice(t *testing.T) { if !errors.Is(err, io.EOF) { t.Fatalf("预期输入结束,得到 %v", err) } - case "empty": + case "empty", "markers-only": if text != "" || err != nil { t.Fatalf("空转写 = %q,%v", text, err) } default: - if text != "最终识别" || err != nil { + want := "最终识别" + if mode == "marked" { + want = "嗯,帮我查询一下成都后面\n两天的天气。" + } else if mode == "brackets" { + want = "请保留[备注]和[123abc]。" + } + if text != want || err != nil { t.Fatalf("转写 = %q,%v", text, err) } if mode == "manual" { diff --git a/legacy/main.go b/legacy/main.go index 9e7f81e..7fd2a2f 100644 --- a/legacy/main.go +++ b/legacy/main.go @@ -11,10 +11,10 @@ import ( "strings" "syscall" - "example.com/ueino/internal/opt" "example.com/ueino/legacy/round" "example.com/ueino/pkg/memory" "example.com/ueino/pkg/model" + "example.com/ueino/pkg/opt" "example.com/ueino/pkg/provider" "example.com/ueino/pkg/tool" ) diff --git a/legacy/round/round.go b/legacy/round/round.go index 1d185d2..3e02d57 100644 --- a/legacy/round/round.go +++ b/legacy/round/round.go @@ -5,8 +5,8 @@ import ( "fmt" "log" - "example.com/ueino/internal/opt" "example.com/ueino/pkg/model" + "example.com/ueino/pkg/opt" "example.com/ueino/pkg/tool" ) diff --git a/internal/opt/const.go b/pkg/opt/const.go similarity index 100% rename from internal/opt/const.go rename to pkg/opt/const.go diff --git a/pkg/tool/weather.go b/pkg/tool/weather.go index 52b9593..5cb1c26 100644 --- a/pkg/tool/weather.go +++ b/pkg/tool/weather.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "log" "net/http" "strings" "time" @@ -48,6 +49,7 @@ func (w *Weather) Definition() model.ToolDefinition { func (w *Weather) Execute(ctx context.Context, arguments string) (string, error) { var args model.WeatherArguments if err := json.Unmarshal([]byte(arguments), &args); err != nil { + log.Printf("[D] unmarshal weather arguments failed, err = %v, raw = %s", err, arguments) return "", fmt.Errorf("天气参数无效: %w", err) } location := strings.TrimSpace(args.Location) diff --git a/pkg/tool/weather_eino.go b/pkg/tool/weather_eino.go index ce39602..3b4965f 100644 --- a/pkg/tool/weather_eino.go +++ b/pkg/tool/weather_eino.go @@ -15,8 +15,8 @@ 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;不传则查北京时间今天的预报"}, - "end_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 } diff --git a/steps/asr/internal/chain.go b/steps/asr/internal/chain.go index cd42f4a..73d78d7 100644 --- a/steps/asr/internal/chain.go +++ b/steps/asr/internal/chain.go @@ -10,6 +10,7 @@ import ( "strings" "sync" + "example.com/ueino/pkg/opt" "example.com/ueino/pkg/provider" "github.com/cloudwego/eino/components/model" "github.com/cloudwego/eino/compose" @@ -134,7 +135,7 @@ func newTranscriptCollector(show func(Transcript)) *compose.Lambda { func beforeChat(ctx context.Context, messages []*schema.Message, _ *struct{}) ([]*schema.Message, error) { // 在调用模型前插入 system prompt,可在这里按需改写消息。 - return append([]*schema.Message{schema.SystemMessage("你是一个简洁的中文助手。")}, messages...), nil + return append([]*schema.Message{schema.SystemMessage(opt.SYSTEM_PROMPT)}, messages...), nil } // pcmReader 把 Eino 的块流适配给 ASR provider 的 io.Reader。 diff --git a/steps/basic/main.go b/steps/basic/main.go index 07e3d8c..1c3ee6a 100644 --- a/steps/basic/main.go +++ b/steps/basic/main.go @@ -9,6 +9,7 @@ import ( "os/signal" "syscall" + "example.com/ueino/pkg/opt" "example.com/ueino/steps/basic/internal" "github.com/cloudwego/eino/adk" "github.com/cloudwego/eino/components/tool" @@ -21,7 +22,7 @@ func main() { assistant, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{ Name: "terminal_chat", - Instruction: "你是一个简洁的中文助手。", + Instruction: opt.SYSTEM_PROMPT, Model: internal.MustNewChatModel(ctx), MaxIterations: 10, ToolsConfig: adk.ToolsConfig{ diff --git a/steps/interaction/main.go b/steps/interaction/main.go index d8ca835..0caeb62 100644 --- a/steps/interaction/main.go +++ b/steps/interaction/main.go @@ -11,6 +11,7 @@ import ( "strings" "syscall" + "example.com/ueino/pkg/opt" "example.com/ueino/steps/interaction/internal" "github.com/cloudwego/eino/adk" "github.com/cloudwego/eino/components/tool" @@ -37,7 +38,7 @@ func main() { assistant, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{ Name: "terminal_chat", - Instruction: "你是一个简洁的中文助手。", + Instruction: opt.SYSTEM_PROMPT, Model: internal.MustNewChatModel(ctx), MaxIterations: 10, ToolsConfig: adk.ToolsConfig{ diff --git a/steps/trans/internal/chain.go b/steps/trans/internal/chain.go index 761e6ae..9dc1053 100644 --- a/steps/trans/internal/chain.go +++ b/steps/trans/internal/chain.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "example.com/ueino/pkg/opt" "github.com/cloudwego/eino/components/model" "github.com/cloudwego/eino/compose" "github.com/cloudwego/eino/schema" @@ -46,9 +47,10 @@ func NewChain(ctx context.Context, chat model.BaseChatModel) (compose.Runnable[[ func beforeChat(ctx context.Context, messages []*schema.Message, _ *struct{}) ([]*schema.Message, error) { now := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)) - sp := fmt.Sprintf(`你是一个简洁的中文助手。 + sp := fmt.Sprintf(`%s --- -"当前时区:Asia/Shanghai(UTC+08:00)\n当前时间:%s`, now.Format("2006-01-02 15:04:05")) +"当前时区:Asia/Shanghai(UTC+08:00) +当前时间:%s`, opt.SYSTEM_PROMPT, now.Format("2006-01-02 15:04:05")) return append([]*schema.Message{schema.SystemMessage(sp)}, messages...), nil } diff --git a/steps/weather/internal/trace.go b/steps/weather/internal/trace.go new file mode 100644 index 0000000..1320fde --- /dev/null +++ b/steps/weather/internal/trace.go @@ -0,0 +1,160 @@ +package internal + +import ( + "context" + "fmt" + "io" + "log" + "sync" + "sync/atomic" + "time" + + "github.com/cloudwego/eino/adk" + "github.com/cloudwego/eino/callbacks" + "github.com/cloudwego/eino/components" + "github.com/cloudwego/eino/components/model" + "github.com/cloudwego/eino/components/tool" + "github.com/cloudwego/eino/schema" +) + +type traceKey struct{} + +type traceSpan struct { + id uint64 + parent uint64 + name string + started time.Time +} + +type TraceHandler struct { + callbacks.Handler + next atomic.Uint64 + pending sync.WaitGroup +} + +func NewTraceHandler() *TraceHandler { + h := &TraceHandler{} + h.Handler = callbacks.NewHandlerBuilder(). + OnStartFn(h.start). + OnEndFn(h.end). + OnErrorFn(h.fail). + OnEndWithStreamOutputFn(h.endStream). + Build() + return h +} + +// Wait 等待回调的流副本读完,避免上一轮 trace 混入下一轮。 +func (h *TraceHandler) Wait() { + h.pending.Wait() +} + +func (h *TraceHandler) Needed(ctx context.Context, info *callbacks.RunInfo, timing callbacks.CallbackTiming) bool { + return traced(info) && h.Handler.(callbacks.TimingChecker).Needed(ctx, info, timing) +} + +func traced(info *callbacks.RunInfo) bool { + return info != nil && (info.Component == adk.ComponentOfAgent || + info.Component == components.ComponentOfChatModel || info.Component == components.ComponentOfTool) +} + +func (h *TraceHandler) start(ctx context.Context, info *callbacks.RunInfo, input callbacks.CallbackInput) context.Context { + if !traced(info) { + return ctx + } + span := &traceSpan{id: h.next.Add(1), name: fmt.Sprintf("%s/%s", info.Component, info.Name), started: time.Now()} + if parent, ok := ctx.Value(traceKey{}).(*traceSpan); ok { + span.parent = parent.id + } + log.Printf("[trace] start span=%d parent=%d %s", span.id, span.parent, span.name) + switch info.Component { + case components.ComponentOfChatModel: + if in := model.ConvCallbackInput(input); in != nil { + log.Printf("[trace] span=%d model input messages=%d", span.id, len(in.Messages)) + } + case components.ComponentOfTool: + if in := tool.ConvCallbackInput(input); in != nil { + log.Printf("[trace] span=%d tool arguments=%s", span.id, in.ArgumentsInJSON) + } + } + return context.WithValue(ctx, traceKey{}, span) +} + +func finishTrace(ctx context.Context, err error) { + if span, ok := ctx.Value(traceKey{}).(*traceSpan); ok { + log.Printf("[trace] end span=%d %s duration=%s error=%v", span.id, span.name, time.Since(span.started).Round(time.Millisecond), err) + } +} + +func (h *TraceHandler) end(ctx context.Context, info *callbacks.RunInfo, output callbacks.CallbackOutput) context.Context { + if !traced(info) { + return ctx + } + if out := adk.ConvAgentCallbackOutput(output); out != nil && out.Events != nil { + // Agent 返回的是事件迭代器;读完副本后才是整轮执行结束。 + h.pending.Add(1) + go func() { + defer h.pending.Done() + var runErr error + for { + event, ok := out.Events.Next() + if !ok { + break + } + if event.Err != nil { + runErr = event.Err + } + if event.Output != nil && event.Output.MessageOutput != nil { + if _, err := event.Output.MessageOutput.GetMessage(); err != nil { + runErr = err + } + } + } + finishTrace(ctx, runErr) + }() + return ctx + } + if info.Component == components.ComponentOfTool { + if out := tool.ConvCallbackOutput(output); out != nil { + log.Printf("[trace] tool output=%s", out.Response) + } + } + finishTrace(ctx, nil) + return ctx +} + +func (h *TraceHandler) fail(ctx context.Context, info *callbacks.RunInfo, err error) context.Context { + if traced(info) { + finishTrace(ctx, err) + } + return ctx +} + +func (h *TraceHandler) endStream(ctx context.Context, info *callbacks.RunInfo, output *schema.StreamReader[callbacks.CallbackOutput]) context.Context { + if !traced(info) { + output.Close() + return ctx + } + h.pending.Add(1) + go func() { + defer h.pending.Done() + defer output.Close() + chunks := 0 + for { + chunk, err := output.Recv() + if err == io.EOF { + log.Printf("[trace] model output chunks=%d", chunks) + finishTrace(ctx, nil) + return + } + if err != nil { + finishTrace(ctx, err) + return + } + chunks++ + if out := model.ConvCallbackOutput(chunk); out != nil && out.TokenUsage != nil { + log.Printf("[trace] model token usage=%+v", *out.TokenUsage) + } + } + }() + return ctx +} diff --git a/steps/weather/internal/trace_test.go b/steps/weather/internal/trace_test.go new file mode 100644 index 0000000..3e7ceef --- /dev/null +++ b/steps/weather/internal/trace_test.go @@ -0,0 +1,128 @@ +package internal + +import ( + "bytes" + "context" + "errors" + "io" + "log" + "strings" + "testing" + "time" + + "github.com/cloudwego/eino/adk" + "github.com/cloudwego/eino/components/model" + "github.com/cloudwego/eino/components/tool" + "github.com/cloudwego/eino/compose" + "github.com/cloudwego/eino/schema" +) + +type traceTestModel struct { + model.ToolCallingChatModel + calls int + err error +} + +func (m *traceTestModel) WithTools([]*schema.ToolInfo) (model.ToolCallingChatModel, error) { + return m, nil +} + +func (m *traceTestModel) Stream(context.Context, []*schema.Message, ...model.Option) (*schema.StreamReader[*schema.Message], error) { + if m.err != nil { + return nil, m.err + } + m.calls++ + if m.calls == 1 { + return schema.StreamReaderFromArray([]*schema.Message{ + schema.AssistantMessage("", []schema.ToolCall{{ID: "weather-1", Type: "function", Function: schema.FunctionCall{Name: "get_weather", Arguments: `{"location":"北京"}`}}}), + }), nil + } + return schema.StreamReaderFromArray([]*schema.Message{ + schema.AssistantMessage("北京", nil), schema.AssistantMessage("晴。", nil), + }), nil +} + +type traceTestWeather struct{} + +func (*traceTestWeather) Info(context.Context) (*schema.ToolInfo, error) { + return &schema.ToolInfo{Name: "get_weather", Desc: "查询天气"}, nil +} + +func (*traceTestWeather) InvokableRun(context.Context, string, ...tool.Option) (string, error) { + return `{"condition":"晴"}`, nil +} + +func TestTraceHandler(t *testing.T) { + for _, fail := range []bool{false, true} { + name := "streaming weather" + if fail { + name = "model error" + } + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var logs bytes.Buffer + previous := log.Writer() + log.SetOutput(&logs) + defer log.SetOutput(previous) + chat := &traceTestModel{} + if fail { + chat.err = errors.New("model unavailable") + } + agent, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{ + Name: "weather_test", Model: chat, MaxIterations: 3, + ToolsConfig: adk.ToolsConfig{ToolsNodeConfig: compose.ToolsNodeConfig{Tools: []tool.BaseTool{&traceTestWeather{}}}}, + }) + if err != nil { + t.Fatal(err) + } + trace := NewTraceHandler() + runner := adk.NewRunner(ctx, adk.RunnerConfig{Agent: agent, EnableStreaming: true}) + iter := runner.Query(ctx, "北京天气", adk.WithCallbacks(trace)) + var reply strings.Builder + var runErr error + for { + event, ok := iter.Next() + if !ok { + break + } + if event.Err != nil { + runErr = event.Err + } + if event.Output == nil || event.Output.MessageOutput == nil { + continue + } + output := event.Output.MessageOutput + if !output.IsStreaming { + continue + } + for { + chunk, err := output.MessageStream.Recv() + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + reply.WriteString(chunk.Content) + } + output.MessageStream.Close() + } + trace.Wait() + if fail { + if runErr == nil || !strings.Contains(logs.String(), "model unavailable") { + t.Fatalf("error=%v trace=%s", runErr, logs.String()) + } + return + } + if runErr != nil || reply.String() != "北京晴。" { + t.Fatalf("reply=%q error=%v trace=%s", reply.String(), runErr, logs.String()) + } + for _, want := range []string{"parent=0 Agent/weather_test", "parent=1 ChatModel/", "Tool/get_weather", `tool arguments={"location":"北京"}`, `tool output={"condition":"晴"}`, "model output chunks=2", "end span=1 Agent/weather_test", "duration="} { + if !strings.Contains(logs.String(), want) { + t.Errorf("missing %q in trace:\n%s", want, logs.String()) + } + } + }) + } +} diff --git a/steps/weather/main.go b/steps/weather/main.go index 0d3a1dc..a8b921b 100644 --- a/steps/weather/main.go +++ b/steps/weather/main.go @@ -11,6 +11,7 @@ import ( "strings" "syscall" + "example.com/ueino/pkg/opt" pkgTool "example.com/ueino/pkg/tool" "example.com/ueino/steps/weather/internal" "github.com/cloudwego/eino/adk" @@ -38,7 +39,7 @@ func main() { assistant, err := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{ Name: "terminal_chat", - Instruction: "你是一个简洁的中文助手。", + Instruction: opt.SYSTEM_PROMPT, Model: internal.MustNewChatModel(ctx), MaxIterations: 10, ToolsConfig: adk.ToolsConfig{ @@ -75,7 +76,8 @@ func main() { } history = append(history, schema.UserMessage(input)) - iter := runner.Run(ctx, history) + trace := internal.NewTraceHandler() + iter := runner.Run(ctx, history, adk.WithCallbacks(trace)) for { event, ok := iter.Next() if !ok { @@ -132,5 +134,6 @@ func main() { } history = append(history, m) } + trace.Wait() } }