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 <traecli@bytedance.com>
This commit is contained in:
1 parent
ee8afb10db
commit
1512f0516f
15 files changed
+332
-17
No files matched your search
@@ -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。
|
||||
|
||||
+2
-1
@@ -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{
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user