Skip to content

Commit a5982f9

Browse files
committed
lfg
1 parent 7ec0bcd commit a5982f9

33 files changed

+5690
-376
lines changed

app/(chat)/api/chat/delete-all/route.ts

Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,18 @@ export async function DELETE(request: Request) {
1919

2020
// Get the container tag to delete from Supermemory
2121
const containerTag = session.user.id;
22-
console.log('[Delete All] Starting deletion for containerTag:', containerTag);
22+
console.log(
23+
'[Delete All] Starting deletion for containerTag:',
24+
containerTag,
25+
);
2326

2427
// Delete all memories from Supermemory using the bulk delete endpoint
2528
const supermemoryApiKey = process.env.SUPERMEMORY_API_KEY;
2629
if (!supermemoryApiKey) {
2730
console.error('[Delete All] SUPERMEMORY_API_KEY not configured');
28-
return new NextResponse('Supermemory API key not configured', { status: 500 });
31+
return new NextResponse('Supermemory API key not configured', {
32+
status: 500,
33+
});
2934
}
3035

3136
console.log('[Delete All] Sending bulk delete request to Supermemory...');
@@ -35,28 +40,46 @@ export async function DELETE(request: Request) {
3540
};
3641
console.log('[Delete All] Request body:', JSON.stringify(requestBody));
3742

38-
const deleteMemoriesResponse = await fetch('https://api.supermemory.ai/v3/documents/bulk', {
39-
method: 'DELETE',
40-
headers: {
41-
'Authorization': `Bearer ${supermemoryApiKey}`,
42-
'Content-Type': 'application/json',
43+
const deleteMemoriesResponse = await fetch(
44+
'https://api.supermemory.ai/v3/documents/bulk',
45+
{
46+
method: 'DELETE',
47+
headers: {
48+
Authorization: `Bearer ${supermemoryApiKey}`,
49+
'Content-Type': 'application/json',
50+
},
51+
body: JSON.stringify(requestBody),
4352
},
44-
body: JSON.stringify(requestBody),
45-
});
53+
);
4654

47-
console.log('[Delete All] Supermemory response status:', deleteMemoriesResponse.status);
55+
console.log(
56+
'[Delete All] Supermemory response status:',
57+
deleteMemoriesResponse.status,
58+
);
4859

4960
if (!deleteMemoriesResponse.ok) {
5061
const errorText = await deleteMemoriesResponse.text();
51-
console.error('[Delete All] Failed to delete memories from Supermemory:', errorText);
52-
console.error('[Delete All] Response status:', deleteMemoriesResponse.status);
62+
console.error(
63+
'[Delete All] Failed to delete memories from Supermemory:',
64+
errorText,
65+
);
66+
console.error(
67+
'[Delete All] Response status:',
68+
deleteMemoriesResponse.status,
69+
);
5370
return new NextResponse('Failed to delete memories', { status: 500 });
5471
}
5572

5673
const deleteResult = await deleteMemoriesResponse.json();
57-
console.log('[Delete All] Successfully deleted memories:', JSON.stringify(deleteResult, null, 2));
74+
console.log(
75+
'[Delete All] Successfully deleted memories:',
76+
JSON.stringify(deleteResult, null, 2),
77+
);
5878
} catch (error) {
59-
console.error('[Delete All] Error deleting memories from Supermemory:', error);
79+
console.error(
80+
'[Delete All] Error deleting memories from Supermemory:',
81+
error,
82+
);
6083
return new NextResponse('Failed to delete memories', { status: 500 });
6184
}
6285

@@ -73,10 +96,13 @@ export async function DELETE(request: Request) {
7396
// Don't fail the whole operation if profile chat deletion fails
7497
}
7598

76-
return NextResponse.json({
77-
success: true,
78-
message: 'All memories and conversation history deleted successfully',
79-
}, { status: 200 });
99+
return NextResponse.json(
100+
{
101+
success: true,
102+
message: 'All memories and conversation history deleted successfully',
103+
},
104+
{ status: 200 },
105+
);
80106
} catch (error) {
81107
console.error('Error in delete-all:', error);
82108
return new NextResponse('Internal Server Error', { status: 500 });

app/(chat)/api/chat/route.ts

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,57 @@ export async function POST(request: Request) {
142142
const containerTag = session.user.id;
143143
console.log('[Chat API] Using container tag:', containerTag);
144144

145+
// Check if user has existing memories to determine if they're new
146+
let isNewUser = true;
147+
148+
// Only check for existing memories if this is the first message in a new conversation
149+
if (previousMessages.length === 0) {
150+
try {
151+
console.log(
152+
'[Chat API] Checking for existing memories for user:',
153+
containerTag,
154+
);
155+
const profileResponse = await fetch(
156+
'https://api.supermemory.ai/v4/profile',
157+
{
158+
method: 'POST',
159+
headers: {
160+
'Content-Type': 'application/json',
161+
Authorization: `Bearer ${supermemoryApiKey}`,
162+
},
163+
body: JSON.stringify({
164+
containerTag: containerTag,
165+
}),
166+
},
167+
);
168+
169+
if (profileResponse.ok) {
170+
const profileData = await profileResponse.json();
171+
// If profile exists and has content, user is not new
172+
if (profileData?.profile.length > 0) {
173+
isNewUser = false;
174+
console.log(
175+
'[Chat API] User has existing memories, not a new user',
176+
);
177+
} else {
178+
console.log(
179+
'[Chat API] No existing memories found, treating as new user',
180+
);
181+
}
182+
}
183+
} catch (error) {
184+
console.error(
185+
'[Chat API] Error checking for existing memories:',
186+
error,
187+
);
188+
// Default to treating as existing user if check fails to avoid unnecessary onboarding
189+
isNewUser = false;
190+
}
191+
} else {
192+
// If there are previous messages in this conversation, definitely not a new user
193+
isNewUser = false;
194+
}
195+
145196
// Create tools
146197
const memoryTools = createMemoryTools(supermemoryApiKey, containerTag);
147198
const webSearchTool = createWebSearchTool(exaApiKey);
@@ -176,7 +227,7 @@ export async function POST(request: Request) {
176227

177228
const result = streamText({
178229
model: modelWithMemory,
179-
system: systemPrompt({ selectedChatModel, requestHints }),
230+
system: systemPrompt({ selectedChatModel, requestHints, isNewUser }),
180231
messages: convertedMessages,
181232
tools: toolsConfig,
182233
stopWhen: stepCountIs(3), // Allows up to 3 steps for tool calls and responses

app/(chat)/api/documents/route.ts

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { auth } from '@/app/(auth)/auth';
2+
import { NextResponse } from 'next/server';
3+
4+
export const maxDuration = 30;
5+
6+
export async function POST(request: Request) {
7+
try {
8+
const session = await auth();
9+
10+
if (!session?.user) {
11+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
12+
}
13+
14+
if (!process.env.SUPERMEMORY_API_KEY) {
15+
return NextResponse.json(
16+
{ error: 'Supermemory API key not configured' },
17+
{ status: 500 },
18+
);
19+
}
20+
21+
// Parse request body
22+
const body = await request.json();
23+
const {
24+
page = 1,
25+
limit = 500, // Start with 500 documents
26+
sort = 'createdAt',
27+
order = 'desc',
28+
} = body;
29+
30+
// Always use user ID as container tag
31+
const containerTag = session.user.id;
32+
console.log('[Documents API] Using container tag:', containerTag);
33+
console.log('[Documents API] Fetching page:', page, 'limit:', limit);
34+
35+
try {
36+
// Fetch documents from Supermemory API
37+
const response = await fetch(
38+
'https://api.supermemory.ai/v3/documents/documents',
39+
{
40+
method: 'POST',
41+
headers: {
42+
'Content-Type': 'application/json',
43+
'x-api-key': process.env.SUPERMEMORY_API_KEY,
44+
},
45+
body: JSON.stringify({
46+
page,
47+
limit,
48+
sort,
49+
order,
50+
containerTags: [containerTag], // Filter by user's container tag only
51+
}),
52+
},
53+
);
54+
55+
if (!response.ok) {
56+
console.error(
57+
'[Documents API] Failed to fetch documents:',
58+
response.status,
59+
);
60+
const errorText = await response.text();
61+
console.error('[Documents API] Error details:', errorText);
62+
63+
return NextResponse.json(
64+
{
65+
documents: [],
66+
pagination: {
67+
currentPage: 1,
68+
totalPages: 0,
69+
totalItems: 0,
70+
limit: limit,
71+
},
72+
},
73+
{ status: 200 },
74+
);
75+
}
76+
77+
const data = await response.json();
78+
console.log(
79+
'[Documents API] Fetched',
80+
data.documents?.length || 0,
81+
'documents',
82+
);
83+
84+
console.log(data);
85+
86+
// Transform the data if needed to match the expected format
87+
const result = {
88+
documents: data.documents || [],
89+
pagination: data.pagination || {
90+
currentPage: page,
91+
totalPages: 0,
92+
totalItems: 0,
93+
limit: limit,
94+
},
95+
};
96+
97+
return NextResponse.json(result, { status: 200 });
98+
} catch (fetchError) {
99+
console.error(
100+
'[Documents API] Error fetching from Supermemory:',
101+
fetchError,
102+
);
103+
104+
// Return empty documents list if API fails
105+
return NextResponse.json(
106+
{
107+
documents: [],
108+
pagination: {
109+
currentPage: page,
110+
totalPages: 0,
111+
totalItems: 0,
112+
limit: limit,
113+
},
114+
},
115+
{ status: 200 },
116+
);
117+
}
118+
} catch (error) {
119+
console.error('[Documents API] Error:', error);
120+
return NextResponse.json(
121+
{ error: 'Internal server error' },
122+
{ status: 500 },
123+
);
124+
}
125+
}

0 commit comments

Comments
 (0)