feat(observability): instrument agent ReAct loop and tool calls in Langfuse

The existing Langfuse integration covered Chat / Embedding / Rerank / VLM /
ASR generations plus the HTTP + asynq spans, but the agent's own execution
tree was invisible: tool calls never appeared, multi-round ReAct iterations
were flat under the HTTP trace, and there was no single node representing
"one agent run".

This change adds three levels of agent-side spans:

  - agent.execute       — wraps AgentEngine.Execute, records query preview,
                           knowledge bases, allowed tools, final-answer length
                           and totals on finish.
  - agent.round.<N>     — wraps each ReAct iteration; records finish_reason,
                           tool-call count, token usage and duration.
  - agent.tool.<name>   — wraps each tool invocation; records arguments,
                           success, duration, output preview (rune-safe, 4KB
                           cap), error, data keys and image count.

To keep the loop's many exit paths (natural stop, stuck loop, empty-content
retry, final_answer, context cancellation) span-safe, the iteration body was
extracted into runReActIteration with a single defer span.Finish() and an
iterOutcome sentinel driving the outer loop. database_query arguments are
redacted (keys only) to avoid leaking raw SQL into the observability
backend, mirroring the existing UI hint policy.

Adds unit tests for the new helpers (truncateForLangfuse, argKeys, dataKeys,
finishToolSpan nil-safety, iterOutcome.String).
This commit is contained in:
wizardchen
2026-04-24 19:16:45 +08:00
committed by lyingbug
parent 8103398fcf
commit c12296aa88
4 changed files with 552 additions and 115 deletions
+134 -2
View File
@@ -3,7 +3,9 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"sync"
"time"
@@ -11,10 +13,106 @@ import (
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"golang.org/x/sync/errgroup"
)
// langfuseToolOutputPreview caps the Output field we send to Langfuse for a
// tool call. Tool outputs are already truncated by the registry to
// DefaultMaxToolOutput (16KB) before this point, but rendering 16KB in the
// Langfuse UI for every tool call is noisy. We keep a generous slice so the
// gist is preserved, and include the original length in metadata.
const langfuseToolOutputPreview = 4000
// truncateForLangfuse returns s truncated to at most n runes, with a "…"
// marker appended when truncated. Runes (not bytes) are used so multi-byte
// CJK content is never split mid-character.
func truncateForLangfuse(s string, n int) string {
if n <= 0 || len(s) == 0 {
return s
}
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
// argKeys returns the sorted list of top-level keys in a tool's argument
// map. Used when we choose not to send the raw arguments to Langfuse
// (e.g. database_query's SQL) but still want to signal what was passed in.
func argKeys(args map[string]any) []string {
keys := make([]string, 0, len(args))
for k := range args {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// finishToolSpan serialises a completed tool call into a Langfuse span
// update. Extracted from runToolCall so the tool-call pipeline keeps
// a single assignment per line and the observability-specific logic
// (payload shaping, error classification) lives in one place.
func finishToolSpan(span *langfuse.Span, tc types.ToolCall, execErr error, durationMs int64) {
if span == nil {
return
}
success := tc.Result != nil && tc.Result.Success
output := map[string]interface{}{
"success": success,
"duration_ms": durationMs,
}
if tc.Result != nil {
if tc.Result.Output != "" {
output["output"] = truncateForLangfuse(tc.Result.Output, langfuseToolOutputPreview)
output["output_len"] = len(tc.Result.Output)
}
if tc.Result.Error != "" {
output["error"] = tc.Result.Error
}
if len(tc.Result.Data) > 0 {
// Data is structured but can be arbitrarily large (e.g. full
// search-result payloads). Only report key shape so Langfuse
// users see what was surfaced without blowing up trace size.
output["data_keys"] = dataKeys(tc.Result.Data)
}
if len(tc.Result.Images) > 0 {
output["image_count"] = len(tc.Result.Images)
}
}
// Classify the span's outcome: a non-nil execErr is always an error, and
// a result with Success=false is treated as an error too (matches the
// user-visible behaviour — the LLM would see this as a failed tool call
// and try a different approach).
var spanErr error
switch {
case execErr != nil:
spanErr = execErr
case tc.Result != nil && !tc.Result.Success:
msg := tc.Result.Error
if msg == "" {
msg = "tool returned success=false"
}
spanErr = errors.New(msg)
}
span.Finish(output, map[string]interface{}{
"success": success,
"duration_ms": durationMs,
}, spanErr)
}
// dataKeys returns the sorted top-level keys of a tool's Data map.
func dataKeys(data map[string]interface{}) []string {
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// toolDisplayNames maps internal tool names to user-friendly display labels.
var toolDisplayNames = map[string]string{
agenttools.ToolThinking: "深度思考",
@@ -262,9 +360,41 @@ func (e *AgentEngine) runToolCall(
"tool_index": fmt.Sprintf("%d/%s", i+1, total),
})
toolCtx, toolCancel := context.WithTimeout(ctx, defaultToolExecTimeout)
// Open a Langfuse span for the tool invocation so the Langfuse UI shows
// trace → agent.execute → agent.round.N → agent.tool.<name>, alongside
// any nested generations (embedding/rerank/VLM) that the tool itself
// triggers. No-op when Langfuse is disabled.
mgr := langfuse.GetManager()
toolSpanInput := map[string]interface{}{
"arguments": args,
"tool_call_id": tc.ID,
}
// database_query's SQL is treated as sensitive by the UI hint layer
// (toolHintSensitiveArgs) because it exposes implementation details.
// Mirror that policy for Langfuse: redact raw arguments to avoid
// leaking raw SQL into the observability backend.
if toolHintSensitiveArgs[tc.Function.Name] {
toolSpanInput = map[string]interface{}{
"tool_call_id": tc.ID,
"arg_keys": argKeys(args),
"args_redacted": true,
}
}
toolCtx, toolSpan := mgr.StartSpan(ctx, langfuse.SpanOptions{
Name: "agent.tool." + tc.Function.Name,
Input: toolSpanInput,
Metadata: map[string]interface{}{
"iteration": iteration,
"round": round,
"tool_index": i + 1,
"tool_call_id": tc.ID,
"session_id": sessionID,
},
})
execCtx, toolCancel := context.WithTimeout(toolCtx, defaultToolExecTimeout)
result, err := e.toolRegistry.ExecuteTool(
toolCtx, tc.Function.Name,
execCtx, tc.Function.Name,
json.RawMessage(tc.Function.Arguments),
)
toolCancel()
@@ -294,6 +424,8 @@ func (e *AgentEngine) runToolCall(
toolTag, duration, success, outputLen)
}
finishToolSpan(toolSpan, toolCall, err, duration)
// Pipeline event for monitoring
toolSuccess := toolCall.Result != nil && toolCall.Result.Success
pipelineFields := map[string]interface{}{