1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
|
---
title: "Profile Examples"
description: "Complete code examples for integrating user profiles"
sidebarTitle: "Examples"
icon: "laptop-code"
---
## Building a Personalized Prompt
The most common use case: inject profile data into your LLM's system prompt.
<CodeGroup>
```typescript TypeScript
async function handleChatMessage(userId: string, message: string) {
// Get user profile
const profileResponse = await fetch('https://api.supermemory.ai/v4/profile', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ containerTag: userId })
});
const { profile } = await profileResponse.json();
// Build personalized system prompt
const systemPrompt = `You are assisting a user with the following context:
ABOUT THE USER:
${profile.static?.join('\n') || 'No profile information yet.'}
CURRENT CONTEXT:
${profile.dynamic?.join('\n') || 'No recent activity.'}
Provide responses personalized to their expertise level and preferences.`;
// Send to your LLM
const response = await llm.chat({
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: message }
]
});
return response;
}
```
```python Python
import requests
import os
async def handle_chat_message(user_id: str, message: str):
# Get user profile
response = requests.post(
'https://api.supermemory.ai/v4/profile',
headers={
'Authorization': f'Bearer {os.getenv("SUPERMEMORY_API_KEY")}',
'Content-Type': 'application/json'
},
json={'containerTag': user_id}
)
profile = response.json()['profile']
# Build personalized system prompt
static_facts = '\n'.join(profile.get('static', ['No profile information yet.']))
dynamic_context = '\n'.join(profile.get('dynamic', ['No recent activity.']))
system_prompt = f"""You are assisting a user with the following context:
ABOUT THE USER:
{static_facts}
CURRENT CONTEXT:
{dynamic_context}
Provide responses personalized to their expertise level and preferences."""
# Send to your LLM
llm_response = await llm.chat(
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": message}
]
)
return llm_response
```
</CodeGroup>
## Full Context Mode
Combine profile data with query-specific search for comprehensive context:
<CodeGroup>
```typescript TypeScript
async function getFullContext(userId: string, userQuery: string) {
// Single call gets both profile and search results
const response = await fetch('https://api.supermemory.ai/v4/profile', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
containerTag: userId,
q: userQuery // Include the user's query
})
});
const data = await response.json();
return {
// Static background about the user
userBackground: data.profile.static,
// Current activities and context
currentContext: data.profile.dynamic,
// Query-specific memories
relevantMemories: data.searchResults?.results || []
};
}
// Usage
const context = await getFullContext('user_123', 'deployment error last week');
const systemPrompt = `
User Background:
${context.userBackground.join('\n')}
Current Context:
${context.currentContext.join('\n')}
Relevant Information:
${context.relevantMemories.map(m => m.content).join('\n')}
`;
```
```python Python
async def get_full_context(user_id: str, user_query: str):
# Single call gets both profile and search results
response = requests.post(
'https://api.supermemory.ai/v4/profile',
headers={
'Authorization': f'Bearer {os.getenv("SUPERMEMORY_API_KEY")}',
'Content-Type': 'application/json'
},
json={
'containerTag': user_id,
'q': user_query # Include the user's query
}
)
data = response.json()
return {
'user_background': data['profile'].get('static', []),
'current_context': data['profile'].get('dynamic', []),
'relevant_memories': data.get('searchResults', {}).get('results', [])
}
# Usage
context = await get_full_context('user_123', 'deployment error last week')
system_prompt = f"""
User Background:
{chr(10).join(context['user_background'])}
Current Context:
{chr(10).join(context['current_context'])}
Relevant Information:
{chr(10).join(m['content'] for m in context['relevant_memories'])}
"""
```
</CodeGroup>
## Filtering with Threshold
Use the optional `threshold` parameter to filter search results by relevance score:
<CodeGroup>
```typescript TypeScript
async function getHighQualityContext(userId: string, userQuery: string) {
const response = await fetch('https://api.supermemory.ai/v4/profile', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
containerTag: userId,
threshold: 0.7, // Only include high-confidence results
q: userQuery
})
});
const data = await response.json();
// Only highly relevant memories are included
return data;
}
```
```python Python
async def get_high_quality_context(user_id: str, user_query: str):
response = requests.post(
'https://api.supermemory.ai/v4/profile',
headers={
'Authorization': f'Bearer {os.getenv("SUPERMEMORY_API_KEY")}',
'Content-Type': 'application/json'
},
json={
'containerTag': user_id,
'threshold': 0.7, # Only include high-confidence results
'q': user_query
}
)
data = response.json()
# Only highly relevant memories are included
return data
```
</CodeGroup>
## Separate Profile and Search
For more control, you can call profile and search endpoints separately:
```typescript TypeScript
async function advancedContext(userId: string, query: string) {
// Parallel requests for profile and search
const [profileRes, searchRes] = await Promise.all([
fetch('https://api.supermemory.ai/v4/profile', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ containerTag: userId })
}),
fetch('https://api.supermemory.ai/v3/search', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
q: query,
containerTag: userId,
limit: 5
})
})
]);
const profile = await profileRes.json();
const search = await searchRes.json();
return { profile: profile.profile, searchResults: search.results };
}
```
## Express.js Middleware
Add profile context to all authenticated requests:
```typescript TypeScript
import express from 'express';
// Middleware to fetch user profile
async function withUserProfile(req, res, next) {
if (!req.user?.id) {
return next();
}
try {
const response = await fetch('https://api.supermemory.ai/v4/profile', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ containerTag: req.user.id })
});
req.userProfile = await response.json();
} catch (error) {
console.error('Failed to fetch profile:', error);
req.userProfile = null;
}
next();
}
const app = express();
// Apply to all routes
app.use(withUserProfile);
app.post('/chat', async (req, res) => {
const { message } = req.body;
// Profile is automatically available
const profile = req.userProfile?.profile;
// Use in your LLM call...
});
```
## Next.js API Route
```typescript TypeScript
// app/api/chat/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
const { userId, message } = await req.json();
// Fetch profile
const profileRes = await fetch('https://api.supermemory.ai/v4/profile', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.SUPERMEMORY_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ containerTag: userId })
});
const { profile } = await profileRes.json();
// Build context and call your LLM...
const response = await generateResponse(message, profile);
return NextResponse.json({ response });
}
```
## AI SDK Integration
For the cleanest integration, use the Supermemory AI SDK middleware:
```typescript TypeScript
import { generateText } from "ai"
import { withSupermemory } from "@supermemory/tools/ai-sdk"
import { openai } from "@ai-sdk/openai"
// One line setup - profiles automatically injected
const model = withSupermemory(openai("gpt-4"), "user-123")
const result = await generateText({
model,
messages: [{ role: "user", content: "Help me with my current project" }]
})
// Model automatically has access to user's profile!
```
<Card title="AI SDK User Profiles" icon="triangle" href="/ai-sdk/user-profiles">
Learn more about automatic profile injection with the AI SDK
</Card>
|