-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Gemini.ts
242 lines (220 loc) · 7.03 KB
/
Gemini.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
class Gemini extends BaseLLM {
static providerName: ModelProvider = "gemini";
static defaultOptions: Partial<LLMOptions> = {
model: "gemini-pro",
apiBase: "https://generativelanguage.googleapis.com/v1beta/",
};
// Function to convert completion options to Gemini format
private _convertArgs(options: CompletionOptions) {
const finalOptions: any = {}; // Initialize an empty object
// Map known options
if (options.topK) {
finalOptions.topK = options.topK;
}
if (options.topP) {
finalOptions.topP = options.topP;
}
if (options.temperature !== undefined && options.temperature !== null) {
finalOptions.temperature = options.temperature;
}
if (options.maxTokens) {
finalOptions.maxOutputTokens = options.maxTokens;
}
if (options.stop) {
finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== "");
}
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
options,
)) {
yield stripImages(message.content);
}
}
private removeSystemMessage(messages: ChatMessage[]) {
const msgs = [...messages];
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
}
}
return msgs;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
// Ensure this.apiBase is used if available, otherwise use default
const apiBase =
this.apiBase ||
Gemini.defaultOptions?.apiBase ||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
// Conditionally apply removeSystemMessage
const convertedMsgs = isV1API
? this.removeSystemMessage(messages)
: messages;
if (options.model.includes("gemini")) {
for await (const message of this.streamChatGemini(
convertedMsgs,
options,
)) {
yield message;
}
} else {
for await (const message of this.streamChatBison(
convertedMsgs,
options,
)) {
yield message;
}
}
}
private _continuePartToGeminiPart(part: MessagePart) {
return part.type === "text"
? {
text: part.text,
}
: {
inlineData: {
mimeType: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
this.apiBase,
);
// This feels hacky to repeat code from above function but was the quickest
// way to ensure system message re-formatting isn't done if user has specified v1
const apiBase =
this.apiBase ||
Gemini.defaultOptions?.apiBase ||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
const isV1API = apiBase.includes("/v1/");
const contents = messages
.map((msg) => {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
return {
role: msg.role === "assistant" ? "model" : "user",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this._continuePartToGeminiPart),
};
})
.filter((c) => c !== null);
const body = {
...this._convertArgs(options),
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&
!isV1API && {
systemInstruction: { parts: [{ text: this.systemMessage }] },
}),
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
let buffer = "";
for await (const chunk of streamResponse(response)) {
buffer += chunk;
if (buffer.startsWith("[")) {
buffer = buffer.slice(1);
}
if (buffer.endsWith("]")) {
buffer = buffer.slice(0, -1);
}
if (buffer.startsWith(",")) {
buffer = buffer.slice(1);
}
const parts = buffer.split("\n,");
let foundIncomplete = false;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
let data;
try {
data = JSON.parse(part);
} catch (e) {
foundIncomplete = true;
continue; // yo!
}
if (data.error) {
throw new Error(data.error.message);
}
// Check for existence of each level before accessing the final 'text' property
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
// Incrementally stream the content to make it smoother
const content = data.candidates[0].content.parts[0].text;
const words = content.split(/(\s+)/);
const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1);
while (words.length > 0) {
const wordsToYield = Math.min(3, words.length);
yield {
role: "assistant",
content: words.splice(0, wordsToYield).join(""),
};
await delay(delaySeconds);
}
} else {
// Handle the case where the expected data structure is not found
console.warn("Unexpected response format:", data);
}
}
if (foundIncomplete) {
buffer = parts[parts.length - 1];
} else {
buffer = "";
}
}
}
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const msgList = [];
for (const message of messages) {
msgList.push({ content: message.content });
}
const apiURL = new URL(
`models/${options.model}:generateMessage?key=${this.apiKey}`,
this.apiBase,
);
const body = { prompt: { messages: msgList } };
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };
}
}
async function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
export default Gemini;