langchain 0.0.184 → 0.0.185

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 (44) hide show
  1. package/agents/format_scratchpad/openai_tools.cjs +1 -0
  2. package/agents/format_scratchpad/openai_tools.d.ts +1 -0
  3. package/agents/format_scratchpad/openai_tools.js +1 -0
  4. package/dist/agents/format_scratchpad/openai_tools.cjs +19 -0
  5. package/dist/agents/format_scratchpad/openai_tools.d.ts +3 -0
  6. package/dist/agents/format_scratchpad/openai_tools.js +15 -0
  7. package/dist/agents/openai/output_parser.cjs +66 -1
  8. package/dist/agents/openai/output_parser.d.ts +26 -2
  9. package/dist/agents/openai/output_parser.js +65 -1
  10. package/dist/agents/structured_chat/index.cjs +1 -2
  11. package/dist/agents/structured_chat/index.d.ts +2 -0
  12. package/dist/agents/structured_chat/index.js +1 -2
  13. package/dist/agents/types.cjs +8 -1
  14. package/dist/agents/types.d.ts +6 -0
  15. package/dist/agents/types.js +6 -0
  16. package/dist/document_loaders/fs/pdf.cjs +17 -3
  17. package/dist/document_loaders/fs/pdf.js +17 -3
  18. package/dist/document_loaders/web/apify_dataset.cjs +12 -6
  19. package/dist/document_loaders/web/apify_dataset.d.ts +9 -6
  20. package/dist/document_loaders/web/apify_dataset.js +12 -6
  21. package/dist/document_loaders/web/pdf.cjs +17 -3
  22. package/dist/document_loaders/web/pdf.js +17 -3
  23. package/dist/document_loaders/web/puppeteer.cjs +37 -0
  24. package/dist/document_loaders/web/puppeteer.d.ts +17 -0
  25. package/dist/document_loaders/web/puppeteer.js +37 -0
  26. package/dist/experimental/plan_and_execute/agent_executor.cjs +28 -2
  27. package/dist/experimental/plan_and_execute/agent_executor.d.ts +10 -3
  28. package/dist/experimental/plan_and_execute/agent_executor.js +26 -1
  29. package/dist/experimental/plan_and_execute/prompt.d.ts +2 -1
  30. package/dist/load/import_map.cjs +3 -2
  31. package/dist/load/import_map.d.ts +1 -0
  32. package/dist/load/import_map.js +1 -0
  33. package/dist/prompts/chat.cjs +22 -1
  34. package/dist/prompts/chat.d.ts +1 -0
  35. package/dist/prompts/chat.js +22 -1
  36. package/dist/schema/index.d.ts +1 -0
  37. package/dist/tools/convert_to_openai.cjs +2 -1
  38. package/dist/tools/convert_to_openai.js +2 -1
  39. package/dist/tools/index.cjs +2 -1
  40. package/dist/tools/index.d.ts +1 -1
  41. package/dist/tools/index.js +1 -1
  42. package/dist/vectorstores/momento_vector_index.cjs +1 -1
  43. package/dist/vectorstores/momento_vector_index.js +1 -1
  44. package/package.json +15 -7
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/agents/format_scratchpad/openai_tools.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/openai_tools.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/agents/format_scratchpad/openai_tools.js'
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatToOpenAIToolMessages = void 0;
4
+ const index_js_1 = require("../../schema/index.cjs");
5
+ function formatToOpenAIToolMessages(steps) {
6
+ return steps.flatMap(({ action, observation }) => {
7
+ if ("messageLog" in action && action.messageLog !== undefined) {
8
+ const log = action.messageLog;
9
+ return log.concat(new index_js_1.ToolMessage({
10
+ content: observation,
11
+ tool_call_id: action.toolCallId,
12
+ }));
13
+ }
14
+ else {
15
+ return [new index_js_1.AIMessage(action.log)];
16
+ }
17
+ });
18
+ }
19
+ exports.formatToOpenAIToolMessages = formatToOpenAIToolMessages;
@@ -0,0 +1,3 @@
1
+ import type { ToolsAgentStep } from "../openai/output_parser.js";
2
+ import { type BaseMessage } from "../../schema/index.js";
3
+ export declare function formatToOpenAIToolMessages(steps: ToolsAgentStep[]): BaseMessage[];
@@ -0,0 +1,15 @@
1
+ import { ToolMessage, AIMessage, } from "../../schema/index.js";
2
+ export function formatToOpenAIToolMessages(steps) {
3
+ return steps.flatMap(({ action, observation }) => {
4
+ if ("messageLog" in action && action.messageLog !== undefined) {
5
+ const log = action.messageLog;
6
+ return log.concat(new ToolMessage({
7
+ content: observation,
8
+ tool_call_id: action.toolCallId,
9
+ }));
10
+ }
11
+ else {
12
+ return [new AIMessage(action.log)];
13
+ }
14
+ });
15
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OpenAIFunctionsAgentOutputParser = void 0;
3
+ exports.OpenAIToolsAgentOutputParser = exports.OpenAIFunctionsAgentOutputParser = void 0;
4
4
  const index_js_1 = require("../../schema/index.cjs");
5
5
  const types_js_1 = require("../types.cjs");
6
6
  const output_parser_js_1 = require("../../schema/output_parser.cjs");
@@ -66,3 +66,68 @@ class OpenAIFunctionsAgentOutputParser extends types_js_1.AgentActionOutputParse
66
66
  }
67
67
  }
68
68
  exports.OpenAIFunctionsAgentOutputParser = OpenAIFunctionsAgentOutputParser;
69
+ class OpenAIToolsAgentOutputParser extends types_js_1.AgentMultiActionOutputParser {
70
+ constructor() {
71
+ super(...arguments);
72
+ Object.defineProperty(this, "lc_namespace", {
73
+ enumerable: true,
74
+ configurable: true,
75
+ writable: true,
76
+ value: ["langchain", "agents", "openai"]
77
+ });
78
+ }
79
+ static lc_name() {
80
+ return "OpenAIToolsAgentOutputParser";
81
+ }
82
+ async parse(text) {
83
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
84
+ }
85
+ async parseResult(generations) {
86
+ if ("message" in generations[0] && (0, index_js_1.isBaseMessage)(generations[0].message)) {
87
+ return this.parseAIMessage(generations[0].message);
88
+ }
89
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
90
+ }
91
+ /**
92
+ * Parses the output message into a ToolsAgentAction[] or AgentFinish
93
+ * object.
94
+ * @param message The BaseMessage to parse.
95
+ * @returns A ToolsAgentAction[] or AgentFinish object.
96
+ */
97
+ parseAIMessage(message) {
98
+ if (message.content && typeof message.content !== "string") {
99
+ throw new Error("This agent cannot parse non-string model responses.");
100
+ }
101
+ if (message.additional_kwargs.tool_calls) {
102
+ const toolCalls = message.additional_kwargs.tool_calls;
103
+ try {
104
+ return toolCalls.map((toolCall, i) => {
105
+ const toolInput = toolCall.function.arguments
106
+ ? JSON.parse(toolCall.function.arguments)
107
+ : {};
108
+ const messageLog = i === 0 ? [message] : [];
109
+ return {
110
+ tool: toolCall.function.name,
111
+ toolInput,
112
+ toolCallId: toolCall.id,
113
+ log: `Invoking "${toolCall.function.name}" with ${toolCall.function.arguments ?? "{}"}\n${message.content}`,
114
+ messageLog,
115
+ };
116
+ });
117
+ }
118
+ catch (error) {
119
+ throw new output_parser_js_1.OutputParserException(`Failed to parse tool arguments from chat model response. Text: "${JSON.stringify(toolCalls)}". ${error}`);
120
+ }
121
+ }
122
+ else {
123
+ return {
124
+ returnValues: { output: message.content },
125
+ log: message.content,
126
+ };
127
+ }
128
+ }
129
+ getFormatInstructions() {
130
+ throw new Error("getFormatInstructions not implemented inside OpenAIToolsAgentOutputParser.");
131
+ }
132
+ }
133
+ exports.OpenAIToolsAgentOutputParser = OpenAIToolsAgentOutputParser;
@@ -1,5 +1,5 @@
1
- import { AgentAction, AgentFinish, BaseMessage, ChatGeneration } from "../../schema/index.js";
2
- import { AgentActionOutputParser } from "../types.js";
1
+ import { AgentAction, AgentFinish, AgentStep, BaseMessage, ChatGeneration } from "../../schema/index.js";
2
+ import { AgentActionOutputParser, AgentMultiActionOutputParser } from "../types.js";
3
3
  /**
4
4
  * Type that represents an agent action with an optional message log.
5
5
  */
