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
import Anthropic from "npm:@anthropic-ai/sdk@0.24.3";
export default async function(req: Request): Promise<Response> {
if (req.method === "OPTIONS") {
return new Response(null, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*",
},
});
}
// Check that your valtown API key is sent in the 'x-authorization' header
// Delete this line if you don't mind other parties hitting this endpoint
if (req.headers.get("x-authorization") !== Deno.env.get("valtown")) {
return new Response(null, {
status: 401,
});
}
try {
const body = await req.json();
const apiKey = req.headers.get("x-api-key");
if (!body) {
throw new Error("No body provided");
}
if (!apiKey) {
throw new Error("No API key provided");
}
const anthropic = new Anthropic({ apiKey });
if (body?.stream) {
let { readable, writable } = new TransformStream();
let writer = writable.getWriter();
const textEncoder = new TextEncoder();
anthropic.messages.stream(body).on("text", (data) => {
writer.write(textEncoder.encode(data));
}).on("end", () => {
writer.close();
});
return new Response(readable, {
headers: {
"Content-Type": "text/html",
},
});
} else {
const response = await anthropic.messages.create(body);
return Response.json(response);
}
} catch (e) {
if (e instanceof Anthropic.APIError) {
return Response.json(e.error, { status: e.status });
}
return Response.json({ ok: false }, { status: 500 });
}
}