-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcf_ai.ts
72 lines (70 loc) · 1.93 KB
/
cf_ai.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const CLOUDFLARE_ACCOUNT_ID = Deno.env.get('CLOUDFLARE_ACCOUNT_ID') || '';
const CLOUDFLARE_AUTH_TOKEN = Deno.env.get('CLOUDFLARE_AUTH_TOKEN') || '';
export async function cfAI(
prompt: string,
system: string = 'you are a AI helper.',
): Promise<string> {
const url = 'https://api.cloudflare.com/client/v4/accounts/' +
CLOUDFLARE_ACCOUNT_ID +
'/ai/run/@cf/meta/llama-3-8b-instruct';
const payload = {
temperature: 0.01,
stream: false,
messages: [
{ 'role': 'system', 'content': system },
{ 'role': 'user', 'content': prompt },
],
};
const options = {
method: 'POST',
headers: {
'Authorization': `Bearer ${CLOUDFLARE_AUTH_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(
`Failed to fetch ${url}: ${response.statusText} ${await response
.text()}`,
);
}
const result: { result: { response: string }; success: boolean } =
await response.json();
if (!result.success) {
throw new Error(`Failed to fetch ${url}: ${result}`);
}
return result.result.response;
}
export async function cfAIstream(
prompt: string,
system: string = 'you are a AI helper.',
): Promise<ReadableStreamDefaultReader<Uint8Array>> {
const url = 'https://api.cloudflare.com/client/v4/accounts/' +
CLOUDFLARE_ACCOUNT_ID + '/ai/run/@cf/meta/llama-3-8b-instruct';
const payload = {
temperature: 0.01,
stream: true,
messages: [
{ 'role': 'system', 'content': system },
{ 'role': 'user', 'content': prompt },
],
};
const options = {
method: 'POST',
headers: {
'Authorization': `Bearer ${CLOUDFLARE_AUTH_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(
`Failed to fetch ${url}: ${response.statusText} ${await response
.text()}`,
);
}
return response.body!.getReader();
}