@@ -20,3 +20,27 @@ export declare class OpenAIFunctionsAgentOutputParser extends AgentActionOutputP
20
20
  parseAIMessage(message: BaseMessage): FunctionsAgentAction | AgentFinish;
21
21
  getFormatInstructions(): string;
22
22
  }
23
+ /**
24
+ * Type that represents an agent action with an optional message log.
25
+ */
26
+ export type ToolsAgentAction = AgentAction & {
27
+ toolCallId: string;
28
+ messageLog?: BaseMessage[];
29
+ };
30
+ export type ToolsAgentStep = AgentStep & {
31
+ action: ToolsAgentAction;
32
+ };
33
+ export declare class OpenAIToolsAgentOutputParser extends AgentMultiActionOutputParser {
34
+ lc_namespace: string[];
35
+ static lc_name(): string;
36
+ parse(text: string): Promise<AgentAction[] | AgentFinish>;
37
+ parseResult(generations: ChatGeneration[]): Promise<AgentFinish | ToolsAgentAction[]>;
38
+ /**
39
+ * Parses the output message into a ToolsAgentAction[] or AgentFinish
40
+ * object.
41
+ * @param message The BaseMessage to parse.
42
+ * @returns A ToolsAgentAction[] or AgentFinish object.
43
+ */
44
+ parseAIMessage(message: BaseMessage): ToolsAgentAction[] | AgentFinish;
45
+ getFormatInstructions(): string;
46
+ }
@@ -1,5 +1,5 @@
1
1
  import { isBaseMessage, } from "../../schema/index.js";
2
- import { AgentActionOutputParser } from "../types.js";
2
+ import { AgentActionOutputParser, AgentMultiActionOutputParser, } from "../types.js";
3
3
  import { OutputParserException } from "../../schema/output_parser.js";
4
4
  export class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
5
5
  constructor() {
@@ -62,3 +62,67 @@ export class OpenAIFunctionsAgentOutputParser extends AgentActionOutputParser {
62
62
  throw new Error("getFormatInstructions not implemented inside OpenAIFunctionsAgentOutputParser.");
63
63
  }
64
64
  }
