@librechat/agents 4.2.7 → 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.
Files changed (46) hide show
  1. package/dist/cjs/harness/modelService.cjs +3 -29
  2. package/dist/cjs/harness/modelService.cjs.map +1 -1
  3. package/dist/cjs/llm/google/completion.cjs +49 -0
  4. package/dist/cjs/llm/google/completion.cjs.map +1 -0
  5. package/dist/cjs/llm/google/index.cjs +45 -20
  6. package/dist/cjs/llm/google/index.cjs.map +1 -1
  7. package/dist/cjs/llm/google/transport.cjs +133 -0
  8. package/dist/cjs/llm/google/transport.cjs.map +1 -0
  9. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  10. package/dist/cjs/llm/stream/chunkAdapters.cjs +3 -2
  11. package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
  12. package/dist/cjs/main.cjs +2 -0
  13. package/dist/cjs/messages/index.cjs +1 -0
  14. package/dist/cjs/messages/stored.cjs +34 -0
  15. package/dist/cjs/messages/stored.cjs.map +1 -0
  16. package/dist/esm/harness/modelService.mjs +4 -30
  17. package/dist/esm/harness/modelService.mjs.map +1 -1
  18. package/dist/esm/llm/google/completion.mjs +48 -0
  19. package/dist/esm/llm/google/completion.mjs.map +1 -0
  20. package/dist/esm/llm/google/index.mjs +46 -21
  21. package/dist/esm/llm/google/index.mjs.map +1 -1
  22. package/dist/esm/llm/google/transport.mjs +133 -0
  23. package/dist/esm/llm/google/transport.mjs.map +1 -0
  24. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  25. package/dist/esm/llm/stream/chunkAdapters.mjs +3 -2
  26. package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
  27. package/dist/esm/main.mjs +2 -1
  28. package/dist/esm/messages/index.mjs +1 -0
  29. package/dist/esm/messages/stored.mjs +34 -0
  30. package/dist/esm/messages/stored.mjs.map +1 -0
  31. package/dist/types/llm/google/completion.d.ts +4 -0
  32. package/dist/types/llm/google/index.d.ts +3 -1
  33. package/dist/types/llm/google/transport.d.ts +15 -0
  34. package/dist/types/llm/google/utils/common.d.ts +5 -3
  35. package/dist/types/llm/stream/chunkAdapters.d.ts +2 -1
  36. package/dist/types/messages/index.d.ts +1 -0
  37. package/dist/types/messages/stored.d.ts +7 -0
  38. package/package.json +2 -1
  39. package/src/harness/modelService.ts +3 -38
  40. package/src/llm/google/completion.ts +91 -0
  41. package/src/llm/google/index.ts +95 -34
  42. package/src/llm/google/transport.ts +202 -0
  43. package/src/llm/google/utils/common.ts +6 -2
  44. package/src/llm/stream/chunkAdapters.ts +3 -1
  45. package/src/messages/index.ts +1 -0
  46. package/src/messages/stored.ts +48 -0
@@ -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: EnhancedGenerateContentResponse,
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: EnhancedGenerateContentResponse,
944
+ response: GoogleResponse,
941
945
  extra?: {
942
946
  usageMetadata: UsageMetadata | undefined;
943
947
  model?: string;
@@ -285,11 +285,13 @@ export async function* smoothGenerationChunks({
285
285
  delayMs,
286
286
  signal,
287
287
  runManager,
288
+ abortUpstream,
288
289
  }: {
289
290
  chunks: AsyncGenerator<ChatGenerationChunk>;
290
291
  delayMs: number;
291
292
  signal?: AbortSignal;
292
293
  runManager?: CallbackManagerForLLMRun;
294
+ abortUpstream?: () => void;
293
295
  }): AsyncGenerator<ChatGenerationChunk> {
294
296
  const source = (async function* (): AsyncGenerator<
295
297
  SmoothItem<ChatGenerationChunk>
@@ -299,7 +301,7 @@ export async function* smoothGenerationChunks({
299
301
  }
300
302
  })();
301
303
 
302
- for await (const outputChunk of smoothStream({ source, delayMs, signal })) {
304
+ for await (const outputChunk of smoothStream({ source, delayMs, signal, abortUpstream })) {
303
305
  yield outputChunk;
304
306
  await runManager?.handleLLMNewToken(
305
307
  outputChunk.text || '',
@@ -18,3 +18,4 @@ export * from './assistantPhase';
18
18
  export * from './provenance';
19
19
  export * from './projectionInvariant';
20
20
  export * from './fading';
21
+ export { toStoredMessage } from './stored';
@@ -0,0 +1,48 @@
1
+ import {
2
+ isAIMessage,
3
+ isAIMessageChunk,
4
+ isToolMessage,
5
+ isChatMessage,
6
+ isBaseMessageChunk,
7
+ } from '@langchain/core/messages';
8
+ import type { BaseMessage, StoredMessage } from '@langchain/core/messages';
9
+
10
+ /**
11
+ * Native stored-message data without LangChain's JSON-oriented object escaping.
12
+ * Values retain their native types and references: callers must snapshot/encode
13
+ * with their own bounded codec before retaining or transmitting the result.
14
+ */
15
+ export function toStoredMessage(message: BaseMessage): StoredMessage {
16
+ if (Object.keys(message.lc_secrets ?? {}).length > 0) {
17
+ throw new Error('SDK native message secrets require an explicit codec');
18
+ }
19
+ const data = {
20
+ ...message.lc_kwargs,
21
+ content: message.content,
22
+ additional_kwargs: message.additional_kwargs,
23
+ response_metadata: message.response_metadata,
24
+ id: message.id,
25
+ name: message.name,
26
+ role: isChatMessage(message) ? message.role : undefined,
27
+ tool_call_id: undefined,
28
+ ...(isAIMessage(message)
29
+ ? {
30
+ tool_calls: message.tool_calls,
31
+ invalid_tool_calls: message.invalid_tool_calls,
32
+ usage_metadata: message.usage_metadata,
33
+ }
34
+ : {}),
35
+ ...(isBaseMessageChunk(message) && isAIMessageChunk(message)
36
+ ? { tool_call_chunks: message.tool_call_chunks }
37
+ : {}),
38
+ ...(isToolMessage(message)
39
+ ? {
40
+ tool_call_id: message.tool_call_id,
41
+ artifact: message.artifact,
42
+ status: message.status,
43
+ }
44
+ : {}),
45
+ };
46
+ // LangChain's StoredMessageData types content as string, but its codec supports native blocks.
47
+ return { type: message.getType(), data } as StoredMessage;
48
+ }