-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhttp-stream-test.js
More file actions
68 lines (57 loc) · 1.55 KB
/
http-stream-test.js
File metadata and controls
68 lines (57 loc) · 1.55 KB
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
const url = "http://localhost:3000/services/job_chat/stream";
console.log("Starting HTTP stream request...");
const payload = {
content: "what are collections?",
history: [],
context: {
expression: "// write your job code here",
adaptor: "@openfn/language-salesforce@4.6.10",
input: null,
output: null,
log: null,
},
api_key: process.env.AI_ASSISTANT_API_KEY,
};
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
})
.then((response) => {
console.log("Connected!");
const reader = response.body.getReader();
const decoder = new TextDecoder();
function readStream() {
reader.read().then(({ done, value }) => {
if (done) {
console.log("Stream closed");
return;
}
const chunk = decoder.decode(value, { stream: true });
const lines = chunk.split("\n");
let eventType;
for (const line of lines) {
if (line.startsWith("event:")) {
eventType = line.substring(6).trim();
continue;
}
if (line.startsWith("data:")) {
const data = line.substring(5).trim();
try {
const parsed = JSON.parse(data);
console.log(`${eventType}:`, parsed);
} catch (e) {
// Skip empty or malformed data lines
}
}
}
readStream();
});
}
readStream();
})
.catch((error) => {
console.error("Connection failed:", error);
});