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
// This val implements a function to call the Claude API using fetch.
// It handles the API request and response processing.
// The Claude API key is expected to be provided in the request headers.
// CORS is enabled for all origins.
export default async function server(req: Request): Promise<Response> {
// Handle preflight requests
if (req.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, x-api-key",
},
});
}
if (req.method !== "POST") {
return new Response("Method Not Allowed", { status: 405 });
}
const apiKey = req.headers.get("x-api-key");
if (!apiKey) {
return new Response("Claude API key not provided in headers", { status: 400 });
}
try {
const body = await req.text();
const params = JSON.parse(body);
const systemPrompt = params["system_prompt"];
const userPrompt = params["user_prompt"];
const claudeResponse = await callClaudeApi(systemPrompt, userPrompt, apiKey);
return new Response(claudeResponse, {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
} catch (error) {
console.error("Error:", error);
return new Response(`Error: ${error.message}`, {
status: 400,
headers: {
"Access-Control-Allow-Origin": "*",
},
});
}
}
async function callClaudeApi(systemPrompt: string, userPrompt: string, apiKey: string): Promise<string> {
const url = "https://api.anthropic.com/v1/messages";
const headers = {
"Content-Type": "application/json",
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"anthropic-beta": "prompt-caching-2024-07-31",
};
const data = {
"model": "claude-3-5-sonnet-20240620",
"max_tokens": 1000,
"temperature": 0,
"system": [
{
"type": "text",
"text": systemPrompt,
"cache_control": { "type": "ephemeral" },
},
],
"messages": [
{
"role": "user",
"content": userPrompt,
},
],
};
try {
const response = await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(data),
});
const responseData = await response.json();
console.log("Claude API response:", responseData);
if (response.ok) {
return responseData.content[0].text;
} else {
throw new Error(`API Error: ${response.status}, ${JSON.stringify(responseData)}`);
}
} catch (error) {
console.error("Error calling Claude API:", error);
throw error;
}
}