forked from xiangsx/gpt4free-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
99 lines (93 loc) · 2.35 KB
/
index.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
87
88
89
90
91
92
93
94
95
96
97
98
99
import {
Chat,
ChatOptions,
ChatRequest,
ChatResponse,
ModelType,
} from '../base';
import { AxiosInstance, AxiosRequestConfig, CreateAxiosDefaults } from 'axios';
import { CreateAxiosProxy } from '../../utils/proxyAgent';
import es from 'event-stream';
import {
ErrorData,
Event,
EventStream,
MessageData,
parseJSON,
} from '../../utils';
interface Message {
role: string;
content: string;
}
interface RealReq {
messages: Message[];
stream: boolean;
model: string;
temperature: number;
presence_penalty: number;
}
export class Mcbbs extends Chat {
private client: AxiosInstance;
constructor(options?: ChatOptions) {
super(options);
this.client = CreateAxiosProxy({
baseURL: 'https://ai.88lin.eu.org/api',
headers: {
'Content-Type': 'application/json',
accept: 'text/event-stream',
'Cache-Control': 'no-cache',
'Proxy-Connection': 'keep-alive',
},
} as CreateAxiosDefaults);
}
support(model: ModelType): number {
switch (model) {
case ModelType.GPT3p5Turbo:
return 4000;
case ModelType.GPT3p5_16k:
return 15000;
default:
return 0;
}
}
public async askStream(req: ChatRequest, stream: EventStream) {
const data: RealReq = {
stream: true,
messages: [{ role: 'user', content: req.prompt }],
temperature: 1,
presence_penalty: 2,
model: 'gpt-3.5-turbo',
};
try {
const res = await this.client.post('/openai/v1/chat/completions', data, {
responseType: 'stream',
} as AxiosRequestConfig);
res.data.pipe(es.split(/\r?\n\r?\n/)).pipe(
es.map(async (chunk: any, cb: any) => {
const dataStr = chunk.replace('data: ', '');
if (dataStr === '[DONE]') {
stream.write(Event.done, { content: '' });
return;
}
const data = parseJSON(dataStr, {} as any);
if (!data?.choices) {
cb(null, '');
return;
}
const [
{
delta: { content = '' },
},
] = data.choices;
stream.write(Event.message, { content });
}),
);
res.data.on('close', () => {
stream.end();
});
} catch (e: any) {
console.error(e.message);
stream.write(Event.error, { error: e.message });
}
}
}