oneie 3.6.35 → 3.6.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,715 @@
1
+ ---
2
+ title: Ai Api Reference
3
+ dimension: knowledge
4
+ category: api
5
+ tags: ai, api, reference, mutations, queries
6
+ related_dimensions: things, connections
7
+ scope: global
8
+ created: 2025-11-10
9
+ updated: 2025-11-10
10
+ version: 1.0.0
11
+ ---
12
+
13
+ # AI API Reference
14
+
15
+ **Version:** 1.0.0
16
+ **Last Updated:** 2025-11-10
17
+ **Stack:** Vercel AI SDK 5 + Effect.ts + Convex
18
+
19
+ ## Overview
20
+
21
+ Complete API reference for AI integration including mutations, queries, services, hooks, and components.
22
+
23
+ ## Mutations
24
+
25
+ ### generateResponse
26
+
27
+ Generate AI text response.
28
+
29
+ **Location:** `backend/convex/mutations/ai/generate.ts`
30
+
31
+ **Parameters:**
32
+ ```typescript
33
+ {
34
+ groupId: Id<"groups">; // REQUIRED: Multi-tenant scope
35
+ prompt: string; // REQUIRED: User prompt
36
+ model?: string; // Optional: Specific model (e.g., "gpt-4-turbo")
37
+ provider?: string; // Optional: "openai" | "anthropic" | "google"
38
+ systemPrompt?: string; // Optional: System instructions
39
+ }
40
+ ```
41
+
42
+ **Returns:**
43
+ ```typescript
44
+ {
45
+ success: boolean;
46
+ text: string;
47
+ usage: {
48
+ promptTokens: number;
49
+ completionTokens: number;
50
+ totalTokens: number;
51
+ };
52
+ }
53
+ ```
54
+
55
+ **Example:**
56
+ ```typescript
57
+ const response = await generateResponse({
58
+ groupId: userGroupId,
59
+ prompt: "Explain quantum computing in simple terms",
60
+ provider: "anthropic"
61
+ });
62
+
63
+ console.log(response.text);
64
+ // "Quantum computing uses quantum mechanics..."
65
+ ```
66
+
67
+ **Events Emitted:**
68
+ - `ai_generation_completed` (on success)
69
+ - `ai_error_occurred` (on failure)
70
+
71
+ ---
72
+
73
+ ### streamAgentResponse
74
+
75
+ Stream AI response in real-time.
76
+
77
+ **Location:** `backend/convex/mutations/ai/stream.ts`
78
+
79
+ **Parameters:**
80
+ ```typescript
81
+ {
82
+ groupId: Id<"groups">; // REQUIRED
83
+ threadId: Id<"aiThreads">; // REQUIRED: Conversation thread
84
+ message: string; // REQUIRED: User message
85
+ systemPrompt?: string; // Optional: System instructions
86
+ }
87
+ ```
88
+
89
+ **Returns:**
90
+ ```typescript
91
+ {
92
+ threadId: Id<"aiThreads">;
93
+ stream: AsyncIterable<string>; // Streaming text
94
+ usage: {
95
+ promptTokens: number;
96
+ completionTokens: number;
97
+ totalTokens: number;
98
+ };
99
+ }
100
+ ```
101
+
102
+ **Example:**
103
+ ```typescript
104
+ const { stream } = await streamAgentResponse({
105
+ groupId: userGroupId,
106
+ threadId: conversationId,
107
+ message: "Write a blog post about AI"
108
+ });
109
+
110
+ for await (const chunk of stream) {
111
+ console.log(chunk); // Real-time chunks
112
+ }
113
+ ```
114
+
115
+ ---
116
+
117
+ ### analyzeMessage
118
+
119
+ Analyze message with structured output.
120
+
121
+ **Location:** `backend/convex/mutations/ai/analyze.ts`
122
+
123
+ **Parameters:**
124
+ ```typescript
125
+ {
126
+ groupId: Id<"groups">; // REQUIRED
127
+ message: string; // REQUIRED: Message to analyze
128
+ }
129
+ ```
130
+
131
+ **Returns:**
132
+ ```typescript
133
+ {
134
+ analysis: {
135
+ sentiment: "positive" | "neutral" | "negative";
136
+ topics: string[];
137
+ urgency: number; // 0-10
138
+ action_items: string[];
139
+ summary: string;
140
+ };
141
+ usage: {
142
+ promptTokens: number;
143
+ completionTokens: number;
144
+ totalTokens: number;
145
+ };
146
+ }
147
+ ```
148
+
149
+ **Example:**
150
+ ```typescript
151
+ const { analysis } = await analyzeMessage({
152
+ groupId: userGroupId,
153
+ message: "Our sales increased 50% this quarter! We need to hire more engineers ASAP."
154
+ });
155
+
156
+ console.log(analysis);
157
+ // {
158
+ // sentiment: "positive",
159
+ // topics: ["sales", "hiring", "growth"],
160
+ // urgency: 8,
161
+ // action_items: ["Hire engineers", "Scale team"],
162
+ // summary: "Strong sales growth requiring immediate hiring"
163
+ // }
164
+ ```
165
+
166
+ ---
167
+
168
+ ### generateWithTools
169
+
170
+ Generate response with function calling.
171
+
172
+ **Location:** `backend/convex/mutations/ai/tools.ts`
173
+
174
+ **Parameters:**
175
+ ```typescript
176
+ {
177
+ groupId: Id<"groups">; // REQUIRED
178
+ prompt: string; // REQUIRED
179
+ tools: {
180
+ [key: string]: {
181
+ description: string;
182
+ parameters: ZodSchema;
183
+ execute: (args: any) => Promise<any>;
184
+ };
185
+ };
186
+ }
187
+ ```
188
+
189
+ **Returns:**
190
+ ```typescript
191
+ {
192
+ text: string;
193
+ toolCalls: Array<{
194
+ toolName: string;
195
+ arguments: any;
196
+ result: any;
197
+ }>;
198
+ usage: TokenUsage;
199
+ }
200
+ ```
201
+
202
+ **Example:**
203
+ ```typescript
204
+ import { z } from "zod";
205
+
206
+ const result = await generateWithTools({
207
+ groupId: userGroupId,
208
+ prompt: "What's the weather in San Francisco?",
209
+ tools: {
210
+ getWeather: {
211
+ description: "Get current weather",
212
+ parameters: z.object({
213
+ location: z.string()
214
+ }),
215
+ execute: async ({ location }) => {
216
+ return `Weather in ${location}: 72°F, Sunny`;
217
+ }
218
+ }
219
+ }
220
+ });
221
+
222
+ console.log(result.text);
223
+ // "The current weather in San Francisco is 72°F and sunny."
224
+ ```
225
+
226
+ ---
227
+
228
+ ## Queries
229
+
230
+ ### getCallsByGroup
231
+
232
+ Get AI calls for a group.
233
+
234
+ **Location:** `backend/convex/queries/ai/calls.ts`
235
+
236
+ **Parameters:**
237
+ ```typescript
238
+ {
239
+ groupId: Id<"groups">; // REQUIRED
240
+ }
241
+ ```
242
+
243
+ **Returns:**
244
+ ```typescript
245
+ Array<{
246
+ _id: Id<"aiCalls">;
247
+ groupId: Id<"groups">;
248
+ model: string;
249
+ provider: string;
250
+ prompt: string;
251
+ result: string;
252
+ tokensUsed: {
253
+ input: number;
254
+ output: number;
255
+ total: number;
256
+ };
257
+ duration: number;
258
+ timestamp: number;
259
+ }>
260
+ ```
261
+
262
+ **Example:**
263
+ ```typescript
264
+ const calls = await getCallsByGroup({ groupId: userGroupId });
265
+
266
+ console.log(calls.length); // 42
267
+ console.log(calls[0].provider); // "anthropic"
268
+ console.log(calls[0].tokensUsed.total); // 1523
269
+ ```
270
+
271
+ ---
272
+
273
+ ### getTokenUsageStats
274
+
275
+ Get token usage statistics by provider.
276
+
277
+ **Location:** `backend/convex/queries/ai/calls.ts`
278
+
279
+ **Parameters:**
280
+ ```typescript
281
+ {
282
+ groupId: Id<"groups">; // REQUIRED
283
+ }
284
+ ```
285
+
286
+ **Returns:**
287
+ ```typescript
288
+ {
289
+ [provider: string]: {
290
+ calls: number;
291
+ tokens: number;
292
+ errors: number;
293
+ };
294
+ }
295
+ ```
296
+
297
+ **Example:**
298
+ ```typescript
299
+ const stats = await getTokenUsageStats({ groupId: userGroupId });
300
+
301
+ console.log(stats);
302
+ // {
303
+ // openai: { calls: 150, tokens: 250000, errors: 2 },
304
+ // anthropic: { calls: 300, tokens: 500000, errors: 0 },
305
+ // google: { calls: 50, tokens: 75000, errors: 1 }
306
+ // }
307
+ ```
308
+
309
+ ---
310
+
311
+ ## Effect.ts Services
312
+
313
+ ### LLMService
314
+
315
+ **Location:** `backend/convex/services/llm-service.ts`
316
+
317
+ #### generateText
318
+
319
+ ```typescript
320
+ generateText: (
321
+ prompt: string,
322
+ options?: {
323
+ model?: string;
324
+ provider?: string;
325
+ systemPrompt?: string;
326
+ temperature?: number;
327
+ maxTokens?: number;
328
+ }
329
+ ) => Effect.Effect<{ text: string; usage: any }, LLMError>
330
+ ```
331
+
332
+ #### streamText
333
+
334
+ ```typescript
335
+ streamText: (
336
+ prompt: string,
337
+ options?: {
338
+ model?: string;
339
+ provider?: string;
340
+ systemPrompt?: string;
341
+ }
342
+ ) => Effect.Effect<{ stream: any; usage: any }, LLMError>
343
+ ```
344
+
345
+ #### generateObject
346
+
347
+ ```typescript
348
+ generateObject: <T>(
349
+ prompt: string,
350
+ schema: ZodSchema,
351
+ options?: {
352
+ model?: string;
353
+ provider?: string;
354
+ }
355
+ ) => Effect.Effect<{ object: T; usage: any }, LLMError>
356
+ ```
357
+
358
+ **Example:**
359
+ ```typescript
360
+ import { Effect } from "effect";
361
+ import { LLMService, LLMServiceLive } from "./llm-service";
362
+
363
+ const program = Effect.gen(function* () {
364
+ const llm = yield* LLMService;
365
+
366
+ const result = yield* llm.generateText("What is 2+2?", {
367
+ provider: "openai",
368
+ temperature: 0.1
369
+ });
370
+
371
+ return result.text;
372
+ });
373
+
374
+ const answer = await Effect.runPromise(
375
+ program.pipe(Effect.provide(LLMServiceLive))
376
+ );
377
+
378
+ console.log(answer); // "2+2 equals 4."
379
+ ```
380
+
381
+ ---
382
+
383
+ ### AgentUIService
384
+
385
+ **Location:** `backend/convex/services/agent-ui.ts`
386
+
387
+ #### sendText
388
+
389
+ ```typescript
390
+ sendText: (args: {
391
+ agentId: Id<'things'>;
392
+ conversationId: Id<'things'>;
393
+ text: string;
394
+ sentiment?: 'positive' | 'neutral' | 'negative';
395
+ }) => Effect.Effect<Id<'things'>, never>
396
+ ```
397
+
398
+ #### sendUI
399
+
400
+ ```typescript
401
+ sendUI: (args: {
402
+ agentId: Id<'things'>;
403
+ conversationId: Id<'things'>;
404
+ component: ComponentData;
405
+ }) => Effect.Effect<Id<'things'>, never>
406
+ ```
407
+
408
+ #### sendActions
409
+
410
+ ```typescript
411
+ sendActions: (args: {
412
+ agentId: Id<'things'>;
413
+ conversationId: Id<'things'>;
414
+ actions: Array<{
415
+ id: string;
416
+ label: string;
417
+ description?: string;
418
+ params?: any;
419
+ }>;
420
+ }) => Effect.Effect<Id<'things'>, never>
421
+ ```
422
+
423
+ **Example:**
424
+ ```typescript
425
+ import { AgentUIService, AgentUIServiceLive } from "./agent-ui";
426
+
427
+ const program = Effect.gen(function* () {
428
+ const agentUI = yield* AgentUIService;
429
+
430
+ // Send chart
431
+ yield* agentUI.sendUI({
432
+ agentId: AGENT_ID,
433
+ conversationId: conversationId,
434
+ component: {
435
+ component: 'chart',
436
+ data: {
437
+ title: 'Revenue Trend',
438
+ chartType: 'line',
439
+ labels: ['Jan', 'Feb', 'Mar'],
440
+ datasets: [{ label: 'Revenue', data: [10, 20, 30] }]
441
+ }
442
+ }
443
+ });
444
+
445
+ // Send actions
446
+ yield* agentUI.sendActions({
447
+ agentId: AGENT_ID,
448
+ conversationId: conversationId,
449
+ actions: [
450
+ { id: 'export', label: 'Export Report', params: { format: 'pdf' } }
451
+ ]
452
+ });
453
+ });
454
+
455
+ await Effect.runPromise(
456
+ program.pipe(Effect.provide(AgentUIServiceLive))
457
+ );
458
+ ```
459
+
460
+ ---
461
+
462
+ ## React Hooks
463
+
464
+ ### useAIChat
465
+
466
+ **Location:** `web/src/hooks/ai/useAIChat.ts`
467
+
468
+ ```typescript
469
+ function useAIChat(
470
+ groupId: Id<"groups">,
471
+ agentId: Id<"things">
472
+ ): {
473
+ messages: Message[];
474
+ input: string;
475
+ setInput: (value: string) => void;
476
+ isLoading: boolean;
477
+ sendMessage: (content: string) => Promise<void>;
478
+ }
479
+ ```
480
+
481
+ **Example:**
482
+ ```tsx
483
+ import { useAIChat } from '@/hooks/ai/useAIChat';
484
+
485
+ function ChatComponent() {
486
+ const { messages, input, setInput, isLoading, sendMessage } =
487
+ useAIChat(groupId, agentId);
488
+
489
+ return (
490
+ <div>
491
+ {messages.map((msg, i) => (
492
+ <div key={i}>{msg.content}</div>
493
+ ))}
494
+ <input
495
+ value={input}
496
+ onChange={e => setInput(e.target.value)}
497
+ />
498
+ <button onClick={() => sendMessage(input)}>
499
+ {isLoading ? 'Sending...' : 'Send'}
500
+ </button>
501
+ </div>
502
+ );
503
+ }
504
+ ```
505
+
506
+ ---
507
+
508
+ ### useTokenUsage
509
+
510
+ **Location:** `web/src/hooks/ai/useTokenUsage.ts`
511
+
512
+ ```typescript
513
+ function useTokenUsage(
514
+ groupId: Id<"groups">
515
+ ): {
516
+ stats: Record<string, { calls: number; tokens: number; errors: number }>;
517
+ totalTokens: number;
518
+ estimatedCost: number;
519
+ providers: string[];
520
+ } | null
521
+ ```
522
+
523
+ **Example:**
524
+ ```tsx
525
+ import { useTokenUsage } from '@/hooks/ai/useTokenUsage';
526
+
527
+ function UsageDisplay() {
528
+ const usage = useTokenUsage(groupId);
529
+
530
+ if (!usage) return <div>Loading...</div>;
531
+
532
+ return (
533
+ <div>
534
+ <h2>Total Tokens: {usage.totalTokens.toLocaleString()}</h2>
535
+ <p>Estimated Cost: ${usage.estimatedCost.toFixed(2)}</p>
536
+ {usage.providers.map(provider => (
537
+ <div key={provider}>
538
+ {provider}: {usage.stats[provider].calls} calls
539
+ </div>
540
+ ))}
541
+ </div>
542
+ );
543
+ }
544
+ ```
545
+
546
+ ---
547
+
548
+ ## React Components
549
+
550
+ ### Chatbot
551
+
552
+ **Location:** `web/src/components/ai/Chatbot.tsx`
553
+
554
+ ```typescript
555
+ interface ChatbotProps {
556
+ groupId: Id<"groups">;
557
+ agentId: Id<"things">;
558
+ systemPrompt?: string;
559
+ }
560
+
561
+ function Chatbot(props: ChatbotProps): JSX.Element
562
+ ```
563
+
564
+ **Example:**
565
+ ```tsx
566
+ import { Chatbot } from '@/components/ai/Chatbot';
567
+
568
+ <Chatbot
569
+ groupId={userGroupId}
570
+ agentId={agentId}
571
+ systemPrompt="You are a helpful assistant"
572
+ client:load
573
+ />
574
+ ```
575
+
576
+ ---
577
+
578
+ ### GenerativeUIRenderer
579
+
580
+ **Location:** `web/src/components/ai/GenerativeUIRenderer.tsx`
581
+
582
+ ```typescript
583
+ interface GenerativeUIRendererProps {
584
+ payload: {
585
+ component: 'chart' | 'table' | 'card' | 'form';
586
+ data: ComponentData;
587
+ layout?: {
588
+ width?: 'full' | 'half' | 'third';
589
+ height?: string;
590
+ };
591
+ };
592
+ }
593
+
594
+ function GenerativeUIRenderer(props: GenerativeUIRendererProps): JSX.Element
595
+ ```
596
+
597
+ **Example:**
598
+ ```tsx
599
+ import { GenerativeUIRenderer } from '@/components/ai/GenerativeUIRenderer';
600
+
601
+ <GenerativeUIRenderer
602
+ payload={{
603
+ component: 'chart',
604
+ data: {
605
+ title: 'Revenue',
606
+ chartType: 'line',
607
+ labels: ['Jan', 'Feb'],
608
+ datasets: [{ label: 'Revenue', data: [10, 20] }]
609
+ },
610
+ layout: { width: 'full' }
611
+ }}
612
+ />
613
+ ```
614
+
615
+ ---
616
+
617
+ ## Error Types
618
+
619
+ ### LLMError
620
+
621
+ ```typescript
622
+ class LLMError extends Data.TaggedError("LLMError")<{
623
+ model: string;
624
+ provider: string;
625
+ cause: unknown;
626
+ }> {}
627
+ ```
628
+
629
+ ### RateLimitError
630
+
631
+ ```typescript
632
+ class RateLimitError extends Data.TaggedError("RateLimitError")<{
633
+ retryAfter: number;
634
+ }> {}
635
+ ```
636
+
637
+ ### QuotaExceededError
638
+
639
+ ```typescript
640
+ class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{
641
+ quotaLimit: number;
642
+ currentUsage: number;
643
+ }> {}
644
+ ```
645
+
646
+ ---
647
+
648
+ ## Type Definitions
649
+
650
+ ### Message
651
+
652
+ ```typescript
653
+ interface Message {
654
+ id: string;
655
+ role: "user" | "assistant";
656
+ content: string;
657
+ timestamp: number;
658
+ metadata?: any;
659
+ }
660
+ ```
661
+
662
+ ### ComponentData
663
+
664
+ ```typescript
665
+ type ComponentData =
666
+ | ChartComponentData
667
+ | TableComponentData
668
+ | CardComponentData
669
+ | FormComponentData;
670
+ ```
671
+
672
+ ### ChartComponentData
673
+
674
+ ```typescript
675
+ interface ChartComponentData {
676
+ component: 'chart';
677
+ data: {
678
+ title: string;
679
+ description?: string;
680
+ chartType: 'line' | 'bar' | 'pie' | 'area';
681
+ labels: string[];
682
+ datasets: Array<{
683
+ label: string;
684
+ data: number[];
685
+ color?: string;
686
+ fill?: boolean;
687
+ }>;
688
+ };
689
+ }
690
+ ```
691
+
692
+ ---
693
+
694
+ ## Rate Limits
695
+
696
+ | Provider | Calls/Minute | Tokens/Minute |
697
+ |----------|--------------|---------------|
698
+ | OpenAI | 500 | 150,000 |
699
+ | Anthropic | 1,000 | 200,000 |
700
+ | Google | 300 | 100,000 |
701
+
702
+ **Quota Enforcement:**
703
+ - Per group: 1M tokens/month default
704
+ - Configurable per group
705
+ - Auto-scaling available
706
+
707
+ ---
708
+
709
+ ## Related Documentation
710
+
711
+ - [Implementation Guide](./ai-sdk-implementation.md)
712
+ - [AG-UI Protocol](./ag-ui-protocol.md)
713
+ - [Generative UI Patterns](./generative-ui-patterns.md)
714
+ - [Quick Start Guide](./ai-quickstart.md)
715
+