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
351 lines (300 loc) · 9.66 KB
/
main.go
File metadata and controls
351 lines (300 loc) · 9.66 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
//
// 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 memory management using the Runner with streaming
// output, session management, and memory tools.
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/memory"
memoryinmemory "trpc.group/trpc-go/trpc-agent-go/memory/inmemory"
memoryredis "trpc.group/trpc-go/trpc-agent-go/memory/redis"
"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"
sessioninmemory "trpc.group/trpc-go/trpc-agent-go/session/inmemory"
)
var (
modelName = flag.String("model", "deepseek-chat", "Name of the model to use")
memServiceName = flag.String("memory", "inmemory", "Name of the memory service to use, inmemory / redis")
redisAddr = flag.String("redis-addr", "localhost:6379", "Redis address")
streaming = flag.Bool("streaming", true, "Enable streaming mode for responses")
)
func main() {
// Parse command line flags.
flag.Parse()
fmt.Printf("🧠 Multi Turn Chat with Memory\n")
fmt.Printf("Model: %s\n", *modelName)
fmt.Printf("Memory Service: %s\n", *memServiceName)
if *memServiceName == "redis" {
fmt.Printf("Redis: %s\n", *redisAddr)
}
fmt.Printf("Streaming: %t\n", *streaming)
fmt.Printf("Available tools: memory_add, memory_update, memory_search, memory_load\n")
fmt.Printf("(memory_delete, memory_clear disabled by default, and can be enabled or customized)\n")
fmt.Println(strings.Repeat("=", 50))
// Create and run the chat.
chat := &memoryChat{
modelName: *modelName,
memServiceName: *memServiceName,
redisAddr: *redisAddr,
streaming: *streaming,
}
if err := chat.run(); err != nil {
log.Fatalf("Chat failed: %v", err)
}
}
// memoryChat manages the conversation with memory capabilities.
type memoryChat struct {
modelName string
memServiceName string
redisAddr string
streaming bool
runner runner.Runner
userID string
sessionID string
}
// run starts the interactive chat session.
func (c *memoryChat) run() error {
ctx := context.Background()
// Setup the runner.
if err := c.setup(ctx); err != nil {
return fmt.Errorf("setup failed: %w", err)
}
// Start interactive chat.
return c.startChat(ctx)
}
// setup creates the runner with LLM agent and memory tools.
func (c *memoryChat) setup(_ context.Context) error {
// Create OpenAI model.
modelInstance := openai.New(c.modelName)
// Create memory service based on configuration.
var (
memoryService memory.Service
err error
)
switch c.memServiceName {
case "redis":
redisURL := fmt.Sprintf("redis://%s", c.redisAddr)
memoryService, err = memoryredis.NewService(
memoryredis.WithRedisClientURL(redisURL),
// You can enable or disable tools and create custom tools here.
memoryredis.WithToolEnabled(memory.DeleteToolName, false), // delete tool is disabled by default
memoryredis.WithCustomTool(memory.ClearToolName, customClearMemoryTool), // custom clear tool
)
if err != nil {
return fmt.Errorf("failed to create redis memory service: %w", err)
}
default: // inmemory
memoryService = memoryinmemory.NewMemoryService(
// You can enable or disable tools and create custom tools here.
memoryinmemory.WithToolEnabled(memory.DeleteToolName, true), // delete tool is disabled by default
memoryinmemory.WithCustomTool(memory.ClearToolName, customClearMemoryTool), // custom clear tool
)
}
// Setup identifiers first.
c.userID = "user"
c.sessionID = fmt.Sprintf("memory-session-%d", time.Now().Unix())
// Create LLM agent with memory service.
genConfig := model.GenerationConfig{
MaxTokens: intPtr(2000),
Temperature: floatPtr(0.7),
Stream: c.streaming,
}
appName := "memory-chat"
agentName := "memory-assistant"
llmAgent := llmagent.New(
agentName,
llmagent.WithModel(modelInstance),
llmagent.WithDescription("A helpful AI assistant with memory capabilities. "+
"I can remember important information about you and recall it when needed."),
llmagent.WithGenerationConfig(genConfig),
llmagent.WithTools(memoryService.Tools()), // Step 1: Prepare memory tools and instruction.
)
// Create runner.
c.runner = runner.NewRunner(
appName,
llmAgent,
runner.WithSessionService(sessioninmemory.NewSessionService()),
runner.WithMemoryService(memoryService), // Step 2: Set memory service.
)
fmt.Printf("✅ Memory chat ready! Session: %s\n\n", c.sessionID)
return nil
}
// startChat runs the interactive conversation loop.
func (c *memoryChat) startChat(ctx context.Context) error {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("💡 Special commands:")
fmt.Println(" /memory - Show user memories")
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 "/memory":
userInput = "show what you remember about me"
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 *memoryChat) 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 response.
return c.processResponse(eventChan)
}
// processResponse handles both streaming and non-streaming responses with tool call visualization.
func (c *memoryChat) processResponse(eventChan <-chan *event.Event) error {
fmt.Print("🤖 Assistant: ")
var (
fullContent string
toolCallsDetected bool
assistantStarted bool
)
for event := range eventChan {
// Handle errors.
if event.Error != nil {
fmt.Printf("\n❌ Error: %s\n", event.Error.Message)
continue
}
// Handle tool calls.
if c.hasToolCalls(event) {
toolCallsDetected = true
c.handleToolCalls(event, assistantStarted)
assistantStarted = true
continue
}
// Handle tool responses.
if c.hasToolResponses(event) {
c.handleToolResponses(event)
continue
}
// Handle content.
if content := c.extractContent(event); content != "" {
if !assistantStarted {
if toolCallsDetected {
fmt.Printf("\n🤖 Assistant: ")
}
assistantStarted = true
}
fmt.Print(content)
fullContent += content
}
// Check if this is the final event.
if event.IsFinalResponse() {
fmt.Printf("\n")
break
}
}
return nil
}
// hasToolCalls checks if the event contains tool calls.
func (c *memoryChat) hasToolCalls(event *event.Event) bool {
return len(event.Response.Choices) > 0 && len(event.Response.Choices[0].Message.ToolCalls) > 0
}
// hasToolResponses checks if the event contains tool responses.
func (c *memoryChat) hasToolResponses(event *event.Event) bool {
if event.Response == nil || len(event.Response.Choices) == 0 {
return false
}
for _, choice := range event.Response.Choices {
if choice.Message.Role == model.RoleTool && choice.Message.ToolID != "" {
return true
}
}
return false
}
// handleToolCalls displays tool call information.
func (c *memoryChat) handleToolCalls(event *event.Event, assistantStarted bool) {
if assistantStarted {
fmt.Printf("\n")
}
fmt.Printf("🔧 Memory tool calls initiated:\n")
for _, toolCall := range event.Response.Choices[0].Message.ToolCalls {
fmt.Printf(" • %s (ID: %s)\n", toolCall.Function.Name, toolCall.ID)
if len(toolCall.Function.Arguments) > 0 {
fmt.Printf(" Args: %s\n", string(toolCall.Function.Arguments))
}
}
fmt.Printf("\n🔄 Executing memory tools...\n")
}
// handleToolResponses displays tool response information.
func (c *memoryChat) handleToolResponses(event *event.Event) {
for _, choice := range event.Response.Choices {
if choice.Message.Role == model.RoleTool && choice.Message.ToolID != "" {
fmt.Printf("✅ Memory tool response (ID: %s): %s\n",
choice.Message.ToolID,
strings.TrimSpace(choice.Message.Content))
}
}
}
// extractContent extracts content from the event based on streaming mode.
func (c *memoryChat) extractContent(event *event.Event) string {
if len(event.Response.Choices) == 0 {
return ""
}
choice := event.Response.Choices[0]
if c.streaming {
return choice.Delta.Content
}
return choice.Message.Content
}
// startNewSession creates a new session ID.
func (c *memoryChat) startNewSession() {
oldSessionID := c.sessionID
c.sessionID = fmt.Sprintf("memory-session-%d", time.Now().Unix())
fmt.Printf("🆕 Started new memory session!\n")
fmt.Printf(" Previous: %s\n", oldSessionID)
fmt.Printf(" Current: %s\n", c.sessionID)
fmt.Printf(" (Memory and conversation history have been reset)\n")
fmt.Println()
}
// Helper functions for creating pointers to primitive types.
func intPtr(i int) *int {
return &i
}
func floatPtr(f float64) *float64 {
return &f
}