Skip to content

Commit 0649a6b

Browse files
nextjs ai-sdk demo with stream storage and node library
1 parent feecfcf commit 0649a6b

File tree

12 files changed

+1224
-1
lines changed

12 files changed

+1224
-1
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ npm-debug.log*
55
yarn-debug.log*
66
yarn-error.log*
77
lerna-debug.log*
8-
8+
.DS_Store
99
# Diagnostic reports (https://nodejs.org/api/report.html)
1010
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
1111

examples/nextjs-ai-chatbot

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit b460603fb88dbd92a0e38d87edfb2b72575aa7d5

packages/node-sdk/README.md

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
# AI SDK Storage
2+
3+
A library that provides Stream Chat infrastructure integration for AI SDK, enabling persistent message storage and real-time chat functionality.
4+
5+
## Features
6+
7+
- 🚀 **Easy Integration**: Simple API for integrating with AI SDK
8+
- 💬 **Stream Chat**: Built on Stream Chat infrastructure for real-time messaging
9+
- 📁 **File Attachments**: Support for image and file uploads
10+
- 🔧 **TypeScript**: Full TypeScript support with comprehensive type definitions
11+
- 🛠️ **AI SDK Compatible**: Designed to work seamlessly with AI SDK's streaming APIs
12+
13+
## Installation
14+
15+
```bash
16+
npm install @stream-io/ai-sdk-storage
17+
```
18+
19+
## Quick Start
20+
21+
### 1. Basic Setup
22+
23+
```typescript
24+
import { createStreamStorageClient } from "@stream-io/ai-sdk-storage";
25+
26+
const { streamStorage, aiSDKStreamStorage } = createStreamStorageClient({
27+
apiKey: "your-stream-api-key",
28+
apiSecret: "your-stream-api-secret",
29+
botUserId: "ai-bot", // optional, defaults to 'ai-bot'
30+
adminUserId: "admin", // optional, defaults to 'admin'
31+
});
32+
```
33+
34+
### 2. Environment Variables
35+
36+
```bash
37+
STREAM_API_KEY=your-stream-api-key
38+
STREAM_API_SECRET=your-stream-api-secret
39+
STREAM_BOT_USER_ID=ai-bot # optional
40+
STREAM_ADMIN_USER_ID=admin # optional
41+
```
42+
43+
```typescript
44+
import { createConfigFromEnv } from "@stream-io/ai-sdk-storage";
45+
46+
const { streamStorage, aiSDKStreamStorage } = createStreamStorageClient(
47+
createConfigFromEnv()
48+
);
49+
```
50+
51+
## Usage Examples
52+
53+
### Basic Channel Management
54+
55+
```typescript
56+
// Create a new channel
57+
const channel = await streamStorage.getOrCreateChannel({
58+
userId: "user123",
59+
channelName: "Hi there",
60+
channelId: "optional-custom-id", // optional
61+
});
62+
63+
// Get all channels for a user
64+
const channels = await streamStorage.getChannels("user123");
65+
```
66+
67+
### Sending Messages
68+
69+
```typescript
70+
// Send a simple text message
71+
await streamStorage.sendMessage("channel-id", {
72+
text: "Hello, world!",
73+
userId: "user123",
74+
});
75+
76+
// Send a message with attachments
77+
await streamStorage.sendMessage("channel-id", {
78+
text: "Check out this image!",
79+
userId: "user123",
80+
attachments: [
81+
{
82+
url: "https://example.com/image.jpg",
83+
filename: "image.jpg",
84+
type: "image/jpeg",
85+
},
86+
],
87+
});
88+
```
89+
90+
### AI SDK Integration
91+
92+
```typescript
93+
import { streamText } from "ai";
94+
import { AISDKStreamStorage } from "@stream-io/ai-sdk-storage";
95+
96+
// Create AI SDK Stream Storage instance
97+
const aiSDKStorage = new AISDKStreamStorage(streamStorage);
98+
99+
// Handle AI SDK streaming with Stream Chat integration
100+
const result = streamText({
101+
model: yourModel,
102+
messages: convertToModelMessages(messages),
103+
onFinish: async (responseMessage) => {
104+
// Process AI response and send to Stream Chat
105+
await aiSDKStorage.processAIResponse("channel-id", responseMessage);
106+
},
107+
});
108+
109+
// Process user message with attachments
110+
const { processUserMessage } = await aiSDKStorage.handleStreamText(
111+
"channel-id",
112+
messages,
113+
userId,
114+
async (responseMessage) => {
115+
await aiSDKStorage.processAIResponse("channel-id", responseMessage);
116+
}
117+
);
118+
119+
await processUserMessage();
120+
```
121+
122+
### Complete Next.js API Route Example
123+
124+
```typescript
125+
import { NextRequest, NextResponse } from "next/server";
126+
import { streamText } from "ai";
127+
import {
128+
createStreamStorageClient,
129+
createConfigFromEnv,
130+
} from "@stream-io/ai-sdk-storage";
131+
132+
export async function POST(req: NextRequest) {
133+
const { messages, channelId, userId, channelName } = await req.json();
134+
135+
const { streamStorage, aiSDKStreamStorage } = createStreamStorageClient(
136+
createConfigFromEnv()
137+
);
138+
139+
const { processUserMessage, processAIResponse } =
140+
await storage.aiSDKStreamStorage.handleStreamText(
141+
id,
142+
messages,
143+
user_id,
144+
async (responseMessage) => {
145+
await storage.aiSDKStreamStorage.processAIResponse(id, responseMessage);
146+
}
147+
);
148+
149+
await processUserMessage();
150+
// Stream AI response
151+
const result = streamText({
152+
model: yourModel,
153+
messages: convertToModelMessages(messages),
154+
});
155+
156+
return result.toUIMessageStreamResponse({
157+
originalMessages: messages,
158+
onFinish: async ({ responseMessage }) => {
159+
await processAIResponse(responseMessage);
160+
},
161+
onError: (error) => {
162+
console.error(error, "error");
163+
return "Error: " + error;
164+
},
165+
});
166+
}
167+
```
168+
169+
## API Reference
170+
171+
### StreamStorage
172+
173+
The main class for Stream Chat operations.
174+
175+
#### Methods
176+
177+
- `createChannel(options: CreateChannelOptions): Promise<Channel | null>`
178+
- `getChannels(userId: string): Promise<Channel[] | null>`
179+
- `sendMessage(channelId: string, options: SendMessageOptions): Promise<any>`
180+
- `sendImage(channelId: string, imageStream: ReadableStream, filename: string, mediaType: string, userId: string): Promise<any>`
181+
- `processMessageParts(channelId: string, message: AISDKMessage, userId: string): Promise<ProcessedMessage>`
182+
- `getChannelData(channel: Channel): ChannelData`
183+
- `getChannelMessages(channelId: string): Promise<MessageResponse[]>`
184+
185+
### AISDKStreamStorage
186+
187+
Helper class for AI SDK integration.
188+
189+
#### Methods
190+
191+
- `handleStreamText(channelId: string, messages: AISDKMessage[], userId: string, onFinish: Function): Promise<StreamHandlers>`
192+
- `processAIResponse(channelId: string, responseMessage: any): Promise<void>`
193+
- `createChannelForAI(userId: string, channelName?: string, channelId?: string): Promise<Channel | null>`
194+
- `getUserChannels(userId: string): Promise<ChannelData[]>`
195+
- `generateChannelId(): string`
196+
197+
## Types
198+
199+
```typescript
200+
interface StreamStorageConfig {
201+
apiKey: string;
202+
apiSecret: string;
203+
botUserId?: string;
204+
adminUserId?: string;
205+
}
206+
207+
interface CreateChannelOptions {
208+
channelId?: string;
209+
channelName?: string;
210+
userId: string;
211+
members?: string[];
212+
metadata?: Record<string, any>;
213+
}
214+
215+
interface AISDKMessage {
216+
id?: string;
217+
role: "user" | "assistant" | "system";
218+
content: string;
219+
parts?: Array<{
220+
type: "text" | "file";
221+
text?: string;
222+
url?: string;
223+
filename?: string;
224+
mediaType?: string;
225+
}>;
226+
}
227+
```
228+
229+
## Error Handling
230+
231+
The library includes comprehensive error handling:
232+
233+
```typescript
234+
try {
235+
const channel = await streamStorage.getOrCreateChannel({
236+
userId: "user123",
237+
channelName: "Hi there",
238+
});
239+
240+
if (!channel) {
241+
console.error("Failed to create channel");
242+
return;
243+
}
244+
245+
// Use channel...
246+
} catch (error) {
247+
console.error("Error:", error);
248+
}
249+
```
250+
251+
## Contributing
252+
253+
1. Fork the repository
254+
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
255+
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
256+
4. Push to the branch (`git push origin feature/amazing-feature`)
257+
5. Open a Pull Request
258+
259+
## License
260+
261+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
262+
263+
## Support
264+
265+
For support, email [email protected].

