forked from trpc-group/trpc-agent-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
548 lines (481 loc) · 13.6 KB
/
Copy pathmain.go
File metadata and controls
548 lines (481 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//
// Tencent is pleased to support the open source community by making
// trpc-agent-go available.
//
// Copyright (C) 2025 Tencent. All rights reserved.
//
// trpc-agent-go is licensed under the Apache License Version 2.0.
//
//
// Package main demonstrates how to use agent tools to wrap agents as tools
// within a larger application.
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"trpc.group/trpc-go/trpc-agent-go/agent/llmagent"
"trpc.group/trpc-go/trpc-agent-go/event"
"trpc.group/trpc-go/trpc-agent-go/model"
"trpc.group/trpc-go/trpc-agent-go/model/openai"
"trpc.group/trpc-go/trpc-agent-go/runner"
"trpc.group/trpc-go/trpc-agent-go/tool"
agenttool "trpc.group/trpc-go/trpc-agent-go/tool/agent"
"trpc.group/trpc-go/trpc-agent-go/tool/function"
)
const (
defaultModelName = "deepseek-v4-flash"
defaultInnerTextMode = string(agenttool.InnerTextModeInclude)
responseModeDefault = "default"
responseModeFinal = "final-only"
)
var (
modelName = flag.String(
"model",
defaultModelName,
"Name of the model to use",
)
debugAuthors = flag.Bool(
"debug",
false,
"Print event author names with streamed text",
)
showTool = flag.Bool(
"show-tool",
false,
"Show tool outputs (tool.response) in the transcript",
)
showInner = flag.Bool(
"show-inner",
true,
"Show inner agent transcript forwarded by agent tool",
)
innerTextMode = flag.String(
"inner-text",
defaultInnerTextMode,
"Inner text mode: include or exclude",
)
toolResponseMode = flag.String(
"response-mode",
responseModeDefault,
"AgentTool response mode: default or final-only",
)
persistentChildHistory = flag.Bool(
"persistent-child-history",
false,
"Enable stable child event-filter key for the math-specialist AgentTool",
)
persistentChildKey = flag.String(
"persistent-child-key",
"",
"Stable child event-filter key (advanced)",
)
)
func main() {
// Parse command line flags.
flag.Parse()
mode, err := parseInnerTextMode(*innerTextMode)
if err != nil {
log.Fatalf("invalid -inner-text: %v", err)
}
responseMode, err := parseResponseMode(*toolResponseMode)
if err != nil {
log.Fatalf("invalid -response-mode: %v", err)
}
fmt.Printf("🚀 Agent Tool Example\n")
fmt.Printf("Model: %s\n", *modelName)
fmt.Printf("Show inner: %t\n", *showInner)
fmt.Printf("Inner text mode: %s\n", mode)
fmt.Printf("Response mode: %s\n", responseModeName(responseMode))
fmt.Printf("Show tool: %t\n", *showTool)
fmt.Printf("Persistent child history: %t\n",
*persistentChildHistory || strings.TrimSpace(*persistentChildKey) != "",
)
if strings.TrimSpace(*persistentChildKey) != "" {
fmt.Printf("Persistent child key: %s\n", strings.TrimSpace(*persistentChildKey))
}
fmt.Printf("Available tools: current_time, math-specialist(agent_tool)\n")
fmt.Println(strings.Repeat("=", 50))
// Create and run the chat.
chat := &agentToolChat{
modelName: *modelName,
debugAuthors: *debugAuthors,
showTool: *showTool,
showInner: *showInner,
innerTextMode: mode,
responseMode: responseMode,
persistent: *persistentChildHistory,
persistentKey: *persistentChildKey,
}
if err := chat.run(); err != nil {
log.Fatalf("Chat failed: %v", err)
}
}
// agentToolChat manages the conversation with agent tools.
type agentToolChat struct {
modelName string
runner runner.Runner
userID string
sessionID string
debugAuthors bool
agentName string
streaming bool
showTool bool
showInner bool
innerTextMode agenttool.InnerTextMode
responseMode agenttool.ResponseMode
persistent bool
persistentKey string
}
// run starts the interactive chat session.
func (c *agentToolChat) run() error {
ctx := context.Background()
// Setup the runner.
if err := c.setup(ctx); err != nil {
return fmt.Errorf("setup failed: %w", err)
}
// Ensure runner resources are cleaned up (trpc-agent-go >= v0.5.0)
defer c.runner.Close()
// Start interactive chat.
return c.startChat(ctx)
}
// setup creates the runner with LLM agent and tools including agent tools.
func (c *agentToolChat) setup(_ context.Context) error {
// Create OpenAI model.
modelInstance := openai.New(c.modelName)
// Create tools.
calculatorTool := function.NewFunctionTool(
c.calculate,
function.WithName("calculator"),
function.WithDescription(
"Perform basic mathematical calculations",
),
)
// Create a specialized agent for math operations.
mathAgent := llmagent.New(
"math-specialist",
llmagent.WithModel(modelInstance),
llmagent.WithDescription(
"A specialized agent for mathematical operations",
),
llmagent.WithInstruction(
"You are a math specialist. Focus on mathematical "+
"operations, calculations, and numerical reasoning. "+
"When you receive a calculation request, use your "+
"calculator tool to compute the result, then provide "+
"a clear, natural language response explaining the "+
"calculation and result.",
),
llmagent.WithGenerationConfig(model.GenerationConfig{
Stream: true,
}),
llmagent.WithTools([]tool.Tool{calculatorTool}),
llmagent.WithInputSchema(map[string]any{
"type": "object",
"properties": map[string]any{
"request": map[string]any{
"type": "string",
"description": "The mathematical problem or question to solve",
},
},
"required": []any{"request"},
}),
)
// Create tools.
timeTool := function.NewFunctionTool(
c.getCurrentTime,
function.WithName("current_time"),
function.WithDescription(
"Get the current time and date for a specific timezone",
),
)
// Create agent tool that wraps the math specialist agent.
// SkipSummarization surfaces the child tool result directly.
// The run still finishes on runner.completion.
agentToolOpts := []agenttool.Option{
agenttool.WithSkipSummarization(true),
agenttool.WithStreamInner(c.showInner),
agenttool.WithInnerTextMode(c.innerTextMode),
agenttool.WithResponseMode(c.responseMode),
}
if strings.TrimSpace(c.persistentKey) != "" {
agentToolOpts = append(
agentToolOpts,
agenttool.WithPersistentHistoryKey(c.persistentKey),
)
} else if c.persistent {
agentToolOpts = append(agentToolOpts, agenttool.WithPersistentHistory())
}
agentTool := agenttool.NewTool(mathAgent, agentToolOpts...)
// Create LLM agent with tools including the agent tool.
genConfig := model.GenerationConfig{
Stream: true, // Enable streaming
}
c.agentName = "chat-assistant"
llmAgent := llmagent.New(
c.agentName,
llmagent.WithModel(modelInstance),
llmagent.WithDescription(
"A helpful AI assistant with time tools and agent tools",
),
llmagent.WithInstruction(
"Use tools when appropriate for time queries or "+
"mathematical operations. For any math calculations, "+
"always use the math-specialist agent tool. After "+
"receiving the math-specialist's response, present "+
"the result clearly to the user. Be helpful and "+
"conversational.",
),
llmagent.WithGenerationConfig(genConfig),
llmagent.WithTools([]tool.Tool{timeTool, agentTool}),
)
// Remember streaming mode for printing logic.
c.streaming = genConfig.Stream
// Create runner.
appName := "agent-tool-chat"
c.runner = runner.NewRunner(
appName,
llmAgent,
)
// Setup identifiers.
c.userID = "user"
c.sessionID = fmt.Sprintf("chat-session-%d", time.Now().Unix())
fmt.Printf("✅ Chat ready! Session: %s\n\n", c.sessionID)
return nil
}
// startChat runs the interactive conversation loop.
func (c *agentToolChat) startChat(ctx context.Context) error {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("💡 Special commands:")
fmt.Println(" /history - Show conversation history")
fmt.Println(" /new - Start a new session")
fmt.Println(" /exit - End the conversation")
fmt.Println()
for {
fmt.Print("👤 You: ")
if !scanner.Scan() {
break
}
userInput := strings.TrimSpace(scanner.Text())
if userInput == "" {
continue
}
// Handle special commands.
switch strings.ToLower(userInput) {
case "/exit":
fmt.Println("👋 Goodbye!")
return nil
case "/history":
userInput = "show our conversation history"
case "/new":
c.startNewSession()
continue
}
// Process the user message.
if err := c.processMessage(ctx, userInput); err != nil {
fmt.Printf("❌ Error: %v\n", err)
}
fmt.Println() // Add spacing between turns
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("input scanner error: %w", err)
}
return nil
}
// processMessage handles a single message exchange.
func (c *agentToolChat) processMessage(
ctx context.Context,
userMessage string,
) error {
message := model.NewUserMessage(userMessage)
// Run the agent through the runner.
eventChan, err := c.runner.Run(ctx, c.userID, c.sessionID, message)
if err != nil {
return fmt.Errorf("failed to run agent: %w", err)
}
// Process streaming response.
return c.processStreamingResponse(eventChan)
}
// processStreamingResponse handles streaming with tool call visualization.
func (c *agentToolChat) processStreamingResponse(
eventChan <-chan *event.Event,
) error {
fmt.Print("🤖 Assistant: ")
var (
assistantStarted bool
fullContent strings.Builder
)
for ev := range eventChan {
if c.handleEvent(ev, &assistantStarted, &fullContent) {
continue
}
}
fmt.Println()
return nil
}
// handleEvent processes one event and returns true when it was handled.
func (c *agentToolChat) handleEvent(
ev *event.Event,
assistantStarted *bool,
fullContent *strings.Builder,
) bool {
// Handle errors
if ev.Error != nil {
fmt.Printf("\n❌ Error: %s\n", ev.Error.Message)
return true
}
// Handle tool calls
if c.handleToolCalls(ev, assistantStarted) {
return true
}
// Handle inner agent streaming
if c.handleInnerAgentStreaming(ev) {
return true
}
// Handle outer assistant streaming
if c.handleAssistantStreaming(ev, assistantStarted, fullContent) {
return true
}
// Handle tool responses
if c.handleToolResponses(ev) {
return true
}
return false
}
// handleToolCalls processes tool call events.
func (c *agentToolChat) handleToolCalls(
ev *event.Event,
assistantStarted *bool,
) bool {
if ev.Response == nil || len(ev.Response.Choices) == 0 {
return false
}
ch := ev.Response.Choices[0]
if len(ch.Message.ToolCalls) == 0 {
return false
}
if *assistantStarted {
fmt.Printf("\n")
}
fmt.Printf("🔧 Tool calls initiated:\n")
for _, tc := range ch.Message.ToolCalls {
fmt.Printf(" • %s (ID: %s)\n", tc.Function.Name, tc.ID)
if len(tc.Function.Arguments) > 0 {
fmt.Printf(" Args: %s\n", string(tc.Function.Arguments))
}
}
fmt.Printf("\n🔄 Executing tools...\n")
return true
}
// handleInnerAgentStreaming processes inner agent streaming events.
func (c *agentToolChat) handleInnerAgentStreaming(ev *event.Event) bool {
if !c.showInner ||
ev.Author == c.agentName ||
ev.Response == nil ||
len(ev.Response.Choices) == 0 {
return false
}
ch := ev.Response.Choices[0]
if ch.Delta.Content == "" {
return false
}
if c.debugAuthors {
fmt.Printf("[%s] ", ev.Author)
}
fmt.Print(ch.Delta.Content)
return true
}
// handleAssistantStreaming processes outer assistant streaming events.
func (c *agentToolChat) handleAssistantStreaming(
ev *event.Event,
assistantStarted *bool,
fullContent *strings.Builder,
) bool {
if ev.Author != c.agentName ||
ev.Response == nil ||
len(ev.Response.Choices) == 0 {
return false
}
ch := ev.Response.Choices[0]
if ch.Delta.Content == "" {
return false
}
if c.debugAuthors && !*assistantStarted {
fmt.Printf("[%s] ", ev.Author)
}
*assistantStarted = true
fmt.Print(ch.Delta.Content)
fullContent.WriteString(ch.Delta.Content)
return true
}
// handleToolResponses processes tool response events.
func (c *agentToolChat) handleToolResponses(ev *event.Event) bool {
if ev.Response == nil ||
ev.Object != model.ObjectTypeToolResponse ||
len(ev.Response.Choices) == 0 {
return false
}
ch := ev.Response.Choices[0]
if ch.Delta.Content != "" {
// Partial tool delta; only show if inner streaming is hidden.
if c.showTool && !c.showInner {
fmt.Printf("\n🛠️ tool> %s", ch.Delta.Content)
}
return true
}
if ch.Message.Content != "" {
// Final tool message - show detailed response
if c.showTool {
fmt.Printf(
"\n✅ Tool response (ID: %s): %s\n",
ch.Message.ToolID,
strings.TrimSpace(ch.Message.Content),
)
} else {
fmt.Printf("\n✅ Tool execution completed.\n")
}
return true
}
// Tool execution completed
fmt.Printf("\n✅ Tool execution completed.\n")
return true
}
// startNewSession creates a new session.
func (c *agentToolChat) startNewSession() {
c.sessionID = fmt.Sprintf("chat-session-%d", time.Now().Unix())
fmt.Printf("🔄 New session started: %s\n\n", c.sessionID)
}
func parseInnerTextMode(mode string) (agenttool.InnerTextMode, error) {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "", string(agenttool.InnerTextModeInclude):
return agenttool.InnerTextModeInclude, nil
case string(agenttool.InnerTextModeExclude):
return agenttool.InnerTextModeExclude, nil
default:
return "", fmt.Errorf("unsupported mode %q", mode)
}
}
func parseResponseMode(mode string) (agenttool.ResponseMode, error) {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "", responseModeDefault:
return agenttool.ResponseModeDefault, nil
case responseModeFinal:
return agenttool.ResponseModeFinalOnly, nil
default:
return agenttool.ResponseModeDefault,
fmt.Errorf("unsupported response mode %q", mode)
}
}
func responseModeName(mode agenttool.ResponseMode) string {
switch mode {
case agenttool.ResponseModeFinalOnly:
return responseModeFinal
default:
return responseModeDefault
}
}