-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessQuery.js
44 lines (38 loc) · 1.25 KB
/
processQuery.js
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
// Documentation at https://github.com/ollama/ollama/blob/main/docs/api.md
export async function processQuery(url, prompt) {
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ model: "llama3.2", prompt: "Answer with a short message. " + prompt }),
}
const response = await fetch(url, config)
if (!response.ok) {
throw new Error(`Error fetching data: ${response.statusText}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
const data = [];
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const lines = decoder.decode(value, { stream: true }).split('\n');
for (const line of lines) {
if (line.trim()) {
try {
const parsed = JSON.parse(line);
if (parsed.done) {
break
}
data.push(parsed.response);
} catch (error) {
throw new Error(`Error parsing JSON: ${error.message}`);
}
}
}
}
return data.join("");
}