-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.ts
53 lines (44 loc) · 1.27 KB
/
server.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
import { askBingGenerator } from "https://deno.land/x/[email protected]/mod.ts";
import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { Application, Router } from "https://deno.land/x/[email protected]/mod.ts";
const askBingSchema = z.object({
userMessage: z.string(),
cookie: z.string(),
history: z.object({
author: z.enum(["user", "bot", "system"]),
text: z.string(),
}).array().optional(),
});
const app = new Application();
const router = new Router();
router.post("/chat", async (ctx) => {
const body = ctx.request.body({ type: "json" });
const params = askBingSchema.safeParse(await body.value);
if (!params.success) {
ctx.response.status = 400;
ctx.response.body = params.error;
return;
}
const abortController = new AbortController();
const result = askBingGenerator({
...params.data,
signal: abortController.signal,
});
const target = ctx.sendEvents();
target.addEventListener("close", () => {
abortController.abort();
});
setTimeout(async () => {
try {
for await (const event of result) {
target.dispatchMessage(event);
}
} catch {
abortController.abort();
} finally {
await target.close();
}
});
});
app.use(router.routes());
await app.listen({ port: 8000 });