@librechat/agents 4.2.6 → 4.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/cjs/harness/index.cjs +2 -0
- package/dist/cjs/harness/index.cjs.map +1 -1
- package/dist/cjs/harness/model.cjs +244 -0
- package/dist/cjs/harness/model.cjs.map +1 -0
- package/dist/cjs/harness/modelService.cjs +335 -0
- package/dist/cjs/harness/modelService.cjs.map +1 -0
- package/dist/cjs/harness/modelStreamCallbacks.cjs +102 -0
- package/dist/cjs/harness/modelStreamCallbacks.cjs.map +1 -0
- package/dist/cjs/harness/providerText.cjs +6 -1
- package/dist/cjs/harness/providerText.cjs.map +1 -1
- package/dist/cjs/llm/google/completion.cjs +49 -0
- package/dist/cjs/llm/google/completion.cjs.map +1 -0
- package/dist/cjs/llm/google/index.cjs +45 -20
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/transport.cjs +133 -0
- package/dist/cjs/llm/google/transport.cjs.map +1 -0
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +3 -18
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/modelCallbackRun.cjs +26 -0
- package/dist/cjs/llm/modelCallbackRun.cjs.map +1 -0
- package/dist/cjs/llm/stream/chunkAdapters.cjs +3 -2
- package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
- package/dist/cjs/main.cjs +12 -0
- package/dist/cjs/messages/index.cjs +1 -0
- package/dist/cjs/messages/stored.cjs +34 -0
- package/dist/cjs/messages/stored.cjs.map +1 -0
- package/dist/cjs/protection/providerText.cjs +68 -14
- package/dist/cjs/protection/providerText.cjs.map +1 -1
- package/dist/cjs/protection/providerTextAdmission.cjs +56 -0
- package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -0
- package/dist/esm/harness/index.mjs +2 -0
- package/dist/esm/harness/index.mjs.map +1 -1
- package/dist/esm/harness/model.mjs +241 -0
- package/dist/esm/harness/model.mjs.map +1 -0
- package/dist/esm/harness/modelService.mjs +334 -0
- package/dist/esm/harness/modelService.mjs.map +1 -0
- package/dist/esm/harness/modelStreamCallbacks.mjs +102 -0
- package/dist/esm/harness/modelStreamCallbacks.mjs.map +1 -0
- package/dist/esm/harness/providerText.mjs +7 -2
- package/dist/esm/harness/providerText.mjs.map +1 -1
- package/dist/esm/llm/google/completion.mjs +48 -0
- package/dist/esm/llm/google/completion.mjs.map +1 -0
- package/dist/esm/llm/google/index.mjs +46 -21
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/transport.mjs +133 -0
- package/dist/esm/llm/google/transport.mjs.map +1 -0
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +3 -18
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/modelCallbackRun.mjs +26 -0
- package/dist/esm/llm/modelCallbackRun.mjs.map +1 -0
- package/dist/esm/llm/stream/chunkAdapters.mjs +3 -2
- package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
- package/dist/esm/main.mjs +6 -2
- package/dist/esm/messages/index.mjs +1 -0
- package/dist/esm/messages/stored.mjs +34 -0
- package/dist/esm/messages/stored.mjs.map +1 -0
- package/dist/esm/protection/providerText.mjs +66 -15
- package/dist/esm/protection/providerText.mjs.map +1 -1
- package/dist/esm/protection/providerTextAdmission.mjs +56 -0
- package/dist/esm/protection/providerTextAdmission.mjs.map +1 -0
- package/dist/types/harness/index.d.ts +4 -0
- package/dist/types/harness/model.d.ts +104 -0
- package/dist/types/harness/modelService.d.ts +50 -0
- package/dist/types/harness/modelStreamCallbacks.d.ts +11 -0
- package/dist/types/harness/providerText.d.ts +5 -0
- package/dist/types/index.d.ts +4 -2
- package/dist/types/llm/google/completion.d.ts +4 -0
- package/dist/types/llm/google/index.d.ts +3 -1
- package/dist/types/llm/google/transport.d.ts +15 -0
- package/dist/types/llm/google/utils/common.d.ts +5 -3
- package/dist/types/llm/modelCallbackRun.d.ts +9 -0
- package/dist/types/llm/stream/chunkAdapters.d.ts +2 -1
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/stored.d.ts +7 -0
- package/dist/types/protection/providerText.d.ts +15 -1
- package/dist/types/protection/providerTextAdmission.d.ts +29 -0
- package/package.json +2 -1
- package/src/harness/index.ts +12 -0
- package/src/harness/model.ts +392 -0
- package/src/harness/modelService.ts +525 -0
- package/src/harness/modelStreamCallbacks.ts +137 -0
- package/src/harness/providerText.ts +13 -1
- package/src/index.ts +9 -0
- package/src/llm/google/completion.ts +91 -0
- package/src/llm/google/index.ts +95 -34
- package/src/llm/google/transport.ts +202 -0
- package/src/llm/google/utils/common.ts +6 -2
- package/src/llm/invoke.ts +3 -72
- package/src/llm/modelCallbackRun.ts +77 -0
- package/src/llm/stream/chunkAdapters.ts +3 -1
- package/src/messages/index.ts +1 -0
- package/src/messages/stored.ts +48 -0
- package/src/protection/providerText.ts +93 -14
- package/src/protection/providerTextAdmission.ts +86 -0
package/src/index.ts
CHANGED
|
@@ -126,11 +126,14 @@ export * from './rerank';
|
|
|
126
126
|
export {
|
|
127
127
|
PROVIDER_TEXT_PROTECTION_VERSION,
|
|
128
128
|
ProviderTextProtectionError,
|
|
129
|
+
serializeProviderTextProtectionError,
|
|
130
|
+
deserializeProviderTextProtectionError,
|
|
129
131
|
} from './protection/providerText';
|
|
130
132
|
export type {
|
|
131
133
|
ProviderTextProtection,
|
|
132
134
|
ProviderTextProtectionResult,
|
|
133
135
|
ProviderTextProtectionErrorCode,
|
|
136
|
+
ProviderTextProtectionFailure,
|
|
134
137
|
} from './protection/providerText';
|
|
135
138
|
|
|
136
139
|
export {
|
|
@@ -144,3 +147,9 @@ export type { GeminiReplayPart } from './llm/google/utils/signatures';
|
|
|
144
147
|
|
|
145
148
|
/* Host execution harness */
|
|
146
149
|
export * from './harness';
|
|
150
|
+
|
|
151
|
+
export { ProviderTextAdmission } from './protection/providerTextAdmission';
|
|
152
|
+
export type {
|
|
153
|
+
ProviderTextAdmissionLimits,
|
|
154
|
+
ProviderTextAdmissionSnapshot,
|
|
155
|
+
} from './protection/providerTextAdmission';
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FinishReason,
|
|
3
|
+
GoogleGenerativeAIRequestInputError,
|
|
4
|
+
GoogleGenerativeAIResponseError,
|
|
5
|
+
} from '@google/generative-ai';
|
|
6
|
+
import type {
|
|
7
|
+
Part,
|
|
8
|
+
FunctionCall,
|
|
9
|
+
GenerateContentRequest,
|
|
10
|
+
GenerateContentResponse,
|
|
11
|
+
EnhancedGenerateContentResponse,
|
|
12
|
+
} from '@google/generative-ai';
|
|
13
|
+
|
|
14
|
+
export function formatRequest(
|
|
15
|
+
input: GenerateContentRequest | string | (string | Part)[]
|
|
16
|
+
): GenerateContentRequest {
|
|
17
|
+
if (typeof input !== 'string' && !Array.isArray(input)) return input;
|
|
18
|
+
const parts: Part[] = [];
|
|
19
|
+
let functionParts = 0;
|
|
20
|
+
for (const value of typeof input === 'string' ? [input] : input) {
|
|
21
|
+
const part = typeof value === 'string' ? { text: value } : value;
|
|
22
|
+
if ('functionResponse' in part) functionParts++;
|
|
23
|
+
parts.push(part);
|
|
24
|
+
}
|
|
25
|
+
if (parts.length === 0) {
|
|
26
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
27
|
+
'No content is provided for sending chat message.'
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
if (functionParts !== 0 && functionParts !== parts.length) {
|
|
31
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
32
|
+
'Within a single message, FunctionResponse cannot be mixed with other types of part.'
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
contents: [{ role: functionParts > 0 ? 'function' : 'user', parts }],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Compatibility helpers promised by the inherited completionWithRetry API. */
|
|
41
|
+
export function enhanceResponse(
|
|
42
|
+
response: GenerateContentResponse
|
|
43
|
+
): EnhancedGenerateContentResponse {
|
|
44
|
+
function parts(): Part[] {
|
|
45
|
+
const candidate = response.candidates?.[0];
|
|
46
|
+
if (candidate == null && response.promptFeedback != null) {
|
|
47
|
+
throw new GoogleGenerativeAIResponseError(
|
|
48
|
+
'Response was blocked',
|
|
49
|
+
response
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
if (
|
|
53
|
+
candidate?.finishReason === FinishReason.SAFETY ||
|
|
54
|
+
candidate?.finishReason === FinishReason.RECITATION ||
|
|
55
|
+
candidate?.finishReason === FinishReason.LANGUAGE
|
|
56
|
+
) {
|
|
57
|
+
throw new GoogleGenerativeAIResponseError(
|
|
58
|
+
`Candidate was blocked due to ${candidate.finishReason}`,
|
|
59
|
+
response
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const content = candidate?.content;
|
|
63
|
+
return content?.parts ?? [];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function functionCalls(): FunctionCall[] | undefined {
|
|
67
|
+
const calls: FunctionCall[] = [];
|
|
68
|
+
for (const part of parts()) {
|
|
69
|
+
if (part.functionCall) calls.push(part.functionCall);
|
|
70
|
+
}
|
|
71
|
+
return calls.length > 0 ? calls : undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return Object.assign(response, {
|
|
75
|
+
text(): string {
|
|
76
|
+
let text = '';
|
|
77
|
+
for (const part of parts()) {
|
|
78
|
+
text += part.text ?? '';
|
|
79
|
+
if (part.executableCode) {
|
|
80
|
+
text += `\n\`\`\`${part.executableCode.language}\n${part.executableCode.code}\n\`\`\`\n`;
|
|
81
|
+
}
|
|
82
|
+
if (part.codeExecutionResult) {
|
|
83
|
+
text += `\n\`\`\`\n${part.codeExecutionResult.output}\n\`\`\`\n`;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return text;
|
|
87
|
+
},
|
|
88
|
+
functionCall: (): FunctionCall | undefined => functionCalls()?.[0],
|
|
89
|
+
functionCalls,
|
|
90
|
+
});
|
|
91
|
+
}
|
package/src/llm/google/index.ts
CHANGED
|
@@ -5,10 +5,13 @@ import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
|
|
|
5
5
|
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
6
6
|
import {
|
|
7
7
|
FunctionCallingMode,
|
|
8
|
-
|
|
8
|
+
GoogleGenerativeAIRequestInputError,
|
|
9
9
|
} from '@google/generative-ai';
|
|
10
10
|
import type {
|
|
11
11
|
GenerateContentRequest,
|
|
12
|
+
CachedContent,
|
|
13
|
+
ModelParams,
|
|
14
|
+
RequestOptions,
|
|
12
15
|
SafetySetting,
|
|
13
16
|
ToolConfig,
|
|
14
17
|
} from '@google/generative-ai';
|
|
@@ -25,6 +28,7 @@ import {
|
|
|
25
28
|
} from './utils/common';
|
|
26
29
|
import { smoothGenerationChunks } from '@/llm/stream/chunkAdapters';
|
|
27
30
|
import { resolveStreamDelay } from '@/llm/stream/smoother';
|
|
31
|
+
import { GoogleTransport } from './transport';
|
|
28
32
|
|
|
29
33
|
type GoogleToolConfigWithServerSideInvocations = ToolConfig & {
|
|
30
34
|
includeServerSideToolInvocations?: boolean;
|
|
@@ -40,6 +44,7 @@ type GoogleToolConfigWithServerSideInvocations = ToolConfig & {
|
|
|
40
44
|
|
|
41
45
|
export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
42
46
|
_lc_stream_delay: number;
|
|
47
|
+
private transport: GoogleTransport;
|
|
43
48
|
thinkingConfig?: ChatGoogleGenerativeAI['thinkingConfig'];
|
|
44
49
|
includeServerSideToolInvocations?: boolean;
|
|
45
50
|
|
|
@@ -126,8 +131,8 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
126
131
|
this.streaming = fields.streaming ?? this.streaming;
|
|
127
132
|
this.json = fields.json;
|
|
128
133
|
|
|
129
|
-
|
|
130
|
-
|
|
134
|
+
this.transport = new GoogleTransport(
|
|
135
|
+
this.apiKey,
|
|
131
136
|
{
|
|
132
137
|
model: this.model,
|
|
133
138
|
safetySettings: this.safetySettings as SafetySetting[],
|
|
@@ -148,9 +153,64 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
148
153
|
customHeaders: fields.customHeaders,
|
|
149
154
|
}
|
|
150
155
|
);
|
|
156
|
+
// @ts-ignore - The parent keeps its transport private.
|
|
157
|
+
this.client = this.transport;
|
|
151
158
|
this.streamUsage = fields.streamUsage ?? this.streamUsage;
|
|
152
159
|
}
|
|
153
160
|
|
|
161
|
+
useCachedContent(
|
|
162
|
+
cachedContent: CachedContent,
|
|
163
|
+
modelParams?: ModelParams,
|
|
164
|
+
requestOptions?: RequestOptions
|
|
165
|
+
): void {
|
|
166
|
+
if (this.apiKey == null || this.apiKey === '') return;
|
|
167
|
+
if (
|
|
168
|
+
cachedContent.name == null ||
|
|
169
|
+
cachedContent.name === '' ||
|
|
170
|
+
cachedContent.model == null ||
|
|
171
|
+
cachedContent.model === ''
|
|
172
|
+
) {
|
|
173
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
174
|
+
'Cached content must contain `name` and `model` fields.'
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
if (
|
|
178
|
+
modelParams?.model != null &&
|
|
179
|
+
modelParams.model !== '' &&
|
|
180
|
+
modelParams.model.replace(/^models\//, '') !==
|
|
181
|
+
cachedContent.model.replace(/^models\//, '')
|
|
182
|
+
) {
|
|
183
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
184
|
+
'Different model specified in modelParams and cachedContent.'
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
if (
|
|
188
|
+
modelParams?.systemInstruction != null &&
|
|
189
|
+
modelParams.systemInstruction !== '' &&
|
|
190
|
+
cachedContent.systemInstruction != null &&
|
|
191
|
+
cachedContent.systemInstruction !== '' &&
|
|
192
|
+
modelParams.systemInstruction !== cachedContent.systemInstruction
|
|
193
|
+
) {
|
|
194
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
195
|
+
'Different systemInstruction specified in modelParams and cachedContent.'
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
this.transport = new GoogleTransport(
|
|
199
|
+
this.apiKey,
|
|
200
|
+
{
|
|
201
|
+
...modelParams,
|
|
202
|
+
model: cachedContent.model,
|
|
203
|
+
systemInstruction: cachedContent.systemInstruction,
|
|
204
|
+
tools: cachedContent.tools,
|
|
205
|
+
toolConfig: cachedContent.toolConfig,
|
|
206
|
+
},
|
|
207
|
+
requestOptions,
|
|
208
|
+
cachedContent.name
|
|
209
|
+
);
|
|
210
|
+
// @ts-ignore - The parent keeps its transport private.
|
|
211
|
+
this.client = this.transport;
|
|
212
|
+
}
|
|
213
|
+
|
|
154
214
|
static lc_name(): 'LibreChatGoogleGenerativeAI' {
|
|
155
215
|
return 'LibreChatGoogleGenerativeAI';
|
|
156
216
|
}
|
|
@@ -212,15 +272,6 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
212
272
|
options?: this['ParsedCallOptions']
|
|
213
273
|
): Omit<GenerateContentRequest, 'contents'> {
|
|
214
274
|
const params = super.invocationParams(options);
|
|
215
|
-
if (this.thinkingConfig) {
|
|
216
|
-
/** @ts-ignore */
|
|
217
|
-
this.client.generationConfig = {
|
|
218
|
-
/** @ts-ignore */
|
|
219
|
-
...this.client.generationConfig,
|
|
220
|
-
/** @ts-ignore */
|
|
221
|
-
thinkingConfig: this.thinkingConfig,
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
275
|
if (
|
|
225
276
|
this.includeServerSideToolInvocations === true &&
|
|
226
277
|
Array.isArray(params.tools) &&
|
|
@@ -258,41 +309,38 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
258
309
|
this.model
|
|
259
310
|
);
|
|
260
311
|
let actualPrompt = prompt;
|
|
312
|
+
let systemInstruction: GenerateContentRequest['systemInstruction'];
|
|
261
313
|
if (prompt?.[0].role === 'system') {
|
|
262
|
-
|
|
263
|
-
/** @ts-ignore */
|
|
264
|
-
this.client.systemInstruction = systemInstruction;
|
|
314
|
+
[systemInstruction] = prompt;
|
|
265
315
|
actualPrompt = prompt.slice(1);
|
|
266
316
|
}
|
|
267
317
|
actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
|
|
268
318
|
const parameters = this.invocationParams(options);
|
|
269
319
|
const request = {
|
|
270
320
|
...parameters,
|
|
271
|
-
|
|
321
|
+
...(systemInstruction != null ? { systemInstruction } : {}),
|
|
322
|
+
contents: actualPrompt ?? [],
|
|
272
323
|
};
|
|
273
324
|
|
|
274
325
|
const res = await this.caller.callWithOptions(
|
|
275
326
|
{ signal: options.signal },
|
|
276
327
|
async () =>
|
|
277
|
-
|
|
278
|
-
this.client.generateContent(request)
|
|
328
|
+
this.transport.generateContent(request, { signal: options.signal })
|
|
279
329
|
);
|
|
280
330
|
|
|
281
331
|
const response = res.response;
|
|
282
332
|
const usageMetadata = this._convertToUsageMetadata(
|
|
283
|
-
|
|
284
|
-
response.usageMetadata,
|
|
333
|
+
response.usageMetadata as GeminiApiUsageMetadata | undefined,
|
|
285
334
|
this.model
|
|
286
335
|
);
|
|
287
336
|
|
|
288
|
-
/** @ts-ignore */
|
|
289
337
|
const generationResult = mapGenerateContentResultToChatResult(response, {
|
|
290
338
|
usageMetadata,
|
|
291
339
|
model: this.model,
|
|
292
340
|
});
|
|
293
341
|
|
|
294
342
|
await runManager?.handleLLMNewToken(
|
|
295
|
-
generationResult.generations[0]
|
|
343
|
+
generationResult.generations[0]?.text || '',
|
|
296
344
|
undefined,
|
|
297
345
|
undefined,
|
|
298
346
|
undefined,
|
|
@@ -307,12 +355,24 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
307
355
|
options: this['ParsedCallOptions'],
|
|
308
356
|
runManager?: CallbackManagerForLLMRun
|
|
309
357
|
): AsyncGenerator<ChatGenerationChunk> {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
358
|
+
const controller = new AbortController();
|
|
359
|
+
const upstreamSignal = options.signal
|
|
360
|
+
? AbortSignal.any([options.signal, controller.signal])
|
|
361
|
+
: controller.signal;
|
|
362
|
+
try {
|
|
363
|
+
yield* smoothGenerationChunks({
|
|
364
|
+
chunks: this._streamProviderChunks(messages, {
|
|
365
|
+
...options,
|
|
366
|
+
signal: upstreamSignal,
|
|
367
|
+
}),
|
|
368
|
+
delayMs: this._lc_stream_delay,
|
|
369
|
+
signal: options.signal,
|
|
370
|
+
runManager,
|
|
371
|
+
abortUpstream: () => controller.abort(),
|
|
372
|
+
});
|
|
373
|
+
} finally {
|
|
374
|
+
controller.abort();
|
|
375
|
+
}
|
|
316
376
|
}
|
|
317
377
|
|
|
318
378
|
private async *_streamProviderChunks(
|
|
@@ -326,23 +386,24 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
326
386
|
this.model
|
|
327
387
|
);
|
|
328
388
|
let actualPrompt = prompt;
|
|
389
|
+
let systemInstruction: GenerateContentRequest['systemInstruction'];
|
|
329
390
|
if (prompt?.[0].role === 'system') {
|
|
330
|
-
|
|
331
|
-
/** @ts-ignore */
|
|
332
|
-
this.client.systemInstruction = systemInstruction;
|
|
391
|
+
[systemInstruction] = prompt;
|
|
333
392
|
actualPrompt = prompt.slice(1);
|
|
334
393
|
}
|
|
335
394
|
actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
|
|
336
395
|
const parameters = this.invocationParams(options);
|
|
337
396
|
const request = {
|
|
338
397
|
...parameters,
|
|
339
|
-
|
|
398
|
+
...(systemInstruction != null ? { systemInstruction } : {}),
|
|
399
|
+
contents: actualPrompt ?? [],
|
|
340
400
|
};
|
|
341
401
|
const stream = await this.caller.callWithOptions(
|
|
342
402
|
{ signal: options.signal },
|
|
343
403
|
async () => {
|
|
344
|
-
|
|
345
|
-
|
|
404
|
+
const { stream } = await this.transport.generateContentStream(request, {
|
|
405
|
+
signal: options.signal,
|
|
406
|
+
});
|
|
346
407
|
return stream;
|
|
347
408
|
}
|
|
348
409
|
);
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { createParser } from 'eventsource-parser';
|
|
2
|
+
import { GoogleGenerativeAIFetchError } from '@google/generative-ai';
|
|
3
|
+
import type {
|
|
4
|
+
Content,
|
|
5
|
+
Part,
|
|
6
|
+
GenerateContentResult,
|
|
7
|
+
ErrorDetails,
|
|
8
|
+
GenerateContentRequest,
|
|
9
|
+
GenerateContentResponse,
|
|
10
|
+
ModelParams,
|
|
11
|
+
RequestOptions,
|
|
12
|
+
SingleRequestOptions,
|
|
13
|
+
} from '@google/generative-ai';
|
|
14
|
+
import type { EventSourceParser } from 'eventsource-parser';
|
|
15
|
+
import { enhanceResponse, formatRequest } from './completion';
|
|
16
|
+
|
|
17
|
+
type GoogleError = {
|
|
18
|
+
code?: number;
|
|
19
|
+
message?: string;
|
|
20
|
+
status?: string;
|
|
21
|
+
details?: ErrorDetails[];
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
type GoogleResponse = GenerateContentResponse & { error?: GoogleError };
|
|
25
|
+
|
|
26
|
+
function providerError(
|
|
27
|
+
error?: GoogleError,
|
|
28
|
+
status = 500,
|
|
29
|
+
statusText = ''
|
|
30
|
+
): GoogleGenerativeAIFetchError {
|
|
31
|
+
return new GoogleGenerativeAIFetchError(
|
|
32
|
+
error?.message ?? `Google request failed: ${status} ${statusText}`,
|
|
33
|
+
status,
|
|
34
|
+
statusText,
|
|
35
|
+
error?.details
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function formatSystemInstruction(
|
|
40
|
+
input: GenerateContentRequest['systemInstruction']
|
|
41
|
+
): Content | undefined {
|
|
42
|
+
if (input == null) return undefined;
|
|
43
|
+
if (typeof input === 'string') {
|
|
44
|
+
return { role: 'system', parts: [{ text: input }] };
|
|
45
|
+
}
|
|
46
|
+
if ('text' in input && input.text != null && input.text !== '') {
|
|
47
|
+
return { role: 'system', parts: [input] };
|
|
48
|
+
}
|
|
49
|
+
if ('parts' in input) {
|
|
50
|
+
return { ...input, role: input.role || 'system' };
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Follows LangChainJS's GenerateContentApiHandler fetch/SSE flow, retaining our wire contract. */
|
|
56
|
+
export class GoogleTransport {
|
|
57
|
+
readonly generationConfig: NonNullable<ModelParams['generationConfig']>;
|
|
58
|
+
|
|
59
|
+
constructor(
|
|
60
|
+
private readonly apiKey: string,
|
|
61
|
+
private readonly params: ModelParams,
|
|
62
|
+
private readonly options: RequestOptions = {},
|
|
63
|
+
private readonly cachedContent?: string
|
|
64
|
+
) {
|
|
65
|
+
this.generationConfig = params.generationConfig ?? {};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private async request(
|
|
69
|
+
request: GenerateContentRequest,
|
|
70
|
+
streaming: boolean,
|
|
71
|
+
options: SingleRequestOptions = {}
|
|
72
|
+
): Promise<Response> {
|
|
73
|
+
const { model, cachedContent, ...defaults } = this.params;
|
|
74
|
+
const cacheName = this.cachedContent ?? cachedContent?.name;
|
|
75
|
+
const requestOptions = { ...this.options, ...options };
|
|
76
|
+
const baseUrl = (
|
|
77
|
+
requestOptions.baseUrl ?? 'https://generativelanguage.googleapis.com'
|
|
78
|
+
).replace(/\/$/, '');
|
|
79
|
+
const apiVersion = requestOptions.apiVersion ?? 'v1beta';
|
|
80
|
+
const method = streaming
|
|
81
|
+
? 'streamGenerateContent?alt=sse'
|
|
82
|
+
: 'generateContent';
|
|
83
|
+
const url = `${baseUrl}/${apiVersion}/models/${model.replace(/^models\//, '')}:${method}`;
|
|
84
|
+
const headers = new Headers({
|
|
85
|
+
'content-type': 'application/json',
|
|
86
|
+
'x-goog-api-key': this.apiKey,
|
|
87
|
+
});
|
|
88
|
+
if (requestOptions.apiClient != null) {
|
|
89
|
+
headers.set('x-goog-api-client', requestOptions.apiClient);
|
|
90
|
+
}
|
|
91
|
+
new Headers(requestOptions.customHeaders).forEach((value, name) => {
|
|
92
|
+
headers.set(name, value);
|
|
93
|
+
});
|
|
94
|
+
const timeout = requestOptions.timeout;
|
|
95
|
+
const timeoutSignal =
|
|
96
|
+
timeout != null && timeout >= 0
|
|
97
|
+
? AbortSignal.timeout(Math.trunc(timeout))
|
|
98
|
+
: undefined;
|
|
99
|
+
const signal =
|
|
100
|
+
options.signal && timeoutSignal
|
|
101
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
102
|
+
: (options.signal ?? timeoutSignal);
|
|
103
|
+
const body: GenerateContentRequest = {
|
|
104
|
+
...defaults,
|
|
105
|
+
...(cacheName != null && cacheName !== ''
|
|
106
|
+
? { cachedContent: cacheName }
|
|
107
|
+
: {}),
|
|
108
|
+
...request,
|
|
109
|
+
systemInstruction: formatSystemInstruction(
|
|
110
|
+
request.systemInstruction ?? defaults.systemInstruction
|
|
111
|
+
),
|
|
112
|
+
};
|
|
113
|
+
const response = await fetch(
|
|
114
|
+
new Request(url, {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers,
|
|
117
|
+
body: JSON.stringify(body),
|
|
118
|
+
signal,
|
|
119
|
+
})
|
|
120
|
+
);
|
|
121
|
+
if (!response.ok) {
|
|
122
|
+
const payload: GoogleResponse | undefined = await response
|
|
123
|
+
.json()
|
|
124
|
+
.catch(() => undefined);
|
|
125
|
+
throw providerError(payload?.error, response.status, response.statusText);
|
|
126
|
+
}
|
|
127
|
+
return response;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async generateContent(
|
|
131
|
+
request: GenerateContentRequest | string | (string | Part)[],
|
|
132
|
+
options?: SingleRequestOptions
|
|
133
|
+
): Promise<GenerateContentResult> {
|
|
134
|
+
const response = await this.request(formatRequest(request), false, options);
|
|
135
|
+
const payload: GoogleResponse = await response.json();
|
|
136
|
+
if (payload.error) throw providerError(payload.error, payload.error.code);
|
|
137
|
+
return { response: enhanceResponse(payload) };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async generateContentStream(
|
|
141
|
+
request: GenerateContentRequest,
|
|
142
|
+
options?: SingleRequestOptions
|
|
143
|
+
): Promise<{ stream: AsyncGenerator<GenerateContentResponse> }> {
|
|
144
|
+
const controller = new AbortController();
|
|
145
|
+
const signal = options?.signal
|
|
146
|
+
? AbortSignal.any([options.signal, controller.signal])
|
|
147
|
+
: controller.signal;
|
|
148
|
+
try {
|
|
149
|
+
const response = await this.request(request, true, {
|
|
150
|
+
...options,
|
|
151
|
+
signal,
|
|
152
|
+
});
|
|
153
|
+
if (response.body == null)
|
|
154
|
+
throw new Error('Google response body is empty');
|
|
155
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
156
|
+
let parser: EventSourceParser;
|
|
157
|
+
const reader = response.body
|
|
158
|
+
.pipeThrough(
|
|
159
|
+
new TransformStream<Uint8Array, GenerateContentResponse>({
|
|
160
|
+
start(output): void {
|
|
161
|
+
parser = createParser({
|
|
162
|
+
onEvent(event): void {
|
|
163
|
+
const payload: GoogleResponse = JSON.parse(event.data);
|
|
164
|
+
if (payload.error)
|
|
165
|
+
throw providerError(payload.error, payload.error.code);
|
|
166
|
+
output.enqueue(payload);
|
|
167
|
+
},
|
|
168
|
+
onError(error): void {
|
|
169
|
+
throw error;
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
},
|
|
173
|
+
transform(chunk): void {
|
|
174
|
+
parser.feed(decoder.decode(chunk, { stream: true }));
|
|
175
|
+
},
|
|
176
|
+
flush(): void {
|
|
177
|
+
parser.feed(decoder.decode());
|
|
178
|
+
parser.feed('\n\n');
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
)
|
|
182
|
+
.getReader();
|
|
183
|
+
async function* stream(): AsyncGenerator<GenerateContentResponse> {
|
|
184
|
+
try {
|
|
185
|
+
for (;;) {
|
|
186
|
+
const { done, value } = await reader.read();
|
|
187
|
+
if (done) return;
|
|
188
|
+
yield value;
|
|
189
|
+
}
|
|
190
|
+
} finally {
|
|
191
|
+
controller.abort();
|
|
192
|
+
await reader.cancel().catch(() => undefined);
|
|
193
|
+
reader.releaseLock();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { stream: stream() };
|
|
197
|
+
} catch (error) {
|
|
198
|
+
controller.abort();
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
type InlineDataPart,
|
|
31
31
|
type FunctionCallPart,
|
|
32
32
|
type GenerateContentCandidate,
|
|
33
|
+
type GenerateContentResponse,
|
|
33
34
|
type EnhancedGenerateContentResponse,
|
|
34
35
|
type FunctionDeclaration as GenerativeAIFunctionDeclaration,
|
|
35
36
|
type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,
|
|
@@ -56,6 +57,9 @@ import { GoogleGenerativeAIToolType } from '../types';
|
|
|
56
57
|
export const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =
|
|
57
58
|
'__gemini_function_call_thought_signatures__';
|
|
58
59
|
|
|
60
|
+
type GoogleResponse = GenerateContentResponse &
|
|
61
|
+
Partial<EnhancedGenerateContentResponse>;
|
|
62
|
+
|
|
59
63
|
const DUMMY_SIGNATURE =
|
|
60
64
|
'ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==';
|
|
61
65
|
|
|
@@ -759,7 +763,7 @@ export function dropUnsupportedModelTurnPrefill<T extends { role: string }>(
|
|
|
759
763
|
}
|
|
760
764
|
|
|
761
765
|
export function convertResponseContentToChatGenerationChunk(
|
|
762
|
-
response:
|
|
766
|
+
response: GoogleResponse,
|
|
763
767
|
extra: {
|
|
764
768
|
usageMetadata?: UsageMetadata | undefined;
|
|
765
769
|
index: number;
|
|
@@ -937,7 +941,7 @@ export function convertResponseContentToChatGenerationChunk(
|
|
|
937
941
|
* Maps a Google GenerateContentResult to a LangChain ChatResult
|
|
938
942
|
*/
|
|
939
943
|
export function mapGenerateContentResultToChatResult(
|
|
940
|
-
response:
|
|
944
|
+
response: GoogleResponse,
|
|
941
945
|
extra?: {
|
|
942
946
|
usageMetadata: UsageMetadata | undefined;
|
|
943
947
|
model?: string;
|
package/src/llm/invoke.ts
CHANGED
|
@@ -2,11 +2,6 @@ import { concat } from '@langchain/core/utils/stream';
|
|
|
2
2
|
import { AIMessageChunk } from '@langchain/core/messages';
|
|
3
3
|
import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
|
|
4
4
|
import { getCallbackManagerForConfig } from '@langchain/core/runnables';
|
|
5
|
-
import {
|
|
6
|
-
CallbackManager,
|
|
7
|
-
CallbackManagerForLLMRun,
|
|
8
|
-
type Callbacks,
|
|
9
|
-
} from '@langchain/core/callbacks/manager';
|
|
10
5
|
import type { Serialized } from '@langchain/core/load/serializable';
|
|
11
6
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
12
7
|
import type { ChatGeneration } from '@langchain/core/outputs';
|
|
@@ -65,6 +60,7 @@ import { getContextOverflowInfo, isProviderCancellation } from '@/utils/errors';
|
|
|
65
60
|
import { ChatModelStreamHandler, dispatchesChatModelStream } from '@/stream';
|
|
66
61
|
import { Constants, ContentTypes, GraphEvents, Providers } from '@/common';
|
|
67
62
|
import { withProviderTextBoundary } from '@/llm/providerTextBoundary';
|
|
63
|
+
import { getModelCallbackRunManager } from '@/llm/modelCallbackRun';
|
|
68
64
|
import { PreparedSubagentError } from '@/tools/preparedSubagents';
|
|
69
65
|
import { assertNotTruncatedToolCall } from '@/llm/truncation';
|
|
70
66
|
import { resolveClientOptionsModel } from '@/llm/request';
|
|
@@ -478,45 +474,6 @@ function getMessageText(chunk: AIMessageChunk): string {
|
|
|
478
474
|
* Falls back to a custom-event dispatch if the id was never observed, so the
|
|
479
475
|
* host still records usage even when the native close is unavailable.
|
|
480
476
|
*/
|
|
481
|
-
/**
|
|
482
|
-
* Every callbacks source the real model run would compose beyond the per-call
|
|
483
|
-
* config. `model` here is whatever `createCallModel` produced — with tools
|
|
484
|
-
* that is `bindTools(...)`'s `RunnableBinding`, and a system runnable pipes a
|
|
485
|
-
* `RunnableSequence` on top — while `clientOptions.callbacks` lives on the
|
|
486
|
-
* chat model at the BOTTOM of that stack. Walks `bound` (bindings) and
|
|
487
|
-
* `last`/`steps` (sequences), collecting each wrapper's own `callbacks` and
|
|
488
|
-
* any binding-config callbacks along the way, since the binding merges its
|
|
489
|
-
* config into the call before the chat model composes.
|
|
490
|
-
*/
|
|
491
|
-
function collectModelCallbackSources(model: unknown): Callbacks[] {
|
|
492
|
-
const sources: Callbacks[] = [];
|
|
493
|
-
const seen = new Set<unknown>();
|
|
494
|
-
let current: unknown = model;
|
|
495
|
-
while (current != null && typeof current === 'object' && !seen.has(current)) {
|
|
496
|
-
seen.add(current);
|
|
497
|
-
const wrapper = current as {
|
|
498
|
-
callbacks?: Callbacks;
|
|
499
|
-
config?: { callbacks?: Callbacks };
|
|
500
|
-
bound?: unknown;
|
|
501
|
-
last?: unknown;
|
|
502
|
-
steps?: unknown[];
|
|
503
|
-
};
|
|
504
|
-
if (wrapper.callbacks != null) {
|
|
505
|
-
sources.push(wrapper.callbacks);
|
|
506
|
-
}
|
|
507
|
-
if (wrapper.config?.callbacks != null) {
|
|
508
|
-
sources.push(wrapper.config.callbacks);
|
|
509
|
-
}
|
|
510
|
-
current =
|
|
511
|
-
wrapper.bound ??
|
|
512
|
-
wrapper.last ??
|
|
513
|
-
(Array.isArray(wrapper.steps)
|
|
514
|
-
? wrapper.steps[wrapper.steps.length - 1]
|
|
515
|
-
: undefined);
|
|
516
|
-
}
|
|
517
|
-
return sources;
|
|
518
|
-
}
|
|
519
|
-
|
|
520
477
|
async function endSealedModelRun(
|
|
521
478
|
context: InvokeContext | undefined,
|
|
522
479
|
chunk: AIMessageChunk,
|
|
@@ -543,34 +500,8 @@ async function endSealedModelRun(
|
|
|
543
500
|
synthesizeSealedUsage(context, chunk, prompt, metadata);
|
|
544
501
|
if (llmRunId != null) {
|
|
545
502
|
try {
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
* The real model run composes the per-call config's callbacks WITH the
|
|
549
|
-
* model's own (`CallbackManager.configure(config.callbacks,
|
|
550
|
-
* this.callbacks, …)` in `@langchain/core`'s base chat model), so a
|
|
551
|
-
* handler supplied via `clientOptions.callbacks` received
|
|
552
|
-
* `handleChatModelStart` for this run. Rebuilding from the config alone
|
|
553
|
-
* would close the run for every handler EXCEPT those — leaving their
|
|
554
|
-
* span open forever. Composed the same way the real run composes:
|
|
555
|
-
* model callbacks appended non-inheritable, parent run id preserved by
|
|
556
|
-
* `copy`, tracers deduped by `configure`.
|
|
557
|
-
*/
|
|
558
|
-
for (const source of collectModelCallbackSources(model)) {
|
|
559
|
-
callbackManager =
|
|
560
|
-
CallbackManager.configure(callbackManager ?? undefined, source) ??
|
|
561
|
-
callbackManager;
|
|
562
|
-
}
|
|
563
|
-
if (callbackManager != null) {
|
|
564
|
-
const runManager = new CallbackManagerForLLMRun(
|
|
565
|
-
llmRunId,
|
|
566
|
-
callbackManager.handlers,
|
|
567
|
-
callbackManager.inheritableHandlers,
|
|
568
|
-
callbackManager.tags,
|
|
569
|
-
callbackManager.inheritableTags,
|
|
570
|
-
callbackManager.metadata,
|
|
571
|
-
callbackManager.inheritableMetadata,
|
|
572
|
-
callbackManager.getParentRunId()
|
|
573
|
-
);
|
|
503
|
+
const runManager = await getModelCallbackRunManager(llmRunId, config, model);
|
|
504
|
+
if (runManager != null) {
|
|
574
505
|
const generation: ChatGeneration = {
|
|
575
506
|
text: getMessageText(chunk),
|
|
576
507
|
message: chunk,
|