oneie 3.6.33 → 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,355 @@
1
+ ---
2
+ title: Ai Quickstart
3
+ dimension: knowledge
4
+ category: guides
5
+ tags: ai, quickstart, tutorial, getting-started
6
+ related_dimensions: things
7
+ scope: global
8
+ created: 2025-11-10
9
+ updated: 2025-11-10
10
+ version: 1.0.0
11
+ ---
12
+
13
+ # AI Integration - Quick Start Guide
14
+
15
+ **Time:** 5 minutes
16
+ **Difficulty:** Beginner
17
+ **Stack:** Vercel AI SDK 5 + Convex + React
18
+
19
+ ## Prerequisites
20
+
21
+ - Node.js 18+
22
+ - Bun or npm
23
+ - Convex account
24
+ - OpenAI or Anthropic API key
25
+
26
+ ## Step 1: Install Dependencies (1 minute)
27
+
28
+ ```bash
29
+ # Backend
30
+ cd backend
31
+ npm install ai @ai-sdk/openai @ai-sdk/anthropic zod effect
32
+
33
+ # Frontend
34
+ cd web
35
+ npm install ai @ai-sdk/react zod recharts
36
+ ```
37
+
38
+ ## Step 2: Configure Environment (1 minute)
39
+
40
+ **Create `backend/.env.local`:**
41
+
42
+ ```bash
43
+ # Get your API key from https://platform.openai.com/api-keys
44
+ OPENAI_API_KEY=sk-...
45
+
46
+ # Or use Anthropic: https://console.anthropic.com/settings/keys
47
+ ANTHROPIC_API_KEY=sk-ant-...
48
+
49
+ # Convex deployment
50
+ CONVEX_DEPLOYMENT=prod:shocking-falcon-870
51
+ ```
52
+
53
+ ## Step 3: Deploy Schema (1 minute)
54
+
55
+ **Add to `backend/convex/schema.ts`:**
56
+
57
+ ```typescript
58
+ export default defineSchema({
59
+ // ... existing tables ...
60
+
61
+ aiCalls: defineTable({
62
+ groupId: v.id("groups"),
63
+ model: v.string(),
64
+ provider: v.string(),
65
+ prompt: v.string(),
66
+ result: v.string(),
67
+ tokensUsed: v.object({
68
+ input: v.number(),
69
+ output: v.number(),
70
+ total: v.number(),
71
+ }),
72
+ duration: v.number(),
73
+ timestamp: v.number(),
74
+ }).index("by_groupId", ["groupId"]),
75
+ });
76
+ ```
77
+
78
+ **Deploy:**
79
+
80
+ ```bash
81
+ cd backend
82
+ npx convex deploy
83
+ ```
84
+
85
+ ## Step 4: Create AI Mutation (1 minute)
86
+
87
+ **Create `backend/convex/mutations/ai-simple.ts`:**
88
+
89
+ ```typescript
90
+ import { mutation } from "../_generated/server";
91
+ import { v } from "convex/values";
92
+ import { generateText } from "ai";
93
+ import { openai } from "@ai-sdk/openai";
94
+
95
+ export const chat = mutation({
96
+ args: {
97
+ groupId: v.id("groups"),
98
+ prompt: v.string(),
99
+ },
100
+ handler: async (ctx, args) => {
101
+ const model = openai("gpt-4-turbo");
102
+
103
+ const { text, usage } = await generateText({
104
+ model,
105
+ prompt: args.prompt,
106
+ });
107
+
108
+ await ctx.db.insert("aiCalls", {
109
+ groupId: args.groupId,
110
+ model: "gpt-4-turbo",
111
+ provider: "openai",
112
+ prompt: args.prompt,
113
+ result: text,
114
+ tokensUsed: {
115
+ input: usage?.promptTokens || 0,
116
+ output: usage?.completionTokens || 0,
117
+ total: usage?.totalTokens || 0,
118
+ },
119
+ duration: 0,
120
+ timestamp: Date.now(),
121
+ });
122
+
123
+ return { text, usage };
124
+ },
125
+ });
126
+ ```
127
+
128
+ ## Step 5: Create React Component (1 minute)
129
+
130
+ **Create `web/src/components/SimpleChat.tsx`:**
131
+
132
+ ```tsx
133
+ import { useMutation } from "convex/react";
134
+ import { api } from "@/convex/_generated/api";
135
+ import { useState } from "react";
136
+
137
+ export function SimpleChat({ groupId }: { groupId: string }) {
138
+ const [input, setInput] = useState("");
139
+ const [messages, setMessages] = useState<any[]>([]);
140
+ const [isLoading, setIsLoading] = useState(false);
141
+
142
+ const chat = useMutation(api.mutations['ai-simple'].chat);
143
+
144
+ const sendMessage = async (e: React.FormEvent) => {
145
+ e.preventDefault();
146
+ if (!input.trim()) return;
147
+
148
+ setIsLoading(true);
149
+ setMessages(prev => [...prev, { role: "user", content: input }]);
150
+
151
+ try {
152
+ const response = await chat({ groupId, prompt: input });
153
+ setMessages(prev => [...prev, { role: "assistant", content: response.text }]);
154
+ setInput("");
155
+ } finally {
156
+ setIsLoading(false);
157
+ }
158
+ };
159
+
160
+ return (
161
+ <div className="flex flex-col h-96 max-w-2xl mx-auto p-4 border rounded-lg">
162
+ <div className="flex-1 overflow-y-auto space-y-4 mb-4">
163
+ {messages.map((msg, i) => (
164
+ <div
165
+ key={i}
166
+ className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
167
+ >
168
+ <div
169
+ className={`max-w-xs px-4 py-2 rounded-lg ${
170
+ msg.role === "user"
171
+ ? "bg-blue-500 text-white"
172
+ : "bg-gray-200 text-gray-900"
173
+ }`}
174
+ >
175
+ {msg.content}
176
+ </div>
177
+ </div>
178
+ ))}
179
+ {isLoading && (
180
+ <div className="text-center text-gray-500">AI is thinking...</div>
181
+ )}
182
+ </div>
183
+
184
+ <form onSubmit={sendMessage} className="flex gap-2">
185
+ <input
186
+ value={input}
187
+ onChange={e => setInput(e.target.value)}
188
+ placeholder="Ask me anything..."
189
+ disabled={isLoading}
190
+ className="flex-1 px-4 py-2 border rounded-lg"
191
+ />
192
+ <button
193
+ type="submit"
194
+ disabled={isLoading || !input.trim()}
195
+ className="px-6 py-2 bg-blue-500 text-white rounded-lg disabled:opacity-50"
196
+ >
197
+ Send
198
+ </button>
199
+ </form>
200
+ </div>
201
+ );
202
+ }
203
+ ```
204
+
205
+ ## Step 6: Use in Your Page (30 seconds)
206
+
207
+ **Add to `web/src/pages/chat.astro`:**
208
+
209
+ ```astro
210
+ ---
211
+ import Layout from '@/layouts/Layout.astro';
212
+ import SimpleChat from '@/components/SimpleChat';
213
+
214
+ const groupId = 'your-group-id'; // Get from Convex dashboard
215
+ ---
216
+
217
+ <Layout title="AI Chat">
218
+ <h1>Chat with AI</h1>
219
+ <SimpleChat groupId={groupId} client:load />
220
+ </Layout>
221
+ ```
222
+
223
+ ## Step 7: Test! (30 seconds)
224
+
225
+ ```bash
226
+ cd web
227
+ bun run dev
228
+ ```
229
+
230
+ Visit `http://localhost:4321/chat` and start chatting!
231
+
232
+ ## Next Steps
233
+
234
+ ### Add Streaming
235
+
236
+ ```typescript
237
+ import { streamText } from "ai";
238
+
239
+ export const chatStream = mutation({
240
+ args: { groupId: v.id("groups"), prompt: v.string() },
241
+ handler: async (ctx, args) => {
242
+ const model = openai("gpt-4-turbo");
243
+ const { textStream } = await streamText({ model, prompt: args.prompt });
244
+
245
+ // Return stream for client
246
+ return textStream;
247
+ }
248
+ });
249
+ ```
250
+
251
+ ### Add Structured Output
252
+
253
+ ```typescript
254
+ import { generateObject } from "ai";
255
+ import { z } from "zod";
256
+
257
+ const schema = z.object({
258
+ sentiment: z.enum(["positive", "neutral", "negative"]),
259
+ topics: z.array(z.string()),
260
+ summary: z.string(),
261
+ });
262
+
263
+ export const analyze = mutation({
264
+ args: { groupId: v.id("groups"), message: v.string() },
265
+ handler: async (ctx, args) => {
266
+ const model = openai("gpt-4-turbo");
267
+ const { object } = await generateObject({
268
+ model,
269
+ schema,
270
+ prompt: `Analyze: ${args.message}`
271
+ });
272
+
273
+ return object;
274
+ }
275
+ });
276
+ ```
277
+
278
+ ### Add Function Calling
279
+
280
+ ```typescript
281
+ import { tool } from "ai";
282
+
283
+ const tools = {
284
+ getWeather: tool({
285
+ description: "Get current weather",
286
+ parameters: z.object({ location: z.string() }),
287
+ execute: async ({ location }) => {
288
+ return `Weather in ${location}: 72°F, Sunny`;
289
+ }
290
+ })
291
+ };
292
+
293
+ export const chatWithTools = mutation({
294
+ args: { groupId: v.id("groups"), prompt: v.string() },
295
+ handler: async (ctx, args) => {
296
+ const model = openai("gpt-4-turbo");
297
+ const result = await generateText({
298
+ model,
299
+ tools,
300
+ prompt: args.prompt
301
+ });
302
+
303
+ return result;
304
+ }
305
+ });
306
+ ```
307
+
308
+ ### Switch Providers
309
+
310
+ ```typescript
311
+ // Use Anthropic instead of OpenAI
312
+ import { anthropic } from "@ai-sdk/anthropic";
313
+
314
+ const model = anthropic("claude-3-5-sonnet-20241022");
315
+
316
+ // Or Google
317
+ import { google } from "@ai-sdk/google";
318
+
319
+ const model = google("gemini-1.5-pro");
320
+
321
+ // Same code, different provider!
322
+ ```
323
+
324
+ ## Common Issues
325
+
326
+ **Q: "TypeError: Cannot read property 'text' of undefined"**
327
+ A: Check that your API key is set correctly in `.env.local`
328
+
329
+ **Q: "Rate limit exceeded"**
330
+ A: Wait a moment or upgrade your API plan
331
+
332
+ **Q: "groupId is not defined"**
333
+ A: Get your groupId from Convex dashboard → Data → groups table
334
+
335
+ **Q: "Module not found: ai"**
336
+ A: Run `npm install ai` in the correct directory
337
+
338
+ ## Related Documentation
339
+
340
+ - [Complete Implementation Guide](/one/knowledge/ai-sdk-implementation.md)
341
+ - [AG-UI Protocol](/one/knowledge/ag-ui-protocol.md)
342
+ - [Generative UI Patterns](/one/knowledge/generative-ui-patterns.md)
343
+ - [API Reference](/one/knowledge/ai-api-reference.md)
344
+ - [AI SDK Docs](https://ai-sdk.dev/)
345
+
346
+ ## Support
347
+
348
+ - **Discord**: Join our community
349
+ - **Email**: support@one.ie
350
+ - **GitHub**: Report issues
351
+
352
+ ---
353
+
354
+ **Congratulations!** You now have AI chat working in 5 minutes. 🎉
355
+