-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagentize.go
More file actions
406 lines (333 loc) · 12 KB
/
agentize.go
File metadata and controls
406 lines (333 loc) · 12 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
package agentize
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"github.com/ghiac/agentize/debuger"
"github.com/ghiac/agentize/debuger/ui"
"github.com/ghiac/agentize/engine"
"github.com/ghiac/agentize/fsrepo"
"github.com/ghiac/agentize/llmutils"
"github.com/ghiac/agentize/log"
"github.com/ghiac/agentize/model"
"github.com/ghiac/agentize/store"
"github.com/ghiac/agentize/visualize"
"github.com/gin-gonic/gin"
)
// Version returns the current version of the library
func Version() string {
return "0.1.0"
}
// DebugPage represents an external page added to the debug panel
type DebugPage struct {
Path string // e.g., "/agentize/debug/quota"
Title string // Nav label
Icon string // Nav icon emoji
Handler gin.HandlerFunc // Route handler
}
// Agentize is the main entry point for the library
// It loads and manages the entire knowledge tree
type Agentize struct {
// Core processing engine (holds repo, sessions, functions)
engine *engine.Engine
// Knowledge tree cache (for visualization/docs)
nodes map[string]*model.Node
mu sync.RWMutex
// Session scheduler for automatic summarization
scheduler *engine.SessionScheduler
schedulerMu sync.RWMutex
// Extra debug pages registered by applications
extraDebugPages []DebugPage
// Optional: provider for user billing/credit HTML on debug user detail page
userBillingHTMLProvider debuger.UserBillingHTMLProvider
// Optional: hook called after DeleteUserData (sessions/messages) so app can delete quota/consumption etc.
userDeleteDataHook func(userID string) error
}
// Options allows configuring Agentize behavior
type Options struct {
// SessionStore allows providing a custom session store
SessionStore store.SessionStore
// Repository allows providing an existing repository instead of creating a new one
Repository *fsrepo.NodeRepository
// FunctionRegistry allows providing an existing function registry instead of creating a new one
FunctionRegistry *model.FunctionRegistry
}
// New creates a new Agentize instance by loading the entire knowledge tree from the given path
func New(path string) (*Agentize, error) {
return NewWithOptions(path, nil)
}
// NewWithOptions creates a new Agentize instance with custom options
func NewWithOptions(path string, opts *Options) (*Agentize, error) {
// Use existing repository or create a new one
var repo *fsrepo.NodeRepository
var err error
if opts != nil && opts.Repository != nil {
repo = opts.Repository
} else {
repo, err = fsrepo.NewNodeRepository(path)
if err != nil {
return nil, fmt.Errorf("failed to create repository: %w", err)
}
}
// Determine session store
var sessionStore store.SessionStore
if opts != nil && opts.SessionStore != nil {
sessionStore = opts.SessionStore
} else {
dbStore, err := store.NewDBStore()
if err != nil {
return nil, fmt.Errorf("failed to create DBStore: %w", err)
}
sessionStore = dbStore
}
// Determine function registry
functionRegistry := model.NewFunctionRegistry()
if opts != nil && opts.FunctionRegistry != nil {
functionRegistry = opts.FunctionRegistry
}
// Create engine
eng := &engine.Engine{
Repo: repo,
Sessions: sessionStore,
Functions: functionRegistry,
}
eng.Executor = func(toolName string, args map[string]interface{}) (string, error) {
if eng.Functions == nil {
return "", fmt.Errorf("function registry is not configured")
}
return eng.Functions.Execute(toolName, args)
}
// Create Agentize instance
ag := &Agentize{
engine: eng,
nodes: make(map[string]*model.Node),
}
// Load all nodes recursively (for visualization cache)
if err := ag.loadAllNodes(); err != nil {
return nil, fmt.Errorf("failed to load knowledge tree: %w", err)
}
return ag, nil
}
// ============================================================================
// Node Management
// ============================================================================
// loadAllNodes recursively loads all nodes from the knowledge tree
func (ag *Agentize) loadAllNodes() error {
ag.mu.Lock()
defer ag.mu.Unlock()
return ag.loadNodeRecursiveLocked("root")
}
// loadNodeRecursiveLocked recursively loads a node and all its children
// Must be called with ag.mu.Lock() already held
func (ag *Agentize) loadNodeRecursiveLocked(path string) error {
if _, exists := ag.nodes[path]; exists {
return nil
}
node, err := ag.engine.Repo.LoadNode(path)
if err != nil {
return fmt.Errorf("failed to load node %s: %w", path, err)
}
ag.nodes[path] = node
children, err := ag.engine.Repo.GetChildren(path)
if err == nil {
for _, childPath := range children {
if err := ag.loadNodeRecursiveLocked(childPath); err != nil {
return err
}
}
}
return nil
}
// GetNode returns a node by its path
func (ag *Agentize) GetNode(path string) (*model.Node, error) {
ag.mu.RLock()
defer ag.mu.RUnlock()
node, ok := ag.nodes[path]
if !ok {
return nil, fmt.Errorf("node not found: %s", path)
}
return node, nil
}
// GetAllNodes returns all loaded nodes
func (ag *Agentize) GetAllNodes() map[string]*model.Node {
ag.mu.RLock()
defer ag.mu.RUnlock()
nodes := make(map[string]*model.Node)
for k, v := range ag.nodes {
nodes[k] = v
}
return nodes
}
// GetRoot returns the root node
func (ag *Agentize) GetRoot() *model.Node {
ag.mu.RLock()
defer ag.mu.RUnlock()
return ag.nodes["root"]
}
// GetNodePaths returns all node paths in order (from root to deepest)
func (ag *Agentize) GetNodePaths() []string {
ag.mu.RLock()
defer ag.mu.RUnlock()
paths := make([]string, 0, len(ag.nodes))
visited := make(map[string]bool)
var traverse func(path string)
traverse = func(path string) {
if visited[path] {
return
}
visited[path] = true
paths = append(paths, path)
children, err := ag.engine.Repo.GetChildren(path)
if err == nil {
for _, childPath := range children {
traverse(childPath)
}
}
}
traverse("root")
return paths
}
// Reload reloads all nodes from the filesystem
func (ag *Agentize) Reload() error {
ag.mu.Lock()
ag.nodes = make(map[string]*model.Node)
ag.engine.Repo.InvalidateCache("")
ag.mu.Unlock()
return ag.loadAllNodes()
}
// ReloadNode reloads a specific node from the filesystem
func (ag *Agentize) ReloadNode(path string) error {
ag.mu.Lock()
defer ag.mu.Unlock()
ag.engine.Repo.InvalidateCache(path)
delete(ag.nodes, path)
return ag.loadNodeRecursiveLocked(path)
}
// ============================================================================
// Engine & Store Accessors
// ============================================================================
// GetRepository returns the underlying repository
func (ag *Agentize) GetRepository() *fsrepo.NodeRepository {
return ag.engine.Repo
}
// GetSessionStore returns the session store
func (ag *Agentize) GetSessionStore() store.SessionStore {
return ag.engine.Sessions
}
// GetEngine returns the internal engine
func (ag *Agentize) GetEngine() *engine.Engine {
return ag.engine
}
// GetRegisteredTools returns the list of registered tool names from the FunctionRegistry
func (ag *Agentize) GetRegisteredTools() []string {
if ag.engine != nil && ag.engine.Functions != nil {
return ag.engine.Functions.GetAllRegistered()
}
return nil
}
// ============================================================================
// LLM Configuration
// ============================================================================
// UseLLMConfig configures the LLM client for the agentize instance
// It also automatically starts the scheduler if enabled
func (ag *Agentize) UseLLMConfig(config engine.LLMConfig) error {
if err := ag.engine.UseLLMConfig(config); err != nil {
return err
}
// Automatically start scheduler if LLM is configured
ctx := context.Background()
if err := ag.StartScheduler(ctx); err != nil {
log.Log.Warnf("[Agentize] ⚠️ Failed to start scheduler: %v", err)
}
return nil
}
// UseFunctionRegistry configures the function registry for tool execution
func (ag *Agentize) UseFunctionRegistry(registry *model.FunctionRegistry) {
ag.engine.UseFunctionRegistry(registry)
}
// InitializeSummaries generates concise summaries for all nodes that don't have one
func (ag *Agentize) InitializeSummaries(ctx context.Context, forceSummary bool) error {
llmClient := ag.engine.GetLLMClient()
if llmClient == nil {
return fmt.Errorf("LLM client is not configured")
}
llmConfig := ag.engine.GetLLMConfig()
modelName := llmConfig.CollectResultModel
if modelName == "" {
modelName = llmConfig.Model
}
summaryConfig := llmutils.SummaryConfig{Model: modelName}
ag.engine.Repo.SetSummaryGenerator(func(ctx context.Context, content string) (string, error) {
return llmutils.GenerateSummary(ctx, llmClient, content, summaryConfig)
})
return ag.engine.Repo.EnsureSummaries(ctx, forceSummary)
}
// ============================================================================
// Session & Message Processing
// ============================================================================
// ProcessMessage routes a user message through the LLM workflow and tool executor
func (ag *Agentize) ProcessMessage(ctx context.Context, sessionID string, userMessage string) (string, int, error) {
return ag.engine.ProcessMessage(ctx, sessionID, userMessage)
}
// CreateSession initializes a fresh session anchored at the root node
func (ag *Agentize) CreateSession(userID string) (*model.Session, error) {
return ag.engine.CreateSession(userID)
}
// SetProgress sets the progress state for a session
func (ag *Agentize) SetProgress(sessionID string, inProgress bool) error {
return ag.engine.SetProgress(sessionID, inProgress)
}
// ============================================================================
// Visualization
// ============================================================================
// GenerateGraphVisualization generates a graph visualization of the knowledge tree
func (ag *Agentize) GenerateGraphVisualization(filename string, title string) error {
ag.mu.RLock()
nodes := make(map[string]*model.Node)
for k, v := range ag.nodes {
nodes[k] = v
}
ag.mu.RUnlock()
visualizer := visualize.NewGraphVisualizer(nodes)
return visualizer.SaveToFile(filename, title)
}
// ============================================================================
// Lifecycle
// ============================================================================
// AddDebugPage registers an external page to the debug panel.
// The page will appear in the debugger navbar and be accessible via its Path.
func (ag *Agentize) AddDebugPage(page DebugPage) {
ag.extraDebugPages = append(ag.extraDebugPages, page)
// Also register in the global UI navbar so it shows on all debugger pages
ui.RegisterNavItem(ui.NavItem{URL: page.Path, Icon: page.Icon, Text: page.Title})
}
// SetUserBillingHTMLProvider sets the optional provider for billing/credit HTML on the user detail page (/agentize/debug/users/:userID).
// When set, the returned HTML is rendered on the user detail page below the user info card.
func (ag *Agentize) SetUserBillingHTMLProvider(fn debuger.UserBillingHTMLProvider) {
ag.userBillingHTMLProvider = fn
}
// SetUserDeleteDataHook sets an optional hook called after DeleteUserData (sessions, messages) for a user.
// The application can use it to delete quota usage, consumption records, balance, etc. for that user.
func (ag *Agentize) SetUserDeleteDataHook(fn func(userID string) error) {
ag.userDeleteDataHook = fn
}
// GetDebugNavItems returns the full set of navigation items including extra pages.
func (ag *Agentize) GetDebugNavItems() []ui.NavItem {
items := ui.DefaultNavItems()
for _, p := range ag.extraDebugPages {
items = append(items, ui.NavItem{URL: p.Path, Icon: p.Icon, Text: p.Title})
}
return items
}
// WaitForShutdown waits for shutdown signals and performs graceful shutdown
func (ag *Agentize) WaitForShutdown() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
sig := <-sigChan
log.Log.Infof("[Agentize] 📡 Received signal: %v, initiating graceful shutdown...", sig)
ag.StopScheduler()
log.Log.Infof("[Agentize] ✅ Graceful shutdown completed")
}