packages/node-sdk/package.json

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
{
2+
"name": "@stream-io/ai-sdk-storage",
3+
"version": "1.0.0",
4+
"description": "AI SDK storage connector using Stream Chat infrastructure",
5+
"main": "dist/index.js",
6+
"private": true,
7+
"types": "dist/index.d.ts",
8+
"files": [
9+
"dist"
10+
],
11+
"scripts": {
12+
"build": "tsc",
13+
"dev": "tsc --watch",
14+
"prepublishOnly": "npm run build"
15+
},
16+
"keywords": [
17+
"ai-sdk",
18+
"stream-chat",
19+
"storage",
20+
"messaging",
21+
"ai",
22+
"chat"
23+
],
24+
"author": "GetStream",
25+
"license": "MIT",
26+
"dependencies": {
27+
"stream-chat": "^9.24.0"
28+
},
29+
"peerDependencies": {
30+
"ai": "^5.0.0"
31+
},
32+
"devDependencies": {
33+
"@types/node": "^20",
34+
"typescript": "^5"
35+
},
36+
"repository": {
37+
"type": "git",
38+
"url": "https://github.com/GetStream/ai-sdk-storage.git"
39+
},
40+
"bugs": {
41+
"url": "https://github.com/GetStream/ai-sdk-storage/issues"
42+
},
43+
"homepage": "https://github.com/GetStream/ai-sdk-storage#readme",
44+
"packageManager": "[email protected]+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610"
45+
}

0 commit comments

Comments
 (0)