-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm.txt
More file actions
1569 lines (1310 loc) · 41.4 KB
/
Copy pathllm.txt
File metadata and controls
1569 lines (1310 loc) · 41.4 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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# AI SDK - LLM Context File
> **Project**: Enterprise-Grade AI SDK for Go
> **Purpose**: Production-ready, type-safe AI SDK with advanced features like multi-tier memory, RAG, workflow orchestration, and agentic patterns
> **Language**: Go 1.21+
> **Status**: Alpha (81%+ test coverage)
---
## Project Overview
This is a comprehensive AI SDK for Go that provides:
- Fluent API with type-safe builders
- Structured output with Go generics
- Enhanced streaming with reasoning steps
- RAG (Retrieval Augmented Generation) support
- Multi-tier memory system (Working → Short-term → Long-term → Episodic)
- Dynamic tool system with auto-discovery
- Workflow engine (DAG-based)
- Three agent patterns: Basic, ReAct, Plan-Execute
- Native safety guardrails (PII, toxicity, injection detection)
- Cost management and optimization
- Resilience patterns (circuit breakers, retries, rate limiting)
- Comprehensive observability (tracing, profiling, debugging)
### Key Differentiators
- **Zero external dependencies** for core features
- **Native Go concurrency** with goroutines
- **Production-first design** with built-in observability
- **Type safety** with compile-time guarantees
- **17 production-ready integrations** (pgvector, Qdrant, Pinecone, Redis, etc.)
---
## Core Architecture
### 1. SDK Entry Point (`sdk.go`)
- `SDK` struct: Main entry point with builders
- Builder pattern for all major components
- Centralized configuration and dependency injection
### 2. LLM Management (`llm/`)
- `LLMManager`: Unified interface for multiple providers
- Supports: OpenAI, Anthropic, Google, Cohere, Ollama
- Provider-agnostic request/response handling
- Streaming support with SSE
### 3. Memory System (`memory.go`, `memory_*.go`)
**Four-Tier Architecture:**
- **Working Memory**: Limited capacity (10-20 items), immediate context
- **Short-Term Memory**: TTL-based (24h default), recent interactions
- **Long-Term Memory**: Persistent, high-importance memories
- **Episodic Memory**: Grouped memories with narrative structure
**Key Types:**
```go
type MemoryManager struct {
agentID string
embedder EmbeddingModel
vectorStore VectorStore
workingMemory []MemoryEntry
tiers map[MemoryTier]*MemoryTier
}
type MemoryEntry struct {
ID string
Content string
Importance float64 // 0-1
Timestamp time.Time
Metadata map[string]any
Embedding []float64
}
type EpisodicMemory struct {
ID string
Title string
Description string
Memories []string // Memory IDs
Tags []string
Importance float64
}
```
**Operations:**
- `Store(ctx, content, importance, metadata)`: Store new memory
- `Recall(ctx, query, tier, limit)`: Retrieve relevant memories
- `Promote(ctx, memoryID)`: Move to higher tier
- `CreateEpisode(ctx, episode)`: Group related memories
- `ConsolidateMemories(ctx)`: Prune low-importance memories
### 4. RAG System (`rag.go`)
**Pipeline:**
1. Document ingestion with chunking
2. Embedding generation
3. Vector storage
4. Semantic search with reranking
5. Context injection into prompts
**Key Types:**
```go
type RAG struct {
embedder EmbeddingModel
vectorStore VectorStore
reranker Reranker
chunkSize int
chunkOverlap int
topK int
}
```
**Usage:**
```go
rag.IndexDocument(ctx, docID, content)
results, _ := rag.Retrieve(ctx, query, topK)
response, _ := rag.GenerateWithContext(ctx, generator, query, topK)
```
### 5. Tool System (`tools.go`, `toolchain.go`)
**Auto-Discovery from Go Functions:**
```go
registry := NewToolRegistry(logger, metrics)
registry.RegisterFunc("search", "Search the web", searchFunc)
```
**Tool Structure:**
```go
type Tool struct {
Name string
Description string
Parameters map[string]any // JSON schema
Handler ToolHandler
Timeout time.Duration
Middleware []ToolMiddleware
}
type ToolHandler func(ctx context.Context, params map[string]any) (any, error)
```
**Toolchain for Sequential Execution:**
```go
chain := NewToolchain(registry, logger)
chain.AddStep("search", params1)
chain.AddStep("summarize", params2)
result, _ := chain.Execute(ctx)
```
### 6. Workflow Engine (`workflow.go`)
**DAG-Based Orchestration:**
```go
type Workflow struct {
ID string
Name string
Nodes map[string]*WorkflowNode
Edges map[string][]string // nodeID -> dependencies
StartNode string
}
type WorkflowNode struct {
ID string
Type NodeType // Tool, Agent, Condition, Parallel, Subworkflow
Config map[string]any
Condition string // For conditional nodes
}
// Node Types
const (
NodeTypeTool NodeType = "tool"
NodeTypeAgent NodeType = "agent"
NodeTypeCondition NodeType = "condition"
NodeTypeParallel NodeType = "parallel"
NodeTypeSubworkflow NodeType = "subworkflow"
)
```
**Execution:**
- Topological sort for dependency resolution
- Parallel execution of independent nodes
- Conditional branching
- Subworkflow composition
---
## Agent Patterns
### 1. Basic Agent (`agent.go`)
**Simple conversational agent with:**
- Stateful execution with history
- Tool calling support
- Memory integration
- State persistence
```go
type Agent struct {
ID string
Name string
Description string
SystemPrompt string
Tools []Tool
MaxIterations int
Temperature float64
History []Message
}
```
**When to Use:** Simple Q&A, conversational interfaces, single-step tasks
### 2. ReAct Agent (`react_agent.go`, `react_strategy.go`)
**Iterative Reasoning + Acting Pattern:**
**Core Loop:**
```
1. Thought: What should I do next?
2. Action: Execute a tool or provide answer
3. Observation: What was the result?
4. Reflection: How well did that work? (periodic)
... repeat until final answer
```
**Key Types:**
```go
type ReactAgent struct {
*Agent
strategy *ReactStrategy
}
type ReactStrategy struct {
maxIterations int
reflectionInterval int // Reflect every N steps
confidenceThreshold float64 // Min confidence to continue
reflectionEngine *ReflectionEngine
memoryManager *MemoryManager
}
type ReasoningTrace struct {
Step int
Thought string
Action string
Observation string
Reflection string
Confidence float64
Timestamp time.Time
Metadata map[string]any
}
```
**Builder:**
```go
agent, _ := NewReactAgentBuilder("researcher").
WithModel("gpt-4").
WithTools(searchTool, calculatorTool).
WithLLMManager(llmManager).
WithMemoryManager(memoryManager).
WithMaxIterations(10).
WithReflectionInterval(3).
WithConfidenceThreshold(0.7).
Build()
```
**When to Use:** Research tasks, exploratory problems, multi-step reasoning, transparent decision-making
### 3. Plan-Execute Agent (`plan_execute_agent.go`, `plan_execute_strategy.go`)
**Structured Multi-Step Task Execution:**
**Three Phases:**
```
1. PLAN: Decompose task into steps with dependencies
2. EXECUTE: Run steps (parallel where possible)
3. VERIFY: Check quality and correctness
└─> REPLAN: If needed, create improved plan
```
**Key Types:**
```go
type PlanExecuteAgent struct {
*Agent
strategy *PlanExecuteStrategy
}
type Plan struct {
ID string
AgentID string
Goal string
Steps []PlanStep
Status PlanStatus
Version int
ParentPlanID string // For replans
CreatedAt time.Time
UpdatedAt time.Time
}
type PlanStep struct {
ID string
Index int
Description string
ToolsNeeded []string
Dependencies []string // Step IDs that must complete first
Status PlanStepStatus
Result any
Error string
Verification *VerificationResult
RetryCount int
MaxRetries int
}
type PlanStatus string
const (
PlanStatusPending PlanStatus = "pending"
PlanStatusRunning PlanStatus = "running"
PlanStatusCompleted PlanStatus = "completed"
PlanStatusFailed PlanStatus = "failed"
)
type PlanStepStatus string
const (
PlanStepStatusPending PlanStepStatus = "pending"
PlanStepStatusRunning PlanStepStatus = "running"
PlanStepStatusCompleted PlanStepStatus = "completed"
PlanStepStatusFailed PlanStepStatus = "failed"
PlanStepStatusSkipped PlanStepStatus = "skipped"
)
```
**Builder:**
```go
agent, _ := NewPlanExecuteAgentBuilder("project_manager").
WithModel("gpt-4").
WithTools(fileTool, dbTool, apiTool).
WithLLMManager(llmManager).
WithPlanStore(planStore).
WithMemoryManager(memoryManager).
WithAllowReplanning(true).
WithVerifySteps(true).
WithMaxReplanAttempts(3).
WithTimeout(30 * time.Minute).
Build()
```
**When to Use:** Complex projects, multi-step workflows, tasks requiring verification, progress tracking needs
---
## Advanced Features
### 1. Reflection System (`reflection.go`)
**Self-Evaluation of Reasoning Quality:**
```go
type ReflectionEngine struct {
llmManager LLMManager
qualityThreshold float64
criteria []ReflectionCriterion
}
type ReflectionResult struct {
Quality string // "good", "needs_improvement", "invalid"
Score float64 // 0-1
Issues []string
Suggestions []string
ShouldReplan bool
Reasoning string
Timestamp time.Time
}
type ReflectionCriterion struct {
Name string // e.g., "Logical Coherence"
Description string
Weight float64 // 0-1, importance
}
```
**Operations:**
- `EvaluateStep(ctx, step, history)`: Evaluate single reasoning step
- `EvaluatePlan(ctx, plan)`: Evaluate entire plan
**Used By:** ReAct agents (periodic), Plan-Execute agents (before replanning)
### 2. Replanning Engine (`replan_engine.go`)
**Intelligent Plan Improvement:**
```go
type ReplanEngine struct {
plannerLLM LLMManager
reflectionEngine *ReflectionEngine
memoryManager *MemoryManager
triggers []ReplanTrigger
maxReplanAttempts int
failurePatterns map[string]int
}
type ReplanTrigger struct {
Name string
Description string
Condition func(*Plan, *ReflectionResult) bool
Priority int
}
```
**Features:**
- Automatic trigger evaluation
- Failure pattern learning
- Context-aware plan generation
- Preserves completed steps
**Operations:**
- `ShouldReplan(ctx, plan, reflection)`: Check if replanning needed
- `Replan(ctx, originalPlan, failureContext)`: Generate improved plan
- `LearnFromFailure(ctx, plan, context)`: Store failure patterns
### 3. Plan Verification (`plan_verification.go`)
**Quality Assurance for Plans:**
```go
type PlanVerifier struct {
verifierLLM LLMManager
qualityThreshold float64
structuralChecks bool
semanticChecks bool
}
type VerificationResult struct {
IsValid bool
Score float64
Issues []string
Suggestions []string
Reasoning string
Timestamp time.Time
}
```
**Two Levels:**
- **Structural**: Dependencies, cycles, completeness
- **Semantic**: Quality, feasibility, clarity
**Operations:**
- `VerifyStep(ctx, step, expectedOutcome)`: Verify step output
- `VerifyPlan(ctx, plan)`: Verify entire plan structure and quality
### 4. Memory Integration (`memory_integration.go`)
**Helpers for Agent Memory:**
```go
// Store reasoning traces
StoreReasoningTrace(ctx, mm, trace) -> *MemoryEntry
// Recall similar traces
RecallReasoningTraces(ctx, mm, query, limit) -> []*ReasoningTrace
// Store plans
StorePlan(ctx, mm, plan) -> *MemoryEntry
// Recall similar plans
RecallPlans(ctx, mm, query, limit) -> []*Plan
// Store reflections
StoreReflectionResult(ctx, mm, reflection, agentID, executionID, stepIndex)
// Store verifications
StoreVerificationResult(ctx, mm, verification, agentID, planID, stepID)
// Get execution context
GetExecutionContext(ctx, mm, goal, agentID) -> *ExecutionContextBuilder
```
**Purpose:** Enable agents to learn from past executions and avoid repeated mistakes
---
## Key Interfaces
### 1. LLMManager
```go
type LLMManager interface {
Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error)
Stream(ctx context.Context, req ChatRequest) (*StreamResponse, error)
GenerateEmbedding(ctx context.Context, text string) ([]float64, error)
}
```
### 2. VectorStore
```go
type VectorStore interface {
Store(ctx context.Context, id string, embedding []float64, metadata map[string]any) error
Query(ctx context.Context, embedding []float64, limit int) ([]VectorResult, error)
Delete(ctx context.Context, id string) error
}
```
### 3. StateStore
```go
type StateStore interface {
SaveState(ctx context.Context, agentID string, state map[string]any) error
LoadState(ctx context.Context, agentID string) (map[string]any, error)
DeleteState(ctx context.Context, agentID string) error
}
```
### 4. PlanStore
```go
type PlanStore interface {
SavePlan(ctx context.Context, plan *Plan) error
LoadPlan(ctx context.Context, planID string) (*Plan, error)
ListPlans(ctx context.Context, agentID string) ([]*Plan, error)
DeletePlan(ctx context.Context, planID string) error
}
```
### 5. EmbeddingModel
```go
type EmbeddingModel interface {
Embed(ctx context.Context, text string) ([]float64, error)
EmbedBatch(ctx context.Context, texts []string) ([][]float64, error)
Dimensions() int
}
```
---
## UI Generation System
### Overview
The SDK includes a comprehensive UI generation system that allows AI agents to create rich, interactive user interfaces. Instead of returning plain text, agents can generate structured responses with:
- Tables, charts, metrics dashboards
- Interactive forms and buttons
- Timeline and kanban boards
- Cards, alerts, progress indicators
- Galleries, carousels, and more
**Benefits:**
- Type-safe Go structs for all UI components
- Framework-agnostic JSON output (React, Vue, Angular, etc.)
- Streaming support for progressive rendering
- 12 built-in presentation tools for AI to call
- 25+ ContentPart types for rich UIs
### StructuredResponse Architecture
```go
type StructuredResponse struct {
ID string // Unique response ID
Parts []ContentPart // Ordered content parts
Artifacts []Artifact // Exportable content
Citations []Citation // Source references
Suggestions []Suggestion // Follow-up actions
Metadata ResponseMetadata // Model, duration, tokens
}
type ContentPart interface {
Type() ContentPartType
ToJSON() ([]byte, error)
}
```
### ContentPart Types
**Base Types** (response.go):
- `PartTypeText` - Plain or formatted text
- `PartTypeMarkdown` - Markdown content
- `PartTypeCode` - Syntax-highlighted code blocks
- `PartTypeTable` - Tabular data with sorting/filtering
- `PartTypeCard` - Contained content with actions
- `PartTypeList` - Ordered/unordered/checkbox lists
- `PartTypeImage` - Images with captions
- `PartTypeThinking` - AI reasoning process
- `PartTypeQuote` - Quotations and citations
- `PartTypeDivider` - Visual separator
- `PartTypeAlert` - Notifications (info/success/warning/error)
- `PartTypeProgress` - Progress bars and indicators
- `PartTypeChart` - Data visualizations (line, bar, pie, doughnut, area, scatter)
- `PartTypeJSON` - Structured JSON display
- `PartTypeCollapsible` - Expandable content
**Advanced UI Types** (ui_parts.go):
- `PartTypeButtonGroup` - Interactive action buttons
- `PartTypeTimeline` - Chronological events
- `PartTypeKanban` - Task board with draggable cards
- `PartTypeMetric` - KPIs with trends and sparklines
- `PartTypeForm` - Interactive forms with validation
- `PartTypeTabs` - Tabbed content sections
- `PartTypeAccordion` - Collapsible accordion
- `PartTypeInlineCitation` - Inline source references
- `PartTypeStats` - Compact statistics display
- `PartTypeCarousel` - Sliding content carousel
- `PartTypeGallery` - Image/media gallery
### Presentation Tools (presentation_tools.go)
**12 built-in tools AI can call to generate UI components:**
1. **render_table** - Display tabular data
- Parameters: title, headers, rows, options (sortable, searchable, paginated)
- Use for: data grids, search results, database records, comparisons
2. **render_chart** - Display data visualizations
- Parameters: title, type (line/bar/pie/doughnut/area/scatter), labels, datasets, options
- Use for: trends, distributions, comparisons, time series
3. **render_metrics** - Display KPIs and dashboards
- Parameters: title, metrics (with trends, sparklines, targets), layout, columns
- Use for: business dashboards, analytics, performance monitoring
4. **render_timeline** - Display chronological events
- Parameters: title, events (with timestamps, icons, status), orientation
- Use for: history, milestones, activity logs, order tracking
5. **render_kanban** - Display task boards
- Parameters: title, columns (with cards, colors, limits), draggable
- Use for: task management, workflows, project boards, pipelines
6. **render_buttons** - Display interactive buttons
- Parameters: title, buttons (with actions, variants, icons), layout
- Use for: action choices, navigation, quick replies, confirmations
7. **render_form** - Display interactive forms
- Parameters: id, title, fields (with types, validation, options), submitLabel
- Use for: data entry, settings, filters, surveys, registration
8. **render_card** - Display content cards
- Parameters: title, subtitle, content, icon, image, footer, actions
- Use for: highlights, summaries, profiles, featured content
9. **render_stats** - Display compact statistics
- Parameters: title, stats (with changes, icons), layout
- Use for: quick overviews, summaries, key numbers
10. **render_gallery** - Display image/media galleries
- Parameters: title, items (with thumbnails, descriptions), layout, columns
- Use for: photo collections, portfolios, product images
11. **render_alert** - Display alerts and notifications
- Parameters: title, message, type (info/success/warning/error), dismissible, actions
- Use for: warnings, errors, success messages, important notices
12. **render_progress** - Display progress indicators
- Parameters: label, value (0-100), max, showPercentage, variant
- Use for: completion status, loading, step-by-step progress
### Using Presentation Tools
```go
// Get tool schemas for LLM
schemas := sdk.GetPresentationToolSchemas()
// Add to agent
agent, _ := sdk.NewAgentBuilder().
WithTools(schemas...).
WithSystemPrompt(`Use presentation tools to visualize data:
- render_table for structured data
- render_chart for trends
- render_metrics for KPIs
- render_timeline for events
- render_kanban for task boards`).
Build()
// Execute tool manually
result, _ := sdk.ExecutePresentationTool(ctx, "render_table", params, onEvent, executionID)
```
### ResponseBuilder API
Fluent API for building structured responses:
```go
response := sdk.NewResponseBuilder().
WithMetadata("gpt-4", "openai", duration).
WithTokenUsage(inputTokens, outputTokens).
AddText("Analysis complete!").
AddMarkdown("## Summary\n...").
AddCode(code, "go").
AddTable(headers, rows).
AddChart(chartType, data).
AddDivider().
AddAlert("Success!", sdk.AlertSuccess).
AddThinking("Reasoning process...").
AddArtifact(artifact).
AddCitation(citation).
AddSuggestion(suggestion).
Build()
// Convert to JSON for frontend
jsonData, _ := response.ToJSON()
plainText := response.ToPlainText()
```
### ResponseParser
Parse raw LLM output into structured parts:
```go
parser := sdk.NewResponseParser()
// Parses code blocks, tables, thinking tags, etc.
parts := parser.Parse(llmOutput)
// Enable UI block parsing
parser.WithUIBlocks(true)
```
### UI Component Examples
**ButtonGroup:**
```go
buttons := sdk.NewButtonGroupPart(
sdk.Button{
ID: "approve",
Label: "Approve",
Variant: sdk.ButtonPrimary,
Action: sdk.ButtonAction{Type: sdk.ActionTypeTool, Value: "approve_request"},
},
sdk.Button{
ID: "reject",
Label: "Reject",
Variant: sdk.ButtonDanger,
Action: sdk.ButtonAction{Type: sdk.ActionTypeTool, Value: "reject_request"},
},
)
```
**Timeline:**
```go
timeline := sdk.NewTimelinePart(
sdk.TimelineEvent{
Title: "Order Placed",
Description: "Order #12345 placed",
Timestamp: time.Now(),
Icon: "shopping-cart",
Status: sdk.TimelineStatusCompleted,
},
sdk.TimelineEvent{
Title: "Shipped",
Timestamp: time.Now().Add(24 * time.Hour),
Status: sdk.TimelineStatusInProgress,
},
)
```
**Kanban:**
```go
kanban := sdk.NewKanbanPart(
sdk.KanbanColumn{
ID: "todo",
Title: "To Do",
Cards: []sdk.KanbanCard{
{Title: "Task 1", Priority: "high"},
{Title: "Task 2", Priority: "medium"},
},
},
sdk.KanbanColumn{
ID: "in_progress",
Title: "In Progress",
Cards: []sdk.KanbanCard{
{Title: "Task 3", Progress: 60.0},
},
},
)
```
**Metrics:**
```go
metrics := sdk.NewMetricPart(
sdk.Metric{
Label: "Revenue",
Value: 125000,
FormattedValue: "$125,000",
Icon: "dollar-sign",
Trend: &sdk.MetricTrend{
Direction: sdk.TrendUp,
Percentage: 12.5,
},
Status: sdk.MetricStatusGood,
},
)
```
**Form:**
```go
form := sdk.NewFormPart("registration",
sdk.FormField{
Name: "email",
Label: "Email Address",
Type: sdk.FieldTypeEmail,
Required: true,
Placeholder: "you@example.com",
},
sdk.FormField{
Name: "role",
Label: "Role",
Type: sdk.FieldTypeSelect,
Options: []sdk.FormFieldOption{
{Value: "admin", Label: "Administrator"},
{Value: "user", Label: "Regular User"},
},
},
)
```
### Streaming UI
Progressive rendering of complex UIs:
```go
streamer := sdk.NewUIPartStreamer(sdk.UIPartStreamerConfig{
PartType: sdk.PartTypeTable,
ExecutionID: executionID,
OnEvent: onEvent,
})
streamer.Start()
streamer.StreamSection("title", "Sales Data")
streamer.StreamHeader(headers)
// Stream rows in batches
for _, batch := range rowBatches {
streamer.StreamRows(batch)
}
streamer.End()
```
### Frontend Integration
**React Example:**
```typescript
function ContentPartRenderer({ part }: { part: ContentPart }) {
switch (part.type) {
case 'table': return <TableComponent {...part} />;
case 'chart': return <ChartComponent {...part} />;
case 'button_group': return <ButtonGroup {...part} />;
case 'timeline': return <Timeline {...part} />;
case 'kanban': return <KanbanBoard {...part} />;
case 'metric': return <MetricsDashboard {...part} />;
case 'form': return <DynamicForm {...part} />;
default: return <div>Unsupported: {part.type}</div>;
}
}
```
### Best Practices for UI Generation
1. **Choose Appropriate Components**: Use tables for data, charts for trends, metrics for KPIs
2. **Progressive Disclosure**: Use accordions/tabs for large content
3. **Actionable UIs**: Provide buttons for next actions
4. **Stream Large Data**: Use streaming for tables > 100 rows
5. **Consistent Styling**: Use defined variants and colors
6. **Accessibility**: Include labels, tooltips, alt text
7. **Mobile-Friendly**: Use responsive layouts and columns
### UI Generation Decision Guide
**Use render_table when:**
- Displaying structured data with rows/columns
- Showing database records or search results
- Need sorting, filtering, or pagination
**Use render_chart when:**
- Visualizing trends over time
- Comparing multiple datasets
- Showing distributions or proportions
**Use render_metrics when:**
- Displaying KPIs and dashboards
- Showing trends and sparklines
- Monitoring performance metrics
**Use render_timeline when:**
- Showing chronological events
- Tracking order/project status
- Displaying activity logs
**Use render_kanban when:**
- Managing tasks across stages
- Visualizing workflows
- Showing project boards
**Use render_buttons when:**
- Presenting action choices
- Providing quick replies
- Offering navigation options
**Use render_form when:**
- Collecting user input
- Building settings interfaces
- Creating search filters
---
## Structured Output
### Type-Safe Object Generation
```go
type Person struct {
Name string `json:"name" description:"Full name"`
Age int `json:"age" description:"Age in years"`
Hobbies []string `json:"hobbies"`
}
result, _ := NewGenerateObjectBuilder[Person](ctx, llmManager, logger, metrics).
WithProvider("openai").
WithModel("gpt-4").
WithPrompt("Extract person info: John Doe, 30, loves reading").
WithValidator(func(p *Person) error {
if p.Age < 0 || p.Age > 150 {
return fmt.Errorf("invalid age")
}
return nil
}).
Execute()
// result is *Person with type safety
```
### Streaming Objects
```go
stream := NewStreamObjectBuilder[Person](ctx, llmManager, logger, metrics).
WithPrompt("Extract person info...").
OnPartial(func(partial *Person) {
fmt.Printf("Partial: %+v\n", partial)
}).
OnComplete(func(final *Person) {
fmt.Printf("Complete: %+v\n", final)
}).
Stream()
```
---
## UI Output System
### ContentPart Interface
```go
type ContentPart interface {
Type() ContentPartType
Content() map[string]any
Metadata() map[string]any
}
type ContentPartType string
const (
PartTypeText ContentPartType = "text"
PartTypeThinking ContentPartType = "thinking"
PartTypeImage ContentPartType = "image"
PartTypeTimeline ContentPartType = "timeline"
PartTypeKanban ContentPartType = "kanban"
PartTypeButtonGroup ContentPartType = "button_group"
PartTypeForm ContentPartType = "form"
PartTypeTable ContentPartType = "table"
)
```
### Structured Response
```go
type StructuredResponse struct {
Parts []ContentPart
Metadata map[string]any
Cost float64
}
// Create UI response
response := &StructuredResponse{
Parts: []ContentPart{
NewTextPart("Here's the plan:"),
NewTimelinePart(steps),
NewButtonGroupPart(actions),
},
}
```
---
## Cost Management
### Cost Tracker
```go
type CostTracker struct {
records []UsageRecord
budgets map[string]*Budget
optimizations []OptimizationRule
}
type UsageRecord struct {
Provider string
Model string
InputTokens int
OutputTokens int
Cost float64
Timestamp time.Time
}
type Budget struct {
Name string
Limit float64
Period time.Duration
AlertThreshold float64
Current float64
}
// Usage
tracker := NewCostTracker(logger, metrics, opts)
tracker.SetBudget("monthly", 1000.0, 30*24*time.Hour, 0.8)
tracker.RecordUsage(ctx, record)