-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathroute.ts
executable file
·229 lines (196 loc) · 6.56 KB
/
route.ts
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
import { OpenAIStream, StreamingTextResponse } from 'ai'
export const runtime = 'edge'
/**
* Stream AI Chat Messages from Langbase
*
* @param req
* @returns
*/
export async function POST(req: Request) {
try {
const { searchParams } = new URL(req.url);
const action = searchParams.get('action');
const body = await req.json();
const userApiKey = body.userApiKey;
const ownerLogin = body.ownerLogin;
if (action !== null && !userApiKey) {
throw new Error('User API Key is missing');
}
if (action !== null && !ownerLogin) {
throw new Error('Owner Login is missing');
}
if (!process.env.LANGBASE_PIPE_API_KEY) {
throw new Error(
'Please set LANGBASE_PIPE_API_KEY in your environment variables.'
)
}
if (action === 'createMemory') {
return handleCreateMemory(req, userApiKey)
} else if (action === 'uploadFile') {
return handleFileUpload(req, userApiKey, ownerLogin)
} else if (action === 'getMemorySets') {
return handleGetMemorySets(userApiKey)
} else if (action === 'updatePipe') {
const { memoryName } = body;
return updatePipe(ownerLogin, memoryName, userApiKey)
} else {
const endpointUrl = 'https://api.langbase.com/beta/chat'
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.LANGBASE_PIPE_API_KEY}`
}
// Get chat prompt messages and threadId from the client.
const { messages, threadId } = body
const requestBody = {
messages,
...(threadId && { threadId }) // Only include threadId if it exists
}
// Send the request to Langbase API.
const response = await fetch(endpointUrl, {
method: 'POST',
headers,
body: JSON.stringify(requestBody)
})
if (!response.ok) {
const res = await response.json()
throw new Error(`Error ${res.error.status}: ${res.error.message}`)
}
// Handle Langbase response, which is a stream in OpenAI format.
const stream = OpenAIStream(response)
// Respond with a text stream.
return new StreamingTextResponse(stream, {
headers: response.headers
})
}
} catch (error: any) {
console.error('Uncaught API Error:', error)
return new Response(JSON.stringify(error), { status: 500 })
}
}
async function handleCreateMemory(req: Request, userApiKey: string) {
const { name, description } = await req.json()
const response = await fetch('https://api.langbase.com/beta/user/memorysets', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userApiKey}`
},
body: JSON.stringify({ name, description })
})
const data = await response.json()
return new Response(JSON.stringify(data), {
status: response.status,
headers: { 'Content-Type': 'application/json' }
})
}
async function handleFileUpload(req: Request, userApiKey: string, ownerLogin: string) {
const formData = await req.formData();
const file = formData.get('fileName') as File;
const memoryName = formData.get('memoryName') as string;
if (!file || !memoryName) {
return new Response(JSON.stringify({ error: 'Invalid file or memory name' }), { status: 400 });
}
const signedUrlResponse = await fetch('https://api.langbase.com/beta/user/memorysets/documents', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userApiKey}`
},
body: JSON.stringify({
memoryName: memoryName,
ownerLogin: ownerLogin,
fileName: file.name,
})
});
const { signedUrl } = await signedUrlResponse.json();
const uploadResponse = await fetch(signedUrl, {
method: 'PUT',
headers: {
'Content-Type': file.type,
},
body: file,
});
if (uploadResponse.ok) {
const pipeUpdateResponse = await updatePipe(ownerLogin, memoryName, userApiKey);
return new Response(JSON.stringify({
success: true,
fileUpload: uploadResponse.ok,
pipeUpdate: pipeUpdateResponse
}), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}
return new Response(JSON.stringify({ success: false }), {
status: uploadResponse.status,
headers: { 'Content-Type': 'application/json' }
});
}
async function updatePipe(ownerLogin: string | undefined, memoryName: string, userApiKey: string) {
if (!ownerLogin || !memoryName || !userApiKey) {
return new Response(JSON.stringify({ error: 'Missing required parameters' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
const url = `https://api.langbase.com/beta/pipes/${ownerLogin}/career-prep-coach`;
const pipe = {
name: "career-prep-coach",
description: "Your AI-powered personal interview coach, expertly preparing you for success using proven techniques and tailored feedback.",
status: "private",
config: {
memorysets: [memoryName]
}
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${userApiKey}`,
},
body: JSON.stringify(pipe),
});
const updatedPipe = await response.json();
return new Response(JSON.stringify(updatedPipe), {
status: response.status,
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.error('Error updating pipe:', error);
return new Response(JSON.stringify({ error: 'Failed to update pipe' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
};
async function handleGetMemorySets(userApiKey: string) {
const url = 'https://api.langbase.com/beta/user/memorysets';
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${userApiKey}`
}
});
if (!response.ok) {
const errorText = await response.text();
console.error('Error fetching memory sets:', response.status, errorText);
return new Response(JSON.stringify({
success: false,
error: {
code: 'BAD_REQUEST',
status: response.status,
message: errorText,
docs: 'https://langbase.com/docs/api-reference/errors/bad_request'
}
}), {
status: response.status,
headers: { 'Content-Type': 'application/json' }
});
}
const memorySetsList = await response.json();
return new Response(JSON.stringify(memorySetsList), {
headers: { 'Content-Type': 'application/json' }
});
}