MCPcopy Create free account
hub / github.com/astercloud/aster / Example

Function Example

pkg/telemetry/integration_example.go:11–94  ·  view source on GitHub ↗

Example 演示如何在 Agent 中集成 Telemetry

()

Source from the content-addressed store, hash-verified

9
10// Example 演示如何在 Agent 中集成 Telemetry
11func Example() {
12 // 1. 初始化 Tracer 和 Metrics
13 tracer := NewSimpleTracer()
14 metrics := NewSimpleMetrics()
15 agentMetrics := NewAgentMetrics(metrics)
16
17 // 设置为全局实例
18 SetGlobalTracer(tracer)
19 SetGlobalMetrics(metrics)
20
21 // 2. 模拟 Agent 执行
22 ctx := context.Background()
23 agentID := "agent-001"
24
25 // 开始追踪
26 ctx, span := tracer.StartSpan(ctx, "agent.chat",
27 WithSpanKind(SpanKindServer),
28 WithAttributes(
29 String("agent.id", agentID),
30 String("user.id", "user-123"),
31 ),
32 )
33 defer span.End()
34
35 startTime := time.Now()
36
37 // 3. 执行业务逻辑
38 span.AddEvent("processing_message", String("message", "Hello"))
39
40 // 模拟模型调用
41 _, modelSpan := tracer.StartSpan(ctx, "model.generate")
42 modelSpan.SetAttributes(
43 String("model", "claude-3-5-sonnet"),
44 Int("input_tokens", 100),
45 )
46 time.Sleep(100 * time.Millisecond) // 模拟延迟
47 modelSpan.End()
48
49 // 记录 token 使用
50 agentMetrics.RecordTokens(agentID, 100, 200)
51
52 // 模拟工具调用
53 _, toolSpan := tracer.StartSpan(ctx, "tool.execute")
54 toolSpan.SetAttributes(String("tool.name", "search"))
55 time.Sleep(50 * time.Millisecond)
56 toolSpan.End()
57
58 // 记录工具调用
59 agentMetrics.RecordToolCall(agentID, "search", 50*time.Millisecond, true)
60
61 // 4. 记录请求完成
62 duration := time.Since(startTime)
63 agentMetrics.RecordRequest(agentID, duration)
64 span.SetStatus(StatusCodeOK, "completed")
65
66 // 5. 输出指标快照
67 snapshot := metrics.Snapshot()
68 fmt.Printf("\n📊 Metrics Snapshot:\n")

Callers

nothing calls this directly

Calls 15

StartSpanMethod · 0.95
RecordTokensMethod · 0.95
RecordToolCallMethod · 0.95
RecordRequestMethod · 0.95
SnapshotMethod · 0.95
GetSpansMethod · 0.95
NewSimpleTracerFunction · 0.85
NewSimpleMetricsFunction · 0.85
NewAgentMetricsFunction · 0.85
SetGlobalTracerFunction · 0.85
SetGlobalMetricsFunction · 0.85
WithSpanKindFunction · 0.85

Tested by

no test coverage detected