forked from xiangsx/gpt4free-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.ts
61 lines (50 loc) · 1.43 KB
/
base.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
import {EventStream, getTokenSize} from "../utils";
export interface ChatOptions {
}
export interface ChatResponse {
content?: string;
error?: string;
}
export type Message = {
role: string;
content: string;
}
export enum ModelType {
GPT3p5Turbo = 'gpt3.5-turbo',
GPT4 = 'gpt4',
NetGpt3p5 = 'net-gpt3.5-turbo',
}
export interface ChatRequest {
prompt: string;
model: ModelType;
}
export function PromptToString(prompt: string, limit: number): string {
try {
const messages: Message[] = JSON.parse(prompt);
let result: Message[] = [];
let tokenSize = 0;
for (let i = messages.length - 1; i >= 0; i--) {
const item = messages[i];
const {role, content} = item;
tokenSize += getTokenSize(content);
if (tokenSize > limit) {
break;
}
result.push(item);
}
return `${result.reverse().map(item => `${item.role}
: ${item.content}
`).join('\n')}\nassistant: `;
} catch (e) {
return prompt;
}
}
export abstract class Chat {
protected options: ChatOptions | undefined;
protected constructor(options?: ChatOptions) {
this.options = options;
}
public abstract support(model: ModelType): number
public abstract ask(req: ChatRequest): Promise<ChatResponse>
public abstract askStream(req: ChatRequest, stream: EventStream): Promise<void>
}