Readme

This Val will proxy anthropic HTTP requests from some frontend client, like langchain, so that you can utilize anthropic apis from the browser.

Convert it to an HTTP val in order to use it (you may want to setup an ENV var / header to protect the endpoint with a secret key)

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 });
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
August 24, 2024