-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpresentation_tools.go
More file actions
1762 lines (1504 loc) · 44 KB
/
presentation_tools.go
File metadata and controls
1762 lines (1504 loc) · 44 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
package sdk
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/xraph/ai-sdk/llm"
)
// PresentationToolName constants for built-in presentation tools.
const (
ToolRenderTable = "render_table"
ToolRenderChart = "render_chart"
ToolRenderMetrics = "render_metrics"
ToolRenderTimeline = "render_timeline"
ToolRenderKanban = "render_kanban"
ToolRenderButtons = "render_buttons"
ToolRenderForm = "render_form"
ToolRenderCard = "render_card"
ToolRenderStats = "render_stats"
ToolRenderGallery = "render_gallery"
ToolRenderAlert = "render_alert"
ToolRenderProgress = "render_progress"
)
// PresentationTools returns all built-in presentation tools that AI can call.
func PresentationTools() []UITool {
return []UITool{
newRenderTableTool(),
newRenderChartTool(),
newRenderMetricsTool(),
newRenderTimelineTool(),
newRenderKanbanTool(),
newRenderButtonsTool(),
newRenderFormTool(),
newRenderCardTool(),
newRenderStatsTool(),
newRenderGalleryTool(),
newRenderAlertTool(),
newRenderProgressTool(),
}
}
// GetPresentationToolSchemas returns LLM-ready tool definitions for all presentation tools.
func GetPresentationToolSchemas() []llm.Tool {
tools := PresentationTools()
schemas := make([]llm.Tool, len(tools))
for i, tool := range tools {
schemas[i] = llm.Tool{
Type: "function",
Function: &llm.FunctionDefinition{
Name: tool.Name(),
Description: tool.Description(),
Parameters: toolParamsToMap(tool.GetParameters()),
},
}
}
return schemas
}
// toolParamsToMap converts ToolParameterSchema to map[string]any for LLM.
func toolParamsToMap(schema ToolParameterSchema) map[string]any {
props := make(map[string]any)
for name, prop := range schema.Properties {
propMap := map[string]any{
"type": prop.Type,
"description": prop.Description,
}
if len(prop.Enum) > 0 {
propMap["enum"] = prop.Enum
}
if prop.Default != nil {
propMap["default"] = prop.Default
}
props[name] = propMap
}
return map[string]any{
"type": schema.Type,
"properties": props,
"required": schema.Required,
}
}
// =============================================================================
// render_table - Display data as an interactive table
// =============================================================================
func newRenderTableTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderTable,
Description: "Display data as an interactive table. Use when showing tabular data, lists of items, database records, comparisons, or any structured data with rows and columns.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"title": {
Type: "string",
Description: "Title of the table",
},
"headers": {
Type: "array",
Description: "Array of column headers. Each header should have 'label' (display name) and 'key' (data key). Optional: 'sortable' (boolean), 'width' (string)",
},
"rows": {
Type: "array",
Description: "Array of rows. Each row is an array of cell values matching header order. Values can be strings, numbers, or objects with 'value' and 'display' keys",
},
"options": {
Type: "object",
Description: "Optional table options: 'sortable' (boolean), 'searchable' (boolean), 'paginated' (boolean), 'pageSize' (number)",
},
},
Required: []string{"headers", "rows"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeTable,
StreamingEnabled: true,
},
Handler: handleRenderTable,
RenderFunc: renderTableUI,
})
}
func handleRenderTable(ctx context.Context, params map[string]any) (any, error) {
// Pass through the params as the result - the render function will handle it
return params, nil
}
func renderTableUI(ctx context.Context, result any, streamer *UIPartStreamer) error {
params, ok := result.(map[string]any)
if !ok {
return errors.New("invalid result type for render_table")
}
if err := streamer.Start(); err != nil {
return err
}
// Stream title
if title, ok := params["title"].(string); ok && title != "" {
if err := streamer.StreamSection("title", title); err != nil {
return err
}
}
// Stream headers
if headersRaw, ok := params["headers"]; ok {
headers := parseTableHeaders(headersRaw)
if err := streamer.StreamHeader(headers); err != nil {
return err
}
}
// Stream rows
if rowsRaw, ok := params["rows"].([]any); ok {
rows := parseTableRows(rowsRaw)
// Stream in batches of 10
batchSize := 10
for i := 0; i < len(rows); i += batchSize {
end := i + batchSize
if end > len(rows) {
end = len(rows)
}
if err := streamer.StreamRows(rows[i:end]); err != nil {
return err
}
}
}
// Stream options as metadata
if options, ok := params["options"].(map[string]any); ok {
if err := streamer.StreamMetadata(options); err != nil {
return err
}
}
return streamer.End()
}
func parseTableHeaders(raw any) []TableHeader {
headers := make([]TableHeader, 0)
switch v := raw.(type) {
case []any:
for _, h := range v {
switch hv := h.(type) {
case string:
headers = append(headers, TableHeader{Label: hv, Key: hv})
case map[string]any:
header := TableHeader{}
if label, ok := hv["label"].(string); ok {
header.Label = label
}
if key, ok := hv["key"].(string); ok {
header.Key = key
} else {
header.Key = header.Label
}
if sortable, ok := hv["sortable"].(bool); ok {
header.Sortable = sortable
}
if width, ok := hv["width"].(string); ok {
header.Width = width
}
headers = append(headers, header)
}
}
}
return headers
}
func parseTableRows(raw []any) [][]TableCell {
rows := make([][]TableCell, 0, len(raw))
for _, r := range raw {
if rowArr, ok := r.([]any); ok {
cells := make([]TableCell, 0, len(rowArr))
for _, c := range rowArr {
cell := TableCell{}
switch cv := c.(type) {
case string:
cell.Value = cv
cell.Display = cv
case float64:
cell.Value = cv
cell.Display = fmt.Sprintf("%v", cv)
case int:
cell.Value = cv
cell.Display = strconv.Itoa(cv)
case map[string]any:
if val, ok := cv["value"]; ok {
cell.Value = val
}
if disp, ok := cv["display"].(string); ok {
cell.Display = disp
} else {
cell.Display = fmt.Sprintf("%v", cell.Value)
}
if style, ok := cv["style"].(string); ok {
cell.Style = style
}
if link, ok := cv["link"].(string); ok {
cell.Link = link
}
default:
cell.Value = cv
cell.Display = fmt.Sprintf("%v", cv)
}
cells = append(cells, cell)
}
rows = append(rows, cells)
}
}
return rows
}
// =============================================================================
// render_chart - Display data as a chart
// =============================================================================
func newRenderChartTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderChart,
Description: "Display data as an interactive chart. Use for visualizing trends, comparisons, distributions, or any data that benefits from graphical representation. Supports line, bar, pie, doughnut, area, and scatter charts.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"title": {
Type: "string",
Description: "Title of the chart",
},
"type": {
Type: "string",
Description: "Chart type",
Enum: []string{"line", "bar", "pie", "doughnut", "area", "scatter"},
},
"labels": {
Type: "array",
Description: "X-axis labels or category names",
},
"datasets": {
Type: "array",
Description: "Array of datasets. Each dataset has 'label' (string), 'data' (array of numbers), optional 'backgroundColor' and 'borderColor'",
},
"options": {
Type: "object",
Description: "Optional chart options: 'showLegend' (boolean), 'showGrid' (boolean), 'stacked' (boolean)",
},
},
Required: []string{"type", "labels", "datasets"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeChart,
StreamingEnabled: false, // Charts render all at once
},
Handler: handleRenderChart,
RenderFunc: renderChartUI,
})
}
func handleRenderChart(ctx context.Context, params map[string]any) (any, error) {
return params, nil
}
func renderChartUI(ctx context.Context, result any, streamer *UIPartStreamer) error {
params, ok := result.(map[string]any)
if !ok {
return errors.New("invalid result type for render_chart")
}
if err := streamer.Start(); err != nil {
return err
}
// Stream title
if title, ok := params["title"].(string); ok && title != "" {
if err := streamer.StreamSection("title", title); err != nil {
return err
}
}
// Stream chart type
if chartType, ok := params["type"].(string); ok {
if err := streamer.StreamSection("chartType", chartType); err != nil {
return err
}
}
// Build and stream chart data
chartData := ChartData{}
if labels, ok := params["labels"].([]any); ok {
for _, l := range labels {
if s, ok := l.(string); ok {
chartData.Labels = append(chartData.Labels, s)
}
}
}
if datasets, ok := params["datasets"].([]any); ok {
for _, ds := range datasets {
if dsMap, ok := ds.(map[string]any); ok {
dataset := ChartDataset{}
if label, ok := dsMap["label"].(string); ok {
dataset.Label = label
}
if data, ok := dsMap["data"].([]any); ok {
for _, d := range data {
switch v := d.(type) {
case float64:
dataset.Data = append(dataset.Data, v)
case int:
dataset.Data = append(dataset.Data, float64(v))
}
}
}
if bg, ok := dsMap["backgroundColor"].(string); ok {
dataset.BackgroundColor = bg
}
if bc, ok := dsMap["borderColor"].(string); ok {
dataset.BorderColor = bc
}
chartData.Datasets = append(chartData.Datasets, dataset)
}
}
}
if err := streamer.StreamSection("data", chartData); err != nil {
return err
}
// Stream options
if options, ok := params["options"].(map[string]any); ok {
if err := streamer.StreamMetadata(options); err != nil {
return err
}
}
return streamer.End()
}
// =============================================================================
// render_metrics - Display KPIs and metrics
// =============================================================================
func newRenderMetricsTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderMetrics,
Description: "Display key performance indicators (KPIs) and metrics. Use for dashboards, stats summaries, or highlighting important numbers with optional trends and sparklines.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"title": {
Type: "string",
Description: "Dashboard or section title",
},
"metrics": {
Type: "array",
Description: "Array of metrics. Each metric has 'label' (string), 'value' (number/string), optional 'unit', 'icon', 'trend' (object with 'direction': up/down/stable, 'percentage'), 'status' (good/warning/bad)",
},
"layout": {
Type: "string",
Description: "Layout style",
Enum: []string{"grid", "list", "compact", "cards"},
},
"columns": {
Type: "integer",
Description: "Number of columns for grid layout (default: 3)",
},
},
Required: []string{"metrics"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeMetric,
StreamingEnabled: true,
},
Handler: handleRenderMetrics,
RenderFunc: renderMetricsUI,
})
}
func handleRenderMetrics(ctx context.Context, params map[string]any) (any, error) {
return params, nil
}
func renderMetricsUI(ctx context.Context, result any, streamer *UIPartStreamer) error {
params, ok := result.(map[string]any)
if !ok {
return errors.New("invalid result type for render_metrics")
}
if err := streamer.Start(); err != nil {
return err
}
// Stream title
if title, ok := params["title"].(string); ok && title != "" {
if err := streamer.StreamSection("title", title); err != nil {
return err
}
}
// Stream metrics one by one
if metricsRaw, ok := params["metrics"].([]any); ok {
for _, m := range metricsRaw {
if mMap, ok := m.(map[string]any); ok {
metric := parseMetric(mMap)
if err := streamer.StreamSection("metrics", metric); err != nil {
return err
}
}
}
}
// Stream layout options
metadata := make(map[string]any)
if layout, ok := params["layout"].(string); ok {
metadata["layout"] = layout
}
if columns, ok := params["columns"].(float64); ok {
metadata["columns"] = int(columns)
}
if len(metadata) > 0 {
if err := streamer.StreamMetadata(metadata); err != nil {
return err
}
}
return streamer.End()
}
func parseMetric(m map[string]any) Metric {
metric := Metric{}
if label, ok := m["label"].(string); ok {
metric.Label = label
}
if value, ok := m["value"]; ok {
metric.Value = value
metric.FormattedValue = fmt.Sprintf("%v", value)
}
if formatted, ok := m["formattedValue"].(string); ok {
metric.FormattedValue = formatted
}
if unit, ok := m["unit"].(string); ok {
metric.Unit = unit
}
if icon, ok := m["icon"].(string); ok {
metric.Icon = icon
}
if color, ok := m["color"].(string); ok {
metric.Color = color
}
if status, ok := m["status"].(string); ok {
metric.Status = MetricStatus(status)
}
// Parse trend
if trendMap, ok := m["trend"].(map[string]any); ok {
trend := &MetricTrend{}
if dir, ok := trendMap["direction"].(string); ok {
trend.Direction = TrendDirection(dir)
}
if pct, ok := trendMap["percentage"].(float64); ok {
trend.Percentage = pct
}
if period, ok := trendMap["period"].(string); ok {
trend.Period = period
}
metric.Trend = trend
}
return metric
}
// =============================================================================
// render_timeline - Display chronological events
// =============================================================================
func newRenderTimelineTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderTimeline,
Description: "Display a timeline of events. Use for showing chronological data, history, project milestones, activity logs, or any sequential events.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"title": {
Type: "string",
Description: "Timeline title",
},
"events": {
Type: "array",
Description: "Array of events. Each event has 'title' (string), 'description' (optional string), 'timestamp' (ISO date string), optional 'icon', 'color', 'status' (pending/in_progress/completed/cancelled/error)",
},
"orientation": {
Type: "string",
Description: "Timeline orientation",
Enum: []string{"vertical", "horizontal"},
},
},
Required: []string{"events"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeTimeline,
StreamingEnabled: true,
},
Handler: handleRenderTimeline,
RenderFunc: renderTimelineUI,
})
}
func handleRenderTimeline(ctx context.Context, params map[string]any) (any, error) {
return params, nil
}
func renderTimelineUI(ctx context.Context, result any, streamer *UIPartStreamer) error {
params, ok := result.(map[string]any)
if !ok {
return errors.New("invalid result type for render_timeline")
}
if err := streamer.Start(); err != nil {
return err
}
// Stream title
if title, ok := params["title"].(string); ok && title != "" {
if err := streamer.StreamSection("title", title); err != nil {
return err
}
}
// Stream events
if eventsRaw, ok := params["events"].([]any); ok {
for _, e := range eventsRaw {
if eMap, ok := e.(map[string]any); ok {
event := parseTimelineEvent(eMap)
if err := streamer.StreamSection("events", event); err != nil {
return err
}
}
}
}
// Stream orientation
if orientation, ok := params["orientation"].(string); ok {
if err := streamer.StreamMetadata(map[string]any{"orientation": orientation}); err != nil {
return err
}
}
return streamer.End()
}
func parseTimelineEvent(e map[string]any) TimelineEvent {
event := TimelineEvent{
ID: fmt.Sprintf("evt_%d", time.Now().UnixNano()),
}
if title, ok := e["title"].(string); ok {
event.Title = title
}
if desc, ok := e["description"].(string); ok {
event.Description = desc
}
if ts, ok := e["timestamp"].(string); ok {
if t, err := time.Parse(time.RFC3339, ts); err == nil {
event.Timestamp = t
} else {
event.Timestamp = time.Now()
}
}
if icon, ok := e["icon"].(string); ok {
event.Icon = icon
}
if color, ok := e["color"].(string); ok {
event.Color = color
}
if status, ok := e["status"].(string); ok {
event.Status = TimelineStatus(status)
}
return event
}
// =============================================================================
// render_kanban - Display a kanban board
// =============================================================================
func newRenderKanbanTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderKanban,
Description: "Display a kanban board with columns and cards. Use for task management, workflow visualization, project status boards, or any columnar organization of items.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"title": {
Type: "string",
Description: "Board title",
},
"columns": {
Type: "array",
Description: "Array of columns. Each column has 'title' (string), 'id' (string), optional 'color', and 'cards' array. Each card has 'title', 'description', optional 'labels', 'priority' (low/medium/high/urgent)",
},
"draggable": {
Type: "boolean",
Description: "Allow drag and drop (default: true)",
},
},
Required: []string{"columns"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeKanban,
StreamingEnabled: true,
},
Handler: handleRenderKanban,
RenderFunc: renderKanbanUI,
})
}
func handleRenderKanban(ctx context.Context, params map[string]any) (any, error) {
return params, nil
}
func renderKanbanUI(ctx context.Context, result any, streamer *UIPartStreamer) error {
params, ok := result.(map[string]any)
if !ok {
return errors.New("invalid result type for render_kanban")
}
if err := streamer.Start(); err != nil {
return err
}
// Stream title
if title, ok := params["title"].(string); ok && title != "" {
if err := streamer.StreamSection("title", title); err != nil {
return err
}
}
// Stream columns
if columnsRaw, ok := params["columns"].([]any); ok {
for _, c := range columnsRaw {
if cMap, ok := c.(map[string]any); ok {
column := parseKanbanColumn(cMap)
if err := streamer.StreamColumns(column); err != nil {
return err
}
}
}
}
// Stream options
metadata := make(map[string]any)
if draggable, ok := params["draggable"].(bool); ok {
metadata["draggable"] = draggable
}
if len(metadata) > 0 {
if err := streamer.StreamMetadata(metadata); err != nil {
return err
}
}
return streamer.End()
}
func parseKanbanColumn(c map[string]any) KanbanColumn {
column := KanbanColumn{
ID: fmt.Sprintf("col_%d", time.Now().UnixNano()),
Cards: make([]KanbanCard, 0),
}
if id, ok := c["id"].(string); ok {
column.ID = id
}
if title, ok := c["title"].(string); ok {
column.Title = title
}
if color, ok := c["color"].(string); ok {
column.Color = color
}
if cardsRaw, ok := c["cards"].([]any); ok {
for _, card := range cardsRaw {
if cardMap, ok := card.(map[string]any); ok {
column.Cards = append(column.Cards, parseKanbanCard(cardMap))
}
}
}
return column
}
func parseKanbanCard(c map[string]any) KanbanCard {
card := KanbanCard{
ID: fmt.Sprintf("card_%d", time.Now().UnixNano()),
}
if id, ok := c["id"].(string); ok {
card.ID = id
}
if title, ok := c["title"].(string); ok {
card.Title = title
}
if desc, ok := c["description"].(string); ok {
card.Description = desc
}
if priority, ok := c["priority"].(string); ok {
card.Priority = priority
}
if labelsRaw, ok := c["labels"].([]any); ok {
for _, l := range labelsRaw {
switch lv := l.(type) {
case string:
card.Labels = append(card.Labels, KanbanLabel{Text: lv})
case map[string]any:
label := KanbanLabel{}
if text, ok := lv["text"].(string); ok {
label.Text = text
}
if color, ok := lv["color"].(string); ok {
label.Color = color
}
card.Labels = append(card.Labels, label)
}
}
}
return card
}
// =============================================================================
// render_buttons - Display interactive buttons
// =============================================================================
func newRenderButtonsTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderButtons,
Description: "Display a group of interactive buttons. Use for presenting action choices, navigation options, quick replies, or any interactive options the user can select.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"title": {
Type: "string",
Description: "Optional title above buttons",
},
"buttons": {
Type: "array",
Description: "Array of buttons. Each button has 'label' (string), 'id' (string), optional 'icon', 'variant' (primary/secondary/outline/danger), 'action' object with 'type' (link/tool/callback/copy) and 'value'",
},
"layout": {
Type: "string",
Description: "Button layout",
Enum: []string{"horizontal", "vertical", "grid", "wrap"},
},
},
Required: []string{"buttons"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeButtonGroup,
StreamingEnabled: false,
},
Handler: handleRenderButtons,
RenderFunc: renderButtonsUI,
})
}
func handleRenderButtons(ctx context.Context, params map[string]any) (any, error) {
return params, nil
}
func renderButtonsUI(ctx context.Context, result any, streamer *UIPartStreamer) error {
params, ok := result.(map[string]any)
if !ok {
return errors.New("invalid result type for render_buttons")
}
if err := streamer.Start(); err != nil {
return err
}
// Stream title
if title, ok := params["title"].(string); ok && title != "" {
if err := streamer.StreamSection("title", title); err != nil {
return err
}
}
// Stream buttons
if buttonsRaw, ok := params["buttons"].([]any); ok {
buttons := make([]Button, 0, len(buttonsRaw))
for _, b := range buttonsRaw {
if bMap, ok := b.(map[string]any); ok {
buttons = append(buttons, parseButton(bMap))
}
}
if err := streamer.StreamSection("buttons", buttons); err != nil {
return err
}
}
// Stream layout
if layout, ok := params["layout"].(string); ok {
if err := streamer.StreamMetadata(map[string]any{"layout": layout}); err != nil {
return err
}
}
return streamer.End()
}
func parseButton(b map[string]any) Button {
button := Button{
ID: fmt.Sprintf("btn_%d", time.Now().UnixNano()),
Variant: ButtonPrimary,
}
if id, ok := b["id"].(string); ok {
button.ID = id
}
if label, ok := b["label"].(string); ok {
button.Label = label
}
if icon, ok := b["icon"].(string); ok {
button.Icon = icon
}
if variant, ok := b["variant"].(string); ok {
button.Variant = ButtonVariant(variant)
}
if disabled, ok := b["disabled"].(bool); ok {
button.Disabled = disabled
}
// Parse action
if actionMap, ok := b["action"].(map[string]any); ok {
action := ButtonAction{}
if actionType, ok := actionMap["type"].(string); ok {
action.Type = ButtonActionType(actionType)
}
if value, ok := actionMap["value"].(string); ok {
action.Value = value
}
if payload, ok := actionMap["payload"].(map[string]any); ok {
action.Payload = payload
}
button.Action = action
}
return button
}
// =============================================================================
// render_form - Display an interactive form
// =============================================================================
func newRenderFormTool() *BaseUITool {
return NewBaseUITool(BaseUIToolConfig{
Name: ToolRenderForm,
Description: "Display an interactive form for collecting user input. Use for data entry, settings, search filters, or any structured input collection.",
Parameters: ToolParameterSchema{
Type: "object",
Properties: map[string]ToolParameterProperty{
"id": {
Type: "string",
Description: "Unique form identifier",
},
"title": {
Type: "string",
Description: "Form title",
},
"description": {
Type: "string",
Description: "Form description or instructions",
},
"fields": {
Type: "array",
Description: "Array of form fields. Each field has 'name' (string), 'label' (string), 'type' (text/email/password/number/select/checkbox/textarea/date), optional 'placeholder', 'required' (boolean), 'options' (for select)",
},
"submitLabel": {
Type: "string",
Description: "Submit button label (default: 'Submit')",
},
},
Required: []string{"fields"},
},
Hints: UIToolHints{
PreferredPartType: PartTypeForm,
StreamingEnabled: true,
},
Handler: handleRenderForm,
RenderFunc: renderFormUI,
})
}
func handleRenderForm(ctx context.Context, params map[string]any) (any, error) {
return params, nil
}
func renderFormUI(ctx context.Context, result any, streamer *UIPartStreamer) error {