@langchain/core 0.1.23 → 0.1.24

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.
@@ -348,6 +348,9 @@ class ToolMessage extends BaseMessage {
348
348
  _getType() {
349
349
  return "tool";
350
350
  }
351
+ static isInstance(message) {
352
+ return message._getType() === "tool";
353
+ }
351
354
  }
352
355
  exports.ToolMessage = ToolMessage;
353
356
  /**
@@ -195,6 +195,7 @@ export declare class ToolMessage extends BaseMessage {
195
195
  constructor(fields: ToolMessageFieldsWithToolCallId);
196
196
  constructor(fields: string | BaseMessageFields, tool_call_id: string, name?: string);
197
197
  _getType(): MessageType;
198
+ static isInstance(message: BaseMessage): message is ToolMessage;
198
199
  }
199
200
  /**
200
201
  * Represents a chunk of a tool message, which can be concatenated
@@ -335,6 +335,9 @@ export class ToolMessage extends BaseMessage {
335
335
  _getType() {
336
336
  return "tool";
337
337
  }
338
+ static isInstance(message) {
339
+ return message._getType() === "tool";
340
+ }
338
341
  }
339
342
  /**
340
343
  * Represents a chunk of a tool message, which can be concatenated
@@ -13,6 +13,12 @@ class ImagePromptTemplate extends base_js_1.BasePromptTemplate {
13
13
  }
14
14
  constructor(input) {
15
15
  super(input);
16
+ Object.defineProperty(this, "lc_namespace", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: ["langchain_core", "prompts", "image"]
21
+ });
16
22
  Object.defineProperty(this, "template", {
17
23
  enumerable: true,
18
24
  configurable: true,
@@ -29,6 +29,7 @@ export interface ImagePromptTemplateInput<RunInput extends InputValues = any, Pa
29
29
  */
