forked from openai/openai-chatkit-starter-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
283 lines (251 loc) · 7.05 KB
/
route.ts
File metadata and controls
283 lines (251 loc) · 7.05 KB
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
import { WORKFLOW_ID } from "@/lib/config";
export const runtime = "edge";
interface CreateSessionRequestBody {
workflow?: { id?: string | null } | null;
scope?: { user_id?: string | null } | null;
workflowId?: string | null;
chatkit_configuration?: {
file_upload?: {
enabled?: boolean;
};
};
}
const DEFAULT_CHATKIT_BASE = "https://api.openai.com";
const SESSION_COOKIE_NAME = "chatkit_session_id";
const SESSION_COOKIE_MAX_AGE = 60 * 60 * 24 * 30; // 30 days
export async function POST(request: Request): Promise<Response> {
if (request.method !== "POST") {
return methodNotAllowedResponse();
}
let sessionCookie: string | null = null;
try {
const openaiApiKey = process.env.OPENAI_API_KEY;
if (!openaiApiKey) {
return new Response(
JSON.stringify({
error: "Missing OPENAI_API_KEY environment variable",
}),
{
status: 500,
headers: { "Content-Type": "application/json" },
}
);
}
const parsedBody = await safeParseJson<CreateSessionRequestBody>(request);
const { userId, sessionCookie: resolvedSessionCookie } =
await resolveUserId(request);
sessionCookie = resolvedSessionCookie;
const resolvedWorkflowId =
parsedBody?.workflow?.id ?? parsedBody?.workflowId ?? WORKFLOW_ID;
if (process.env.NODE_ENV !== "production") {
console.info("[create-session] handling request", {
resolvedWorkflowId,
body: JSON.stringify(parsedBody),
});
}
if (!resolvedWorkflowId) {
return buildJsonResponse(
{ error: "Missing workflow id" },
400,
{ "Content-Type": "application/json" },
sessionCookie
);
}
const apiBase = process.env.CHATKIT_API_BASE ?? DEFAULT_CHATKIT_BASE;
const url = `${apiBase}/v1/chatkit/sessions`;
const upstreamResponse = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openaiApiKey}`,
"OpenAI-Beta": "chatkit_beta=v1",
},
body: JSON.stringify({
workflow: { id: resolvedWorkflowId },
user: userId,
chatkit_configuration: {
file_upload: {
enabled:
parsedBody?.chatkit_configuration?.file_upload?.enabled ?? false,
},
},
}),
});
if (process.env.NODE_ENV !== "production") {
console.info("[create-session] upstream response", {
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
});
}
const upstreamJson = (await upstreamResponse.json().catch(() => ({}))) as
| Record<string, unknown>
| undefined;
if (!upstreamResponse.ok) {
const upstreamError = extractUpstreamError(upstreamJson);
console.error("OpenAI ChatKit session creation failed", {
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
body: upstreamJson,
});
return buildJsonResponse(
{
error:
upstreamError ??
`Failed to create session: ${upstreamResponse.statusText}`,
details: upstreamJson,
},
upstreamResponse.status,
{ "Content-Type": "application/json" },
sessionCookie
);
}
const clientSecret = upstreamJson?.client_secret ?? null;
const expiresAfter = upstreamJson?.expires_after ?? null;
const responsePayload = {
client_secret: clientSecret,
expires_after: expiresAfter,
};
return buildJsonResponse(
responsePayload,
200,
{ "Content-Type": "application/json" },
sessionCookie
);
} catch (error) {
console.error("Create session error", error);
return buildJsonResponse(
{ error: "Unexpected error" },
500,
{ "Content-Type": "application/json" },
sessionCookie
);
}
}
export async function GET(): Promise<Response> {
return methodNotAllowedResponse();
}
function methodNotAllowedResponse(): Response {
return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
status: 405,
headers: { "Content-Type": "application/json" },
});
}
async function resolveUserId(request: Request): Promise<{
userId: string;
sessionCookie: string | null;
}> {
const existing = getCookieValue(
request.headers.get("cookie"),
SESSION_COOKIE_NAME
);
if (existing) {
return { userId: existing, sessionCookie: null };
}
const generated =
typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: Math.random().toString(36).slice(2);
return {
userId: generated,
sessionCookie: serializeSessionCookie(generated),
};
}
function getCookieValue(
cookieHeader: string | null,
name: string
): string | null {
if (!cookieHeader) {
return null;
}
const cookies = cookieHeader.split(";");
for (const cookie of cookies) {
const [rawName, ...rest] = cookie.split("=");
if (!rawName || rest.length === 0) {
continue;
}
if (rawName.trim() === name) {
return rest.join("=").trim();
}
}
return null;
}
function serializeSessionCookie(value: string): string {
const attributes = [
`${SESSION_COOKIE_NAME}=${encodeURIComponent(value)}`,
"Path=/",
`Max-Age=${SESSION_COOKIE_MAX_AGE}`,
"HttpOnly",
"SameSite=Lax",
];
if (process.env.NODE_ENV === "production") {
attributes.push("Secure");
}
return attributes.join("; ");
}
function buildJsonResponse(
payload: unknown,
status: number,
headers: Record<string, string>,
sessionCookie: string | null
): Response {
const responseHeaders = new Headers(headers);
if (sessionCookie) {
responseHeaders.append("Set-Cookie", sessionCookie);
}
return new Response(JSON.stringify(payload), {
status,
headers: responseHeaders,
});
}
async function safeParseJson<T>(req: Request): Promise<T | null> {
try {
const text = await req.text();
if (!text) {
return null;
}
return JSON.parse(text) as T;
} catch {
return null;
}
}
function extractUpstreamError(
payload: Record<string, unknown> | undefined
): string | null {
if (!payload) {
return null;
}
const error = payload.error;
if (typeof error === "string") {
return error;
}
if (
error &&
typeof error === "object" &&
"message" in error &&
typeof (error as { message?: unknown }).message === "string"
) {
return (error as { message: string }).message;
}
const details = payload.details;
if (typeof details === "string") {
return details;
}
if (details && typeof details === "object" && "error" in details) {
const nestedError = (details as { error?: unknown }).error;
if (typeof nestedError === "string") {
return nestedError;
}
if (
nestedError &&
typeof nestedError === "object" &&
"message" in nestedError &&
typeof (nestedError as { message?: unknown }).message === "string"
) {
return (nestedError as { message: string }).message;
}
}
if (typeof payload.message === "string") {
return payload.message;
}
return null;
}