forked from vespaiach/axios-fetch-adapter
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.test.ts
86 lines (76 loc) · 2.21 KB
/
index.test.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import axios from "axios";
import fetchAdapter from "./index";
import { EventSourceParseCallback, createParser } from "eventsource-parser";
it("post request", async () => {
const ax = axios.create({
adapter: fetchAdapter,
});
let response = await ax.request({
url: "https://httpbin.org/post",
method: "post",
data: { hello: "world" },
adapter: fetchAdapter,
});
expect(JSON.parse(response.data.data)).toStrictEqual({ hello: "world" });
});
it("stream openai", async () => {
const ax = axios.create({
adapter: fetchAdapter,
});
let response = await ax.request({
url: "https://api.openai.com/v1/chat/completions",
method: "post",
responseType: "stream",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
data: {
stream: true,
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
],
},
adapter: fetchAdapter,
});
const decoder = new TextDecoder();
const stream = new ReadableStream({
async start(controller) {
const encoder = new TextEncoder();
const onParse: EventSourceParseCallback = (event) => {
if (event.type === "event") {
const data = event.data;
if (data === "[DONE]") {
controller.close();
return;
}
try {
const json = JSON.parse(data);
const text = json.choices[0].delta.content;
const queue = encoder.encode(text);
controller.enqueue(queue);
} catch (e) {
controller.error(e);
}
}
};
const parser = createParser(onParse);
const reader = response.data.getReader();
let done = false;
while (!done) {
const { value: chunk, done: doneReading } = await reader.read();
done = doneReading;
parser.feed(decoder.decode(chunk));
}
},
});
const reader = stream.getReader();
let done = false;
while (!done) {
const { value, done: doneReading } = await reader.read();
done = doneReading;
console.log(decoder.decode(value));
}
console.log("Stream finished");
}, 20000);