File size: 7,110 Bytes
6e6dab9
 
 
4e6658c
451c088
 
 
 
4b79bca
3a17e83
6e6dab9
0213430
 
6e6dab9
38880bf
6e6dab9
fb77726
38880bf
0213430
 
 
38880bf
0213430
 
6e6dab9
0213430
3132327
0213430
 
241c10d
786b7d7
0213430
 
 
 
7626743
6e6dab9
 
0213430
241c10d
 
 
 
 
3132327
7626743
 
 
 
 
6e6dab9
241c10d
6e6dab9
 
7626743
 
786b7d7
 
 
 
 
7626743
 
 
 
 
 
 
 
38880bf
0213430
7626743
 
6e6dab9
 
 
7626743
 
 
6e6dab9
7626743
 
6e6dab9
7626743
6e6dab9
 
ed18d7d
09f5b61
 
 
 
 
 
 
 
 
 
 
 
ed18d7d
a7bf5ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd2b0a7
a7bf5ad
 
 
4b79bca
 
a7bf5ad
4b79bca
045ac52
451c088
4b79bca
045ac52
 
 
4b79bca
 
6e6dab9
 
 
 
 
 
cf6dabc
d0e6713
ae31beb
d0e6713
cf6dabc
 
2fe3cee
cf6dabc
 
 
 
 
 
 
 
d0e6713
 
 
 
 
cf6dabc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a35d38
cf6dabc
 
 
 
5089a01
 
2fe3cee
 
cf6dabc
 
2fe3cee
 
 
 
 
cf6dabc
 
 
6e6dab9
cf6dabc
 
 
 
6e6dab9
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import {
    jsonize_stream_data,
    stringify_stream_bytes,
} from "./stream_jsonizer.js";
import {
    update_message,
    create_messager,
    get_request_messages,
    ContentDisplayerUpdater,
} from "../components/chat_operator.js";

import { get_current_agent_info } from "../storages/agent_storage.js";

export class ChatCompletionsRequester {
    constructor({
        prompt,
        model = null,
        openai_endpoint = null,
        temperature = null,
        top_p = null,
        max_output_tokens = null,
    } = {}) {
        this.agent_info = get_current_agent_info();
        console.log("agent_info:", this.agent_info);
        this.prompt = prompt;
        this.model_id_with_endpoint = this.agent_info.model;
        this.openai_endpoint =
            openai_endpoint || this.extract_openai_endpoint_and_model()[0];
        this.model = model || this.extract_openai_endpoint_and_model()[1];
        this.openai_api_key = this.extract_openai_endpoint_and_model()[2];
        this.system_prompt = this.agent_info.system_prompt;
        this.temperature = temperature || this.agent_info.temperature;
        this.top_p = top_p || this.agent_info.top_p;
        this.max_output_tokens =
            max_output_tokens || this.agent_info.max_output_tokens;
        this.backend_request_endpoint = "/chat/completions";
        this.controller = new AbortController();
    }
    extract_openai_endpoint_and_model() {
        let splits = this.model_id_with_endpoint.split("|");
        let openai_endpoint = splits[0];
        let model = splits[1];
        let openai_api_key = splits[2];
        return [openai_endpoint, model, openai_api_key];
    }
    construct_openai_request_headers() {
        this.backend_request_headers = {
            "Content-Type": "application/json",
        };
        this.openai_request_headers = {
            "Content-Type": "application/json",
            Authorization: `Bearer ${this.openai_api_key}`,
        };
    }
    construct_backend_request_body() {
        this.openai_request_messages = get_request_messages();
        this.system_message = {
            role: "system",
            content: this.system_prompt,
        };
        this.openai_request_messages.unshift(this.system_message);
        this.backend_request_body = {
            openai_endpoint: this.openai_endpoint,
            openai_request_method: "POST",
            openai_request_headers: this.openai_request_headers,
            openai_request_body: {
                model: this.model,
                messages: this.openai_request_messages,
                temperature: this.temperature,
                top_p: this.top_p,
                max_tokens: this.max_output_tokens,
                stream: true,
            },
        };
    }
    construct_request_params() {
        this.construct_openai_request_headers();
        this.construct_backend_request_body();
        this.backend_request_params = {
            method: "POST",
            headers: this.backend_request_headers,
            body: JSON.stringify(this.backend_request_body),
            signal: this.controller.signal,
            stream: true,
        };
    }
    create_messager_components() {
        create_messager({
            role: "user",
            content: this.prompt,
            model: "",
            nickname: "You",
        });
        create_messager({
            role: "assistant",
            content: "",
            model: this.model,
            nickname: `${this.agent_info.name} (${this.model})`,
        });
    }
    async handle_read_stream_data(reader, buffer = "") {
        const { done, value } = await reader.read();
        if (done && buffer.length === 0) {
            return;
        }
        buffer += done ? "" : stringify_stream_bytes(value);
        let new_line_index;
        while ((new_line_index = buffer.indexOf("\n")) !== -1) {
            let json_line = buffer.slice(0, new_line_index);
            buffer = buffer.slice(new_line_index + 1);
            try {
                let json_chunks = jsonize_stream_data(json_line);
                if (!this.content_displayer_updater) {
                    this.content_displayer_updater =
                        new ContentDisplayerUpdater();
                }
                update_message(json_chunks, this.content_displayer_updater);
            } catch (e) {
                console.warn("Invalid JSON:", json_line);
            }
        }
        return this.handle_read_stream_data(reader, buffer);
    }
    async post() {
        this.construct_request_params();
        let response = await fetch(
            this.backend_request_endpoint,
            this.backend_request_params
        );
        let reader = response.body.getReader();
        return this.handle_read_stream_data(reader);
    }
    stop() {
        this.controller.abort();
    }
}

export class AvailableModelsRequester {
    constructor(openai_endpoint, openai_api_key = null) {
        this.openai_endpoint = openai_endpoint;
        this.openai_api_key = openai_api_key;
        this.backend_request_endpoint = "/models";
        this.controller = new AbortController();
        this.available_models = [];
    }
    construct_openai_request_headers() {
        this.backend_request_headers = {
            "Content-Type": "application/json",
        };
        this.openai_request_headers = {
            "Content-Type": "application/json",
        };
        if (this.openai_api_key) {
            this.openai_request_headers[
                "Authorization"
            ] = `Bearer ${this.openai_api_key}`;
        }
    }
    construct_backend_request_body() {
        this.backend_request_body = {
            openai_endpoint: this.openai_endpoint,
            openai_request_method: "GET",
            openai_request_headers: this.openai_request_headers,
        };
    }
    construct_request_params() {
        this.construct_openai_request_headers();
        this.construct_backend_request_body();
        this.backend_request_params = {
            method: "POST",
            headers: this.backend_request_headers,
            body: JSON.stringify(this.backend_request_body),
            signal: this.controller.signal,
        };
    }
    async get() {
        this.construct_request_params();
        return fetch(this.backend_request_endpoint, this.backend_request_params)
            .then((response) => response.json())
            .then((response_json) => {
                let data = response_json.data;
                data.forEach((item) => {
                    if (!this.available_models.includes(item.id)) {
                        this.available_models.push(item.id);
                    }
                });
                console.log(
                    `get available_models of ${this.openai_endpoint}:`,
                    this.available_models
                );
                return this.available_models;
            })
            .catch((error) => {
                console.error("Error:", error);
            });
    }
    stop() {
        this.controller.abort();
    }
}