@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
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
3
|
+
import { isAIMessage, isAIMessageChunk } from '@langchain/core/messages';
|
|
4
|
+
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
|
|
5
|
+
import { convertToOpenAITool } from '@langchain/core/utils/function_calling';
|
|
6
|
+
import type {
|
|
7
|
+
BaseChatModelCallOptions,
|
|
8
|
+
BindToolsInput,
|
|
9
|
+
} from '@langchain/core/language_models/chat_models';
|
|
10
|
+
import type {
|
|
11
|
+
AIMessage,
|
|
12
|
+
AIMessageChunk,
|
|
13
|
+
BaseMessage,
|
|
14
|
+
} from '@langchain/core/messages';
|
|
15
|
+
import type { BaseLanguageModelInput } from '@langchain/core/language_models/base';
|
|
16
|
+
import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
17
|
+
import type { Runnable } from '@langchain/core/runnables';
|
|
18
|
+
import type { ChatResult } from '@langchain/core/outputs';
|
|
19
|
+
import type { ExecutionIdentity } from './identity';
|
|
20
|
+
import { PreparedSubagentError } from '@/tools/preparedSubagents';
|
|
21
|
+
import { stableStringify } from '@/tools/eagerEventExecution';
|
|
22
|
+
import { StreamLimitExceededError } from '@/llm/streamLimits';
|
|
23
|
+
import { snapshotExecutionIdentity } from './identity';
|
|
24
|
+
|
|
25
|
+
type FunctionTool = ReturnType<typeof convertToOpenAITool>;
|
|
26
|
+
|
|
27
|
+
/** Public configuration only. The authenticated host owns the actual model, credentials and callbacks. */
|
|
28
|
+
export interface HostModelDescriptor {
|
|
29
|
+
readonly version: 1;
|
|
30
|
+
readonly reference: string;
|
|
31
|
+
readonly provider: string;
|
|
32
|
+
readonly model: string;
|
|
33
|
+
readonly streaming: boolean;
|
|
34
|
+
readonly tools: readonly FunctionTool[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const nonempty = z.string().refine((value) => value.trim().length > 0);
|
|
38
|
+
export const hostModelDescriptorSchema = z.object({
|
|
39
|
+
version: z.literal(1),
|
|
40
|
+
reference: nonempty,
|
|
41
|
+
provider: nonempty,
|
|
42
|
+
model: nonempty,
|
|
43
|
+
streaming: z.boolean(),
|
|
44
|
+
tools: z.array(
|
|
45
|
+
z
|
|
46
|
+
.object({
|
|
47
|
+
type: z.literal('function'),
|
|
48
|
+
function: z
|
|
49
|
+
.object({
|
|
50
|
+
name: nonempty,
|
|
51
|
+
description: z.string().optional(),
|
|
52
|
+
parameters: z.record(z.string(), z.unknown()),
|
|
53
|
+
strict: z.boolean().nullable().optional(),
|
|
54
|
+
})
|
|
55
|
+
.loose(),
|
|
56
|
+
})
|
|
57
|
+
.loose()
|
|
58
|
+
),
|
|
59
|
+
});
|
|
60
|
+
const choiceSchema = z.union([
|
|
61
|
+
nonempty,
|
|
62
|
+
z.object({
|
|
63
|
+
type: z.literal('function'),
|
|
64
|
+
function: z.object({ name: nonempty }),
|
|
65
|
+
}),
|
|
66
|
+
z.object({ type: z.literal('tool'), name: nonempty }),
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
export type HostModelToolChoice =
|
|
70
|
+
| { readonly mode: 'auto' | 'none' | 'required' }
|
|
71
|
+
| { readonly mode: 'tool'; readonly name: string };
|
|
72
|
+
|
|
73
|
+
export interface HostModelRequest {
|
|
74
|
+
readonly version: 1;
|
|
75
|
+
readonly identity: Readonly<ExecutionIdentity>;
|
|
76
|
+
readonly reference: string;
|
|
77
|
+
readonly messages: readonly BaseMessage[];
|
|
78
|
+
readonly toolNames: readonly string[];
|
|
79
|
+
readonly toolChoice?: HostModelToolChoice;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Host implementations authenticate identity/reference and authorize every selected tool.
|
|
84
|
+
* They invoke an already configured model through its public invoke/stream APIs, keeping
|
|
85
|
+
* credentials, model parameters, input/output protection and callbacks host-side. Streams are
|
|
86
|
+
* pull-based: transports must preserve backpressure, cancellation and native message metadata.
|
|
87
|
+
*/
|
|
88
|
+
export interface HostModelService {
|
|
89
|
+
readonly version: 1;
|
|
90
|
+
invoke(request: HostModelRequest, signal?: AbortSignal): Promise<AIMessage>;
|
|
91
|
+
stream(
|
|
92
|
+
request: HostModelRequest,
|
|
93
|
+
signal?: AbortSignal
|
|
94
|
+
): AsyncIterable<AIMessageChunk>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type HostModelErrorCode =
|
|
98
|
+
| 'incompatible'
|
|
99
|
+
| 'forbidden'
|
|
100
|
+
| 'blocked'
|
|
101
|
+
| 'overflow'
|
|
102
|
+
| 'timeout'
|
|
103
|
+
| 'cancelled'
|
|
104
|
+
| 'unavailable';
|
|
105
|
+
const errorCodes: ReadonlySet<string> = new Set<HostModelErrorCode>([
|
|
106
|
+
'incompatible',
|
|
107
|
+
'forbidden',
|
|
108
|
+
'blocked',
|
|
109
|
+
'overflow',
|
|
110
|
+
'timeout',
|
|
111
|
+
'cancelled',
|
|
112
|
+
'unavailable',
|
|
113
|
+
]);
|
|
114
|
+
|
|
115
|
+
export class HostModelServiceError extends Error {
|
|
116
|
+
constructor(readonly code: HostModelErrorCode) {
|
|
117
|
+
const safeCode = errorCodes.has(code) ? code : 'incompatible';
|
|
118
|
+
super(`Host model service: ${safeCode}`);
|
|
119
|
+
this.code = safeCode;
|
|
120
|
+
this.name = 'HostModelServiceError';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function normalizeHostModelError(
|
|
125
|
+
error: unknown,
|
|
126
|
+
signal?: AbortSignal
|
|
127
|
+
): HostModelServiceError | StreamLimitExceededError | PreparedSubagentError {
|
|
128
|
+
if (
|
|
129
|
+
signal?.aborted === true &&
|
|
130
|
+
(signal.reason instanceof StreamLimitExceededError ||
|
|
131
|
+
signal.reason instanceof PreparedSubagentError)
|
|
132
|
+
)
|
|
133
|
+
return signal.reason;
|
|
134
|
+
if (signal?.aborted === true) return new HostModelServiceError('cancelled');
|
|
135
|
+
try {
|
|
136
|
+
if (
|
|
137
|
+
error != null &&
|
|
138
|
+
typeof error === 'object' &&
|
|
139
|
+
'name' in error &&
|
|
140
|
+
error.name === 'HostModelServiceError' &&
|
|
141
|
+
'code' in error &&
|
|
142
|
+
typeof error.code === 'string' &&
|
|
143
|
+
errorCodes.has(error.code)
|
|
144
|
+
) {
|
|
145
|
+
return new HostModelServiceError(error.code as HostModelErrorCode);
|
|
146
|
+
}
|
|
147
|
+
} catch {
|
|
148
|
+
/* Error getters cannot disclose host data. */
|
|
149
|
+
}
|
|
150
|
+
return new HostModelServiceError('unavailable');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface HostModelCallOptions extends BaseChatModelCallOptions {
|
|
154
|
+
hostToolNames?: string[];
|
|
155
|
+
tool_choice?:
|
|
156
|
+
| string
|
|
157
|
+
| { type: 'function'; function: { name: string } }
|
|
158
|
+
| { type: 'tool'; name: string };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function toolChoice(input: unknown): HostModelToolChoice | undefined {
|
|
162
|
+
if (input === undefined) return undefined;
|
|
163
|
+
const parsed = choiceSchema.safeParse(input);
|
|
164
|
+
if (!parsed.success) throw new HostModelServiceError('incompatible');
|
|
165
|
+
const value = parsed.data;
|
|
166
|
+
if (value === 'auto' || value === 'none') return { mode: value };
|
|
167
|
+
if (value === 'required' || value === 'any') return { mode: 'required' };
|
|
168
|
+
if (typeof value === 'string') return { mode: 'tool', name: value };
|
|
169
|
+
return {
|
|
170
|
+
mode: 'tool',
|
|
171
|
+
name: value.type === 'function' ? value.function.name : value.name,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Observe late settlement without allowing it to release output after caller cancellation. */
|
|
176
|
+
function waitForService<T>(
|
|
177
|
+
operation: () => Promise<T>,
|
|
178
|
+
signal?: AbortSignal
|
|
179
|
+
): Promise<T> {
|
|
180
|
+
signal?.throwIfAborted();
|
|
181
|
+
return new Promise<T>((resolve, reject) => {
|
|
182
|
+
const abort = (): void => {
|
|
183
|
+
signal?.removeEventListener('abort', abort);
|
|
184
|
+
reject(normalizeHostModelError(undefined, signal));
|
|
185
|
+
};
|
|
186
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
187
|
+
try {
|
|
188
|
+
operation().then(
|
|
189
|
+
(value) => {
|
|
190
|
+
signal?.removeEventListener('abort', abort);
|
|
191
|
+
resolve(value);
|
|
192
|
+
},
|
|
193
|
+
(error: Error) => {
|
|
194
|
+
signal?.removeEventListener('abort', abort);
|
|
195
|
+
reject(error);
|
|
196
|
+
}
|
|
197
|
+
);
|
|
198
|
+
if (signal?.aborted === true) abort();
|
|
199
|
+
} catch (error) {
|
|
200
|
+
signal?.removeEventListener('abort', abort);
|
|
201
|
+
reject(error);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Native LangChain model facade; no provider/model options or credentials cross to the host. */
|
|
207
|
+
export class HostChatModel extends BaseChatModel<HostModelCallOptions> {
|
|
208
|
+
private readonly identity: Readonly<ExecutionIdentity>;
|
|
209
|
+
private readonly descriptor: HostModelDescriptor;
|
|
210
|
+
private readonly service: HostModelService;
|
|
211
|
+
private readonly schemas = new Map<string, string>();
|
|
212
|
+
|
|
213
|
+
constructor(options: {
|
|
214
|
+
identity: Readonly<ExecutionIdentity>;
|
|
215
|
+
descriptor: HostModelDescriptor;
|
|
216
|
+
service: HostModelService;
|
|
217
|
+
}) {
|
|
218
|
+
super({});
|
|
219
|
+
const parsed = hostModelDescriptorSchema.safeParse(options.descriptor);
|
|
220
|
+
const serviceVersion: number = options.service.version;
|
|
221
|
+
if (
|
|
222
|
+
!parsed.success ||
|
|
223
|
+
serviceVersion !== 1 ||
|
|
224
|
+
typeof options.service.invoke !== 'function' ||
|
|
225
|
+
typeof options.service.stream !== 'function'
|
|
226
|
+
)
|
|
227
|
+
throw new HostModelServiceError('incompatible');
|
|
228
|
+
try {
|
|
229
|
+
this.identity = snapshotExecutionIdentity(options.identity);
|
|
230
|
+
this.descriptor = structuredClone(parsed.data);
|
|
231
|
+
} catch {
|
|
232
|
+
throw new HostModelServiceError('incompatible');
|
|
233
|
+
}
|
|
234
|
+
this.disableStreaming = !this.descriptor.streaming;
|
|
235
|
+
this.service = options.service;
|
|
236
|
+
for (const tool of this.descriptor.tools) {
|
|
237
|
+
const name = tool.function.name;
|
|
238
|
+
if (this.schemas.has(name))
|
|
239
|
+
throw new HostModelServiceError('incompatible');
|
|
240
|
+
this.schemas.set(name, stableStringify(tool));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
_llmType(): string {
|
|
245
|
+
return 'librechat-host';
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
override get callKeys(): string[] {
|
|
249
|
+
return [...super.callKeys, 'hostToolNames', 'tool_choice'];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
override getLsParams(): ReturnType<BaseChatModel['getLsParams']> {
|
|
253
|
+
return {
|
|
254
|
+
ls_model_type: 'chat',
|
|
255
|
+
ls_provider: this.descriptor.provider,
|
|
256
|
+
ls_model_name: this.descriptor.model,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
override _identifyingParams(): Pick<
|
|
261
|
+
HostModelDescriptor,
|
|
262
|
+
'provider' | 'model' | 'reference'
|
|
263
|
+
> {
|
|
264
|
+
return {
|
|
265
|
+
model: this.descriptor.model,
|
|
266
|
+
provider: this.descriptor.provider,
|
|
267
|
+
reference: this.descriptor.reference,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
override bindTools(
|
|
272
|
+
tools: BindToolsInput[],
|
|
273
|
+
kwargs?: Partial<HostModelCallOptions>
|
|
274
|
+
): Runnable<BaseLanguageModelInput, AIMessageChunk, HostModelCallOptions> {
|
|
275
|
+
const names = tools.map((tool) => {
|
|
276
|
+
const definition = convertToOpenAITool(tool);
|
|
277
|
+
const name = definition.function.name;
|
|
278
|
+
if (!name || this.schemas.get(name) !== stableStringify(definition))
|
|
279
|
+
throw new HostModelServiceError('forbidden');
|
|
280
|
+
return name;
|
|
281
|
+
});
|
|
282
|
+
const choice = toolChoice(kwargs?.tool_choice);
|
|
283
|
+
this.validateTools(names, choice);
|
|
284
|
+
return this.withConfig({ ...kwargs, hostToolNames: names });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private validateTools(
|
|
288
|
+
names: readonly string[],
|
|
289
|
+
choice?: HostModelToolChoice
|
|
290
|
+
): void {
|
|
291
|
+
if (
|
|
292
|
+
!Array.isArray(names) ||
|
|
293
|
+
new Set(names).size !== names.length ||
|
|
294
|
+
names.some((name) => !this.schemas.has(name))
|
|
295
|
+
)
|
|
296
|
+
throw new HostModelServiceError('forbidden');
|
|
297
|
+
if (choice === undefined) return;
|
|
298
|
+
if (
|
|
299
|
+
!['auto', 'none', 'required', 'tool'].includes(choice.mode) ||
|
|
300
|
+
(choice.mode === 'tool' && !names.includes(choice.name)) ||
|
|
301
|
+
(choice.mode === 'required' && names.length === 0)
|
|
302
|
+
)
|
|
303
|
+
throw new HostModelServiceError('forbidden');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private request(
|
|
307
|
+
messages: BaseMessage[],
|
|
308
|
+
options: this['ParsedCallOptions']
|
|
309
|
+
): HostModelRequest {
|
|
310
|
+
const names = options.hostToolNames?.slice() ?? [];
|
|
311
|
+
const choice = toolChoice(options.tool_choice);
|
|
312
|
+
this.validateTools(names, choice);
|
|
313
|
+
return {
|
|
314
|
+
version: 1,
|
|
315
|
+
identity: this.identity,
|
|
316
|
+
reference: this.descriptor.reference,
|
|
317
|
+
messages: messages.slice(),
|
|
318
|
+
toolNames: names,
|
|
319
|
+
...(choice ? { toolChoice: { ...choice } } : {}),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async _generate(
|
|
324
|
+
messages: BaseMessage[],
|
|
325
|
+
options: this['ParsedCallOptions']
|
|
326
|
+
): Promise<ChatResult> {
|
|
327
|
+
const request = this.request(messages, options);
|
|
328
|
+
try {
|
|
329
|
+
options.signal?.throwIfAborted();
|
|
330
|
+
const message = await waitForService(
|
|
331
|
+
() => this.service.invoke(request, options.signal),
|
|
332
|
+
options.signal
|
|
333
|
+
);
|
|
334
|
+
options.signal?.throwIfAborted();
|
|
335
|
+
if (!isAIMessage(message))
|
|
336
|
+
throw new HostModelServiceError('incompatible');
|
|
337
|
+
return { generations: [{ text: message.text, message }] };
|
|
338
|
+
} catch (error) {
|
|
339
|
+
throw normalizeHostModelError(error, options.signal);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async *_streamResponseChunks(
|
|
344
|
+
messages: BaseMessage[],
|
|
345
|
+
options: this['ParsedCallOptions'],
|
|
346
|
+
runManager?: CallbackManagerForLLMRun
|
|
347
|
+
): AsyncGenerator<ChatGenerationChunk> {
|
|
348
|
+
const request = this.request(messages, options);
|
|
349
|
+
const controller = new AbortController();
|
|
350
|
+
const signal = options.signal
|
|
351
|
+
? AbortSignal.any([options.signal, controller.signal])
|
|
352
|
+
: controller.signal;
|
|
353
|
+
let iterator: AsyncIterator<AIMessageChunk> | undefined;
|
|
354
|
+
try {
|
|
355
|
+
signal.throwIfAborted();
|
|
356
|
+
iterator = this.service.stream(request, signal)[Symbol.asyncIterator]();
|
|
357
|
+
for (;;) {
|
|
358
|
+
const next = await waitForService(() => iterator!.next(), signal);
|
|
359
|
+
signal.throwIfAborted();
|
|
360
|
+
if (next.done === true) break;
|
|
361
|
+
const message = next.value;
|
|
362
|
+
if (!isAIMessageChunk(message))
|
|
363
|
+
throw new HostModelServiceError('incompatible');
|
|
364
|
+
const chunk = new ChatGenerationChunk({
|
|
365
|
+
text: message.text,
|
|
366
|
+
message,
|
|
367
|
+
generationInfo: message.response_metadata,
|
|
368
|
+
});
|
|
369
|
+
yield chunk;
|
|
370
|
+
signal.throwIfAborted();
|
|
371
|
+
await runManager?.handleLLMNewToken(
|
|
372
|
+
chunk.text,
|
|
373
|
+
undefined,
|
|
374
|
+
undefined,
|
|
375
|
+
undefined,
|
|
376
|
+
undefined,
|
|
377
|
+
{ chunk }
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
} catch (error) {
|
|
381
|
+
throw normalizeHostModelError(error, options.signal);
|
|
382
|
+
} finally {
|
|
383
|
+
controller.abort();
|
|
384
|
+
// The host/transport retains execution ownership until this cleanup actually settles.
|
|
385
|
+
try {
|
|
386
|
+
void iterator?.return?.().catch(() => undefined);
|
|
387
|
+
} catch {
|
|
388
|
+
/* Cleanup errors must not disclose host data. */
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|