65
+ export class OpenAIToolsAgentOutputParser extends AgentMultiActionOutputParser {
66
+ constructor() {
67
+ super(...arguments);
68
+ Object.defineProperty(this, "lc_namespace", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: ["langchain", "agents", "openai"]
73
+ });
74
+ }
75
+ static lc_name() {
76
+ return "OpenAIToolsAgentOutputParser";
77
+ }
78
+ async parse(text) {
79
+ throw new Error(`OpenAIFunctionsAgentOutputParser can only parse messages.\nPassed input: ${text}`);
80
+ }
81
+ async parseResult(generations) {
82
+ if ("message" in generations[0] && isBaseMessage(generations[0].message)) {
83
+ return this.parseAIMessage(generations[0].message);
84
+ }
85
+ throw new Error("parseResult on OpenAIFunctionsAgentOutputParser only works on ChatGeneration output");
86
+ }
87
+ /**
88
+ * Parses the output message into a ToolsAgentAction[] or AgentFinish
89
+ * object.
90
+ * @param message The BaseMessage to parse.
91
+ * @returns A ToolsAgentAction[] or AgentFinish object.
92
+ */
93
+ parseAIMessage(message) {
94
+ if (message.content && typeof message.content !== "string") {
95
+ throw new Error("This agent cannot parse non-string model responses.");
96
+ }
97
+ if (message.additional_kwargs.tool_calls) {
98
+ const toolCalls = message.additional_kwargs.tool_calls;
99
+ try {
100
+ return toolCalls.map((toolCall, i) => {
101
+ const toolInput = toolCall.function.arguments
102
+ ? JSON.parse(toolCall.function.arguments)
103
+ : {};
104
+ const messageLog = i === 0 ? [message] : [];
105
+ return {
106
+ tool: toolCall.function.name,
107
+ toolInput,
108
+ toolCallId: toolCall.id,
109
+ log: `Invoking "${toolCall.function.name}" with ${toolCall.function.arguments ?? "{}"}\n${message.content}`,
110
+ messageLog,
111
+ };
112
+ });
113
+ }
114
+ catch (error) {
115
+ throw new OutputParserException(`Failed to parse tool arguments from chat model response. Text: "${JSON.stringify(toolCalls)}". ${error}`);
116
+ }
117
+ }
118
+ else {
119
+ return {
120
+ returnValues: { output: message.content },
121
+ log: message.content,
122
+ };
123
+ }
124
+ }
125
+ getFormatInstructions() {
126
+ throw new Error("getFormatInstructions not implemented inside OpenAIToolsAgentOutputParser.");
127
+ }
128
+ }
@@ -102,9 +102,8 @@ class StructuredChatAgent extends agent_js_1.Agent {
102
102
  * @param args.memoryPrompts List of historical prompts from memory.
103
103
  */
104
104
  static createPrompt(tools, args) {
105
- const { prefix = prompt_js_2.PREFIX, suffix = prompt_js_2.SUFFIX, inputVariables = ["input", "agent_scratchpad"], memoryPrompts = [], } = args ?? {};
105
+ const { prefix = prompt_js_2.PREFIX, suffix = prompt_js_2.SUFFIX, inputVariables = ["input", "agent_scratchpad"], humanMessageTemplate = "{input}\n\n{agent_scratchpad}", memoryPrompts = [], } = args ?? {};
106
106
  const template = [prefix, prompt_js_2.FORMAT_INSTRUCTIONS, suffix].join("\n\n");
107
- const humanMessageTemplate = "{input}\n\n{agent_scratchpad}";
108
107
  const messages = [
109
108
  new chat_js_1.SystemMessagePromptTemplate(new prompt_js_1.PromptTemplate({
110
109
  template,
@@ -15,6 +15,8 @@ export interface StructuredChatCreatePromptArgs {
15
15
  suffix?: string;
16
16
  /** String to put before the list of tools. */
17
17
  prefix?: string;
18
+ /** String to use directly as the human message template. */
19
+ humanMessageTemplate?: string;
18
20
  /** List of input variables the final prompt will expect. */
19
21
  inputVariables?: string[];
20
22
  /** List of historical prompts from memory. */
@@ -99,9 +99,8 @@ export class StructuredChatAgent extends Agent {
99
99
  * @param args.memoryPrompts List of historical prompts from memory.
100
100
  */
101
101
  static createPrompt(tools, args) {
102
- const { prefix = PREFIX, suffix = SUFFIX, inputVariables = ["input", "agent_scratchpad"], memoryPrompts = [], } = args ?? {};
102
+ const { prefix = PREFIX, suffix = SUFFIX, inputVariables = ["input", "agent_scratchpad"], humanMessageTemplate = "{input}\n\n{agent_scratchpad}", memoryPrompts = [], } = args ?? {};
103
103
  const template = [prefix, FORMAT_INSTRUCTIONS, suffix].join("\n\n");
104
- const humanMessageTemplate = "{input}\n\n{agent_scratchpad}";
105
104
  const messages = [
106
105
  new SystemMessagePromptTemplate(new PromptTemplate({
107
106
  template,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentActionOutputParser = void 0;
3
+ exports.AgentMultiActionOutputParser = exports.AgentActionOutputParser = void 0;
4
4
  const output_parser_js_1 = require("../schema/output_parser.cjs");
5
5
  /**
6
6
  * Abstract class representing an output parser specifically for agent
@@ -10,3 +10,10 @@ const output_parser_js_1 = require("../schema/output_parser.cjs");
10
10
  class AgentActionOutputParser extends output_parser_js_1.BaseOutputParser {
11
11
  }
12
12
  exports.AgentActionOutputParser = AgentActionOutputParser;
13
+ /**
14
+ * Abstract class representing an output parser specifically for agents
15
+ * that return multiple actions.
16
+ */
17
+ class AgentMultiActionOutputParser extends output_parser_js_1.BaseOutputParser {
18
+ }
19
+ exports.AgentMultiActionOutputParser = AgentMultiActionOutputParser;
@@ -31,6 +31,12 @@ export interface RunnableAgentInput {
31
31
  */
32
32
  export declare abstract class AgentActionOutputParser extends BaseOutputParser<AgentAction | AgentFinish> {
33
33
  }
34
+ /**
35
+ * Abstract class representing an output parser specifically for agents
36
+ * that return multiple actions.
37
+ */
38
+ export declare abstract class AgentMultiActionOutputParser extends BaseOutputParser<AgentAction[] | AgentFinish> {
39
+ }
34
40
  /**
35
41
  * Type representing the stopping method for an agent. It can be either
36
42
  * 'force' or 'generate'.
@@ -6,3 +6,9 @@ import { BaseOutputParser } from "../schema/output_parser.js";
6
6
  */
7
7
  export class AgentActionOutputParser extends BaseOutputParser {
8
8
  }
9
+ /**
10
+ * Abstract class representing an output parser specifically for agents
11
+ * that return multiple actions.
12
+ */
13
+ export class AgentMultiActionOutputParser extends BaseOutputParser {
14
+ }
@@ -59,9 +59,23 @@ class PDFLoader extends buffer_js_1.BufferLoader {
59
59
  if (content.items.length === 0) {
60
60
  continue;
61
61
  }
62
- const text = content.items
63
- .map((item) => item.str)
64
- .join("\n");
62
+ // Eliminate excessive newlines
63
+ // Source: https://github.com/albertcui/pdf-parse/blob/7086fc1cc9058545cdf41dd0646d6ae5832c7107/lib/pdf-parse.js#L16
64
+ let lastY;
65
+ const textItems = [];
66
+ for (const item of content.items) {
67
+ if ("str" in item) {
68
+ if (lastY === item.transform[5] || !lastY) {
69
+ textItems.push(item.str);
70
+ }
71
+ else {
72
+ textItems.push(`\n${item.str}`);
73
+ }
74
+ // eslint-disable-next-line prefer-destructuring
75
+ lastY = item.transform[5];
76
+ }
77
+ }
78
+ const text = textItems.join(" ");
65
79
  documents.push(new document_js_1.Document({
66
80
  pageContent: text,
67
81
  metadata: {
@@ -56,9 +56,23 @@ export class PDFLoader extends BufferLoader {
56
56
  if (content.items.length === 0) {
57
57
  continue;
58
58
  }
59
- const text = content.items
60
- .map((item) => item.str)
61
- .join("\n");
59
+ // Eliminate excessive newlines
60
+ // Source: https://github.com/albertcui/pdf-parse/blob/7086fc1cc9058545cdf41dd0646d6ae5832c7107/lib/pdf-parse.js#L16
61
+ let lastY;
62
+ const textItems = [];
63
+ for (const item of content.items) {
64
+ if ("str" in item) {
65
+ if (lastY === item.transform[5] || !lastY) {
66
+ textItems.push(item.str);
67
+ }
68
+ else {
69
+ textItems.push(`\n${item.str}`);
70
+ }
71
+ // eslint-disable-next-line prefer-destructuring
72
+ lastY = item.transform[5];
73
+ }
74
+ }
75
+ const text = textItems.join(" ");
62
76
  documents.push(new Document({
63
77
  pageContent: text,
64
78
  metadata: {
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.ApifyDatasetLoader = void 0;
5
5
  const apify_client_1 = require("apify-client");
6
+ const async_caller_js_1 = require("../../util/async_caller.cjs");
6
7
  const base_js_1 = require("../base.cjs");
7
8
  const env_js_1 = require("../../util/env.cjs");
8
9
  /**
@@ -31,13 +32,18 @@ class ApifyDatasetLoader extends base_js_1.BaseDocumentLoader {
31
32
  writable: true,
32
33
  value: void 0
33
34
  });
34
- const apifyApiToken = ApifyDatasetLoader._getApifyApiToken(config.clientOptions);
35
- this.apifyClient = new apify_client_1.ApifyClient({
36
- ...config.clientOptions,
37
- token: apifyApiToken,
35
+ Object.defineProperty(this, "caller", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: void 0
38
40
  });
41
+ const { clientOptions, datasetMappingFunction, ...asyncCallerParams } = config;
42
+ const token = ApifyDatasetLoader._getApifyApiToken(clientOptions);
43
+ this.apifyClient = new apify_client_1.ApifyClient({ ...clientOptions, token });
39
44
  this.datasetId = datasetId;
40
- this.datasetMappingFunction = config.datasetMappingFunction;
45
+ this.datasetMappingFunction = datasetMappingFunction;
46
+ this.caller = new async_caller_js_1.AsyncCaller(asyncCallerParams);
41
47
  }
42
48
  static _getApifyApiToken(config) {
43
49
  return config?.token ?? (0, env_js_1.getEnvironmentVariable)("APIFY_API_TOKEN");
@@ -50,7 +56,7 @@ class ApifyDatasetLoader extends base_js_1.BaseDocumentLoader {
50
56
  */
51
57
  async load() {
52
58
  const datasetItems = (await this.apifyClient.dataset(this.datasetId).listItems({ clean: true })).items;
53
- return datasetItems.map(this.datasetMappingFunction);
59
+ return await Promise.all(datasetItems.map((item) => this.caller.call(async () => this.datasetMappingFunction(item))));
54
60
  }
55
61
  /**
56
62
  * Create an ApifyDatasetLoader by calling an Actor on the Apify platform and waiting for its results to be ready.
@@ -1,11 +1,16 @@
1
1
  import { ActorCallOptions, ApifyClient, ApifyClientOptions, TaskCallOptions } from "apify-client";
2
+ import { AsyncCaller, AsyncCallerParams } from "../../util/async_caller.js";
2
3
  import { BaseDocumentLoader, DocumentLoader } from "../base.js";
3
4
  import { Document } from "../../document.js";
4
5
  /**
5
6
  * A type that represents a function that takes a single object (an Apify
6
7
  * dataset item) and converts it to an instance of the Document class.
7
8
  */
8
- export type ApifyDatasetMappingFunction<Metadata extends Record<string, any>> = (item: Record<string | number, unknown>) => Document<Metadata>;
9
+ export type ApifyDatasetMappingFunction<Metadata extends Record<string, any>> = (item: Record<string | number, unknown>) => Document<Metadata> | Promise<Document<Metadata>>;
10
+ export interface ApifyDatasetLoaderConfig<Metadata extends Record<string, any>> extends AsyncCallerParams {
11
+ datasetMappingFunction: ApifyDatasetMappingFunction<Metadata>;
12
+ clientOptions?: ApifyClientOptions;
13
+ }
9
14
  /**
10
15
  * A class that extends the BaseDocumentLoader and implements the
11
16
  * DocumentLoader interface. It represents a document loader that loads
@@ -14,11 +19,9 @@ export type ApifyDatasetMappingFunction<Metadata extends Record<string, any>> =
14
19
  export declare class ApifyDatasetLoader<Metadata extends Record<string, any>> extends BaseDocumentLoader implements DocumentLoader {
15
20
  protected apifyClient: ApifyClient;
16
21
  protected datasetId: string;
17
- protected datasetMappingFunction: (item: Record<string | number, unknown>) => Document<Metadata>;
18
- constructor(datasetId: string, config: {
19
- datasetMappingFunction: ApifyDatasetMappingFunction<Metadata>;
20
- clientOptions?: ApifyClientOptions;
21
- });
22
+ protected datasetMappingFunction: ApifyDatasetMappingFunction<Metadata>;
23
+ protected caller: AsyncCaller;
24
+ constructor(datasetId: string, config: ApifyDatasetLoaderConfig<Metadata>);
22
25
  private static _getApifyApiToken;
23
26
  /**
24
27
  * Retrieves the dataset items from the Apify platform and applies the
@@ -1,5 +1,6 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import { ApifyClient, } from "apify-client";
3
+ import { AsyncCaller } from "../../util/async_caller.js";
3
4
  import { BaseDocumentLoader } from "../base.js";
4
5
  import { getEnvironmentVariable } from "../../util/env.js";
5
6
  /**
@@ -28,13 +29,18 @@ export class ApifyDatasetLoader extends BaseDocumentLoader {
28
29
  writable: true,
29
30
  value: void 0
30
31
  });
31
- const apifyApiToken = ApifyDatasetLoader._getApifyApiToken(config.clientOptions);
32
- this.apifyClient = new ApifyClient({
33
- ...config.clientOptions,
34
- token: apifyApiToken,
32
+ Object.defineProperty(this, "caller", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: void 0
35
37
  });
38
+ const { clientOptions, datasetMappingFunction, ...asyncCallerParams } = config;
39
+ const token = ApifyDatasetLoader._getApifyApiToken(clientOptions);
40
+ this.apifyClient = new ApifyClient({ ...clientOptions, token });
36
41
  this.datasetId = datasetId;
37
- this.datasetMappingFunction = config.datasetMappingFunction;
42
+ this.datasetMappingFunction = datasetMappingFunction;
43
+ this.caller = new AsyncCaller(asyncCallerParams);
38
44
  }
39
45
  static _getApifyApiToken(config) {
40
46
  return config?.token ?? getEnvironmentVariable("APIFY_API_TOKEN");
@@ -47,7 +53,7 @@ export class ApifyDatasetLoader extends BaseDocumentLoader {
47
53
  */
48
54
  async load() {
49
55
  const datasetItems = (await this.apifyClient.dataset(this.datasetId).listItems({ clean: true })).items;
50
- return datasetItems.map(this.datasetMappingFunction);
56
+ return await Promise.all(datasetItems.map((item) => this.caller.call(async () => this.datasetMappingFunction(item))));
51
57
  }
52
58
  /**
53
59
  * Create an ApifyDatasetLoader by calling an Actor on the Apify platform and waiting for its results to be ready.
@@ -52,9 +52,23 @@ class WebPDFLoader extends base_js_1.BaseDocumentLoader {
52
52
  if (content.items.length === 0) {
53
53
  continue;
54
54
  }
55
- const text = content.items
56
- .map((item) => item.str)
57
- .join("\n");
55
+ // Eliminate excessive newlines
56
+ // Source: https://github.com/albertcui/pdf-parse/blob/7086fc1cc9058545cdf41dd0646d6ae5832c7107/lib/pdf-parse.js#L16
57
+ let lastY;
58
+ const textItems = [];
59
+ for (const item of content.items) {
60
+ if ("str" in item) {
61
+ if (lastY === item.transform[5] || !lastY) {
62
+ textItems.push(item.str);
63
+ }
64
+ else {
65
+ textItems.push(`\n${item.str}`);
66
+ }
67
+ // eslint-disable-next-line prefer-destructuring
68
+ lastY = item.transform[5];
69
+ }
70
+ }
71
+ const text = textItems.join(" ");
58
72
  documents.push(new document_js_1.Document({
59
73
  pageContent: text,
60
74
  metadata: {
@@ -49,9 +49,23 @@ export class WebPDFLoader extends BaseDocumentLoader {
49
49
  if (content.items.length === 0) {
50
50
  continue;
51
51
  }
52
- const text = content.items
53
- .map((item) => item.str)
54
- .join("\n");
52
+ // Eliminate excessive newlines
53
+ // Source: https://github.com/albertcui/pdf-parse/blob/7086fc1cc9058545cdf41dd0646d6ae5832c7107/lib/pdf-parse.js#L16
54
+ let lastY;
55
+ const textItems = [];
56
+ for (const item of content.items) {
57
+ if ("str" in item) {
58
+ if (lastY === item.transform[5] || !lastY) {
59
+ textItems.push(item.str);
60
+ }
61
+ else {
62
+ textItems.push(`\n${item.str}`);
63
+ }
64
+ // eslint-disable-next-line prefer-destructuring
65
+ lastY = item.transform[5];
66
+ }
67
+ }
68
+ const text = textItems.join(" ");
55
69
  documents.push(new Document({
56
70
  pageContent: text,
57
71
  metadata: {
@@ -63,6 +63,43 @@ class PuppeteerWebBaseLoader extends base_js_1.BaseDocumentLoader {
63
63
  const metadata = { source: this.webPath };
64
64
  return [new document_js_1.Document({ pageContent: text, metadata })];
65
65
  }
66
+ /**
67
+ * Static class method used to screenshot a web page and return
68
+ * it as a {@link Document} object where the pageContent property
69
+ * is the screenshot encoded in base64.
70
+ *
71
+ * @param {string} url
72
+ * @param {PuppeteerWebBaseLoaderOptions} options
73
+ * @returns {Document} A document object containing the screenshot of the page encoded in base64.
74
+ */
75
+ static async _screenshot(url, options) {
76
+ const { launch } = await PuppeteerWebBaseLoader.imports();
77
+ const browser = await launch({
78
+ headless: true,
79
+ defaultViewport: null,
80
+ ignoreDefaultArgs: ["--disable-extensions"],
81
+ ...options?.launchOptions,
82
+ });
83
+ const page = await browser.newPage();
84
+ await page.goto(url, {
85
+ timeout: 180000,
86
+ waitUntil: "domcontentloaded",
87
+ ...options?.gotoOptions,
88
+ });
89
+ const screenshot = await page.screenshot();
90
+ const base64 = screenshot.toString("base64");
91
+ const metadata = { source: url };
92
+ return new document_js_1.Document({ pageContent: base64, metadata });
93
+ }
94
+ /**
95
+ * Screenshot a web page and return it as a {@link Document} object where
96
+ * the pageContent property is the screenshot encoded in base64.
97
+ *
98
+ * @returns {Promise<Document>} A document object containing the screenshot of the page encoded in base64.
99
+ */
100
+ async screenshot() {
101
+ return PuppeteerWebBaseLoader._screenshot(this.webPath, this.options);
102
+ }
66
103
  /**
67
104
  * Static method that imports the necessary Puppeteer modules. It returns
68
105
  * a Promise that resolves to an object containing the imported modules.
@@ -40,6 +40,23 @@ export declare class PuppeteerWebBaseLoader extends BaseDocumentLoader implement
40
40
  * @returns Promise that resolves to an array of Document objects.
41
41
  */
42
42
  load(): Promise<Document[]>;
43
+ /**
44
+ * Static class method used to screenshot a web page and return
45
+ * it as a {@link Document} object where the pageContent property
46
+ * is the screenshot encoded in base64.
47
+ *
48
+ * @param {string} url
49
+ * @param {PuppeteerWebBaseLoaderOptions} options
50
+ * @returns {Document} A document object containing the screenshot of the page encoded in base64.
51
+ */
52
+ static _screenshot(url: string, options?: PuppeteerWebBaseLoaderOptions): Promise<Document>;
53
+ /**
54
+ * Screenshot a web page and return it as a {@link Document} object where
55
+ * the pageContent property is the screenshot encoded in base64.
56
+ *
57
+ * @returns {Promise<Document>} A document object containing the screenshot of the page encoded in base64.
58
+ */
59
+ screenshot(): Promise<Document>;
43
60
  /**
44
61
  * Static method that imports the necessary Puppeteer modules. It returns
45
62
  * a Promise that resolves to an object containing the imported modules.
@@ -60,6 +60,43 @@ export class PuppeteerWebBaseLoader extends BaseDocumentLoader {
60
60
  const metadata = { source: this.webPath };
61
61
  return [new Document({ pageContent: text, metadata })];
62
62
  }
63
+ /**
64
+ * Static class method used to screenshot a web page and return
65
+ * it as a {@link Document} object where the pageContent property
66
+ * is the screenshot encoded in base64.
67
+ *
68
+ * @param {string} url
69
+ * @param {PuppeteerWebBaseLoaderOptions} options
70
+ * @returns {Document} A document object containing the screenshot of the page encoded in base64.
71
+ */
72
+ static async _screenshot(url, options) {
73
+ const { launch } = await PuppeteerWebBaseLoader.imports();
74
+ const browser = await launch({
75
+ headless: true,
76
+ defaultViewport: null,
77
+ ignoreDefaultArgs: ["--disable-extensions"],
78
+ ...options?.launchOptions,
79
+ });
80
+ const page = await browser.newPage();
81
+ await page.goto(url, {
82
+ timeout: 180000,
83
+ waitUntil: "domcontentloaded",
84
+ ...options?.gotoOptions,
85
+ });
86
+ const screenshot = await page.screenshot();
87
+ const base64 = screenshot.toString("base64");
88
+ const metadata = { source: url };
89
+ return new Document({ pageContent: base64, metadata });
90
+ }
91
+ /**
92
+ * Screenshot a web page and return it as a {@link Document} object where
93
+ * the pageContent property is the screenshot encoded in base64.
94
+ *
95
+ * @returns {Promise<Document>} A document object containing the screenshot of the page encoded in base64.
96
+ */
97
+ async screenshot() {
98
+ return PuppeteerWebBaseLoader._screenshot(this.webPath, this.options);
99
+ }
63
100
  /**
64
101
  * Static method that imports the necessary Puppeteer modules. It returns
65
102
  * a Promise that resolves to an object containing the imported modules.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PlanAndExecuteAgentExecutor = void 0;
3
+ exports.PlanAndExecuteAgentExecutor = exports.isDynamicStructuredTool = void 0;
4
4
  const base_js_1 = require("../../chains/base.cjs");
5
5
  const base_js_2 = require("./base.cjs");
6
6
  const executor_js_1 = require("../../agents/executor.cjs");
@@ -8,6 +8,21 @@ const prompt_js_1 = require("./prompt.cjs");
8
8
  const llm_chain_js_1 = require("../../chains/llm_chain.cjs");
9
9
  const outputParser_js_1 = require("./outputParser.cjs");
10
10
  const index_js_1 = require("../../agents/chat/index.cjs");
11
+ const index_js_2 = require("../../agents/index.cjs");
12
+ /**
13
+ * A utility function to distiguish a dynamicstructuredtool over other tools.
14
+ * @param tool the tool to test
15
+ * @returns bool
16
+ */
17
+ function isDynamicStructuredTool(tool) {
18
+ // We check for the existence of the static lc_name method in the object's constructor
19
+ return (
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
+ typeof tool.constructor.lc_name === "function" &&
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
+ tool.constructor.lc_name() === "DynamicStructuredTool");
24
+ }
25
+ exports.isDynamicStructuredTool = isDynamicStructuredTool;
11
26
  /**
12
27
  * Class representing a plan-and-execute agent executor. This agent
13
28
  * decides on the full sequence of actions upfront, then executes them all
@@ -86,7 +101,18 @@ class PlanAndExecuteAgentExecutor extends base_js_1.BaseChain {
86
101
  * @returns A new ChainStepExecutor instance.
87
102
  */
88
103
  static getDefaultStepExecutor({ llm, tools, humanMessageTemplate = prompt_js_1.DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE, }) {
89
- const agent = index_js_1.ChatAgent.fromLLMAndTools(llm, tools, {
104
+ let agent;
105
+ if (isDynamicStructuredTool(tools[0])) {
106
+ agent = index_js_2.StructuredChatAgent.fromLLMAndTools(llm, tools, {
107
+ humanMessageTemplate,
108
+ inputVariables: ["previous_steps", "current_step", "agent_scratchpad"],
109
+ });
110
+ return new base_js_2.ChainStepExecutor(executor_js_1.AgentExecutor.fromAgentAndTools({
111
+ agent,
112
+ tools,
113
+ }));
114
+ }
115
+ agent = index_js_1.ChatAgent.fromLLMAndTools(llm, tools, {
90
116
  humanMessageTemplate,
91
117
  });
92
118
  return new base_js_2.ChainStepExecutor(executor_js_1.AgentExecutor.fromAgentAndTools({
@@ -4,7 +4,14 @@ import { ChainValues } from "../../schema/index.js";
4
4
  import { BaseLanguageModel } from "../../base_language/index.js";
5
5
  import { CallbackManagerForChainRun } from "../../callbacks/manager.js";
6
6
  import { Tool } from "../../tools/base.js";
7
+ import { DynamicStructuredTool } from "../../tools/dynamic.js";
7
8
  import { SerializedLLMChain } from "../../chains/serde.js";
9
+ /**
10
+ * A utility function to distiguish a dynamicstructuredtool over other tools.
11
+ * @param tool the tool to test
12
+ * @returns bool
13
+ */
14
+ export declare function isDynamicStructuredTool(tool: Tool | DynamicStructuredTool): tool is DynamicStructuredTool;
8
15
  /**
9
16
  * Interface for the input to the PlanAndExecuteAgentExecutor class. It
10
17
  * extends ChainInputs and includes additional properties for the planner,
@@ -42,7 +49,7 @@ export declare class PlanAndExecuteAgentExecutor extends BaseChain {
42
49
  */
43
50
  static getDefaultPlanner({ llm, tools, }: {
44
51
  llm: BaseLanguageModel;
45
- tools: Tool[];
52
+ tools: Tool[] | DynamicStructuredTool[];
46
53
  }): Promise<LLMPlanner>;
47
54
  /**
48
55
  * Static method that returns a default step executor for the agent. It
@@ -55,7 +62,7 @@ export declare class PlanAndExecuteAgentExecutor extends BaseChain {
55
62
  */
56
63
  static getDefaultStepExecutor({ llm, tools, humanMessageTemplate, }: {
57
64
  llm: BaseLanguageModel;
58
- tools: Tool[];
65
+ tools: Tool[] | DynamicStructuredTool[];
59
66
  humanMessageTemplate?: string;
60
67
  }): ChainStepExecutor;
61
68
  /**
@@ -70,7 +77,7 @@ export declare class PlanAndExecuteAgentExecutor extends BaseChain {
70
77
  */
71
78
  static fromLLMAndTools({ llm, tools, humanMessageTemplate, }: {
72
79
  llm: BaseLanguageModel;
73
- tools: Tool[];
80
+ tools: Tool[] | DynamicStructuredTool[];
74
81
  humanMessageTemplate?: string;
75
82
  } & Omit<PlanAndExecuteAgentExecutorInput, "planner" | "stepExecutor">): Promise<PlanAndExecuteAgentExecutor>;
76
83
  /** @ignore */
@@ -5,6 +5,20 @@ import { DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE, getPlannerChatPrompt
5
5
  import { LLMChain } from "../../chains/llm_chain.js";
6
6
  import { PlanOutputParser } from "./outputParser.js";
7
7
  import { ChatAgent } from "../../agents/chat/index.js";
8
+ import { StructuredChatAgent } from "../../agents/index.js";
9
+ /**
10
+ * A utility function to distiguish a dynamicstructuredtool over other tools.
11
+ * @param tool the tool to test
12
+ * @returns bool
13
+ */
14
+ export function isDynamicStructuredTool(tool) {
15
+ // We check for the existence of the static lc_name method in the object's constructor
16
+ return (
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ typeof tool.constructor.lc_name === "function" &&
19
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
20
+ tool.constructor.lc_name() === "DynamicStructuredTool");
21
+ }
8
22
  /**
9
23
  * Class representing a plan-and-execute agent executor. This agent
10
24
  * decides on the full sequence of actions upfront, then executes them all
@@ -83,7 +97,18 @@ export class PlanAndExecuteAgentExecutor extends BaseChain {
83
97
  * @returns A new ChainStepExecutor instance.
84
98
  */
85
99
  static getDefaultStepExecutor({ llm, tools, humanMessageTemplate = DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE, }) {
86
- const agent = ChatAgent.fromLLMAndTools(llm, tools, {
100
+ let agent;
101
+ if (isDynamicStructuredTool(tools[0])) {
102
+ agent = StructuredChatAgent.fromLLMAndTools(llm, tools, {
103
+ humanMessageTemplate,
104
+ inputVariables: ["previous_steps", "current_step", "agent_scratchpad"],
105
+ });
106
+ return new ChainStepExecutor(AgentExecutor.fromAgentAndTools({
107
+ agent,
108
+ tools,
109
+ }));
110
+ }
111
+ agent = ChatAgent.fromLLMAndTools(llm, tools, {
87
112
  humanMessageTemplate,
88
113
  });
89
114
  return new ChainStepExecutor(AgentExecutor.fromAgentAndTools({
@@ -1,5 +1,6 @@
1
1
  import { ChatPromptTemplate } from "../../prompts/chat.js";
2
2
  import { Tool } from "../../tools/base.js";
3
+ import { DynamicStructuredTool } from "../../tools/dynamic.js";
3
4
  export declare const PLANNER_SYSTEM_PROMPT_MESSAGE_TEMPLATE: string;
4
5
  export declare const DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE = "Previous steps: {previous_steps}\n\nCurrent objective: {current_step}\n\n{agent_scratchpad}\n\nYou may extract and combine relevant data from your previous steps when responding to me.";
5
6
  /**
@@ -9,4 +10,4 @@ export declare const DEFAULT_STEP_EXECUTOR_HUMAN_CHAT_MESSAGE_TEMPLATE = "Previo
9
10
  * @param tools the tools available to the `planner`
10
11
  * @returns
11
12
  */
12
- export declare const getPlannerChatPrompt: (tools: Tool[]) => Promise<ChatPromptTemplate<import("../../schema/index.js").InputValues<string>, any>>;
13
+ export declare const getPlannerChatPrompt: (tools: Tool[] | DynamicStructuredTool[]) => Promise<ChatPromptTemplate<import("../../schema/index.js").InputValues<string>, any>>;
@@ -24,12 +24,13 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  return result;
25
25
  };
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.chat_models__cloudflare_workersai = exports.chat_models__anthropic = exports.chat_models__openai = exports.chat_models__base = exports.document_transformers__openai_functions = exports.document_loaders__web__sort_xyz_blockchain = exports.document_loaders__web__serpapi = exports.document_loaders__web__searchapi = exports.document_loaders__base = exports.document = exports.memory = exports.text_splitter = exports.vectorstores__xata = exports.vectorstores__vectara = exports.vectorstores__prisma = exports.vectorstores__memory = exports.vectorstores__base = exports.prompts = exports.llms__fake = exports.llms__yandex = exports.llms__fireworks = exports.llms__ollama = exports.llms__cloudflare_workersai = exports.llms__aleph_alpha = exports.llms__ai21 = exports.llms__openai = exports.llms__base = exports.embeddings__voyage = exports.embeddings__minimax = exports.embeddings__openai = exports.embeddings__ollama = exports.embeddings__fake = exports.embeddings__cache_backed = exports.embeddings__base = exports.chains__openai_functions = exports.chains__combine_documents__reduce = exports.chains = exports.tools__render = exports.tools = exports.base_language = exports.agents__openai__output_parser = exports.agents__xml__output_parser = exports.agents__react__output_parser = exports.agents__format_scratchpad__log_to_message = exports.agents__format_scratchpad__xml = exports.agents__format_scratchpad__log = exports.agents__format_scratchpad = exports.agents__toolkits = exports.agents = exports.load__serializable = void 0;
28
- exports.runnables__remote = exports.evaluation = exports.experimental__chains__violation_of_expectations = exports.experimental__chat_models__bittensor = exports.experimental__plan_and_execute = exports.experimental__generative_agents = exports.experimental__babyagi = exports.experimental__openai_assistant = exports.experimental__autogpt = exports.util__time = exports.util__math = exports.util__document = exports.storage__in_memory = exports.storage__encoder_backed = exports.stores__message__in_memory = exports.stores__file__in_memory = exports.stores__doc__in_memory = exports.cache = exports.retrievers__vespa = exports.retrievers__score_threshold = exports.retrievers__hyde = exports.retrievers__document_compressors__embeddings_filter = exports.retrievers__document_compressors__chain_extract = exports.retrievers__time_weighted = exports.retrievers__tavily_search_api = exports.retrievers__parent_document = exports.retrievers__multi_vector = exports.retrievers__multi_query = exports.retrievers__document_compressors = exports.retrievers__contextual_compression = exports.retrievers__databerry = exports.retrievers__chaindesk = exports.retrievers__remote = exports.output_parsers = exports.callbacks = exports.schema__storage = exports.schema__runnable = exports.schema__retriever = exports.schema__query_constructor = exports.schema__prompt_template = exports.schema__output_parser = exports.schema__document = exports.schema = exports.chat_models__fake = exports.chat_models__yandex = exports.chat_models__minimax = exports.chat_models__ollama = exports.chat_models__baiduwenxin = exports.chat_models__fireworks = void 0;
27
+ exports.chat_models__anthropic = exports.chat_models__openai = exports.chat_models__base = exports.document_transformers__openai_functions = exports.document_loaders__web__sort_xyz_blockchain = exports.document_loaders__web__serpapi = exports.document_loaders__web__searchapi = exports.document_loaders__base = exports.document = exports.memory = exports.text_splitter = exports.vectorstores__xata = exports.vectorstores__vectara = exports.vectorstores__prisma = exports.vectorstores__memory = exports.vectorstores__base = exports.prompts = exports.llms__fake = exports.llms__yandex = exports.llms__fireworks = exports.llms__ollama = exports.llms__cloudflare_workersai = exports.llms__aleph_alpha = exports.llms__ai21 = exports.llms__openai = exports.llms__base = exports.embeddings__voyage = exports.embeddings__minimax = exports.embeddings__openai = exports.embeddings__ollama = exports.embeddings__fake = exports.embeddings__cache_backed = exports.embeddings__base = exports.chains__openai_functions = exports.chains__combine_documents__reduce = exports.chains = exports.tools__render = exports.tools = exports.base_language = exports.agents__openai__output_parser = exports.agents__xml__output_parser = exports.agents__react__output_parser = exports.agents__format_scratchpad__log_to_message = exports.agents__format_scratchpad__xml = exports.agents__format_scratchpad__log = exports.agents__format_scratchpad__openai_tools = exports.agents__format_scratchpad = exports.agents__toolkits = exports.agents = exports.load__serializable = void 0;
28
+ exports.runnables__remote = exports.evaluation = exports.experimental__chains__violation_of_expectations = exports.experimental__chat_models__bittensor = exports.experimental__plan_and_execute = exports.experimental__generative_agents = exports.experimental__babyagi = exports.experimental__openai_assistant = exports.experimental__autogpt = exports.util__time = exports.util__math = exports.util__document = exports.storage__in_memory = exports.storage__encoder_backed = exports.stores__message__in_memory = exports.stores__file__in_memory = exports.stores__doc__in_memory = exports.cache = exports.retrievers__vespa = exports.retrievers__score_threshold = exports.retrievers__hyde = exports.retrievers__document_compressors__embeddings_filter = exports.retrievers__document_compressors__chain_extract = exports.retrievers__time_weighted = exports.retrievers__tavily_search_api = exports.retrievers__parent_document = exports.retrievers__multi_vector = exports.retrievers__multi_query = exports.retrievers__document_compressors = exports.retrievers__contextual_compression = exports.retrievers__databerry = exports.retrievers__chaindesk = exports.retrievers__remote = exports.output_parsers = exports.callbacks = exports.schema__storage = exports.schema__runnable = exports.schema__retriever = exports.schema__query_constructor = exports.schema__prompt_template = exports.schema__output_parser = exports.schema__document = exports.schema = exports.chat_models__fake = exports.chat_models__yandex = exports.chat_models__minimax = exports.chat_models__ollama = exports.chat_models__baiduwenxin = exports.chat_models__fireworks = exports.chat_models__cloudflare_workersai = void 0;
29
29
  exports.load__serializable = __importStar(require("../load/serializable.cjs"));
30
30
  exports.agents = __importStar(require("../agents/index.cjs"));
31
31
  exports.agents__toolkits = __importStar(require("../agents/toolkits/index.cjs"));
32
32
  exports.agents__format_scratchpad = __importStar(require("../agents/format_scratchpad/openai_functions.cjs"));
33
+ exports.agents__format_scratchpad__openai_tools = __importStar(require("../agents/format_scratchpad/openai_tools.cjs"));
33
34
  exports.agents__format_scratchpad__log = __importStar(require("../agents/format_scratchpad/log.cjs"));
34
35
  exports.agents__format_scratchpad__xml = __importStar(require("../agents/format_scratchpad/xml.cjs"));
35
36
  exports.agents__format_scratchpad__log_to_message = __importStar(require("../agents/format_scratchpad/log_to_message.cjs"));
@@ -2,6 +2,7 @@ export * as load__serializable from "../load/serializable.js";
2
2
  export * as agents from "../agents/index.js";
3
3
  export * as agents__toolkits from "../agents/toolkits/index.js";
4
4
  export * as agents__format_scratchpad from "../agents/format_scratchpad/openai_functions.js";
5
+ export * as agents__format_scratchpad__openai_tools from "../agents/format_scratchpad/openai_tools.js";
5
6
  export * as agents__format_scratchpad__log from "../agents/format_scratchpad/log.js";
6
7
  export * as agents__format_scratchpad__xml from "../agents/format_scratchpad/xml.js";
7
8
  export * as agents__format_scratchpad__log_to_message from "../agents/format_scratchpad/log_to_message.js";
@@ -3,6 +3,7 @@ export * as load__serializable from "../load/serializable.js";
3
3
  export * as agents from "../agents/index.js";
4
4
  export * as agents__toolkits from "../agents/toolkits/index.js";
5
5
  export * as agents__format_scratchpad from "../agents/format_scratchpad/openai_functions.js";
6
+ export * as agents__format_scratchpad__openai_tools from "../agents/format_scratchpad/openai_tools.js";
6
7
  export * as agents__format_scratchpad__log from "../agents/format_scratchpad/log.js";
7
8
  export * as agents__format_scratchpad__xml from "../agents/format_scratchpad/xml.js";
8
9
  export * as agents__format_scratchpad__log_to_message from "../agents/format_scratchpad/log_to_message.js";
@@ -337,13 +337,34 @@ class ChatPromptTemplate extends BaseChatPromptTemplate {
337
337
  _getPromptType() {
338
338
  return "chat";
339
339
  }
340
+ async _parseImagePrompts(message, inputValues) {
341
+ if (typeof message.content === "string") {
342
+ return message;
343
+ }
344
+ const formattedMessageContent = await Promise.all(message.content.map(async (item) => {
345
+ if (item.type !== "image_url" ||
346
+ typeof item.image_url === "string" ||
347
+ !item.image_url?.url) {
348
+ return item;
349
+ }
350
+ const imageUrl = item.image_url.url;
351
+ const promptTemplatePlaceholder = prompt_js_1.PromptTemplate.fromTemplate(imageUrl);
352
+ const formattedUrl = await promptTemplatePlaceholder.format(inputValues);
353
+ // eslint-disable-next-line no-param-reassign
354
+ item.image_url.url = formattedUrl;
355
+ return item;
356
+ }));
357
+ // eslint-disable-next-line no-param-reassign
358
+ message.content = formattedMessageContent;
359
+ return message;
360
+ }
340
361
  async formatMessages(values) {
341
362
  const allValues = await this.mergePartialAndUserVariables(values);
342
363
  let resultMessages = [];
343
364
  for (const promptMessage of this.promptMessages) {
344
365
  // eslint-disable-next-line no-instanceof/no-instanceof
345
366
  if (promptMessage instanceof index_js_1.BaseMessage) {
346
- resultMessages.push(promptMessage);
367
+ resultMessages.push(await this._parseImagePrompts(promptMessage, allValues));
347
368
  }
348
369
  else {
349
370
  const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => {
@@ -169,6 +169,7 @@ export declare class ChatPromptTemplate<RunInput extends InputValues = any, Part
169
169
  validateTemplate: boolean;
170
170
  constructor(input: ChatPromptTemplateInput<RunInput, PartialVariableName>);
171
171
  _getPromptType(): "chat";
172
+ private _parseImagePrompts;
172
173
  formatMessages(values: TypedPromptInputValues<RunInput>): Promise<BaseMessage[]>;
173
174
  partial<NewPartialVariableName extends string>(values: PartialValues<NewPartialVariableName>): Promise<ChatPromptTemplate<InputValues<Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>>, any>>;
174
175
  /**
@@ -325,13 +325,34 @@ export class ChatPromptTemplate extends BaseChatPromptTemplate {
325
325
  _getPromptType() {
326
326
  return "chat";
327
327
  }
328
+ async _parseImagePrompts(message, inputValues) {
329
+ if (typeof message.content === "string") {
330
+ return message;
331
+ }
332
+ const formattedMessageContent = await Promise.all(message.content.map(async (item) => {
333
+ if (item.type !== "image_url" ||
334
+ typeof item.image_url === "string" ||
335
+ !item.image_url?.url) {
336
+ return item;
337
+ }
338
+ const imageUrl = item.image_url.url;
339
+ const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl);
340
+ const formattedUrl = await promptTemplatePlaceholder.format(inputValues);
341
+ // eslint-disable-next-line no-param-reassign
342
+ item.image_url.url = formattedUrl;
343
+ return item;
344
+ }));
345
+ // eslint-disable-next-line no-param-reassign
346
+ message.content = formattedMessageContent;
347
+ return message;
348
+ }
328
349
  async formatMessages(values) {
329
350
  const allValues = await this.mergePartialAndUserVariables(values);
330
351
  let resultMessages = [];
331
352
  for (const promptMessage of this.promptMessages) {
332
353
  // eslint-disable-next-line no-instanceof/no-instanceof
333
354
  if (promptMessage instanceof BaseMessage) {
334
- resultMessages.push(promptMessage);
355
+ resultMessages.push(await this._parseImagePrompts(promptMessage, allValues));
335
356
  }
336
357
  else {
337
358
  const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => {
@@ -70,6 +70,7 @@ export type MessageContent = string | {
70
70
  text?: string;
71
71
  image_url?: string | {
72
72
  url: string;
73
+ detail?: "low" | "high";
73
74
  };
74
75
  }[];
75
76
  export interface BaseMessageFields {
@@ -17,12 +17,13 @@ function formatToOpenAIFunction(tool) {
17
17
  }
18
18
  exports.formatToOpenAIFunction = formatToOpenAIFunction;
19
19
  function formatToOpenAITool(tool) {
20
+ const schema = (0, zod_to_json_schema_1.zodToJsonSchema)(tool.schema);
20
21
  return {
21
22
  type: "function",
22
23
  function: {
23
24
  name: tool.name,
24
25
  description: tool.description,
25
- parameters: (0, zod_to_json_schema_1.zodToJsonSchema)(tool.schema),
26
+ parameters: schema,
26
27
  },
27
28
  };
28
29
  }
@@ -13,12 +13,13 @@ export function formatToOpenAIFunction(tool) {
13
13
  };
14
14
  }
15
15
  export function formatToOpenAITool(tool) {
16
+ const schema = zodToJsonSchema(tool.schema);
16
17
  return {
17
18
  type: "function",
18
19
  function: {
19
20
  name: tool.name,
20
21
  description: tool.description,
21
- parameters: zodToJsonSchema(tool.schema),
22
+ parameters: schema,
22
23
  },
23
24
  };
24
25
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatToOpenAIFunction = exports.SearchApi = exports.SearxngSearch = exports.DataForSeoAPISearch = exports.WolframAlphaTool = exports.WikipediaQueryRun = exports.BraveSearch = exports.WriteFileTool = exports.ReadFileTool = exports.AIPluginTool = exports.GoogleCustomSearch = exports.Serper = exports.ZapierNLAWrapper = exports.ZapierNLARunAction = exports.VectorStoreQATool = exports.RequestsPostTool = exports.RequestsGetTool = exports.JsonGetValueTool = exports.JsonListKeysTool = exports.JsonSpec = exports.ChainTool = exports.IFTTTWebhook = exports.DynamicStructuredTool = exports.DynamicTool = exports.StructuredTool = exports.Tool = exports.BingSerpAPI = exports.DadJokeAPI = exports.SerpAPI = void 0;
3
+ exports.formatToOpenAITool = exports.formatToOpenAIFunction = exports.SearchApi = exports.SearxngSearch = exports.DataForSeoAPISearch = exports.WolframAlphaTool = exports.WikipediaQueryRun = exports.BraveSearch = exports.WriteFileTool = exports.ReadFileTool = exports.AIPluginTool = exports.GoogleCustomSearch = exports.Serper = exports.ZapierNLAWrapper = exports.ZapierNLARunAction = exports.VectorStoreQATool = exports.RequestsPostTool = exports.RequestsGetTool = exports.JsonGetValueTool = exports.JsonListKeysTool = exports.JsonSpec = exports.ChainTool = exports.IFTTTWebhook = exports.DynamicStructuredTool = exports.DynamicTool = exports.StructuredTool = exports.Tool = exports.BingSerpAPI = exports.DadJokeAPI = exports.SerpAPI = void 0;
4
4
  var serpapi_js_1 = require("./serpapi.cjs");
5
5
  Object.defineProperty(exports, "SerpAPI", { enumerable: true, get: function () { return serpapi_js_1.SerpAPI; } });
6
6
  var dadjokeapi_js_1 = require("./dadjokeapi.cjs");
@@ -52,3 +52,4 @@ var searchapi_js_1 = require("./searchapi.cjs");
52
52
  Object.defineProperty(exports, "SearchApi", { enumerable: true, get: function () { return searchapi_js_1.SearchApi; } });
53
53
  var convert_to_openai_js_1 = require("./convert_to_openai.cjs");
54
54
  Object.defineProperty(exports, "formatToOpenAIFunction", { enumerable: true, get: function () { return convert_to_openai_js_1.formatToOpenAIFunction; } });
55
+ Object.defineProperty(exports, "formatToOpenAITool", { enumerable: true, get: function () { return convert_to_openai_js_1.formatToOpenAITool; } });
@@ -19,4 +19,4 @@ export { WolframAlphaTool } from "./wolframalpha.js";
19
19
  export { DataForSeoAPISearch, type DataForSeoApiConfig, } from "./dataforseo_api_search.js";
20
20
  export { SearxngSearch } from "./searxng_search.js";
21
21
  export { SearchApi, type SearchApiParameters } from "./searchapi.js";
22
- export { formatToOpenAIFunction } from "./convert_to_openai.js";
22
+ export { formatToOpenAIFunction, formatToOpenAITool, } from "./convert_to_openai.js";
@@ -19,4 +19,4 @@ export { WolframAlphaTool } from "./wolframalpha.js";
19
19
  export { DataForSeoAPISearch, } from "./dataforseo_api_search.js";
20
20
  export { SearxngSearch } from "./searxng_search.js";
21
21
  export { SearchApi } from "./searchapi.js";
22
- export { formatToOpenAIFunction } from "./convert_to_openai.js";
22
+ export { formatToOpenAIFunction, formatToOpenAITool, } from "./convert_to_openai.js";
@@ -224,7 +224,7 @@ class MomentoVectorIndex extends base_js_1.VectorStore {
224
224
  pageContent: hit.metadata[this.textField]?.toString() ?? "",
225
225
  metadata: Object.fromEntries(Object.entries(hit.metadata).filter(([key]) => key !== this.textField)),
226
226
  }),
227
- hit.distance,
227
+ hit.score,
228
228
  ]);
229
229
  }
230
230
  else if (response instanceof sdk_core_1.VectorSearch.Error) {
@@ -198,7 +198,7 @@ export class MomentoVectorIndex extends VectorStore {
198
198
  pageContent: hit.metadata[this.textField]?.toString() ?? "",
199
199
  metadata: Object.fromEntries(Object.entries(hit.metadata).filter(([key]) => key !== this.textField)),
200
200
  }),
201
- hit.distance,
201
+ hit.score,
202
202
  ]);
203
203
  }
204
204
  else if (response instanceof VectorSearch.Error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "langchain",
3
- "version": "0.0.184",
3
+ "version": "0.0.185",
4
4
  "description": "Typescript bindings for langchain",
5
5
  "type": "module",
6
6
  "engines": {
@@ -34,6 +34,9 @@
34
34
  "agents/format_scratchpad.cjs",
35
35
  "agents/format_scratchpad.js",
36
36
  "agents/format_scratchpad.d.ts",
37
+ "agents/format_scratchpad/openai_tools.cjs",
38
+ "agents/format_scratchpad/openai_tools.js",
39
+ "agents/format_scratchpad/openai_tools.d.ts",
37
40
  "agents/format_scratchpad/log.cjs",
38
41
  "agents/format_scratchpad/log.js",
39
42
  "agents/format_scratchpad/log.d.ts",
@@ -838,8 +841,8 @@
838
841
  "@faker-js/faker": "^7.6.0",
839
842
  "@getmetal/metal-sdk": "^4.0.0",
840
843
  "@getzep/zep-js": "^0.9.0",
841
- "@gomomento/sdk": "^1.44.1",
842
- "@gomomento/sdk-core": "^1.44.1",
844
+ "@gomomento/sdk": "^1.47.1",
845
+ "@gomomento/sdk-core": "^1.47.1",
843
846
  "@google-ai/generativelanguage": "^0.2.1",
844
847
  "@google-cloud/storage": "^6.10.1",
845
848
  "@huggingface/inference": "^2.6.4",
@@ -974,9 +977,9 @@
974
977
  "@elastic/elasticsearch": "^8.4.0",
975
978
  "@getmetal/metal-sdk": "*",
976
979
  "@getzep/zep-js": "^0.9.0",
977
- "@gomomento/sdk": "^1.44.1",
978
- "@gomomento/sdk-core": "^1.44.1",
979
- "@gomomento/sdk-web": "^1.44.1",
980
+ "@gomomento/sdk": "^1.47.1",
981
+ "@gomomento/sdk-core": "^1.47.1",
982
+ "@gomomento/sdk-web": "^1.47.1",
980
983
  "@google-ai/generativelanguage": "^0.2.1",
981
984
  "@google-cloud/storage": "^6.10.1",
982
985
  "@huggingface/inference": "^2.6.4",
@@ -1364,7 +1367,7 @@
1364
1367
  "langchainhub": "~0.0.6",
1365
1368
  "langsmith": "~0.0.48",
1366
1369
  "ml-distance": "^4.0.0",
1367
- "openai": "^4.16.1",
1370
+ "openai": "^4.17.0",
1368
1371
  "openapi-types": "^12.1.3",
1369
1372
  "p-queue": "^6.6.2",
1370
1373
  "p-retry": "4",
@@ -1431,6 +1434,11 @@
1431
1434
  "import": "./agents/format_scratchpad.js",
1432
1435
  "require": "./agents/format_scratchpad.cjs"
1433
1436
  },
1437
+ "./agents/format_scratchpad/openai_tools": {
1438
+ "types": "./agents/format_scratchpad/openai_tools.d.ts",
1439
+ "import": "./agents/format_scratchpad/openai_tools.js",
1440
+ "require": "./agents/format_scratchpad/openai_tools.cjs"
1441
+ },
1434
1442
  "./agents/format_scratchpad/log": {
1435
1443
  "types": "./agents/format_scratchpad/log.d.ts",
1436
1444
  "import": "./agents/format_scratchpad/log.js",