oneie 3.6.7 → 3.6.11
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.
- package/.claude/agents/agent-backend.md +83 -0
- package/.claude/agents/agent-designer.md +97 -0
- package/.claude/agents/agent-director.md +118 -7
- package/.claude/agents/agent-documenter.md +93 -0
- package/.claude/agents/agent-frontend.md +96 -0
- package/.claude/agents/agent-ops.md +182 -25
- package/.claude/agents/agent-problem-solver.md +166 -0
- package/.claude/agents/agent-quality.md +127 -0
- package/.claude/commands/build.md +293 -0
- package/.claude/commands/cascade.md +231 -127
- package/.claude/commands/mcp-toggle.md +93 -0
- package/.claude/commands/one.md +198 -116
- package/.claude/commands/plan.md +394 -80
- package/.claude/commands/release.md +41 -19
- package/.claude/commands/server.md +2 -0
- package/.claude/hooks/root-cleanup.py +75 -0
- package/.claude/skills/INDEX.md +523 -0
- package/.claude/skills/REGISTRY.md +529 -0
- package/.claude/skills/agent-backend-create-mutation.md +319 -0
- package/.claude/skills/agent-designer-create-wireframe.md +341 -0
- package/.claude/skills/agent-frontend-create-page.md +413 -0
- package/.claude/skills/agents/README.md +238 -0
- package/dist/clone-web.js +1 -1
- package/dist/clone-web.js.map +1 -1
- package/folders.yaml +1 -1
- package/one/.obsidian/workspace.json +38 -38
- package/one/connections/api/queries-reference.md +842 -0
- package/one/connections/api-reference.md +1011 -0
- package/one/connections/integration-examples.md +875 -0
- package/one/connections/integration-guide.md +869 -0
- package/one/connections/integration-phase2.md +736 -0
- package/one/events/API_ROUTES_FIXES_SUMMARY.md +262 -0
- package/one/events/ASTRO-INTEGRATION-EXAMPLES.md +636 -0
- package/one/events/BEFORE_AFTER_COMPARISON.md +960 -0
- package/one/events/CONNECTIONS_DEMO.md +501 -0
- package/one/events/DELIVERABLES.md +432 -0
- package/one/events/DEMO-GROUPS-PAGE.md +392 -0
- package/one/events/DEMO-TESTING-SUMMARY.md +518 -0
- package/one/events/DEMO_COMPONENTS.md +487 -0
- package/one/events/DEMO_HOOKS_INDEX.md +334 -0
- package/one/events/DEMO_INFRASTRUCTURE.md +905 -0
- package/one/events/DEMO_INFRASTRUCTURE_SUMMARY.md +570 -0
- package/one/events/DEMO_INTEGRATION_CHECKLIST.md +431 -0
- package/one/events/DEMO_QUICK_REFERENCE.md +441 -0
- package/one/events/DEMO_SETUP.md +476 -0
- package/one/events/EFFECT_TS_API_PATTERN.md +478 -0
- package/one/events/GROUPS_DEMO_IMPLEMENTATION.md +414 -0
- package/one/events/HOOKS-DEMO.md +441 -0
- package/one/events/ONTOLOGY-HOOKS-README.md +700 -0
- package/one/events/ONTOLOGY-INTEGRATION-MANIFEST.md +365 -0
- package/one/events/QA-CHECKLIST.md +674 -0
- package/one/events/QUICK-START-ONTOLOGY.md +408 -0
- package/one/events/SEARCH_DEMO_CODE_REFERENCE.md +639 -0
- package/one/events/SEARCH_DEMO_DELIVERY.md +415 -0
- package/one/events/SEARCH_DEMO_SUMMARY.md +303 -0
- package/one/events/SEARCH_DEMO_VISUAL_GUIDE.md +381 -0
- package/one/events/TEST-PLAN-INDEX.md +346 -0
- package/one/events/TEST-PLAN.md +1417 -0
- package/one/events/TESTING-DELIVERY.txt +372 -0
- package/one/events/TRANSITIONS-QUICK-START.md +141 -0
- package/one/events/TYPESCRIPT_FIXES.md +152 -0
- package/one/events/TYPESCRIPT_FIXES_COMPLETE.txt +412 -0
- package/one/events/TYPESCRIPT_FIXES_INDEX.md +341 -0
- package/one/events/VIEW-TRANSITIONS.md +428 -0
- package/one/events/backend-integration-tests.md +606 -0
- package/one/events/backend-structure-diagram.txt +393 -0
- package/one/events/backend-structure-summary.txt +269 -0
- package/one/events/cloudflare-pages-infrastructure-setup.md +264 -0
- package/one/events/convex-analysis-index.md +304 -0
- package/one/events/convex-structure-analysis.md +700 -0
- package/one/events/design-spec-complete.md +208 -0
- package/one/events/ontology-test-examples.md +562 -0
- package/one/events/phase1-backend-implementation-complete.md +518 -0
- package/one/events/test-dashboard.md +345 -0
- package/one/events/test-index.md +361 -0
- package/one/events/test-report-ontology.md +582 -0
- package/one/events/testing-summary.md +344 -0
- package/one/groups/features.md +2878 -0
- package/one/groups/strategy copy.md +869 -0
- package/one/knowledge/backend-api-reference.md +710 -0
- package/one/knowledge/documentation-summary.md +285 -0
- package/one/knowledge/lessons-learned.md +294 -4
- package/one/knowledge/ontology-visual-guide.md +360 -0
- package/one/knowledge/ontology.md +9 -17
- package/one/things/demo-accessibility-animations.md +999 -0
- package/one/things/demo-components.md +1304 -0
- package/one/things/demo-design-summary.md +629 -0
- package/one/things/demo-design-system.md +919 -0
- package/one/things/demo-page-layouts.md +989 -0
- package/one/things/designs/accessibility-audit.md +790 -0
- package/one/things/designs/component-specifications.md +757 -0
- package/one/things/designs/design-overview.md +318 -0
- package/one/things/designs/design-tokens.md +414 -0
- package/one/things/designs/wireframes-dashboard.md +653 -0
- package/one/things/docs/api-requests.md +923 -0
- package/one/things/features/0 All Features.md +2 -0
- package/one/things/implementation/backend-guide.md +412 -0
- package/one/things/plans/2-backend-agnostic-frontend.md +11 -8
- package/one/things/plans/ai-elements.md +1259 -0
- package/one/things/plans/ai-integration.md +947 -0
- package/one/things/plans/ai-sdk.md +761 -0
- package/one/things/plans/app.md +1 -1
- package/one/things/plans/architecture-summary.md +283 -0
- package/one/things/plans/async-ai-agents.md +215 -0
- package/one/things/plans/backend-agnostic-frontend.md +11 -6
- package/one/things/plans/backend-cleanup-quickstart.md +346 -0
- package/one/things/plans/backend-ontology-conformance.md +416 -0
- package/one/things/plans/backend-status.md +541 -0
- package/one/things/plans/backend-structure.md +799 -0
- package/one/things/plans/backend-target-structure.md +438 -0
- package/one/things/plans/backend.md +1133 -0
- package/one/things/plans/better-auth-any-backend.md +11 -11
- package/one/things/plans/cli-updates-required.md +280 -0
- package/one/things/plans/complete-step-by-step.md +1302 -0
- package/one/things/plans/convex-agents.md +1005 -0
- package/one/things/plans/deployment-architecture.md +426 -0
- package/one/things/plans/development-plan.md +1220 -0
- package/one/things/plans/effect.md +808 -48
- package/one/things/plans/integrate-frontend-and-backend.md +579 -0
- package/one/things/plans/mcp-clear-context-prompt.md +60 -0
- package/one/things/plans/mcp-simple.md +228 -0
- package/one/things/plans/one.md +8 -7
- package/one/things/plans/ontology-6-dimensions.md +20 -14
- package/one/things/plans/quick-wins.md +1273 -0
- package/one/things/plans/readme-backend-cleanup.md +361 -0
- package/one/things/plans/separate-demo.md +830 -0
- package/one/things/plans/separate.md +3 -3
- package/one/things/plans/sequence.md +1897 -0
- package/one/things/plans/sync-checklist.md +321 -0
- package/one/things/plans/unified-implementation-plan.md +3 -3
- package/one/things/plans/update-demos.md +513 -0
- package/package.json +1 -1
- package/.claude/agents/backend-specialist.md +0 -169
- package/.claude/agents/designer.md +0 -216
- package/.claude/agents/frontend-specialist.md +0 -236
- package/.claude/commands/done.md +0 -35
- package/.claude/commands/infer.md +0 -138
- package/.claude/commands/next.md +0 -53
- package/.claude/commands/one copy.md +0 -565
- package/.claude/commands/one-template.md +0 -106
- package/.claude/commands/one-v1.md +0 -609
- package/.claude/hooks/__pycache__/knowledge-post.cpython-313.pyc +0 -0
- package/.claude/hooks/__pycache__/knowledge-pre.cpython-313.pyc +0 -0
- package/.claude/hooks/__pycache__/todo.cpython-313.pyc +0 -0
- package/one/groups/nine-padel-customers.md +0 -138
- package/one/groups/nine-padel-data-structure.md +0 -167
- package/one/groups/nine-padel-ontology-specification.md +0 -359
- package/one/groups/nine-padel-ontology.md +0 -143
- package/one/groups/nine-padel-strategy.md +0 -234
- package/one/groups/nine-padel.md +0 -211
- package/one/groups/nine-padle-contents.baked.md +0 -1252
- package/one/groups/nine-padle-contents.md +0 -6
- package/one/things/features/1-1-agent-prompts/design.md +0 -470
- package/one/things/features/1-1-agent-prompts/tests.md +0 -264
- package/one/things/features/1-2-yaml-orchestrator/design.md +0 -497
- package/one/things/features/1-2-yaml-orchestrator/tests.md +0 -227
- package/one/things/features/1-3-event-coordination/design.md +0 -544
- package/one/things/features/1-3-event-coordination/tests.md +0 -223
- package/one/things/features/1-4-knowledge-management/design.md +0 -609
- package/one/things/features/1-4-knowledge-management/tests.md +0 -195
- package/one/things/features/1-5-quality-loops/design.md +0 -797
- package/one/things/features/1-5-quality-loops/tests.md +0 -212
- package/one/things/features/1-6-numbering-structure/design.md +0 -610
- package/one/things/features/1-6-numbering-structure/tests.md +0 -213
- package/one/things/features/dataprovider-interface/1-tests.md +0 -1522
|
@@ -0,0 +1,947 @@
|
|
|
1
|
+
# AI Integration Architecture
|
|
2
|
+
|
|
3
|
+
**Complete integration of AI SDK + Convex Agents + AI Elements with Effect.ts**
|
|
4
|
+
|
|
5
|
+
**Version:** 1.0.0 (Effect.ts Refined)
|
|
6
|
+
**Status:** Planning
|
|
7
|
+
**Created:** 2025-10-24
|
|
8
|
+
**Patterns:** effect.md + effect-components.md
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Core Pattern: Effect.ts Service Layer
|
|
13
|
+
|
|
14
|
+
All AI functionality is implemented as **Effect.ts services** using `Context.Tag` and `Layer` for dependency injection. Convex components provide infrastructure; Effect provides business logic composition:
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
// Layer 1: Error types (tagged classes)
|
|
18
|
+
class LLMError extends Data.TaggedError("LLMError")<{
|
|
19
|
+
model: string
|
|
20
|
+
provider: string
|
|
21
|
+
cause: unknown
|
|
22
|
+
}> {}
|
|
23
|
+
|
|
24
|
+
class AgentError extends Data.TaggedError("AgentError")<{
|
|
25
|
+
agentName: string
|
|
26
|
+
cause: unknown
|
|
27
|
+
}> {}
|
|
28
|
+
|
|
29
|
+
class RAGError extends Data.TaggedError("RAGError")<{
|
|
30
|
+
query: string
|
|
31
|
+
cause: unknown
|
|
32
|
+
}> {}
|
|
33
|
+
|
|
34
|
+
// Layer 2: Service definitions
|
|
35
|
+
class LLMService extends Context.Tag("LLMService")<LLMService, { /* ... */ }>() {}
|
|
36
|
+
class AgentService extends Context.Tag("AgentService")<AgentService, { /* ... */ }>() {}
|
|
37
|
+
class RAGService extends Context.Tag("RAGService")<RAGService, { /* ... */ }>() {}
|
|
38
|
+
|
|
39
|
+
// Layer 3: Service implementations
|
|
40
|
+
const LLMServiceLive = Layer.effect(LLMService, /* ... */);
|
|
41
|
+
const AgentServiceLive = Layer.effect(AgentService, /* ... */);
|
|
42
|
+
const RAGServiceLive = Layer.effect(RAGService, /* ... */);
|
|
43
|
+
|
|
44
|
+
// Layer 4: Composition
|
|
45
|
+
const AppLayer = Layer.mergeAll(
|
|
46
|
+
LLMServiceLive,
|
|
47
|
+
AgentServiceLive,
|
|
48
|
+
RAGServiceLive
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
// Usage in mutations/actions
|
|
52
|
+
export const myAction = action({
|
|
53
|
+
handler: (ctx, args) =>
|
|
54
|
+
Effect.gen(function* () {
|
|
55
|
+
const llm = yield* LLMService;
|
|
56
|
+
const agent = yield* AgentService;
|
|
57
|
+
const rag = yield* RAGService;
|
|
58
|
+
|
|
59
|
+
// Compose services with explicit error handling
|
|
60
|
+
const context = yield* rag.search(args.query);
|
|
61
|
+
const response = yield* agent.generateResponse(ctx, args.message, context);
|
|
62
|
+
|
|
63
|
+
return response;
|
|
64
|
+
}).pipe(
|
|
65
|
+
Effect.provide(AppLayer),
|
|
66
|
+
Effect.catchAll((error) => {
|
|
67
|
+
// Handle errors explicitly
|
|
68
|
+
return Effect.succeed({ error: true });
|
|
69
|
+
})
|
|
70
|
+
)
|
|
71
|
+
});
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Executive Summary
|
|
77
|
+
|
|
78
|
+
This document describes how three powerful technologies integrate into a seamless AI experience:
|
|
79
|
+
|
|
80
|
+
1. **AI SDK** (Vercel) - Unified LLM interface across 20+ providers
|
|
81
|
+
2. **Convex Agents** (Convex) - Backend agent orchestration with persistence
|
|
82
|
+
3. **AI Elements** (Vercel) - Pre-built production-ready UI components
|
|
83
|
+
|
|
84
|
+
**The Result:** A beautiful, type-safe, multi-tenant AI chat platform with:
|
|
85
|
+
- Real-time streaming conversations
|
|
86
|
+
- Tool execution with rich UI feedback
|
|
87
|
+
- RAG-powered knowledge retrieval
|
|
88
|
+
- Complete conversation history
|
|
89
|
+
- Token tracking and billing
|
|
90
|
+
- Enterprise-grade multi-tenancy
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Architecture Diagram
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
┌─────────────────────────────────────────────────────────────────┐
|
|
98
|
+
│ FRONTEND (Astro + React) │
|
|
99
|
+
│ │
|
|
100
|
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
101
|
+
│ │ AI Elements Components (30+ UI elements) │ │
|
|
102
|
+
│ │ - Chatbot, Message, Response, Code Block, Artifact, etc │ │
|
|
103
|
+
│ └──────────────────────────────────────────────────────────┘ │
|
|
104
|
+
│ ↓ │
|
|
105
|
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
106
|
+
│ │ React Hooks (useChat, useCompletion) │ │
|
|
107
|
+
│ │ ↓ │ │
|
|
108
|
+
│ │ useCompleteChatFlow() [Custom Hook] │ │
|
|
109
|
+
│ │ ├─ Thread Management │ │
|
|
110
|
+
│ │ ├─ Message State │ │
|
|
111
|
+
│ │ └─ Streaming State │ │
|
|
112
|
+
│ └──────────────────────────────────────────────────────────┘ │
|
|
113
|
+
└──────────────────────────────────────────────────────────────────┘
|
|
114
|
+
↓ (Convex Mutations)
|
|
115
|
+
┌──────────────────────────────────────────────────────────────────┐
|
|
116
|
+
│ CONVEX BACKEND (Node.js) │
|
|
117
|
+
│ │
|
|
118
|
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
119
|
+
│ │ Convex Mutations │ │
|
|
120
|
+
│ │ ├─ createThread() - Create conversation thread │ │
|
|
121
|
+
│ │ ├─ sendMessage() - Add message to thread │ │
|
|
122
|
+
│ │ ├─ streamResponse() - Stream AI response │ │
|
|
123
|
+
│ │ └─ executeTool() - Execute agent tools │ │
|
|
124
|
+
│ └──────────────────────────────────────────────────────────┘ │
|
|
125
|
+
│ ↓ │
|
|
126
|
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
127
|
+
│ │ Convex Agents Runtime │ │
|
|
128
|
+
│ │ ├─ Thread Management (aiThreads table) │ │
|
|
129
|
+
│ │ ├─ Message Persistence (Convex Agents internal) │ │
|
|
130
|
+
│ │ ├─ Tool Orchestration (executeTools) │ │
|
|
131
|
+
│ │ └─ Streaming Pipeline (WebSocket to client) │ │
|
|
132
|
+
│ └──────────────────────────────────────────────────────────┘ │
|
|
133
|
+
│ ↓ │
|
|
134
|
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
135
|
+
│ │ AI SDK Core Functions │ │
|
|
136
|
+
│ │ ├─ generateText() - Single response │ │
|
|
137
|
+
│ │ ├─ streamText() - Streaming response │ │
|
|
138
|
+
│ │ ├─ generateObject() - Structured output │ │
|
|
139
|
+
│ │ └─ Tool Calls - Function execution │ │
|
|
140
|
+
│ └──────────────────────────────────────────────────────────┘ │
|
|
141
|
+
│ ↓ │
|
|
142
|
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
|
143
|
+
│ │ Convex Database (5-Table Ontology) │ │
|
|
144
|
+
│ │ ├─ groups - Tenants │ │
|
|
145
|
+
│ │ ├─ things - Agents, users, tasks │ │
|
|
146
|
+
│ │ ├─ connections - Relationships │ │
|
|
147
|
+
│ │ ├─ events - Audit trail, usage │ │
|
|
148
|
+
│ │ ├─ knowledge - Embeddings for RAG │ │
|
|
149
|
+
│ │ └─ aiCalls - Token tracking, billing │ │
|
|
150
|
+
│ └──────────────────────────────────────────────────────────┘ │
|
|
151
|
+
└──────────────────────────────────────────────────────────────────┘
|
|
152
|
+
↓ (API Calls)
|
|
153
|
+
┌──────────────────────────────────────────────────────────────────┐
|
|
154
|
+
│ LLM PROVIDERS (External APIs) │
|
|
155
|
+
│ ├─ OpenAI (GPT-4, GPT-4o, GPT-4-turbo) │
|
|
156
|
+
│ ├─ Anthropic (Claude 3 Opus, Sonnet, Haiku) │
|
|
157
|
+
│ ├─ Google (Gemini Pro, Flash) │
|
|
158
|
+
│ ├─ DeepSeek, Mistral, Groq, etc. │
|
|
159
|
+
│ └─ Custom models via API │
|
|
160
|
+
└──────────────────────────────────────────────────────────────────┘
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
**Key Innovation: Effect.ts Service Layer**
|
|
164
|
+
- All business logic composed as Effect services
|
|
165
|
+
- Components handle infrastructure (Agent, RAG, Rate-Limiter)
|
|
166
|
+
- Service layer provides tagged errors, dependency injection, and testability
|
|
167
|
+
- Mutations are thin wrappers that call services with `Effect.provide(AppLayer)`
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## Data Flow: Complete Chat Interaction
|
|
172
|
+
|
|
173
|
+
### Step 1: User Types and Sends Message
|
|
174
|
+
|
|
175
|
+
```
|
|
176
|
+
USER
|
|
177
|
+
↓
|
|
178
|
+
Chatbot Component (AI Elements)
|
|
179
|
+
├─ Captures text in PromptInput
|
|
180
|
+
└─ Calls handleSubmit()
|
|
181
|
+
↓
|
|
182
|
+
useCompleteChatFlow Hook
|
|
183
|
+
├─ Validates input
|
|
184
|
+
├─ Creates thread (if needed)
|
|
185
|
+
└─ Calls sendMessage mutation
|
|
186
|
+
↓
|
|
187
|
+
Convex Mutation (sendMessage)
|
|
188
|
+
├─ Verifies auth & group access
|
|
189
|
+
├─ Stores message in thread
|
|
190
|
+
└─ Calls AI SDK streamText()
|
|
191
|
+
↓
|
|
192
|
+
AI SDK (streamText)
|
|
193
|
+
├─ Gets LLM model from agent config
|
|
194
|
+
├─ Includes conversation history
|
|
195
|
+
├─ Adds system prompt
|
|
196
|
+
└─ Streams to Convex Agents runtime
|
|
197
|
+
↓
|
|
198
|
+
Convex Agents Runtime
|
|
199
|
+
├─ Manages LLM streaming
|
|
200
|
+
├─ Detects tool calls
|
|
201
|
+
├─ Executes tools (searchKnowledge, etc.)
|
|
202
|
+
└─ Re-includes results in context
|
|
203
|
+
↓
|
|
204
|
+
LLM Provider API
|
|
205
|
+
└─ Processes inference
|
|
206
|
+
↓
|
|
207
|
+
Stream Returns to Frontend
|
|
208
|
+
├─ Chunks received via WebSocket
|
|
209
|
+
└─ UI updates in real-time
|
|
210
|
+
↓
|
|
211
|
+
Message Component (AI Elements)
|
|
212
|
+
├─ Displays streaming text
|
|
213
|
+
├─ Renders code blocks if present
|
|
214
|
+
├─ Shows artifact previews
|
|
215
|
+
└─ Updates complete message
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Step 2: Agent Executes Tools
|
|
219
|
+
|
|
220
|
+
```
|
|
221
|
+
AI SDK detects tool call in response
|
|
222
|
+
↓
|
|
223
|
+
Tool Definition (e.g., searchKnowledge)
|
|
224
|
+
├─ Parameters: query, limit
|
|
225
|
+
└─ Handler function
|
|
226
|
+
↓
|
|
227
|
+
Convex Agents executes tool
|
|
228
|
+
├─ Calls handler with context
|
|
229
|
+
└─ Receives results
|
|
230
|
+
↓
|
|
231
|
+
Search Results
|
|
232
|
+
├─ Queries knowledge table via vector embeddings
|
|
233
|
+
├─ Returns relevant documents
|
|
234
|
+
└─ Includes relevance scores
|
|
235
|
+
↓
|
|
236
|
+
Tool Results included in context
|
|
237
|
+
├─ Agent sees results
|
|
238
|
+
├─ Formulates response with citations
|
|
239
|
+
└─ Includes in next message
|
|
240
|
+
↓
|
|
241
|
+
AI Elements Components
|
|
242
|
+
├─ Message with inline citations
|
|
243
|
+
├─ Sources component shows references
|
|
244
|
+
└─ Links back to knowledge items
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### Step 3: Complete Response and Logging
|
|
248
|
+
|
|
249
|
+
```
|
|
250
|
+
Stream completes
|
|
251
|
+
├─ Full message text captured
|
|
252
|
+
├─ Tool calls and results stored
|
|
253
|
+
└─ Usage metrics calculated
|
|
254
|
+
↓
|
|
255
|
+
Log to aiCalls table
|
|
256
|
+
├─ Model, provider, tokens
|
|
257
|
+
├─ Duration, cost
|
|
258
|
+
└─ Metadata (tools, reasoning, etc.)
|
|
259
|
+
↓
|
|
260
|
+
Log to events table
|
|
261
|
+
├─ Type: ai_response_completed
|
|
262
|
+
├─ Actor: user ID
|
|
263
|
+
├─ Metadata: tokens, model, tools used
|
|
264
|
+
└─ Timestamp
|
|
265
|
+
↓
|
|
266
|
+
Update thread in aiThreads
|
|
267
|
+
├─ Set updatedAt
|
|
268
|
+
├─ Increment message count
|
|
269
|
+
└─ Update status if needed
|
|
270
|
+
↓
|
|
271
|
+
UI Reflects Final State
|
|
272
|
+
├─ Message shows complete
|
|
273
|
+
├─ Streaming indicators hidden
|
|
274
|
+
├─ Action buttons available (copy, regenerate, etc.)
|
|
275
|
+
└─ Ready for next message
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## Data Model Integration
|
|
281
|
+
|
|
282
|
+
### How Ontology Dimensions Connect
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
// Groups: Multi-tenancy
|
|
286
|
+
{
|
|
287
|
+
_id: Id<"groups">,
|
|
288
|
+
name: "Acme Corp",
|
|
289
|
+
type: "organization",
|
|
290
|
+
properties: { plan: "pro" }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Things: Agents and Conversations
|
|
294
|
+
{
|
|
295
|
+
_id: Id<"things">,
|
|
296
|
+
type: "agent",
|
|
297
|
+
groupId: Id<"groups">,
|
|
298
|
+
name: "Customer Support Bot",
|
|
299
|
+
properties: {
|
|
300
|
+
model: "gpt-4-turbo",
|
|
301
|
+
provider: "openai",
|
|
302
|
+
systemPrompt: "You are helpful...",
|
|
303
|
+
tools: ["searchKB", "createTicket"]
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Connections: Relationships
|
|
308
|
+
{
|
|
309
|
+
_id: Id<"connections">,
|
|
310
|
+
type: "user_interacts_with_agent",
|
|
311
|
+
groupId: Id<"groups">,
|
|
312
|
+
from: "<user-id>",
|
|
313
|
+
to: "<agent-id>",
|
|
314
|
+
metadata: { lastInteraction: Date.now() }
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Events: Audit Trail
|
|
318
|
+
{
|
|
319
|
+
_id: Id<"events">,
|
|
320
|
+
type: "ai_response_completed",
|
|
321
|
+
groupId: Id<"groups">,
|
|
322
|
+
actorId: "<user-id>",
|
|
323
|
+
targetId: "<agent-id>",
|
|
324
|
+
metadata: {
|
|
325
|
+
model: "gpt-4-turbo",
|
|
326
|
+
tokensUsed: { input: 245, output: 1023 },
|
|
327
|
+
toolsCalled: ["searchKB"],
|
|
328
|
+
duration: 2340
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Knowledge: RAG
|
|
333
|
+
{
|
|
334
|
+
_id: Id<"knowledge">,
|
|
335
|
+
groupId: Id<"groups">,
|
|
336
|
+
title: "How to create a task",
|
|
337
|
+
content: "Use the /task command...",
|
|
338
|
+
embedding: [0.123, -0.456, ...], // 1536 dimensions
|
|
339
|
+
relevance: 0.87,
|
|
340
|
+
source: "<thing-id>"
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// AI-Specific Tables
|
|
344
|
+
{
|
|
345
|
+
// aiCalls: Token tracking for billing
|
|
346
|
+
_id: Id<"aiCalls">,
|
|
347
|
+
groupId: Id<"groups">,
|
|
348
|
+
model: "gpt-4-turbo",
|
|
349
|
+
provider: "openai",
|
|
350
|
+
tokensUsed: { input: 245, output: 1023 },
|
|
351
|
+
cost: 0.052,
|
|
352
|
+
timestamp: Date.now()
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
{
|
|
356
|
+
// aiThreads: Conversation threads
|
|
357
|
+
_id: Id<"aiThreads">,
|
|
358
|
+
groupId: Id<"groups">,
|
|
359
|
+
agentId: Id<"things">,
|
|
360
|
+
title: "Billing Question",
|
|
361
|
+
status: "active",
|
|
362
|
+
metadata: { createdBy: "<user-id>" },
|
|
363
|
+
createdAt: Date.now()
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
---
|
|
368
|
+
|
|
369
|
+
## Technology Stack Integration
|
|
370
|
+
|
|
371
|
+
### Layer 1: Frontend (Astro Pages)
|
|
372
|
+
|
|
373
|
+
```astro
|
|
374
|
+
---
|
|
375
|
+
// src/pages/chat/[threadId].astro
|
|
376
|
+
import CompleteChatUI from "@/components/features/AIChat/CompleteChatUI";
|
|
377
|
+
|
|
378
|
+
// Server-side: Fetch thread data
|
|
379
|
+
const thread = await getThread(Astro.params.threadId);
|
|
380
|
+
---
|
|
381
|
+
|
|
382
|
+
<Layout title={thread.title}>
|
|
383
|
+
<!-- Client-side: Interactive component -->
|
|
384
|
+
<CompleteChatUI
|
|
385
|
+
groupId={thread.groupId}
|
|
386
|
+
agentId={thread.agentId}
|
|
387
|
+
client:load
|
|
388
|
+
/>
|
|
389
|
+
</Layout>
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
### Layer 2: React Components (AI Elements)
|
|
393
|
+
|
|
394
|
+
```typescript
|
|
395
|
+
// src/components/features/AIChat/CompleteChatUI.tsx
|
|
396
|
+
import { Chatbot } from "@/components/ui/ai-elements/chatbot";
|
|
397
|
+
import { Message } from "@/components/ui/ai-elements/message";
|
|
398
|
+
import { CodeBlock } from "@/components/ui/ai-elements/code-block";
|
|
399
|
+
import { useCompleteChatFlow } from "@/lib/hooks/useCompleteChatFlow";
|
|
400
|
+
|
|
401
|
+
export function CompleteChatUI({ groupId, agentId }) {
|
|
402
|
+
const {
|
|
403
|
+
messages,
|
|
404
|
+
input,
|
|
405
|
+
handleInputChange,
|
|
406
|
+
isLoading,
|
|
407
|
+
handleSubmit,
|
|
408
|
+
} = useCompleteChatFlow(groupId, agentId);
|
|
409
|
+
|
|
410
|
+
return (
|
|
411
|
+
<Chatbot
|
|
412
|
+
messages={messages}
|
|
413
|
+
input={input}
|
|
414
|
+
onInputChange={handleInputChange}
|
|
415
|
+
onSubmit={handleSubmit}
|
|
416
|
+
isLoading={isLoading}
|
|
417
|
+
>
|
|
418
|
+
{messages.map(msg => (
|
|
419
|
+
<Message
|
|
420
|
+
key={msg.id}
|
|
421
|
+
role={msg.role}
|
|
422
|
+
content={msg.content}
|
|
423
|
+
metadata={msg.metadata}
|
|
424
|
+
/>
|
|
425
|
+
))}
|
|
426
|
+
</Chatbot>
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
### Layer 3: Custom Hooks (AI SDK Integration)
|
|
432
|
+
|
|
433
|
+
```typescript
|
|
434
|
+
// src/lib/hooks/useCompleteChatFlow.ts
|
|
435
|
+
import { useChat } from "ai/react";
|
|
436
|
+
import { useMutation } from "convex/react";
|
|
437
|
+
|
|
438
|
+
export function useCompleteChatFlow(groupId: string, agentId: string) {
|
|
439
|
+
const sendMessage = useMutation(api.mutations.agentChat.sendMessage);
|
|
440
|
+
const { messages, input, handleInputChange, isLoading } = useChat();
|
|
441
|
+
|
|
442
|
+
const handleSubmit = async (content: string) => {
|
|
443
|
+
await sendMessage({
|
|
444
|
+
groupId,
|
|
445
|
+
agentId,
|
|
446
|
+
threadId: currentThread,
|
|
447
|
+
message: content,
|
|
448
|
+
});
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
return { messages, input, handleInputChange, isLoading, handleSubmit };
|
|
452
|
+
}
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
### Layer 4: Convex Mutations (Backend Orchestration)
|
|
456
|
+
|
|
457
|
+
```typescript
|
|
458
|
+
// backend/convex/mutations/agentChat.ts
|
|
459
|
+
import { mutation } from "./_generated/server";
|
|
460
|
+
import { streamText } from "ai";
|
|
461
|
+
import { selectModel } from "../ai";
|
|
462
|
+
|
|
463
|
+
export const sendMessage = mutation({
|
|
464
|
+
args: {
|
|
465
|
+
groupId: v.id("groups"),
|
|
466
|
+
agentId: v.id("things"),
|
|
467
|
+
threadId: v.string(),
|
|
468
|
+
message: v.string(),
|
|
469
|
+
},
|
|
470
|
+
handler: async (ctx, args) => {
|
|
471
|
+
// 1. Get agent configuration from things table
|
|
472
|
+
const agent = await ctx.db.get(args.agentId);
|
|
473
|
+
|
|
474
|
+
// 2. Get conversation context from thread
|
|
475
|
+
const messages = await getMessages(ctx, { threadId: args.threadId });
|
|
476
|
+
|
|
477
|
+
// 3. Call AI SDK to generate response
|
|
478
|
+
const { textStream, usage } = await streamText({
|
|
479
|
+
model: selectModel(agent.properties.provider, "powerful"),
|
|
480
|
+
system: agent.properties.systemPrompt,
|
|
481
|
+
tools: loadAgentTools(agent),
|
|
482
|
+
messages: [...messages, { role: "user", content: args.message }],
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
// 4. Log usage metrics
|
|
486
|
+
await ctx.db.insert("aiCalls", {
|
|
487
|
+
groupId: args.groupId,
|
|
488
|
+
model: agent.properties.model,
|
|
489
|
+
tokensUsed: usage,
|
|
490
|
+
timestamp: Date.now(),
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
return { stream: textStream, threadId: args.threadId };
|
|
494
|
+
},
|
|
495
|
+
});
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
### Layer 5: AI SDK (LLM Interface)
|
|
499
|
+
|
|
500
|
+
```typescript
|
|
501
|
+
// Unified API across providers
|
|
502
|
+
const { textStream, usage } = await streamText({
|
|
503
|
+
// Works with ANY provider
|
|
504
|
+
model: selectModel("openai", "powerful"), // or anthropic, google, etc.
|
|
505
|
+
|
|
506
|
+
// System context
|
|
507
|
+
system: "You are a helpful assistant...",
|
|
508
|
+
|
|
509
|
+
// Conversation history
|
|
510
|
+
messages: [
|
|
511
|
+
{ role: "user", content: "Hello" },
|
|
512
|
+
{ role: "assistant", content: "Hi!" },
|
|
513
|
+
{ role: "user", content: "What's your name?" },
|
|
514
|
+
],
|
|
515
|
+
|
|
516
|
+
// Tool definitions
|
|
517
|
+
tools: {
|
|
518
|
+
searchKnowledge: {
|
|
519
|
+
description: "Search knowledge base",
|
|
520
|
+
parameters: z.object({ query: z.string() }),
|
|
521
|
+
execute: async ({ query }) => { /* RAG search */ }
|
|
522
|
+
}
|
|
523
|
+
},
|
|
524
|
+
});
|
|
525
|
+
```
|
|
526
|
+
|
|
527
|
+
### Layer 6: Convex Database (Data Persistence)
|
|
528
|
+
|
|
529
|
+
```typescript
|
|
530
|
+
// Automatic persistence by Convex Agents
|
|
531
|
+
tables: {
|
|
532
|
+
groups, // Tenants
|
|
533
|
+
things, // Agents, users, tasks
|
|
534
|
+
connections, // Relationships
|
|
535
|
+
events, // Audit trail
|
|
536
|
+
knowledge, // RAG vectors
|
|
537
|
+
aiCalls, // Token tracking
|
|
538
|
+
aiThreads, // Conversations
|
|
539
|
+
// + Convex Agents internal tables for messages
|
|
540
|
+
}
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
### Layer 7: LLM Providers (Inference)
|
|
544
|
+
|
|
545
|
+
```typescript
|
|
546
|
+
// Supported providers via AI SDK
|
|
547
|
+
providers: [
|
|
548
|
+
"openai", // GPT-4, GPT-4o
|
|
549
|
+
"anthropic", // Claude
|
|
550
|
+
"google", // Gemini
|
|
551
|
+
"azure", // OpenAI Azure
|
|
552
|
+
"cohere", // Cohere
|
|
553
|
+
"deepseek", // DeepSeek
|
|
554
|
+
"mistral", // Mistral
|
|
555
|
+
"groq", // Groq
|
|
556
|
+
"xai", // xAI
|
|
557
|
+
// ... and 10+ more
|
|
558
|
+
]
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
---
|
|
562
|
+
|
|
563
|
+
## Request/Response Flow (Complete Walkthrough)
|
|
564
|
+
|
|
565
|
+
### Sending a Message
|
|
566
|
+
|
|
567
|
+
```
|
|
568
|
+
1. USER
|
|
569
|
+
└─ Types "What is machine learning?" in ChatBot
|
|
570
|
+
|
|
571
|
+
2. FRONTEND (React + AI Elements)
|
|
572
|
+
└─ PromptInput captures input
|
|
573
|
+
└─ handleInputChange updates state
|
|
574
|
+
└─ onSubmit calls handleSubmit()
|
|
575
|
+
|
|
576
|
+
3. CUSTOM HOOK (useCompleteChatFlow)
|
|
577
|
+
└─ Validates message not empty
|
|
578
|
+
└─ Creates thread if first message
|
|
579
|
+
└─ Calls sendMessage mutation
|
|
580
|
+
|
|
581
|
+
4. CONVEX MUTATION (sendMessage)
|
|
582
|
+
└─ Verifies auth (user logged in)
|
|
583
|
+
└─ Verifies group access (user member)
|
|
584
|
+
└─ Fetches agent from things table
|
|
585
|
+
└─ Fetches thread messages
|
|
586
|
+
└─ Calls AI SDK streamText()
|
|
587
|
+
|
|
588
|
+
5. AI SDK (streamText)
|
|
589
|
+
└─ Gets model: "openai/gpt-4-turbo"
|
|
590
|
+
└─ Builds prompt:
|
|
591
|
+
- System: agent.properties.systemPrompt
|
|
592
|
+
- Messages: previous 10 messages + new message
|
|
593
|
+
- Tools: ["searchKnowledge", "createTask"]
|
|
594
|
+
|
|
595
|
+
6. CONVEX AGENTS (Stream Management)
|
|
596
|
+
└─ Handles real-time streaming
|
|
597
|
+
└─ Detects tool calls in response
|
|
598
|
+
└─ When tool called:
|
|
599
|
+
a. Pauses main stream
|
|
600
|
+
b. Executes tool (e.g., RAG search)
|
|
601
|
+
c. Includes results in context
|
|
602
|
+
d. Resumes generation
|
|
603
|
+
|
|
604
|
+
7. LLM PROVIDER (OpenAI API)
|
|
605
|
+
└─ Processes request
|
|
606
|
+
└─ Streams response tokens
|
|
607
|
+
└─ Includes tool calls if applicable
|
|
608
|
+
└─ Sends back token usage
|
|
609
|
+
|
|
610
|
+
8. CONVEX AGENTS (Response Processing)
|
|
611
|
+
└─ Aggregates streamed chunks
|
|
612
|
+
└─ Detects end of stream
|
|
613
|
+
└─ Returns complete response
|
|
614
|
+
|
|
615
|
+
9. CONVEX MUTATION (Logging)
|
|
616
|
+
└─ Inserts aiCall record:
|
|
617
|
+
- model: "gpt-4-turbo"
|
|
618
|
+
- tokensUsed: { input: 245, output: 1023 }
|
|
619
|
+
- cost: $0.052
|
|
620
|
+
└─ Inserts event record:
|
|
621
|
+
- type: "ai_response_completed"
|
|
622
|
+
- metadata: { model, tokensUsed, toolsCalled }
|
|
623
|
+
└─ Updates aiThread:
|
|
624
|
+
- updatedAt: Date.now()
|
|
625
|
+
|
|
626
|
+
10. FRONTEND (WebSocket)
|
|
627
|
+
└─ Receives stream chunks via WebSocket
|
|
628
|
+
└─ Message component updates in real-time
|
|
629
|
+
└─ Shows streaming indicator
|
|
630
|
+
└─ Renders content as it arrives
|
|
631
|
+
|
|
632
|
+
11. UI RENDERS (AI Elements)
|
|
633
|
+
└─ Message component displays response
|
|
634
|
+
└─ If code: CodeBlock with syntax highlighting
|
|
635
|
+
└─ If artifact: Artifact with preview
|
|
636
|
+
└─ If sources: Sources component with links
|
|
637
|
+
└─ Actions available: Copy, Share, Regenerate
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
---
|
|
641
|
+
|
|
642
|
+
## Beautiful Integration Points
|
|
643
|
+
|
|
644
|
+
### 1. Streaming is Seamless
|
|
645
|
+
|
|
646
|
+
- AI SDK handles provider differences
|
|
647
|
+
- Convex Agents manages WebSocket streaming
|
|
648
|
+
- React components update in real-time
|
|
649
|
+
- UI feels instant and responsive
|
|
650
|
+
|
|
651
|
+
### 2. Tools Work Transparently
|
|
652
|
+
|
|
653
|
+
- Agent calls tool → AI SDK detects it
|
|
654
|
+
- Convex executes tool (e.g., RAG search)
|
|
655
|
+
- Results included automatically
|
|
656
|
+
- Agent continues with context
|
|
657
|
+
- User sees sources and citations
|
|
658
|
+
|
|
659
|
+
### 3. Multi-Tenancy is Built-In
|
|
660
|
+
|
|
661
|
+
- Every operation scoped to `groupId`
|
|
662
|
+
- Database queries filtered by group
|
|
663
|
+
- No cross-tenant data leakage
|
|
664
|
+
- Usage tracked per group
|
|
665
|
+
- Billing per group
|
|
666
|
+
|
|
667
|
+
### 4. Type Safety Throughout
|
|
668
|
+
|
|
669
|
+
```typescript
|
|
670
|
+
// Frontend ✓ Type-safe
|
|
671
|
+
const response = await sendMessage({
|
|
672
|
+
groupId: "group_123", // ✓ Id<"groups">
|
|
673
|
+
agentId: "thing_456", // ✓ Id<"things">
|
|
674
|
+
threadId: "thread_789", // ✓ string
|
|
675
|
+
message: "Hello", // ✓ string
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
// Backend ✓ Type-safe
|
|
679
|
+
export const sendMessage = mutation({
|
|
680
|
+
args: {
|
|
681
|
+
groupId: v.id("groups"), // ✓ Validates ID
|
|
682
|
+
agentId: v.id("things"), // ✓ Validates ID
|
|
683
|
+
threadId: v.string(), // ✓ Validates string
|
|
684
|
+
message: v.string(), // ✓ Validates string
|
|
685
|
+
},
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
// AI SDK ✓ Type-safe
|
|
689
|
+
const model = openai("gpt-4-turbo"); // ✓ Typed model
|
|
690
|
+
const result = await generateText({
|
|
691
|
+
model, // ✓ Correct type
|
|
692
|
+
prompt, // ✓ string
|
|
693
|
+
tools: { // ✓ Tool definitions validated
|
|
694
|
+
search: tool({ ... })
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
### 5. Observability Built-In
|
|
700
|
+
|
|
701
|
+
- Every AI call logged to `aiCalls`
|
|
702
|
+
- Every action logged to `events`
|
|
703
|
+
- Tokens tracked for billing
|
|
704
|
+
- Latency measured
|
|
705
|
+
- Errors captured
|
|
706
|
+
- Complete audit trail
|
|
707
|
+
|
|
708
|
+
### 6. RAG Integration Natural
|
|
709
|
+
|
|
710
|
+
- Knowledge stored in `knowledge` table
|
|
711
|
+
- Vectors indexed for similarity search
|
|
712
|
+
- Tools access RAG automatically
|
|
713
|
+
- Citations linked back to source
|
|
714
|
+
- Embeddings updated continuously
|
|
715
|
+
|
|
716
|
+
---
|
|
717
|
+
|
|
718
|
+
## Performance Characteristics
|
|
719
|
+
|
|
720
|
+
| Operation | Latency | Why |
|
|
721
|
+
|-----------|---------|-----|
|
|
722
|
+
| Chat send | ~100ms | Frontend → Convex (fast) |
|
|
723
|
+
| LLM call | 2-5s | API call to provider |
|
|
724
|
+
| Stream start | ~200ms | WebSocket handshake |
|
|
725
|
+
| First token | 0.5-2s | Depends on model |
|
|
726
|
+
| Tool execute | 50-500ms | Search/compute time |
|
|
727
|
+
| UI update | <16ms | React re-render |
|
|
728
|
+
| Message save | ~50ms | Convex DB insert |
|
|
729
|
+
| Event log | ~50ms | Convex DB insert |
|
|
730
|
+
|
|
731
|
+
**Total: 2-5 seconds for complete interaction** (dominated by LLM inference time)
|
|
732
|
+
|
|
733
|
+
---
|
|
734
|
+
|
|
735
|
+
## Security Model
|
|
736
|
+
|
|
737
|
+
### Authentication
|
|
738
|
+
- Convex Auth validates every mutation
|
|
739
|
+
- User identity from auth context
|
|
740
|
+
- Sessions managed by Better Auth
|
|
741
|
+
|
|
742
|
+
### Authorization
|
|
743
|
+
- Group membership checked
|
|
744
|
+
- User can only access own group's data
|
|
745
|
+
- Agent access controlled per group
|
|
746
|
+
- Tenant isolation enforced
|
|
747
|
+
|
|
748
|
+
### Data Protection
|
|
749
|
+
- All LLM calls logged for audit
|
|
750
|
+
- API keys never exposed to frontend
|
|
751
|
+
- Encryption in transit (HTTPS/WSS)
|
|
752
|
+
- Encryption at rest (Convex Cloud)
|
|
753
|
+
|
|
754
|
+
### Rate Limiting
|
|
755
|
+
- Convex Rate Limiter on mutations
|
|
756
|
+
- Per-user rate limits
|
|
757
|
+
- Per-group quota enforcement
|
|
758
|
+
- Token usage tracking for billing
|
|
759
|
+
|
|
760
|
+
---
|
|
761
|
+
|
|
762
|
+
## Error Handling & Resilience
|
|
763
|
+
|
|
764
|
+
```typescript
|
|
765
|
+
// Graceful degradation
|
|
766
|
+
try {
|
|
767
|
+
const response = await streamText({ /* ... */ });
|
|
768
|
+
} catch (error) {
|
|
769
|
+
if (error.code === 'rate_limit_exceeded') {
|
|
770
|
+
return { error: 'Please wait before trying again' };
|
|
771
|
+
}
|
|
772
|
+
if (error.code === 'context_length_exceeded') {
|
|
773
|
+
return { error: 'Message too long for this model' };
|
|
774
|
+
}
|
|
775
|
+
if (error.code === 'api_error') {
|
|
776
|
+
return { error: 'Service temporarily unavailable' };
|
|
777
|
+
}
|
|
778
|
+
return { error: 'Unexpected error. Please try again.' };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// Automatic retry
|
|
782
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
783
|
+
try {
|
|
784
|
+
return await streamText({ /* ... */ });
|
|
785
|
+
} catch (error) {
|
|
786
|
+
if (i === maxRetries - 1) throw error;
|
|
787
|
+
await delay(Math.pow(2, i) * 1000); // Exponential backoff
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// Fallback model
|
|
792
|
+
try {
|
|
793
|
+
return await generateText({ model: primaryModel, /* ... */ });
|
|
794
|
+
} catch {
|
|
795
|
+
return await generateText({ model: fallbackModel, /* ... */ });
|
|
796
|
+
}
|
|
797
|
+
```
|
|
798
|
+
|
|
799
|
+
---
|
|
800
|
+
|
|
801
|
+
## Example: Complete Chat Session
|
|
802
|
+
|
|
803
|
+
```
|
|
804
|
+
1. User visits /chat/thread_abc123
|
|
805
|
+
2. Astro page loads thread metadata
|
|
806
|
+
3. CompleteChatUI renders with groupId, agentId
|
|
807
|
+
4. useCompleteChatFlow initializes with zero messages
|
|
808
|
+
5. AI Elements Chatbot displays "Start a conversation"
|
|
809
|
+
6. User types: "What are the top 3 ML algorithms?"
|
|
810
|
+
7. Frontend sends message via Convex mutation
|
|
811
|
+
8. Mutation:
|
|
812
|
+
- Gets agent config from things table
|
|
813
|
+
- Calls AI SDK streamText()
|
|
814
|
+
- Agent detects tool call: searchKnowledge
|
|
815
|
+
- Tool returns 5 relevant documents
|
|
816
|
+
- Agent generates response with citations
|
|
817
|
+
9. Response streams back to frontend
|
|
818
|
+
10. Message renders with:
|
|
819
|
+
- Original response text
|
|
820
|
+
- Inline citations [1], [2], [3]
|
|
821
|
+
- Sources component showing papers
|
|
822
|
+
- Suggestion buttons for follow-ups
|
|
823
|
+
11. Event logged: ai_response_completed
|
|
824
|
+
- Tokens: input 245, output 1023
|
|
825
|
+
- Cost: $0.052
|
|
826
|
+
- Duration: 2.3s
|
|
827
|
+
12. Next message ready, full conversation history in context
|
|
828
|
+
```
|
|
829
|
+
|
|
830
|
+
---
|
|
831
|
+
|
|
832
|
+
## Configuration Reference
|
|
833
|
+
|
|
834
|
+
### Agent Thing Properties
|
|
835
|
+
|
|
836
|
+
```typescript
|
|
837
|
+
{
|
|
838
|
+
type: "agent",
|
|
839
|
+
properties: {
|
|
840
|
+
model: "gpt-4-turbo",
|
|
841
|
+
provider: "openai",
|
|
842
|
+
systemPrompt: "You are a helpful...",
|
|
843
|
+
temperature: 0.7,
|
|
844
|
+
maxTokens: 2000,
|
|
845
|
+
tools: [
|
|
846
|
+
"searchKnowledge",
|
|
847
|
+
"createTask",
|
|
848
|
+
"updateProfile",
|
|
849
|
+
"callHuman"
|
|
850
|
+
],
|
|
851
|
+
ragEnabled: true,
|
|
852
|
+
ragModel: "text-embedding-3-small",
|
|
853
|
+
ragTopK: 5,
|
|
854
|
+
toolCallTimeout: 5000,
|
|
855
|
+
maxConsecutiveToolCalls: 5,
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
```
|
|
859
|
+
|
|
860
|
+
### Environment Variables
|
|
861
|
+
|
|
862
|
+
```bash
|
|
863
|
+
# Backend (.env.local)
|
|
864
|
+
OPENAI_API_KEY=sk-...
|
|
865
|
+
ANTHROPIC_API_KEY=sk-ant-...
|
|
866
|
+
GOOGLE_GENERATIVE_AI_API_KEY=...
|
|
867
|
+
CONVEX_DEPLOYMENT=prod:xxx
|
|
868
|
+
|
|
869
|
+
# Frontend (.env.local)
|
|
870
|
+
PUBLIC_CONVEX_URL=https://xxx.convex.cloud
|
|
871
|
+
CONVEX_DEPLOYMENT=prod:xxx
|
|
872
|
+
```
|
|
873
|
+
|
|
874
|
+
---
|
|
875
|
+
|
|
876
|
+
## Deployment Checklist
|
|
877
|
+
|
|
878
|
+
- [ ] Install all packages (ai, @ai-sdk/openai, ai-elements)
|
|
879
|
+
- [ ] Configure environment variables
|
|
880
|
+
- [ ] Update schema with ai tables
|
|
881
|
+
- [ ] Deploy backend mutations
|
|
882
|
+
- [ ] Create AI Elements components
|
|
883
|
+
- [ ] Build Astro pages
|
|
884
|
+
- [ ] Test end-to-end chat flow
|
|
885
|
+
- [ ] Verify streaming works
|
|
886
|
+
- [ ] Check tool execution
|
|
887
|
+
- [ ] Monitor token usage
|
|
888
|
+
- [ ] Deploy to production
|
|
889
|
+
- [ ] Set up billing alerts
|
|
890
|
+
|
|
891
|
+
---
|
|
892
|
+
|
|
893
|
+
## Next Steps: Implementation Order
|
|
894
|
+
|
|
895
|
+
1. **Week 1: Setup**
|
|
896
|
+
- Install packages
|
|
897
|
+
- Configure environment
|
|
898
|
+
- Update schema
|
|
899
|
+
|
|
900
|
+
2. **Week 2: Backend**
|
|
901
|
+
- Implement mutations
|
|
902
|
+
- Set up AI SDK
|
|
903
|
+
- Configure Convex Agents
|
|
904
|
+
|
|
905
|
+
3. **Week 3: Frontend**
|
|
906
|
+
- Create AI Elements components
|
|
907
|
+
- Build custom hooks
|
|
908
|
+
- Implement streaming
|
|
909
|
+
|
|
910
|
+
4. **Week 4: Integration**
|
|
911
|
+
- Test end-to-end
|
|
912
|
+
- Add RAG integration
|
|
913
|
+
- Implement tool calls
|
|
914
|
+
|
|
915
|
+
5. **Week 5: Production**
|
|
916
|
+
- Performance optimization
|
|
917
|
+
- Security audit
|
|
918
|
+
- Deploy and monitor
|
|
919
|
+
|
|
920
|
+
---
|
|
921
|
+
|
|
922
|
+
## References
|
|
923
|
+
|
|
924
|
+
- **AI SDK**: [ai-sdk.md](./ai-sdk.md)
|
|
925
|
+
- **Convex Agents**: [convex-agents.md](./convex-agents.md)
|
|
926
|
+
- **AI Elements**: [ai-elements.md](./ai-elements.md)
|
|
927
|
+
- **Ontology**: [../knowledge/ontology.md](../knowledge/ontology.md)
|
|
928
|
+
- **Architecture**: [../knowledge/architecture.md](../knowledge/architecture.md)
|
|
929
|
+
- **Patterns**: [../connections/patterns.md](../connections/patterns.md)
|
|
930
|
+
|
|
931
|
+
---
|
|
932
|
+
|
|
933
|
+
## Success Metrics
|
|
934
|
+
|
|
935
|
+
| Metric | Target | Current |
|
|
936
|
+
|--------|--------|---------|
|
|
937
|
+
| Chat response latency | <3s | - |
|
|
938
|
+
| Streaming start time | <500ms | - |
|
|
939
|
+
| Tool execution accuracy | >95% | - |
|
|
940
|
+
| RAG relevance score | >0.7 | - |
|
|
941
|
+
| Error rate | <0.1% | - |
|
|
942
|
+
| User satisfaction | >4.5/5 | - |
|
|
943
|
+
| Token usage tracking | 100% | - |
|
|
944
|
+
|
|
945
|
+
---
|
|
946
|
+
|
|
947
|
+
**Built with clarity, simplicity, and infinite scale in mind.**
|