30
30
  export declare class ImagePromptTemplate<RunInput extends InputValues = any, PartialVariableName extends string = any> extends BasePromptTemplate<RunInput, ImagePromptValue, PartialVariableName> {
31
31
  static lc_name(): string;
32
+ lc_namespace: string[];
32
33
  template: Record<string, unknown>;
33
34
  templateFormat: TemplateFormat;
34
35
  validateTemplate: boolean;
@@ -10,6 +10,12 @@ export class ImagePromptTemplate extends BasePromptTemplate {
10
10
  }
11
11
  constructor(input) {
12
12
  super(input);
13
+ Object.defineProperty(this, "lc_namespace", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: ["langchain_core", "prompts", "image"]
18
+ });
13
19
  Object.defineProperty(this, "template", {
14
20
  enumerable: true,
15
21
  configurable: true,
@@ -22,3 +22,4 @@ __exportStar(require("./prompt.cjs"), exports);
22
22
  __exportStar(require("./serde.cjs"), exports);
23
23
  __exportStar(require("./string.cjs"), exports);
24
24
  __exportStar(require("./template.cjs"), exports);
25
+ __exportStar(require("./image.cjs"), exports);
@@ -6,3 +6,4 @@ export * from "./prompt.js";
6
6
  export * from "./serde.js";
7
7
  export * from "./string.js";
8
8
  export * from "./template.js";
9
+ export * from "./image.js";
@@ -6,3 +6,4 @@ export * from "./prompt.js";
6
6
  export * from "./serde.js";
7
7
  export * from "./string.js";
8
8
  export * from "./template.js";
9
+ export * from "./image.js";
@@ -0,0 +1,378 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RemoteRunnable = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ const index_js_1 = require("../documents/index.cjs");
6
+ const prompt_values_js_1 = require("../prompt_values.cjs");
7
+ const log_stream_js_1 = require("../tracers/log_stream.cjs");
8
+ const index_js_2 = require("../messages/index.cjs");
9
+ const outputs_js_1 = require("../outputs.cjs");
10
+ const event_source_parse_js_1 = require("../utils/event_source_parse.cjs");
11
+ const stream_js_1 = require("../utils/stream.cjs");
12
+ function isSuperset(set, subset) {
13
+ for (const elem of subset) {
14
+ if (!set.has(elem)) {
15
+ return false;
16
+ }
17
+ }
18
+ return true;
19
+ }
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
+ function revive(obj) {
22
+ if (Array.isArray(obj))
23
+ return obj.map(revive);
24
+ if (typeof obj === "object") {
25
+ // eslint-disable-next-line no-instanceof/no-instanceof
26
+ if (!obj || obj instanceof Date) {
27
+ return obj;
28
+ }
29
+ const keysArr = Object.keys(obj);
30
+ const keys = new Set(keysArr);
31
+ if (isSuperset(keys, new Set(["page_content", "metadata"]))) {
32
+ return new index_js_1.Document({
33
+ pageContent: obj.page_content,
34
+ metadata: obj.metadata,
35
+ });
36
+ }
37
+ if (isSuperset(keys, new Set(["content", "type", "additional_kwargs"]))) {
38
+ if (obj.type === "HumanMessage" || obj.type === "human") {
39
+ return new index_js_2.HumanMessage({
40
+ content: obj.content,
41
+ });
42
+ }
43
+ if (obj.type === "SystemMessage" || obj.type === "system") {
44
+ return new index_js_2.SystemMessage({
45
+ content: obj.content,
46
+ });
47
+ }
48
+ if (obj.type === "ChatMessage" || obj.type === "chat") {
49
+ return new index_js_2.ChatMessage({
50
+ content: obj.content,
51
+ role: obj.role,
52
+ });
53
+ }
54
+ if (obj.type === "FunctionMessage" || obj.type === "function") {
55
+ return new index_js_2.FunctionMessage({
56
+ content: obj.content,
57
+ name: obj.name,
58
+ });
59
+ }
60
+ if (obj.type === "ToolMessage" || obj.type === "tool") {
61
+ return new index_js_2.ToolMessage({
62
+ content: obj.content,
63
+ tool_call_id: obj.tool_call_id,
64
+ });
65
+ }
66
+ if (obj.type === "AIMessage" || obj.type === "ai") {
67
+ return new index_js_2.AIMessage({
68
+ content: obj.content,
69
+ });
70
+ }
71
+ if (obj.type === "HumanMessageChunk") {
72
+ return new index_js_2.HumanMessageChunk({
73
+ content: obj.content,
74
+ });
75
+ }
76
+ if (obj.type === "SystemMessageChunk") {
77
+ return new index_js_2.SystemMessageChunk({
78
+ content: obj.content,
79
+ });
80
+ }
81
+ if (obj.type === "ChatMessageChunk") {
82
+ return new index_js_2.ChatMessageChunk({
83
+ content: obj.content,
84
+ role: obj.role,
85
+ });
86
+ }
87
+ if (obj.type === "FunctionMessageChunk") {
88
+ return new index_js_2.FunctionMessageChunk({
89
+ content: obj.content,
90
+ name: obj.name,
91
+ });
92
+ }
93
+ if (obj.type === "ToolMessageChunk") {
94
+ return new index_js_2.ToolMessageChunk({
95
+ content: obj.content,
96
+ tool_call_id: obj.tool_call_id,
97
+ });
98
+ }
99
+ if (obj.type === "AIMessageChunk") {
100
+ return new index_js_2.AIMessageChunk({
101
+ content: obj.content,
102
+ });
103
+ }
104
+ }
105
+ if (isSuperset(keys, new Set(["text", "generation_info", "type"]))) {
106
+ if (obj.type === "ChatGenerationChunk") {
107
+ return new outputs_js_1.ChatGenerationChunk({
108
+ message: revive(obj.message),
109
+ text: obj.text,
110
+ generationInfo: obj.generation_info,
111
+ });
112
+ }
113
+ else if (obj.type === "ChatGeneration") {
114
+ return {
115
+ message: revive(obj.message),
116
+ text: obj.text,
117
+ generationInfo: obj.generation_info,
118
+ };
119
+ }
120
+ else if (obj.type === "GenerationChunk") {
121
+ return new outputs_js_1.GenerationChunk({
122
+ text: obj.text,
123
+ generationInfo: obj.generation_info,
124
+ });
125
+ }
126
+ else if (obj.type === "Generation") {
127
+ return {
128
+ text: obj.text,
129
+ generationInfo: obj.generation_info,
130
+ };
131
+ }
132
+ }
133
+ if (isSuperset(keys, new Set(["tool", "tool_input", "log", "type"]))) {
134
+ if (obj.type === "AgentAction") {
135
+ return {
136
+ tool: obj.tool,
137
+ toolInput: obj.tool_input,
138
+ log: obj.log,
139
+ };
140
+ }
141
+ }
142
+ if (isSuperset(keys, new Set(["return_values", "log", "type"]))) {
143
+ if (obj.type === "AgentFinish") {
144
+ return {
145
+ returnValues: obj.return_values,
146
+ log: obj.log,
147
+ };
148
+ }
149
+ }
150
+ if (isSuperset(keys, new Set(["generations", "run", "type"]))) {
151
+ if (obj.type === "LLMResult") {
152
+ return {
153
+ generations: revive(obj.generations),
154
+ llmOutput: obj.llm_output,
155
+ [outputs_js_1.RUN_KEY]: obj.run,
156
+ };
157
+ }
158
+ }
159
+ if (isSuperset(keys, new Set(["messages"]))) {
160
+ // TODO: Start checking for type: ChatPromptValue and ChatPromptValueConcrete
161
+ // when LangServe bug is fixed
162
+ return new prompt_values_js_1.ChatPromptValue({
163
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
164
+ messages: obj.messages.map((msg) => revive(msg)),
165
+ });
166
+ }
167
+ if (isSuperset(keys, new Set(["text"]))) {
168
+ // TODO: Start checking for type: StringPromptValue
169
+ // when LangServe bug is fixed
170
+ return new prompt_values_js_1.StringPromptValue(obj.text);
171
+ }
172
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
173
+ const innerRevive = (key) => [
174
+ key,
175
+ revive(obj[key]),
176
+ ];
177
+ const rtn = Object.fromEntries(keysArr.map(innerRevive));
178
+ return rtn;
179
+ }
180
+ return obj;
181
+ }
182
+ function deserialize(str) {
183
+ const obj = JSON.parse(str);
184
+ return revive(obj);
185
+ }
186
+ function removeCallbacks(options) {
187
+ const rest = { ...options };
188
+ delete rest.callbacks;
189
+ return rest;
190
+ }
191
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
192
+ function serialize(input) {
193
+ if (Array.isArray(input))
194
+ return input.map(serialize);
195
+ if ((0, index_js_2.isBaseMessage)(input)) {
196
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
197
+ const serializedMessage = {
198
+ content: input.content,
199
+ type: input._getType(),
200
+ additional_kwargs: input.additional_kwargs,
201
+ name: input.name,
202
+ example: false,
203
+ };
204
+ if (index_js_2.ToolMessage.isInstance(input)) {
205
+ serializedMessage.tool_call_id = input.tool_call_id;
206
+ }
207
+ else if (index_js_2.ChatMessage.isInstance(input)) {
208
+ serializedMessage.role = input.role;
209
+ }
210
+ return serializedMessage;
211
+ }
212
+ if (typeof input === "object") {
213
+ // eslint-disable-next-line no-instanceof/no-instanceof
214
+ if (!input || input instanceof Date) {
215
+ return input;
216
+ }
217
+ const keysArr = Object.keys(input);
218
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
219
+ const innerSerialize = (key) => [
220
+ key,
221
+ serialize(input[key]),
222
+ ];
223
+ const rtn = Object.fromEntries(keysArr.map(innerSerialize));
224
+ return rtn;
225
+ }
226
+ return input;
227
+ }
228
+ class RemoteRunnable extends base_js_1.Runnable {
229
+ constructor(fields) {
230
+ super(fields);
231
+ Object.defineProperty(this, "url", {
232
+ enumerable: true,
233
+ configurable: true,
234
+ writable: true,
235
+ value: void 0
236
+ });
237
+ Object.defineProperty(this, "options", {
238
+ enumerable: true,
239
+ configurable: true,
240
+ writable: true,
241
+ value: void 0
242
+ });
243
+ Object.defineProperty(this, "lc_namespace", {
244
+ enumerable: true,
245
+ configurable: true,
246
+ writable: true,
247
+ value: ["langchain", "schema", "runnable", "remote"]
248
+ });
249
+ const { url, options } = fields;
250
+ this.url = url.replace(/\/$/, ""); // remove trailing slash
251
+ this.options = options;
252
+ }
253
+ async post(path, body) {
254
+ return fetch(`${this.url}${path}`, {
255
+ method: "POST",
256
+ body: JSON.stringify(serialize(body)),
257
+ headers: {
258
+ "Content-Type": "application/json",
259
+ ...this.options?.headers,
260
+ },
261
+ signal: AbortSignal.timeout(this.options?.timeout ?? 60000),
262
+ });
263
+ }
264
+ async invoke(input, options) {
265
+ const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
266
+ const response = await this.post("/invoke", {
267
+ input,
268
+ config: removeCallbacks(config),
269
+ kwargs: kwargs ?? {},
270
+ });
271
+ return revive((await response.json()).output);
272
+ }
273
+ async _batch(inputs, options, _, batchOptions) {
274
+ if (batchOptions?.returnExceptions) {
275
+ throw new Error("returnExceptions is not supported for remote clients");
276
+ }
277
+ const configsAndKwargsArray = options?.map((opts) => this._separateRunnableConfigFromCallOptions(opts));
278
+ const [configs, kwargs] = configsAndKwargsArray?.reduce(([pc, pk], [c, k]) => [
279
+ [...pc, c],
280
+ [...pk, k],
281
+ ], [[], []]) ?? [undefined, undefined];
282
+ const response = await this.post("/batch", {
283
+ inputs,
284
+ config: (configs ?? [])
285
+ .map(removeCallbacks)
286
+ .map((config) => ({ ...config, ...batchOptions })),
287
+ kwargs,
288
+ });
289
+ const body = await response.json();
290
+ if (!body.output)
291
+ throw new Error("Invalid response from remote runnable");
292
+ return revive(body.output);
293
+ }
294
+ async batch(inputs, options, batchOptions) {
295
+ if (batchOptions?.returnExceptions) {
296
+ throw Error("returnExceptions is not supported for remote clients");
297
+ }
298
+ return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
299
+ }
300
+ async stream(input, options) {
301
+ const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
302
+ const response = await this.post("/stream", {
303
+ input,
304
+ config: removeCallbacks(config),
305
+ kwargs,
306
+ });
307
+ if (!response.ok) {
308
+ const json = await response.json();
309
+ const error = new Error(`RemoteRunnable call failed with status code ${response.status}: ${json.message}`);
310
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
311
+ error.response = response;
312
+ throw error;
313
+ }
314
+ const { body } = response;
315
+ if (!body) {
316
+ throw new Error("Could not begin remote stream. Please check the given URL and try again.");
317
+ }
318
+ const stream = new ReadableStream({
319
+ async start(controller) {
320
+ const enqueueLine = (0, event_source_parse_js_1.getMessages)((msg) => {
321
+ if (msg.data)
322
+ controller.enqueue(deserialize(msg.data));
323
+ });
324
+ const onLine = (line, fieldLength, flush) => {
325
+ enqueueLine(line, fieldLength, flush);
326
+ if (flush)
327
+ controller.close();
328
+ };
329
+ await (0, event_source_parse_js_1.getBytes)(body, (0, event_source_parse_js_1.getLines)(onLine));
330
+ },
331
+ });
332
+ return stream_js_1.IterableReadableStream.fromReadableStream(stream);
333
+ }
334
+ async *streamLog(input, options, streamOptions) {
335
+ const [config, kwargs] = this._separateRunnableConfigFromCallOptions(options);
336
+ const stream = new log_stream_js_1.LogStreamCallbackHandler({
337
+ ...streamOptions,
338
+ autoClose: false,
339
+ });
340
+ const { callbacks } = config;
341
+ if (callbacks === undefined) {
342
+ config.callbacks = [stream];
343
+ }
344
+ else if (Array.isArray(callbacks)) {
345
+ config.callbacks = callbacks.concat([stream]);
346
+ }
347
+ else {
348
+ const copiedCallbacks = callbacks.copy();
349
+ copiedCallbacks.inheritableHandlers.push(stream);
350
+ config.callbacks = copiedCallbacks;
351
+ }
352
+ // The type is in camelCase but the API only accepts snake_case.
353
+ const camelCaseStreamOptions = {
354
+ include_names: streamOptions?.includeNames,
355
+ include_types: streamOptions?.includeTypes,
356
+ include_tags: streamOptions?.includeTags,
357
+ exclude_names: streamOptions?.excludeNames,
358
+ exclude_types: streamOptions?.excludeTypes,
359
+ exclude_tags: streamOptions?.excludeTags,
360
+ };
361
+ const response = await this.post("/stream_log", {
362
+ input,
363
+ config: removeCallbacks(config),
364
+ kwargs,
365
+ ...camelCaseStreamOptions,
366
+ diff: false,
367
+ });
368
+ const { body } = response;
369
+ if (!body) {
370
+ throw new Error("Could not begin remote stream log. Please check the given URL and try again.");
371
+ }
372
+ const runnableStream = (0, event_source_parse_js_1.convertEventStreamToIterableReadableDataStream)(body);
373
+ for await (const log of runnableStream) {
374
+ yield revive(JSON.parse(log));
375
+ }
376
+ }
377
+ }
378
+ exports.RemoteRunnable = RemoteRunnable;
@@ -0,0 +1,31 @@
1
+ import { Runnable, RunnableBatchOptions } from "./base.js";
2
+ import type { RunnableConfig } from "./config.js";
3
+ import { CallbackManagerForChainRun } from "../callbacks/manager.js";
4
+ import { type LogStreamCallbackHandlerInput, type RunLogPatch } from "../tracers/log_stream.js";
5
+ import { IterableReadableStream } from "../utils/stream.js";
6
+ type RemoteRunnableOptions = {
7
+ timeout?: number;
8
+ headers?: Record<string, unknown>;
9
+ };
10
+ export declare class RemoteRunnable<RunInput, RunOutput, CallOptions extends RunnableConfig> extends Runnable<RunInput, RunOutput, CallOptions> {
11
+ private url;
12
+ private options?;
13
+ lc_namespace: string[];
14
+ constructor(fields: {
15
+ url: string;
16
+ options?: RemoteRunnableOptions;
17
+ });
18
+ private post;
19
+ invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
20
+ _batch(inputs: RunInput[], options?: Partial<CallOptions>[], _?: (CallbackManagerForChainRun | undefined)[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
21
+ batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
22
+ returnExceptions?: false;
23
+ }): Promise<RunOutput[]>;
24
+ batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
25
+ returnExceptions: true;
26
+ }): Promise<(RunOutput | Error)[]>;
27
+ batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
28
+ stream(input: RunInput, options?: Partial<CallOptions>): Promise<IterableReadableStream<RunOutput>>;
29
+ streamLog(input: RunInput, options?: Partial<CallOptions>, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): AsyncGenerator<RunLogPatch>;
30
+ }
31
+ export {};