oneie 3.6.6 → 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/onboard.md +179 -0
- package/.claude/commands/one.md +236 -516
- package/.claude/commands/plan.md +394 -80
- package/.claude/commands/release.md +41 -19
- package/.claude/commands/server.md +335 -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,761 @@
|
|
|
1
|
+
# AI SDK Implementation Plan
|
|
2
|
+
|
|
3
|
+
**Version:** 1.0.0
|
|
4
|
+
**Status:** Planning
|
|
5
|
+
**Integration:** Convex Agents + AI Elements
|
|
6
|
+
**Target Platform:** Astro 5 + React 19 + Convex Backend
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Overview
|
|
11
|
+
|
|
12
|
+
The **AI SDK** (by Vercel) is a unified TypeScript toolkit for building AI-powered applications. It provides a single API across 20+ LLM providers, eliminating provider lock-in and simplifying model switching.
|
|
13
|
+
|
|
14
|
+
### Why AI SDK?
|
|
15
|
+
|
|
16
|
+
- **Provider Agnostic**: One API works with OpenAI, Anthropic, Google, Azure, DeepSeek, etc.
|
|
17
|
+
- **Unified Interface**: Generate text, objects, tool calls with consistent methods
|
|
18
|
+
- **React Hooks**: Built-in hooks for chat, streaming, and state management
|
|
19
|
+
- **Type-Safe**: Full TypeScript support with automatic type inference
|
|
20
|
+
- **Framework Support**: Works with React, Vue, Svelte, Node.js, and more
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Architecture: Where AI SDK Fits
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
User Interface (Astro + React 19)
|
|
28
|
+
↓
|
|
29
|
+
AI Elements Components (Pre-built UI)
|
|
30
|
+
↓
|
|
31
|
+
AI SDK Core + UI Hooks (generateText, useChat, etc.)
|
|
32
|
+
↓
|
|
33
|
+
Convex Backend (Mutations/Queries)
|
|
34
|
+
↓
|
|
35
|
+
Convex Agents (Thread management, persistence)
|
|
36
|
+
↓
|
|
37
|
+
LLM Providers (OpenAI, Anthropic, etc.)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
**Layer Breakdown:**
|
|
41
|
+
|
|
42
|
+
1. **Frontend (Astro)**: Pages, layouts, static content
|
|
43
|
+
2. **React Components**: AI Elements UI + `client:load` interactive components
|
|
44
|
+
3. **AI SDK Hooks**: `useChat()`, `useCompletion()`, `useObject()` for real-time updates
|
|
45
|
+
4. **Convex Backend**: Mutations that call AI SDK `generateText()` or stream to clients
|
|
46
|
+
5. **Convex Agents**: Manage conversation threads, tool calls, message history
|
|
47
|
+
6. **LLM Providers**: Process inference requests
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Architecture: Effect.ts Service Layer Pattern
|
|
52
|
+
|
|
53
|
+
All AI operations are implemented as **Effect.ts services** for backend-agnostic integration:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
// Define domain errors as tagged classes
|
|
57
|
+
class LLMError extends Data.TaggedError("LLMError")<{
|
|
58
|
+
model: string
|
|
59
|
+
provider: string
|
|
60
|
+
cause: unknown
|
|
61
|
+
}> {}
|
|
62
|
+
|
|
63
|
+
class RateLimitError extends Data.TaggedError("RateLimitError")<{
|
|
64
|
+
retryAfter: number
|
|
65
|
+
}> {}
|
|
66
|
+
|
|
67
|
+
// Define service with Context.Tag
|
|
68
|
+
class LLMService extends Context.Tag("LLMService")<
|
|
69
|
+
LLMService,
|
|
70
|
+
{
|
|
71
|
+
readonly generateText: (
|
|
72
|
+
prompt: string,
|
|
73
|
+
options?: { model?: string; provider?: string }
|
|
74
|
+
) => Effect.Effect<string, LLMError>
|
|
75
|
+
|
|
76
|
+
readonly streamText: (
|
|
77
|
+
prompt: string,
|
|
78
|
+
onChunk: (chunk: string) => void
|
|
79
|
+
) => Effect.Effect<void, LLMError>
|
|
80
|
+
|
|
81
|
+
readonly generateObject: <T extends Schema.Schema<any>>(
|
|
82
|
+
prompt: string,
|
|
83
|
+
schema: T
|
|
84
|
+
) => Effect.Effect<Schema.Type<T>, LLMError>
|
|
85
|
+
}
|
|
86
|
+
>() {}
|
|
87
|
+
|
|
88
|
+
// Implement service
|
|
89
|
+
const LLMServiceLive = Layer.effect(
|
|
90
|
+
LLMService,
|
|
91
|
+
Effect.gen(function* () {
|
|
92
|
+
return {
|
|
93
|
+
generateText: (prompt, options) =>
|
|
94
|
+
Effect.gen(function* () {
|
|
95
|
+
const model = selectModel(options?.provider || "openai", "powerful");
|
|
96
|
+
const result = yield* Effect.tryPromise({
|
|
97
|
+
try: () => generateText({ model, prompt }),
|
|
98
|
+
catch: (error) => new LLMError({
|
|
99
|
+
model: options?.model || "gpt-4-turbo",
|
|
100
|
+
provider: options?.provider || "openai",
|
|
101
|
+
cause: error
|
|
102
|
+
})
|
|
103
|
+
});
|
|
104
|
+
return result.text;
|
|
105
|
+
}),
|
|
106
|
+
|
|
107
|
+
streamText: (prompt, onChunk) => {
|
|
108
|
+
// Implementation with streaming
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
generateObject: (prompt, schema) => {
|
|
112
|
+
// Implementation with structured output
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
})
|
|
116
|
+
);
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## Implementation Phases
|
|
122
|
+
|
|
123
|
+
### Phase 1: Setup & Configuration (Infer 1-10)
|
|
124
|
+
|
|
125
|
+
#### Dependencies
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
npm install ai
|
|
129
|
+
npm install @ai-sdk/openai
|
|
130
|
+
npm install @ai-sdk/anthropic
|
|
131
|
+
npm install @ai-sdk/google
|
|
132
|
+
# Add other providers as needed
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
#### Environment Variables
|
|
136
|
+
|
|
137
|
+
**Backend (.env.local):**
|
|
138
|
+
```bash
|
|
139
|
+
OPENAI_API_KEY=sk-...
|
|
140
|
+
ANTHROPIC_API_KEY=sk-ant-...
|
|
141
|
+
GOOGLE_GENERATIVE_AI_API_KEY=...
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**Frontend (.env.local):**
|
|
145
|
+
```bash
|
|
146
|
+
# Not needed for server-side calls
|
|
147
|
+
# Only needed if calling AI SDK directly from browser
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
#### Provider Configuration (backend/convex/ai.ts)
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import { openai } from "@ai-sdk/openai";
|
|
154
|
+
import { anthropic } from "@ai-sdk/anthropic";
|
|
155
|
+
import { google } from "@ai-sdk/google";
|
|
156
|
+
|
|
157
|
+
// Export default model (easy to switch)
|
|
158
|
+
export const defaultModel = openai("gpt-4-turbo");
|
|
159
|
+
|
|
160
|
+
// Export provider-specific models
|
|
161
|
+
export const models = {
|
|
162
|
+
openai: {
|
|
163
|
+
fast: openai("gpt-4o-mini"),
|
|
164
|
+
powerful: openai("gpt-4-turbo"),
|
|
165
|
+
},
|
|
166
|
+
anthropic: {
|
|
167
|
+
fast: anthropic("claude-3-haiku-20240307"),
|
|
168
|
+
powerful: anthropic("claude-3-opus-20240229"),
|
|
169
|
+
},
|
|
170
|
+
google: {
|
|
171
|
+
fast: google("gemini-1.5-flash"),
|
|
172
|
+
powerful: google("gemini-1.5-pro"),
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
export const selectModel = (provider: string, tier: "fast" | "powerful") => {
|
|
177
|
+
return models[provider]?.[tier] || defaultModel;
|
|
178
|
+
};
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
### Phase 2: Convex Mutations (Infer 11-20)
|
|
184
|
+
|
|
185
|
+
#### Schema Extension
|
|
186
|
+
|
|
187
|
+
The Convex schema already has `events` table. Add AI-specific fields:
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
// backend/convex/schema.ts
|
|
191
|
+
import { defineSchema, defineTable } from "convex/server";
|
|
192
|
+
import { v } from "convex/values";
|
|
193
|
+
|
|
194
|
+
export default defineSchema({
|
|
195
|
+
// ... existing tables ...
|
|
196
|
+
aiCalls: defineTable({
|
|
197
|
+
groupId: v.id("groups"),
|
|
198
|
+
actorId: v.optional(v.string()),
|
|
199
|
+
model: v.string(),
|
|
200
|
+
provider: v.string(),
|
|
201
|
+
prompt: v.string(),
|
|
202
|
+
result: v.string(),
|
|
203
|
+
tokensUsed: v.optional(v.object({
|
|
204
|
+
input: v.number(),
|
|
205
|
+
output: v.number(),
|
|
206
|
+
})),
|
|
207
|
+
duration: v.number(),
|
|
208
|
+
error: v.optional(v.string()),
|
|
209
|
+
metadata: v.any(),
|
|
210
|
+
timestamp: v.number(),
|
|
211
|
+
}).index("by_groupId", ["groupId"]),
|
|
212
|
+
|
|
213
|
+
aiThreads: defineTable({
|
|
214
|
+
groupId: v.id("groups"),
|
|
215
|
+
agentId: v.id("things"),
|
|
216
|
+
title: v.string(),
|
|
217
|
+
status: v.union(v.literal("active"), v.literal("archived"), v.literal("completed")),
|
|
218
|
+
metadata: v.any(),
|
|
219
|
+
createdAt: v.number(),
|
|
220
|
+
updatedAt: v.number(),
|
|
221
|
+
}).index("by_groupId", ["groupId"]).index("by_agentId", ["agentId"]),
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
#### Mutations for Text Generation
|
|
226
|
+
|
|
227
|
+
```typescript
|
|
228
|
+
// backend/convex/mutations/ai.ts
|
|
229
|
+
import { mutation } from "./_generated/server";
|
|
230
|
+
import { v } from "convex/values";
|
|
231
|
+
import { generateText } from "ai";
|
|
232
|
+
import { selectModel } from "../ai";
|
|
233
|
+
|
|
234
|
+
export const generateResponse = mutation({
|
|
235
|
+
args: {
|
|
236
|
+
groupId: v.id("groups"),
|
|
237
|
+
prompt: v.string(),
|
|
238
|
+
model: v.optional(v.string()),
|
|
239
|
+
provider: v.optional(v.string()),
|
|
240
|
+
systemPrompt: v.optional(v.string()),
|
|
241
|
+
},
|
|
242
|
+
handler: async (ctx, args) => {
|
|
243
|
+
const startTime = Date.now();
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
const model = selectModel(args.provider || "openai", "powerful");
|
|
247
|
+
const system = args.systemPrompt || "You are a helpful AI assistant.";
|
|
248
|
+
|
|
249
|
+
const { text, usage } = await generateText({
|
|
250
|
+
model,
|
|
251
|
+
system,
|
|
252
|
+
prompt: args.prompt,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
// Log to aiCalls table
|
|
256
|
+
await ctx.db.insert("aiCalls", {
|
|
257
|
+
groupId: args.groupId,
|
|
258
|
+
model: args.model || "gpt-4-turbo",
|
|
259
|
+
provider: args.provider || "openai",
|
|
260
|
+
prompt: args.prompt,
|
|
261
|
+
result: text,
|
|
262
|
+
tokensUsed: {
|
|
263
|
+
input: usage?.promptTokens || 0,
|
|
264
|
+
output: usage?.completionTokens || 0,
|
|
265
|
+
},
|
|
266
|
+
duration: Date.now() - startTime,
|
|
267
|
+
metadata: {},
|
|
268
|
+
timestamp: Date.now(),
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
// Log to events table
|
|
272
|
+
await ctx.db.insert("events", {
|
|
273
|
+
groupId: args.groupId,
|
|
274
|
+
type: "ai_generation_completed",
|
|
275
|
+
actorId: ctx.auth?.getUserIdentity()?.tokenIdentifier,
|
|
276
|
+
targetId: null,
|
|
277
|
+
timestamp: Date.now(),
|
|
278
|
+
metadata: {
|
|
279
|
+
model: args.model || "gpt-4-turbo",
|
|
280
|
+
provider: args.provider || "openai",
|
|
281
|
+
tokensUsed: usage,
|
|
282
|
+
},
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
return { success: true, text, usage };
|
|
286
|
+
} catch (error) {
|
|
287
|
+
await ctx.db.insert("aiCalls", {
|
|
288
|
+
groupId: args.groupId,
|
|
289
|
+
model: args.model || "gpt-4-turbo",
|
|
290
|
+
provider: args.provider || "openai",
|
|
291
|
+
prompt: args.prompt,
|
|
292
|
+
result: "",
|
|
293
|
+
duration: Date.now() - startTime,
|
|
294
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
295
|
+
metadata: {},
|
|
296
|
+
timestamp: Date.now(),
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
#### Mutations for Streaming (Agent Threads)
|
|
306
|
+
|
|
307
|
+
```typescript
|
|
308
|
+
// backend/convex/mutations/ai.ts (continued)
|
|
309
|
+
import { streamText } from "ai";
|
|
310
|
+
|
|
311
|
+
export const streamAgentResponse = mutation({
|
|
312
|
+
args: {
|
|
313
|
+
groupId: v.id("groups"),
|
|
314
|
+
threadId: v.id("aiThreads"),
|
|
315
|
+
message: v.string(),
|
|
316
|
+
systemPrompt: v.optional(v.string()),
|
|
317
|
+
},
|
|
318
|
+
handler: async (ctx, args) => {
|
|
319
|
+
const model = selectModel("openai", "powerful");
|
|
320
|
+
const system = args.systemPrompt || "You are a helpful AI assistant.";
|
|
321
|
+
|
|
322
|
+
// Stream via websocket (handled by Convex Agents)
|
|
323
|
+
const { textStream, usage } = await streamText({
|
|
324
|
+
model,
|
|
325
|
+
system,
|
|
326
|
+
prompt: args.message,
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
// Return stream for client consumption
|
|
330
|
+
return {
|
|
331
|
+
threadId: args.threadId,
|
|
332
|
+
stream: textStream,
|
|
333
|
+
usage,
|
|
334
|
+
};
|
|
335
|
+
},
|
|
336
|
+
});
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
---
|
|
340
|
+
|
|
341
|
+
### Phase 3: Frontend Integration (Infer 21-30)
|
|
342
|
+
|
|
343
|
+
#### useChat Hook Integration
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
// web/src/lib/hooks/useAIChat.ts
|
|
347
|
+
import { useChat } from "ai/react";
|
|
348
|
+
import { useMutation } from "convex/react";
|
|
349
|
+
import { api } from "@/convex/_generated/api";
|
|
350
|
+
|
|
351
|
+
export function useAIChat(groupId: string, agentId: string) {
|
|
352
|
+
const generateResponse = useMutation(api.mutations.ai.generateResponse);
|
|
353
|
+
const streamResponse = useMutation(api.mutations.ai.streamAgentResponse);
|
|
354
|
+
|
|
355
|
+
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
|
|
356
|
+
api: "/api/chat", // Not used with Convex, but useChat requires it
|
|
357
|
+
id: `${groupId}-${agentId}`,
|
|
358
|
+
onFinish: async (message) => {
|
|
359
|
+
// Optional: Additional processing after generation
|
|
360
|
+
console.log("Message finished:", message);
|
|
361
|
+
},
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
return {
|
|
365
|
+
messages,
|
|
366
|
+
input,
|
|
367
|
+
handleInputChange,
|
|
368
|
+
handleSubmit,
|
|
369
|
+
isLoading,
|
|
370
|
+
sendMessage: async (content: string) => {
|
|
371
|
+
// Call Convex mutation directly
|
|
372
|
+
const response = await generateResponse({
|
|
373
|
+
groupId,
|
|
374
|
+
prompt: content,
|
|
375
|
+
provider: "openai",
|
|
376
|
+
});
|
|
377
|
+
return response;
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
#### React Component Using useChat
|
|
384
|
+
|
|
385
|
+
```typescript
|
|
386
|
+
// web/src/components/features/AIChat.tsx
|
|
387
|
+
import { useAIChat } from "@/lib/hooks/useAIChat";
|
|
388
|
+
import { useState } from "react";
|
|
389
|
+
|
|
390
|
+
interface AIChatProps {
|
|
391
|
+
groupId: string;
|
|
392
|
+
agentId: string;
|
|
393
|
+
systemPrompt?: string;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export function AIChat({ groupId, agentId, systemPrompt }: AIChatProps) {
|
|
397
|
+
const { messages, input, handleInputChange, isLoading, sendMessage } = useAIChat(groupId, agentId);
|
|
398
|
+
const [error, setError] = useState<string | null>(null);
|
|
399
|
+
|
|
400
|
+
const handleSend = async (e: React.FormEvent) => {
|
|
401
|
+
e.preventDefault();
|
|
402
|
+
if (!input.trim()) return;
|
|
403
|
+
|
|
404
|
+
setError(null);
|
|
405
|
+
try {
|
|
406
|
+
await sendMessage(input);
|
|
407
|
+
handleInputChange({ target: { value: "" } } as any);
|
|
408
|
+
} catch (err) {
|
|
409
|
+
setError(err instanceof Error ? err.message : "Failed to send message");
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
return (
|
|
414
|
+
<div className="flex flex-col h-full gap-4">
|
|
415
|
+
{/* Messages Display */}
|
|
416
|
+
<div className="flex-1 overflow-y-auto space-y-4 p-4">
|
|
417
|
+
{messages.map((msg) => (
|
|
418
|
+
<div key={msg.id} className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
|
|
419
|
+
<div className={`max-w-xs rounded-lg px-4 py-2 ${
|
|
420
|
+
msg.role === "user"
|
|
421
|
+
? "bg-blue-500 text-white"
|
|
422
|
+
: "bg-gray-200 text-gray-900"
|
|
423
|
+
}`}>
|
|
424
|
+
{msg.content}
|
|
425
|
+
</div>
|
|
426
|
+
</div>
|
|
427
|
+
))}
|
|
428
|
+
{isLoading && <div className="text-center text-gray-500">AI is thinking...</div>}
|
|
429
|
+
</div>
|
|
430
|
+
|
|
431
|
+
{/* Error Display */}
|
|
432
|
+
{error && <div className="text-red-600 text-sm px-4">{error}</div>}
|
|
433
|
+
|
|
434
|
+
{/* Input Form */}
|
|
435
|
+
<form onSubmit={handleSend} className="border-t p-4 flex gap-2">
|
|
436
|
+
<input
|
|
437
|
+
value={input}
|
|
438
|
+
onChange={handleInputChange}
|
|
439
|
+
placeholder="Type your message..."
|
|
440
|
+
disabled={isLoading}
|
|
441
|
+
className="flex-1 px-4 py-2 border rounded-lg disabled:opacity-50"
|
|
442
|
+
/>
|
|
443
|
+
<button
|
|
444
|
+
type="submit"
|
|
445
|
+
disabled={isLoading || !input.trim()}
|
|
446
|
+
className="px-6 py-2 bg-blue-500 text-white rounded-lg disabled:opacity-50"
|
|
447
|
+
>
|
|
448
|
+
Send
|
|
449
|
+
</button>
|
|
450
|
+
</form>
|
|
451
|
+
</div>
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
---
|
|
457
|
+
|
|
458
|
+
### Phase 4: Advanced Features (Infer 41-50)
|
|
459
|
+
|
|
460
|
+
#### Structured Output (Objects)
|
|
461
|
+
|
|
462
|
+
```typescript
|
|
463
|
+
// backend/convex/mutations/ai.ts (continued)
|
|
464
|
+
import { generateObject } from "ai";
|
|
465
|
+
import { z } from "zod";
|
|
466
|
+
|
|
467
|
+
const analyticsSchema = z.object({
|
|
468
|
+
sentiment: z.enum(["positive", "neutral", "negative"]),
|
|
469
|
+
topics: z.array(z.string()),
|
|
470
|
+
urgency: z.number().min(0).max(10),
|
|
471
|
+
action_items: z.array(z.string()),
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
export const analyzeMessage = mutation({
|
|
475
|
+
args: {
|
|
476
|
+
groupId: v.id("groups"),
|
|
477
|
+
message: v.string(),
|
|
478
|
+
},
|
|
479
|
+
handler: async (ctx, args) => {
|
|
480
|
+
const model = selectModel("openai", "powerful");
|
|
481
|
+
|
|
482
|
+
const { object, usage } = await generateObject({
|
|
483
|
+
model,
|
|
484
|
+
schema: analyticsSchema,
|
|
485
|
+
prompt: `Analyze this message and extract insights:\n\n${args.message}`,
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
return { analysis: object, usage };
|
|
489
|
+
},
|
|
490
|
+
});
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
#### Tool Calls (Function Calling)
|
|
494
|
+
|
|
495
|
+
```typescript
|
|
496
|
+
// backend/convex/mutations/ai.ts (continued)
|
|
497
|
+
import { generateText, tool } from "ai";
|
|
498
|
+
|
|
499
|
+
const tools = {
|
|
500
|
+
getWeather: tool({
|
|
501
|
+
description: "Get the current weather in a location",
|
|
502
|
+
parameters: z.object({
|
|
503
|
+
location: z.string().describe("The city and state, e.g. San Francisco, CA"),
|
|
504
|
+
}),
|
|
505
|
+
execute: async ({ location }) => {
|
|
506
|
+
// Call weather API
|
|
507
|
+
return `Weather in ${location}: 72°F, Sunny`;
|
|
508
|
+
},
|
|
509
|
+
}),
|
|
510
|
+
|
|
511
|
+
createTask: tool({
|
|
512
|
+
description: "Create a new task for the user",
|
|
513
|
+
parameters: z.object({
|
|
514
|
+
title: z.string(),
|
|
515
|
+
description: z.string().optional(),
|
|
516
|
+
dueDate: z.string().optional(),
|
|
517
|
+
}),
|
|
518
|
+
execute: async ({ title, description, dueDate }) => {
|
|
519
|
+
// Create thing in database
|
|
520
|
+
return `Task created: ${title}`;
|
|
521
|
+
},
|
|
522
|
+
}),
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
export const generateWithTools = mutation({
|
|
526
|
+
args: {
|
|
527
|
+
groupId: v.id("groups"),
|
|
528
|
+
prompt: v.string(),
|
|
529
|
+
},
|
|
530
|
+
handler: async (ctx, args) => {
|
|
531
|
+
const model = selectModel("openai", "powerful");
|
|
532
|
+
|
|
533
|
+
const result = await generateText({
|
|
534
|
+
model,
|
|
535
|
+
tools,
|
|
536
|
+
prompt: args.prompt,
|
|
537
|
+
});
|
|
538
|
+
|
|
539
|
+
return result;
|
|
540
|
+
},
|
|
541
|
+
});
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
---
|
|
545
|
+
|
|
546
|
+
### Phase 5: Monitoring & Observability (Infer 61-70)
|
|
547
|
+
|
|
548
|
+
#### Token Usage Tracking
|
|
549
|
+
|
|
550
|
+
```typescript
|
|
551
|
+
// web/src/lib/hooks/useTokenUsage.ts
|
|
552
|
+
import { useQuery } from "convex/react";
|
|
553
|
+
import { api } from "@/convex/_generated/api";
|
|
554
|
+
|
|
555
|
+
export function useTokenUsage(groupId: string) {
|
|
556
|
+
const calls = useQuery(api.queries.ai.getCallsByGroup, { groupId });
|
|
557
|
+
|
|
558
|
+
if (!calls) return null;
|
|
559
|
+
|
|
560
|
+
const totalTokens = calls.reduce((sum, call) => {
|
|
561
|
+
return sum + (call.tokensUsed?.input || 0) + (call.tokensUsed?.output || 0);
|
|
562
|
+
}, 0);
|
|
563
|
+
|
|
564
|
+
const totalCost = totalTokens * 0.00002; // Example: $0.02 per 1M tokens
|
|
565
|
+
|
|
566
|
+
return {
|
|
567
|
+
totalCalls: calls.length,
|
|
568
|
+
totalTokens,
|
|
569
|
+
estimatedCost: totalCost,
|
|
570
|
+
averageLatency: calls.reduce((sum, call) => sum + call.duration, 0) / calls.length,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
#### Query for Analytics
|
|
576
|
+
|
|
577
|
+
```typescript
|
|
578
|
+
// backend/convex/queries/ai.ts
|
|
579
|
+
import { query } from "./_generated/server";
|
|
580
|
+
import { v } from "convex/values";
|
|
581
|
+
|
|
582
|
+
export const getCallsByGroup = query({
|
|
583
|
+
args: { groupId: v.id("groups") },
|
|
584
|
+
handler: async (ctx, args) => {
|
|
585
|
+
return await ctx.db
|
|
586
|
+
.query("aiCalls")
|
|
587
|
+
.withIndex("by_groupId", (q) => q.eq("groupId", args.groupId))
|
|
588
|
+
.order("desc")
|
|
589
|
+
.take(100);
|
|
590
|
+
},
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
export const getTokenUsageStats = query({
|
|
594
|
+
args: { groupId: v.id("groups") },
|
|
595
|
+
handler: async (ctx, args) => {
|
|
596
|
+
const calls = await ctx.db
|
|
597
|
+
.query("aiCalls")
|
|
598
|
+
.withIndex("by_groupId", (q) => q.eq("groupId", args.groupId))
|
|
599
|
+
.collect();
|
|
600
|
+
|
|
601
|
+
const groupedByProvider = calls.reduce((acc, call) => {
|
|
602
|
+
if (!acc[call.provider]) {
|
|
603
|
+
acc[call.provider] = { calls: 0, tokens: 0 };
|
|
604
|
+
}
|
|
605
|
+
acc[call.provider].calls += 1;
|
|
606
|
+
acc[call.provider].tokens += (call.tokensUsed?.input || 0) + (call.tokensUsed?.output || 0);
|
|
607
|
+
return acc;
|
|
608
|
+
}, {} as Record<string, { calls: number; tokens: number }>);
|
|
609
|
+
|
|
610
|
+
return groupedByProvider;
|
|
611
|
+
},
|
|
612
|
+
});
|
|
613
|
+
```
|
|
614
|
+
|
|
615
|
+
---
|
|
616
|
+
|
|
617
|
+
## Integration with 6-Dimension Ontology
|
|
618
|
+
|
|
619
|
+
### Mapping to Ontology Dimensions
|
|
620
|
+
|
|
621
|
+
1. **Things**: AI `agent` entities with properties for model, provider, system prompt
|
|
622
|
+
2. **Connections**: `agent_owns`, `agent_trained_on`, `user_interacted_with_agent`
|
|
623
|
+
3. **Events**: `ai_generation_completed`, `ai_tool_called`, `ai_error_occurred`
|
|
624
|
+
4. **Knowledge**: Embeddings of generated content for RAG
|
|
625
|
+
5. **People**: Track which users interact with which agents
|
|
626
|
+
6. **Groups**: Multi-tenant AI access (each group has separate AI quotas/models)
|
|
627
|
+
|
|
628
|
+
### Schema for Agent Things
|
|
629
|
+
|
|
630
|
+
```typescript
|
|
631
|
+
// Agent as a "thing"
|
|
632
|
+
{
|
|
633
|
+
_id: Id<"things">,
|
|
634
|
+
groupId: Id<"groups">,
|
|
635
|
+
type: "agent",
|
|
636
|
+
name: "Customer Support Bot",
|
|
637
|
+
status: "active",
|
|
638
|
+
properties: {
|
|
639
|
+
model: "gpt-4-turbo",
|
|
640
|
+
provider: "openai",
|
|
641
|
+
systemPrompt: "You are a helpful customer support agent...",
|
|
642
|
+
tools: ["searchKB", "createTicket", "escalateToHuman"],
|
|
643
|
+
temperature: 0.7,
|
|
644
|
+
maxTokens: 2000,
|
|
645
|
+
},
|
|
646
|
+
createdAt: number,
|
|
647
|
+
updatedAt: number,
|
|
648
|
+
}
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
---
|
|
652
|
+
|
|
653
|
+
## Configuration Reference
|
|
654
|
+
|
|
655
|
+
| Setting | Purpose | Default |
|
|
656
|
+
|---------|---------|---------|
|
|
657
|
+
| `model` | Which LLM model | `gpt-4-turbo` |
|
|
658
|
+
| `provider` | Which LLM provider | `openai` |
|
|
659
|
+
| `temperature` | Creativity (0-1) | `0.7` |
|
|
660
|
+
| `maxTokens` | Max response length | `2000` |
|
|
661
|
+
| `systemPrompt` | AI instructions | Generic |
|
|
662
|
+
|
|
663
|
+
---
|
|
664
|
+
|
|
665
|
+
## Common Patterns
|
|
666
|
+
|
|
667
|
+
### Pattern: Provider Agnostic Code
|
|
668
|
+
|
|
669
|
+
```typescript
|
|
670
|
+
// Good: Works with any provider
|
|
671
|
+
async function chat(message: string) {
|
|
672
|
+
const model = selectModel(provider, tier);
|
|
673
|
+
return generateText({ model, prompt: message });
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Bad: Locked to OpenAI
|
|
677
|
+
async function chat(message: string) {
|
|
678
|
+
return openai("gpt-4").generateText({ prompt: message });
|
|
679
|
+
}
|
|
680
|
+
```
|
|
681
|
+
|
|
682
|
+
### Pattern: Error Handling
|
|
683
|
+
|
|
684
|
+
```typescript
|
|
685
|
+
try {
|
|
686
|
+
const result = await generateText({ model, prompt });
|
|
687
|
+
return { success: true, result };
|
|
688
|
+
} catch (error) {
|
|
689
|
+
// Log to database
|
|
690
|
+
await logError(groupId, error);
|
|
691
|
+
|
|
692
|
+
// Re-throw with context
|
|
693
|
+
throw new Error(`AI generation failed: ${error.message}`);
|
|
694
|
+
}
|
|
695
|
+
```
|
|
696
|
+
|
|
697
|
+
---
|
|
698
|
+
|
|
699
|
+
## Testing Strategy
|
|
700
|
+
|
|
701
|
+
### Unit Tests
|
|
702
|
+
|
|
703
|
+
```typescript
|
|
704
|
+
// test/ai/generateResponse.test.ts
|
|
705
|
+
import { expect, test } from "bun:test";
|
|
706
|
+
import { generateResponse } from "@/convex/mutations/ai";
|
|
707
|
+
|
|
708
|
+
test("generateResponse returns text", async () => {
|
|
709
|
+
const result = await generateResponse({
|
|
710
|
+
groupId: "group_123",
|
|
711
|
+
prompt: "What is 2+2?",
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
expect(result.success).toBe(true);
|
|
715
|
+
expect(result.text).toBeDefined();
|
|
716
|
+
});
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
### Integration Tests
|
|
720
|
+
|
|
721
|
+
```typescript
|
|
722
|
+
// test/ai/integration.test.ts
|
|
723
|
+
test("chat flow with AI SDK and Convex", async () => {
|
|
724
|
+
// 1. Create a group
|
|
725
|
+
// 2. Create an agent thing
|
|
726
|
+
// 3. Send message via mutation
|
|
727
|
+
// 4. Verify event logged
|
|
728
|
+
// 5. Verify tokens tracked
|
|
729
|
+
});
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
---
|
|
733
|
+
|
|
734
|
+
## Performance Considerations
|
|
735
|
+
|
|
736
|
+
- **Streaming**: Use `streamText()` for long responses
|
|
737
|
+
- **Caching**: Cache common prompts and responses
|
|
738
|
+
- **Rate Limiting**: Use Convex Rate Limiter for abuse prevention
|
|
739
|
+
- **Async**: Run AI calls asynchronously to not block UI
|
|
740
|
+
- **Token Budget**: Track tokens per group per month for cost control
|
|
741
|
+
|
|
742
|
+
---
|
|
743
|
+
|
|
744
|
+
## Next Steps
|
|
745
|
+
|
|
746
|
+
1. **Install dependencies**: `npm install ai @ai-sdk/openai`
|
|
747
|
+
2. **Set environment variables**: Add LLM provider keys
|
|
748
|
+
3. **Implement backend mutations**: Start with `generateResponse`
|
|
749
|
+
4. **Build frontend components**: Integrate `useChat` hook
|
|
750
|
+
5. **Add monitoring**: Track tokens and latency
|
|
751
|
+
6. **Test end-to-end**: Verify all flows work
|
|
752
|
+
|
|
753
|
+
---
|
|
754
|
+
|
|
755
|
+
## References
|
|
756
|
+
|
|
757
|
+
- [AI SDK Documentation](https://ai-sdk.dev/)
|
|
758
|
+
- [AI SDK React](https://ai-sdk.dev/docs/react)
|
|
759
|
+
- [Supported Models](https://ai-sdk.dev/docs/models)
|
|
760
|
+
- [Tool Calling](https://ai-sdk.dev/docs/tools-and-functions)
|
|
761
|
+
- [Streaming](https://ai-sdk.dev/docs/concepts/streaming)
|