-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
index.ts
320 lines (271 loc) · 9.67 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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import {
Content,
FunctionCallPart,
FunctionDeclaration,
Tool as GoogleFunctionCallTool,
GoogleGenerativeAI,
Part,
SchemaType,
} from '@google/generative-ai';
import { imageUrlToBase64 } from '@/utils/imageToBase64';
import { safeParseJSON } from '@/utils/safeParseJSON';
import { LobeRuntimeAI } from '../BaseAI';
import { AgentRuntimeErrorType, ILobeAgentRuntimeErrorType } from '../error';
import {
ChatCompetitionOptions,
ChatCompletionTool,
ChatStreamPayload,
OpenAIChatMessage,
UserMessageContentPart,
} from '../types';
import { ModelProvider } from '../types/type';
import { AgentRuntimeError } from '../utils/createError';
import { debugStream } from '../utils/debugStream';
import { StreamingResponse } from '../utils/response';
import { GoogleGenerativeAIStream, convertIterableToStream } from '../utils/streams';
import { parseDataUri } from '../utils/uriParser';
enum HarmCategory {
HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',
HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',
HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',
HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
}
enum HarmBlockThreshold {
BLOCK_NONE = 'BLOCK_NONE',
}
export class LobeGoogleAI implements LobeRuntimeAI {
private client: GoogleGenerativeAI;
baseURL?: string;
constructor({ apiKey, baseURL }: { apiKey?: string; baseURL?: string } = {}) {
if (!apiKey) throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);
this.client = new GoogleGenerativeAI(apiKey);
this.baseURL = baseURL;
}
async chat(rawPayload: ChatStreamPayload, options?: ChatCompetitionOptions) {
try {
const payload = this.buildPayload(rawPayload);
const model = payload.model;
const contents = await this.buildGoogleMessages(payload.messages, model);
const geminiStreamResult = await this.client
.getGenerativeModel(
{
generationConfig: {
maxOutputTokens: payload.max_tokens,
temperature: payload.temperature,
topP: payload.top_p,
},
model,
// avoid wide sensitive words
// refs: https://github.com/lobehub/lobe-chat/pull/1418
safetySettings: [
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
],
},
{ apiVersion: 'v1beta', baseUrl: this.baseURL },
)
.generateContentStream({
contents,
systemInstruction: payload.system as string,
tools: this.buildGoogleTools(payload.tools),
});
const googleStream = convertIterableToStream(geminiStreamResult.stream);
const [prod, useForDebug] = googleStream.tee();
if (process.env.DEBUG_GOOGLE_CHAT_COMPLETION === '1') {
debugStream(useForDebug).catch();
}
// Convert the response into a friendly text-stream
const stream = GoogleGenerativeAIStream(prod, options?.callback);
// Respond with the stream
return StreamingResponse(stream, { headers: options?.headers });
} catch (e) {
const err = e as Error;
const { errorType, error } = this.parseErrorMessage(err.message);
throw AgentRuntimeError.chat({ error, errorType, provider: ModelProvider.Google });
}
}
private buildPayload(payload: ChatStreamPayload) {
const system_message = payload.messages.find((m) => m.role === 'system');
const user_messages = payload.messages.filter((m) => m.role !== 'system');
return {
...payload,
messages: user_messages,
system: system_message?.content,
};
}
private convertContentToGooglePart = async (content: UserMessageContentPart): Promise<Part> => {
switch (content.type) {
case 'text': {
return { text: content.text };
}
case 'image_url': {
const { mimeType, base64, type } = parseDataUri(content.image_url.url);
if (type === 'base64') {
if (!base64) {
throw new TypeError("Image URL doesn't contain base64 data");
}
return {
inlineData: {
data: base64,
mimeType: mimeType || 'image/png',
},
};
}
if (type === 'url') {
const { base64, mimeType } = await imageUrlToBase64(content.image_url.url);
return {
inlineData: {
data: base64,
mimeType,
},
};
}
throw new TypeError(`currently we don't support image url: ${content.image_url.url}`);
}
}
};
private convertOAIMessagesToGoogleMessage = async (
message: OpenAIChatMessage,
): Promise<Content> => {
const content = message.content as string | UserMessageContentPart[];
if (!!message.tool_calls) {
return {
parts: message.tool_calls.map<FunctionCallPart>((tool) => ({
functionCall: {
args: safeParseJSON(tool.function.arguments)!,
name: tool.function.name,
},
})),
role: 'function',
};
}
return {
parts:
typeof content === 'string'
? [{ text: content }]
: await Promise.all(content.map(async (c) => await this.convertContentToGooglePart(c))),
role: message.role === 'assistant' ? 'model' : 'user',
};
};
// convert messages from the OpenAI format to Google GenAI SDK
private buildGoogleMessages = async (
messages: OpenAIChatMessage[],
model: string,
): Promise<Content[]> => {
// if the model is gemini-1.0 we need to pair messages
if (model.startsWith('gemini-1.0')) {
const contents: Content[] = [];
let lastRole = 'model';
for (const message of messages) {
// current to filter function message
if (message.role === 'function') {
continue;
}
const googleMessage = await this.convertOAIMessagesToGoogleMessage(message);
// if the last message is a model message and the current message is a model message
// then we need to add a user message to separate them
if (lastRole === googleMessage.role) {
contents.push({ parts: [{ text: '' }], role: lastRole === 'user' ? 'model' : 'user' });
}
// add the current message to the contents
contents.push(googleMessage);
// update the last role
lastRole = googleMessage.role;
}
// if the last message is a user message, then we need to add a model message to separate them
if (lastRole === 'model') {
contents.push({ parts: [{ text: '' }], role: 'user' });
}
return contents;
}
const pools = messages
.filter((message) => message.role !== 'function')
.map(async (msg) => await this.convertOAIMessagesToGoogleMessage(msg));
return Promise.all(pools);
};
private parseErrorMessage(message: string): {
error: any;
errorType: ILobeAgentRuntimeErrorType;
} {
const defaultError = {
error: { message },
errorType: AgentRuntimeErrorType.ProviderBizError,
};
if (message.includes('location is not supported'))
return { error: { message }, errorType: AgentRuntimeErrorType.LocationNotSupportError };
try {
const startIndex = message.lastIndexOf('[');
if (startIndex === -1) {
return defaultError;
}
// 从开始位置截取字符串到最后
const jsonString = message.slice(startIndex);
// 尝试解析 JSON 字符串
const json: GoogleChatErrors = JSON.parse(jsonString);
const bizError = json[0];
switch (bizError.reason) {
case 'API_KEY_INVALID': {
return { ...defaultError, errorType: AgentRuntimeErrorType.InvalidProviderAPIKey };
}
default: {
return { error: json, errorType: AgentRuntimeErrorType.ProviderBizError };
}
}
} catch {
// 如果解析失败,则返回原始错误消息
return defaultError;
}
}
private buildGoogleTools(
tools: ChatCompletionTool[] | undefined,
): GoogleFunctionCallTool[] | undefined {
if (!tools || tools.length === 0) return;
return [
{
functionDeclarations: tools.map((tool) => this.convertToolToGoogleTool(tool)),
},
];
}
private convertToolToGoogleTool = (tool: ChatCompletionTool): FunctionDeclaration => {
const functionDeclaration = tool.function;
const parameters = functionDeclaration.parameters;
// refs: https://github.com/lobehub/lobe-chat/pull/5002
const properties = parameters?.properties && Object.keys(parameters.properties).length > 0
? parameters.properties
: { dummy: { type: 'string' } }; // dummy property to avoid empty object
return {
description: functionDeclaration.description,
name: functionDeclaration.name,
parameters: {
description: parameters?.description,
properties: properties,
required: parameters?.required,
type: SchemaType.OBJECT,
},
};
};
}
export default LobeGoogleAI;
type GoogleChatErrors = GoogleChatError[];
interface GoogleChatError {
'@type': string;
'domain': string;
'metadata': {
service: string;
};
'reason': string;
}