@langchain/core 1.1.42 → 1.1.43

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 (121) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +1 -1
  3. package/dist/callbacks/base.cjs +5 -0
  4. package/dist/callbacks/base.cjs.map +1 -1
  5. package/dist/callbacks/base.d.cts +20 -1
  6. package/dist/callbacks/base.d.cts.map +1 -1
  7. package/dist/callbacks/base.d.ts +20 -1
  8. package/dist/callbacks/base.d.ts.map +1 -1
  9. package/dist/callbacks/base.js +5 -1
  10. package/dist/callbacks/base.js.map +1 -1
  11. package/dist/callbacks/manager.cjs +10 -0
  12. package/dist/callbacks/manager.cjs.map +1 -1
  13. package/dist/callbacks/manager.d.cts +2 -0
  14. package/dist/callbacks/manager.d.cts.map +1 -1
  15. package/dist/callbacks/manager.d.ts +2 -0
  16. package/dist/callbacks/manager.d.ts.map +1 -1
  17. package/dist/callbacks/manager.js +10 -0
  18. package/dist/callbacks/manager.js.map +1 -1
  19. package/dist/language_models/base.cjs +1 -1
  20. package/dist/language_models/base.js +1 -1
  21. package/dist/language_models/chat_models.cjs +103 -1
  22. package/dist/language_models/chat_models.cjs.map +1 -1
  23. package/dist/language_models/chat_models.d.cts +55 -0
  24. package/dist/language_models/chat_models.d.cts.map +1 -1
  25. package/dist/language_models/chat_models.d.ts +55 -0
  26. package/dist/language_models/chat_models.d.ts.map +1 -1
  27. package/dist/language_models/chat_models.js +104 -2
  28. package/dist/language_models/chat_models.js.map +1 -1
  29. package/dist/language_models/compat.cjs +412 -0
  30. package/dist/language_models/compat.cjs.map +1 -0
  31. package/dist/language_models/compat.d.cts +20 -0
  32. package/dist/language_models/compat.d.cts.map +1 -0
  33. package/dist/language_models/compat.d.ts +20 -0
  34. package/dist/language_models/compat.d.ts.map +1 -0
  35. package/dist/language_models/compat.js +404 -0
  36. package/dist/language_models/compat.js.map +1 -0
  37. package/dist/language_models/event.cjs +12 -0
  38. package/dist/language_models/event.cjs.map +1 -0
  39. package/dist/language_models/event.d.cts +185 -0
  40. package/dist/language_models/event.d.cts.map +1 -0
  41. package/dist/language_models/event.d.ts +185 -0
  42. package/dist/language_models/event.d.ts.map +1 -0
  43. package/dist/language_models/event.js +7 -0
  44. package/dist/language_models/event.js.map +1 -0
  45. package/dist/language_models/stream.cjs +464 -0
  46. package/dist/language_models/stream.cjs.map +1 -0
  47. package/dist/language_models/stream.d.cts +106 -0
  48. package/dist/language_models/stream.d.cts.map +1 -0
  49. package/dist/language_models/stream.d.ts +106 -0
  50. package/dist/language_models/stream.d.ts.map +1 -0
  51. package/dist/language_models/stream.js +453 -0
  52. package/dist/language_models/stream.js.map +1 -0
  53. package/dist/load/import_map.cjs +6 -0
  54. package/dist/load/import_map.cjs.map +1 -1
  55. package/dist/load/import_map.js +8 -2
  56. package/dist/load/import_map.js.map +1 -1
  57. package/dist/load/map_keys.cjs +2 -2
  58. package/dist/messages/ai.cjs +11 -8
  59. package/dist/messages/ai.cjs.map +1 -1
  60. package/dist/messages/ai.d.cts.map +1 -1
  61. package/dist/messages/ai.d.ts.map +1 -1
  62. package/dist/messages/ai.js +11 -8
  63. package/dist/messages/ai.js.map +1 -1
  64. package/dist/messages/content/index.cjs.map +1 -1
  65. package/dist/messages/content/index.d.cts +5 -1
  66. package/dist/messages/content/index.d.cts.map +1 -1
  67. package/dist/messages/content/index.d.ts +5 -1
  68. package/dist/messages/content/index.d.ts.map +1 -1
  69. package/dist/messages/content/index.js.map +1 -1
  70. package/dist/messages/index.d.cts +2 -2
  71. package/dist/messages/index.d.ts +2 -2
  72. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.cts +1 -1
  73. package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.ts +1 -1
  74. package/dist/output_parsers/standard_schema.cjs +3 -0
  75. package/dist/output_parsers/standard_schema.cjs.map +1 -1
  76. package/dist/output_parsers/standard_schema.d.cts +2 -0
  77. package/dist/output_parsers/standard_schema.d.cts.map +1 -1
  78. package/dist/output_parsers/standard_schema.d.ts +2 -0
  79. package/dist/output_parsers/standard_schema.d.ts.map +1 -1
  80. package/dist/output_parsers/standard_schema.js +3 -0
  81. package/dist/output_parsers/standard_schema.js.map +1 -1
  82. package/dist/output_parsers/structured.cjs +3 -0
  83. package/dist/output_parsers/structured.cjs.map +1 -1
  84. package/dist/output_parsers/structured.d.cts +2 -0
  85. package/dist/output_parsers/structured.d.cts.map +1 -1
  86. package/dist/output_parsers/structured.d.ts +2 -0
  87. package/dist/output_parsers/structured.d.ts.map +1 -1
  88. package/dist/output_parsers/structured.js +3 -0
  89. package/dist/output_parsers/structured.js.map +1 -1
  90. package/dist/prompts/template.cjs +1 -1
  91. package/dist/singletons/callbacks.cjs +1 -1
  92. package/dist/tracers/console.cjs +1 -1
  93. package/dist/types/type-utils.d.cts +2 -1
  94. package/dist/types/type-utils.d.cts.map +1 -1
  95. package/dist/types/type-utils.d.ts +2 -1
  96. package/dist/types/type-utils.d.ts.map +1 -1
  97. package/dist/utils/async_caller.cjs +3 -2
  98. package/dist/utils/async_caller.cjs.map +1 -1
  99. package/dist/utils/async_caller.js +2 -1
  100. package/dist/utils/async_caller.js.map +1 -1
  101. package/dist/utils/event_source_parse.cjs +5 -12
  102. package/dist/utils/event_source_parse.cjs.map +1 -1
  103. package/dist/utils/event_source_parse.js +5 -12
  104. package/dist/utils/event_source_parse.js.map +1 -1
  105. package/dist/utils/uuid/max.d.cts +1 -1
  106. package/dist/utils/uuid/max.d.ts +1 -1
  107. package/dist/utils/uuid/nil.d.cts +1 -1
  108. package/dist/utils/uuid/nil.d.ts +1 -1
  109. package/language_models/compat.cjs +1 -0
  110. package/language_models/compat.d.cts +1 -0
  111. package/language_models/compat.d.ts +1 -0
  112. package/language_models/compat.js +1 -0
  113. package/language_models/event.cjs +1 -0
  114. package/language_models/event.d.cts +1 -0
  115. package/language_models/event.d.ts +1 -0
  116. package/language_models/event.js +1 -0
  117. package/language_models/stream.cjs +1 -0
  118. package/language_models/stream.d.cts +1 -0
  119. package/language_models/stream.d.ts +1 -0
  120. package/language_models/stream.js +1 -0
  121. package/package.json +34 -1
@@ -1,3 +1,4 @@
1
+ import { BaseMessage } from "../messages/base.cjs";
1
2
  import { BaseOutputParser } from "./base.cjs";
2
3
  import { StandardSchemaV1 } from "@standard-schema/spec";
3
4
 
@@ -9,6 +10,7 @@ declare class StandardSchemaOutputParser<RunOutput extends Record<string, any> =
9
10
  constructor(schema: StandardSchemaV1<RunOutput>);
10
11
  static fromSerializableSchema<RunOutput extends Record<string, any> = Record<string, any>>(schema: StandardSchemaV1<RunOutput>): StandardSchemaOutputParser<RunOutput>;
11
12
  parse(text: string): Promise<RunOutput>;
13
+ protected _baseMessageToString(message: BaseMessage): string;
12
14
  getFormatInstructions(): string;
13
15
  }
14
16
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"standard_schema.d.cts","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"mappings":";;;;cAIa,0BAAA,mBAEO,MAAA,gBAAsB,MAAA,uBAChC,gBAAA,CAAiB,SAAA;EAAA,OAClB,OAAA,CAAA;EAIP,YAAA;EAAA,iBAEiB,MAAA;EAEjB,WAAA,CAAY,MAAA,EAAQ,gBAAA,CAAiB,SAAA;EAAA,OAK9B,sBAAA,mBAEa,MAAA,gBAAsB,MAAA,cAAA,CACxC,MAAA,EAAQ,gBAAA,CAAiB,SAAA,IAAU,0BAAA,CAAA,SAAA;EAI/B,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,SAAA;EAgBnC,qBAAA,CAAA;AAAA"}
1
+ {"version":3,"file":"standard_schema.d.cts","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"mappings":";;;;;cAKa,0BAAA,mBAEO,MAAA,gBAAsB,MAAA,uBAChC,gBAAA,CAAiB,SAAA;EAAA,OAClB,OAAA,CAAA;EAIP,YAAA;EAAA,iBAEiB,MAAA;EAEjB,WAAA,CAAY,MAAA,EAAQ,gBAAA,CAAiB,SAAA;EAAA,OAK9B,sBAAA,mBAEa,MAAA,gBAAsB,MAAA,cAAA,CACxC,MAAA,EAAQ,gBAAA,CAAiB,SAAA,IAAU,0BAAA,CAAA,SAAA;EAI/B,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,SAAA;EAAA,UAgBhB,oBAAA,CAAqB,OAAA,EAAS,WAAA;EAIjD,qBAAA,CAAA;AAAA"}
@@ -1,3 +1,4 @@
1
+ import { BaseMessage } from "../messages/base.js";
1
2
  import { BaseOutputParser } from "./base.js";
2
3
  import { StandardSchemaV1 } from "@standard-schema/spec";
3
4
 
@@ -9,6 +10,7 @@ declare class StandardSchemaOutputParser<RunOutput extends Record<string, any> =
9
10
  constructor(schema: StandardSchemaV1<RunOutput>);
10
11
  static fromSerializableSchema<RunOutput extends Record<string, any> = Record<string, any>>(schema: StandardSchemaV1<RunOutput>): StandardSchemaOutputParser<RunOutput>;
11
12
  parse(text: string): Promise<RunOutput>;
13
+ protected _baseMessageToString(message: BaseMessage): string;
12
14
  getFormatInstructions(): string;
13
15
  }
14
16
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"standard_schema.d.ts","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"mappings":";;;;cAIa,0BAAA,mBAEO,MAAA,gBAAsB,MAAA,uBAChC,gBAAA,CAAiB,SAAA;EAAA,OAClB,OAAA,CAAA;EAIP,YAAA;EAAA,iBAEiB,MAAA;EAEjB,WAAA,CAAY,MAAA,EAAQ,gBAAA,CAAiB,SAAA;EAAA,OAK9B,sBAAA,mBAEa,MAAA,gBAAsB,MAAA,cAAA,CACxC,MAAA,EAAQ,gBAAA,CAAiB,SAAA,IAAU,0BAAA,CAAA,SAAA;EAI/B,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,SAAA;EAgBnC,qBAAA,CAAA;AAAA"}
1
+ {"version":3,"file":"standard_schema.d.ts","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"mappings":";;;;;cAKa,0BAAA,mBAEO,MAAA,gBAAsB,MAAA,uBAChC,gBAAA,CAAiB,SAAA;EAAA,OAClB,OAAA,CAAA;EAIP,YAAA;EAAA,iBAEiB,MAAA;EAEjB,WAAA,CAAY,MAAA,EAAQ,gBAAA,CAAiB,SAAA;EAAA,OAK9B,sBAAA,mBAEa,MAAA,gBAAsB,MAAA,cAAA,CACxC,MAAA,EAAQ,gBAAA,CAAiB,SAAA,IAAU,0BAAA,CAAA,SAAA;EAI/B,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,SAAA;EAAA,UAgBhB,oBAAA,CAAqB,OAAA,EAAS,WAAA;EAIjD,qBAAA,CAAA;AAAA"}
@@ -29,6 +29,9 @@ var StandardSchemaOutputParser = class extends BaseOutputParser {
29
29
  throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
30
30
  }
31
31
  }
32
+ _baseMessageToString(message) {
33
+ return message.text;
34
+ }
32
35
  getFormatInstructions() {
33
36
  return "";
34
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"standard_schema.js","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"sourcesContent":["import { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BaseOutputParser, OutputParserException } from \"./base.js\";\nimport { parseJsonMarkdown } from \"./json.js\";\n\nexport class StandardSchemaOutputParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n> extends BaseOutputParser<RunOutput> {\n static lc_name() {\n return \"StandardSchemaOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"standard_schema\"];\n\n private readonly schema: StandardSchemaV1<RunOutput>;\n\n constructor(schema: StandardSchemaV1<RunOutput>) {\n super();\n this.schema = schema;\n }\n\n static fromSerializableSchema<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(schema: StandardSchemaV1<RunOutput>) {\n return new this(schema);\n }\n\n async parse(text: string): Promise<RunOutput> {\n try {\n const json = parseJsonMarkdown(text, JSON.parse);\n const result = await this.schema[\"~standard\"].validate(json);\n if (result.issues) {\n throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`);\n }\n return result.value as RunOutput;\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n}\n"],"mappings":";;;;AAIA,IAAa,6BAAb,cAGU,iBAA4B;CACpC,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAkB;CAEjE;CAEA,YAAY,QAAqC;AAC/C,SAAO;AACP,OAAK,SAAS;;CAGhB,OAAO,uBAGL,QAAqC;AACrC,SAAO,IAAI,KAAK,OAAO;;CAGzB,MAAM,MAAM,MAAkC;AAC5C,MAAI;GACF,MAAM,OAAO,kBAAkB,MAAM,KAAK,MAAM;GAChD,MAAM,SAAS,MAAM,KAAK,OAAO,aAAa,SAAS,KAAK;AAC5D,OAAI,OAAO,OACT,OAAM,IAAI,MAAM,sBAAsB,KAAK,UAAU,OAAO,OAAO,GAAG;AAExE,UAAO,OAAO;WACP,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;;CAIL,wBAAgC;AAC9B,SAAO"}
1
+ {"version":3,"file":"standard_schema.js","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"sourcesContent":["import { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BaseOutputParser, OutputParserException } from \"./base.js\";\nimport { parseJsonMarkdown } from \"./json.js\";\nimport { BaseMessage } from \"../messages/index.js\";\n\nexport class StandardSchemaOutputParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n> extends BaseOutputParser<RunOutput> {\n static lc_name() {\n return \"StandardSchemaOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"standard_schema\"];\n\n private readonly schema: StandardSchemaV1<RunOutput>;\n\n constructor(schema: StandardSchemaV1<RunOutput>) {\n super();\n this.schema = schema;\n }\n\n static fromSerializableSchema<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(schema: StandardSchemaV1<RunOutput>) {\n return new this(schema);\n }\n\n async parse(text: string): Promise<RunOutput> {\n try {\n const json = parseJsonMarkdown(text, JSON.parse);\n const result = await this.schema[\"~standard\"].validate(json);\n if (result.issues) {\n throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`);\n }\n return result.value as RunOutput;\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n\n protected override _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n}\n"],"mappings":";;;;AAKA,IAAa,6BAAb,cAGU,iBAA4B;CACpC,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAkB;CAEjE;CAEA,YAAY,QAAqC;AAC/C,SAAO;AACP,OAAK,SAAS;;CAGhB,OAAO,uBAGL,QAAqC;AACrC,SAAO,IAAI,KAAK,OAAO;;CAGzB,MAAM,MAAM,MAAkC;AAC5C,MAAI;GACF,MAAM,OAAO,kBAAkB,MAAM,KAAK,MAAM;GAChD,MAAM,SAAS,MAAM,KAAK,OAAO,aAAa,SAAS,KAAK;AAC5D,OAAI,OAAO,OACT,OAAM,IAAI,MAAM,sBAAsB,KAAK,UAAU,OAAO,OAAO,GAAG;AAExE,UAAO,OAAO;WACP,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;;CAIL,qBAAwC,SAA8B;AACpE,SAAO,QAAQ;;CAGjB,wBAAgC;AAC9B,SAAO"}
@@ -77,6 +77,9 @@ ${JSON.stringify(require_utils_json_schema.toJsonSchema(this.schema))}
77
77
  throw new require_base.OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
78
78
  }
79
79
  }
80
+ _baseMessageToString(message) {
81
+ return message.text;
82
+ }
80
83
  };
81
84
  /**
82
85
  * A specific type of `StructuredOutputParser` that parses JSON data
@@ -1 +1 @@
1
- {"version":3,"file":"structured.cjs","names":["BaseOutputParser","z","toJsonSchema","interopParseAsync","OutputParserException"],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;;AA6BA,IAAa,yBAAb,cAEUA,aAAAA,iBAA2C;CACnD,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;;CAGpC,YAAY,QAAkB;AAC5B,QAAM,OAAO;AADI,OAAA,SAAA;;;;;;;CASnB,OAAO,cAAwC,QAAW;AACxD,SAAO,IAAI,KAAK,OAAO;;;;;;;;CASzB,OAAO,yBACL,SACA;EACA,MAAM,YAAYC,OAAAA,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,KACrB,CAAC,MAAM,iBACN,CAAC,MAAMA,OAAAA,EAAE,QAAQ,CAAC,SAAS,YAAY,CAAC,CAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAK,UAAU;;;;;;;;CAS5B,wBAAgC;AAC9B,SAAO;;;;;;;;;;;;EAYT,KAAK,UAAUC,0BAAAA,aAAa,KAAK,OAAO,CAAC,CAAC;;;;;;;;;CAU1C,MAAM,MAAM,MAAiD;AAC3D,MAAI;GACF,MAAM,cAAc,KAAK,MAAM;GAU/B,MAAM,eANJ,YAAY,MAAM,gCAAgC,GAAG,MAErD,YAAY,MAAM,0BAA0B,GAAG,MAE/C,aAGC,QAAQ,8BAA8B,QAAQ,kBAAkB;AAE/D,WAAO,IADqB,cAAc,QAAQ,OAAO,MAAM,CAChC;KAC/B,CACD,QAAQ,OAAO,GAAG;AAErB,UAAO,MAAMC,YAAAA,kBAAkB,KAAK,QAAQ,KAAK,MAAM,YAAY,CAAC;WAC7D,GAAG;AACV,SAAM,IAAIC,aAAAA,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;;;;;;;AASP,IAAa,qCAAb,cAEU,uBAA0B;CAClC,OAAO,UAAU;AACf,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WAAW,gBAAgB;GAC9C,MAAM,cAAc,OAAO,cAAc,OAAO,OAAO,gBAAgB;AACvE,UAAO,GAAG,OAAO,cAAc;;AAGjC,MAAI,WAAW,OACb,QAAO,OAAO,MACX,KAAK,MAAM,KAAK,qBAAqB,GAAG,OAAO,CAAC,CAChD,KAAK,KAAK,IAAI,OAAO,SAAS,EAAE,GAAG;AAGxC,QAAM,IAAI,MAAM,0BAA0B;;CAG5C,OAAO,cAAwC,QAAW;AACxD,SAAO,IAAI,KAAQ,OAAO;;CAG5B,OAAO,yBACL,SACA;EACA,MAAM,YAAYD,OAAAA,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,KACrB,CAAC,MAAM,iBACN,CAAC,MAAMA,OAAAA,EAAE,QAAQ,CAAC,SAAS,YAAY,CAAC,CAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAuB,UAAU;;;;;;;AAchD,IAAsB,mCAAtB,cAGUD,aAAAA,iBAAoB;CAC5B;CAEA,YAAY,EAAE,eAA0D;AACtE,QAAM,GAAG,UAAU;AACnB,OAAK,wBAAwB,IAAI,mCAC/B,YACD;;CAWH,MAAM,MAAM,MAA0B;EACpC,IAAI;AACJ,MAAI;AACF,iBAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;WACnD,GAAG;AACV,SAAM,IAAII,aAAAA,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;AAGH,SAAO,KAAK,gBAAgB,YAAY;;CAG1C,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB"}
1
+ {"version":3,"file":"structured.cjs","names":["BaseOutputParser","z","toJsonSchema","interopParseAsync","OutputParserException"],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport { BaseMessage } from \"../messages/index.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n\n protected override _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;;AA8BA,IAAa,yBAAb,cAEUA,aAAAA,iBAA2C;CACnD,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;;CAGpC,YAAY,QAAkB;AAC5B,QAAM,OAAO;AADI,OAAA,SAAA;;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AW;AACxD,SAAO,IAAI,KAAQ,OAAO;;CAG5B,OAAO,yBACL,SACA;EACA,MAAM,YAAYD,OAAAA,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,KACrB,CAAC,MAAM,iBACN,CAAC,MAAMA,OAAAA,EAAE,QAAQ,CAAC,SAAS,YAAY,CAAC,CAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAuB,UAAU;;;;;;;AAchD,IAAsB,mCAAtB,cAGUD,aAAAA,iBAAoB;CAC5B;CAEA,YAAY,EAAE,eAA0D;AACtE,QAAM,GAAG,UAAU;AACnB,OAAK,wBAAwB,IAAI,mCAC/B,YACD;;CAWH,MAAM,MAAM,MAA0B;EACpC,IAAI;AACJ,MAAI;AACF,iBAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;WACnD,GAAG;AACV,SAAM,IAAII,aAAAA,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;AAGH,SAAO,KAAK,gBAAgB,YAAY;;CAG1C,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB"}
@@ -1,4 +1,5 @@
1
1
  import { SerializedNotImplemented } from "../load/serializable.cjs";
2
+ import { BaseMessage } from "../messages/base.cjs";
2
3
  import { InferInteropZodOutput, InteropZodType } from "../utils/types/zod.cjs";
3
4
  import { BaseOutputParser, FormatInstructionsOptions } from "./base.cjs";
4
5
  import { z } from "zod/v3";
@@ -50,6 +51,7 @@ declare class StructuredOutputParser<T extends InteropZodType> extends BaseOutpu
50
51
  * @returns The parsed output.
51
52
  */
52
53
  parse(text: string): Promise<InferInteropZodOutput<T>>;
54
+ protected _baseMessageToString(message: BaseMessage): string;
53
55
  }
54
56
  /**
55
57
  * A specific type of `StructuredOutputParser` that parses JSON data
@@ -1 +1 @@
1
- {"version":3,"file":"structured.d.cts","names":[],"sources":["../../src/output_parsers/structured.ts"],"mappings":";;;;;;KAqBY,uCAAA;EACV,kBAAA;AAAA;AAAA,UAGe,qCAAA,SAA8C,y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;;;;;UAeG,sCAAA,WACL,cAAA;EAEV,WAAA,EAAa,CAAA;AAAA;;;;;uBAOO,gCAAA,WACV,cAAA,uBAEF,gBAAA,CAAiB,CAAA;EAAA,QACjB,qBAAA;EAER,WAAA,CAAA;IAAc;EAAA,GAAe,sCAAA,CAAuC,CAAA;EAlKxD;;;;;;EAAA,SA+KH,eAAA,CAAgB,KAAA,EAAO,qBAAA,CAAsB,CAAA,IAAK,OAAA,CAAQ,CAAA;EAE7D,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,CAAA;EAcnC,qBAAA,CAAA;AAAA"}
@@ -1,4 +1,5 @@
1
1
  import { SerializedNotImplemented } from "../load/serializable.js";
2
+ import { BaseMessage } from "../messages/base.js";
2
3
  import { InferInteropZodOutput, InteropZodType } from "../utils/types/zod.js";
3
4
  import { BaseOutputParser, FormatInstructionsOptions } from "./base.js";
4
5
  import { z } from "zod/v3";
@@ -50,6 +51,7 @@ declare class StructuredOutputParser<T extends InteropZodType> extends BaseOutpu
50
51
  * @returns The parsed output.
51
52
  */
52
53
  parse(text: string): Promise<InferInteropZodOutput<T>>;
54
+ protected _baseMessageToString(message: BaseMessage): string;
53
55
  }
54
56
  /**
55
57
  * A specific type of `StructuredOutputParser` that parses JSON data
@@ -1 +1 @@
1
- {"version":3,"file":"structured.d.ts","names":[],"sources":["../../src/output_parsers/structured.ts"],"mappings":";;;;;;KAqBY,uCAAA;EACV,kBAAA;AAAA;AAAA,UAGe,qCAAA,SAA8C,yBAAA;EAC7D,kBAAA;AAAA;AAAA,cAGW,sBAAA,WACD,cAAA,UACF,gBAAA,CAAiB,qBAAA,CAAsB,CAAA;EAW5B,MAAA,EAAQ,CAAA;EAAA,OAVpB,OAAA,CAAA;EAIP,YAAA;EAEA,MAAA,CAAA,GAI4B,wBAAA;EAA5B,WAAA,CAAmB,MAAA,EAAQ,CAAA;EAhBT;AAGpB;;;;EAHoB,OAyBX,aAAA,WAAwB,cAAA,CAAA,CAAgB,MAAA,EAAQ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,IAAA,WAAe,OAAA,CAAQ,CAAA;EAcnC,qBAAA,CAAA;AAAA"}
@@ -76,6 +76,9 @@ ${JSON.stringify(toJsonSchema(this.schema))}
76
76
  throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
77
77
  }
78
78
  }
79
+ _baseMessageToString(message) {
80
+ return message.text;
81
+ }
79
82
  };
80
83
  /**
81
84
  * A specific type of `StructuredOutputParser` that parses JSON data
@@ -1 +1 @@
1
- {"version":3,"file":"structured.js","names":[],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;AA6BA,IAAa,yBAAb,cAEU,iBAA2C;CACnD,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;;CAGpC,YAAY,QAAkB;AAC5B,QAAM,OAAO;AADI,OAAA,SAAA;;;;;;;CASnB,OAAO,cAAwC,QAAW;AACxD,SAAO,IAAI,KAAK,OAAO;;;;;;;;CASzB,OAAO,yBACL,SACA;EACA,MAAM,YAAY,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,KACrB,CAAC,MAAM,iBACN,CAAC,MAAM,EAAE,QAAQ,CAAC,SAAS,YAAY,CAAC,CAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAK,UAAU;;;;;;;;CAS5B,wBAAgC;AAC9B,SAAO;;;;;;;;;;;;EAYT,KAAK,UAAU,aAAa,KAAK,OAAO,CAAC,CAAC;;;;;;;;;CAU1C,MAAM,MAAM,MAAiD;AAC3D,MAAI;GACF,MAAM,cAAc,KAAK,MAAM;GAU/B,MAAM,eANJ,YAAY,MAAM,gCAAgC,GAAG,MAErD,YAAY,MAAM,0BAA0B,GAAG,MAE/C,aAGC,QAAQ,8BAA8B,QAAQ,kBAAkB;AAE/D,WAAO,IADqB,cAAc,QAAQ,OAAO,MAAM,CAChC;KAC/B,CACD,QAAQ,OAAO,GAAG;AAErB,UAAO,MAAM,kBAAkB,KAAK,QAAQ,KAAK,MAAM,YAAY,CAAC;WAC7D,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;;;;;;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O,SAAS,EAAE,CAAC,IAAI;;GAEnC,MAAM,aAAa,WAAW,gBAAgB;GAC9C,MAAM,cAAc,OAAO,cAAc,OAAO,OAAO,gBAAgB;AACvE,UAAO,GAAG,OAAO,cAAc;;AAGjC,MAAI,WAAW,OACb,QAAO,OAAO,MACX,KAAK,MAAM,KAAK,qBAAqB,GAAG,OAAO,CAAC,CAChD,KAAK,KAAK,IAAI,OAAO,SAAS,EAAE,GAAG;AAGxC,QAAM,IAAI,MAAM,0BAA0B;;CAG5C,OAAO,cAAwC,QAAW;AACxD,SAAO,IAAI,KAAQ,OAAO;;CAG5B,OAAO,yBACL,SACA;EACA,MAAM,YAAY,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,KACrB,CAAC,MAAM,iBACN,CAAC,MAAM,EAAE,QAAQ,CAAC,SAAS,YAAY,CAAC,CAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAuB,UAAU;;;;;;;AAchD,IAAsB,mCAAtB,cAGU,iBAAoB;CAC5B;CAEA,YAAY,EAAE,eAA0D;AACtE,QAAM,GAAG,UAAU;AACnB,OAAK,wBAAwB,IAAI,mCAC/B,YACD;;CAWH,MAAM,MAAM,MAA0B;EACpC,IAAI;AACJ,MAAI;AACF,iBAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;WACnD,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;AAGH,SAAO,KAAK,gBAAgB,YAAY;;CAG1C,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB"}
1
+ {"version":3,"file":"structured.js","names":[],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport { BaseMessage } from \"../messages/index.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n\n protected override _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;AA8BA,IAAa,yBAAb,cAEU,iBAA2C;CACnD,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;;CAGpC,YAAY,QAAkB;AAC5B,QAAM,OAAO;AADI,OAAA,SAAA;;;;;;;CASnB,OAAO,cAAwC,QAAW;AACxD,S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AO,YACL,OAAO,QAAQ,QAAQ,CAAC,KACrB,CAAC,MAAM,iBACN,CAAC,MAAM,EAAE,QAAQ,CAAC,SAAS,YAAY,CAAC,CAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAuB,UAAU;;;;;;;AAchD,IAAsB,mCAAtB,cAGU,iBAAoB;CAC5B;CAEA,YAAY,EAAE,eAA0D;AACtE,QAAM,GAAG,UAAU;AACnB,OAAK,wBAAwB,IAAI,mCAC/B,YACD;;CAWH,MAAM,MAAM,MAA0B;EACpC,IAAI;AACJ,MAAI;AACF,iBAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;WACnD,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;AAGH,SAAO,KAAK,gBAAgB,YAAY;;CAG1C,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB"}
@@ -1,7 +1,7 @@
1
1
  const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
2
2
  const require_errors_index = require("../errors/index.cjs");
3
3
  let mustache = require("mustache");
4
- mustache = require_runtime.__toESM(mustache);
4
+ mustache = require_runtime.__toESM(mustache, 1);
5
5
  //#region src/prompts/template.ts
6
6
  function configureMustache() {
7
7
  mustache.default.escape = (text) => text;
@@ -2,7 +2,7 @@ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
2
2
  const require_tracer = require("./tracer.cjs");
3
3
  const require_globals = require("./async_local_storage/globals.cjs");
4
4
  let p_queue = require("p-queue");
5
- p_queue = require_runtime.__toESM(p_queue);
5
+ p_queue = require_runtime.__toESM(p_queue, 1);
6
6
  //#region src/singletons/callbacks.ts
7
7
  let queue;
8
8
  /**
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
3
3
  const require_tracers_base = require("./base.cjs");
4
4
  let ansi_styles = require("ansi-styles");
5
- ansi_styles = require_runtime.__toESM(ansi_styles);
5
+ ansi_styles = require_runtime.__toESM(ansi_styles, 1);
6
6
  //#region src/tracers/console.ts
7
7
  var console_exports = /* @__PURE__ */ require_runtime.__exportAll({ ConsoleCallbackHandler: () => ConsoleCallbackHandler });
8
8
  function wrap(style, text) {
@@ -1,5 +1,6 @@
1
1
  //#region src/types/type-utils.d.ts
2
2
  type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
3
+ type DeepPartial<T> = { [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P] };
3
4
  //#endregion
4
- export { Optional };
5
+ export { DeepPartial, Optional };
5
6
  //# sourceMappingURL=type-utils.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"type-utils.d.cts","names":[],"sources":["../../src/types/type-utils.ts"],"mappings":";KAEY,QAAA,oBAA4B,CAAA,IAAK,IAAA,CAAK,CAAA,EAAG,CAAA,IAAK,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,CAAA"}
1
+ {"version":3,"file":"type-utils.d.cts","names":[],"sources":["../../src/types/type-utils.ts"],"mappings":";KAEY,QAAA,oBAA4B,CAAA,IAAK,IAAA,CAAK,CAAA,EAAG,CAAA,IAAK,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,CAAA;AAAA,KAG9D,WAAA,oBACE,CAAA,IAAK,CAAA,CAAE,CAAA,mBAAoB,WAAA,CAAY,CAAA,CAAE,CAAA,KAAM,CAAA,CAAE,CAAA"}
@@ -1,5 +1,6 @@
1
1
  //#region src/types/type-utils.d.ts
2
2
  type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
3
+ type DeepPartial<T> = { [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P] };
3
4
  //#endregion
4
- export { Optional };
5
+ export { DeepPartial, Optional };
5
6
  //# sourceMappingURL=type-utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"type-utils.d.ts","names":[],"sources":["../../src/types/type-utils.ts"],"mappings":";KAEY,QAAA,oBAA4B,CAAA,IAAK,IAAA,CAAK,CAAA,EAAG,CAAA,IAAK,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,CAAA"}
1
+ {"version":3,"file":"type-utils.d.ts","names":[],"sources":["../../src/types/type-utils.ts"],"mappings":";KAEY,QAAA,oBAA4B,CAAA,IAAK,IAAA,CAAK,CAAA,EAAG,CAAA,IAAK,OAAA,CAAQ,IAAA,CAAK,CAAA,EAAG,CAAA;AAAA,KAG9D,WAAA,oBACE,CAAA,IAAK,CAAA,CAAE,CAAA,mBAAoB,WAAA,CAAY,CAAA,CAAE,CAAA,KAAM,CAAA,CAAE,CAAA"}
@@ -3,7 +3,7 @@ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
3
3
  const require_signal = require("./signal.cjs");
4
4
  const require_index = require("./p-retry/index.cjs");
5
5
  let p_queue = require("p-queue");
6
- p_queue = require_runtime.__toESM(p_queue);
6
+ p_queue = require_runtime.__toESM(p_queue, 1);
7
7
  //#region src/utils/async_caller.ts
8
8
  var async_caller_exports = /* @__PURE__ */ require_runtime.__exportAll({ AsyncCaller: () => AsyncCaller });
9
9
  const STATUS_NO_RETRY = [
@@ -58,7 +58,8 @@ var AsyncCaller = class {
58
58
  this.maxConcurrency = params.maxConcurrency ?? Infinity;
59
59
  this.maxRetries = params.maxRetries ?? 6;
60
60
  this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler;
61
- this.queue = new ("default" in p_queue.default ? p_queue.default.default : p_queue.default)({ concurrency: this.maxConcurrency });
61
+ const PQueue = "default" in p_queue.default ? p_queue.default.default : p_queue.default;
62
+ this.queue = new PQueue({ concurrency: this.maxConcurrency });
62
63
  }
63
64
  async call(callable, ...args) {
64
65
  return this.queue.add(() => require_index.default(() => callable(...args).catch((error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"async_caller.cjs","names":["PQueueMod","pRetry","getAbortSignalError"],"sources":["../../src/utils/async_caller.ts"],"sourcesContent":["import PQueueMod from \"p-queue\";\n\nimport { getAbortSignalError } from \"./signal.js\";\nimport pRetry from \"./p-retry/index.js\";\n\nconst STATUS_NO_RETRY = [\n 400, // Bad Request\n 401, // Unauthorized\n 402, // Payment Required\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 407, // Proxy Authentication Required\n 409, // Conflict\n];\n\n/**\n * The default failed attempt handler for the AsyncCaller.\n * @param error - The error to handle.\n * @returns void\n */\nconst defaultFailedAttemptHandler = (error: unknown) => {\n if (typeof error !== \"object\" || error === null) {\n return;\n }\n\n if (\n (\"message\" in error &&\n typeof error.message === \"string\" &&\n (error.message.startsWith(\"Cancel\") ||\n error.message.startsWith(\"AbortError\"))) ||\n (\"name\" in error &&\n typeof error.name === \"string\" &&\n error.name === \"AbortError\")\n ) {\n throw error;\n }\n if (\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code === \"ECONNABORTED\"\n ) {\n throw error;\n }\n const responseStatus =\n \"response\" in error &&\n typeof error.response === \"object\" &&\n error.response !== null &&\n \"status\" in error.response &&\n typeof error.response.status === \"number\"\n ? error.response.status\n : undefined;\n\n // OpenAI SDK errors expose status directly on the error object\n const directStatus =\n \"status\" in error && typeof error.status === \"number\"\n ? error.status\n : undefined;\n\n const status = responseStatus ?? directStatus;\n if (status && STATUS_NO_RETRY.includes(+status)) {\n throw error;\n }\n\n const code =\n \"error\" in error &&\n typeof error.error === \"object\" &&\n error.error !== null &&\n \"code\" in error.error &&\n typeof error.error.code === \"string\"\n ? error.error.code\n : undefined;\n if (code === \"insufficient_quota\") {\n const err = new Error(\n \"message\" in error && typeof error.message === \"string\"\n ? error.message\n : \"Insufficient quota\"\n );\n err.name = \"InsufficientQuotaError\";\n throw err;\n }\n};\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type FailedAttemptHandler = (error: any) => any;\n\nexport interface AsyncCallerParams {\n /**\n * The maximum number of concurrent calls that can be made.\n * Defaults to `Infinity`, which means no limit.\n */\n maxConcurrency?: number;\n /**\n * The maximum number of retries that can be made for a single call,\n * with an exponential backoff between each attempt. Defaults to 6.\n */\n maxRetries?: number;\n /**\n * Custom handler to handle failed attempts. Takes the originally thrown\n * error object as input, and should itself throw an error if the input\n * error is not retryable.\n */\n onFailedAttempt?: FailedAttemptHandler;\n}\n\nexport interface AsyncCallerCallOptions {\n signal?: AbortSignal;\n}\n\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of \"expensive\" external resource,\n * be it because it's rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nexport class AsyncCaller {\n protected maxConcurrency: AsyncCallerParams[\"maxConcurrency\"];\n\n protected maxRetries: AsyncCallerParams[\"maxRetries\"];\n\n protected onFailedAttempt: AsyncCallerParams[\"onFailedAttempt\"];\n\n private queue: (typeof import(\"p-queue\"))[\"default\"][\"prototype\"];\n\n constructor(params: AsyncCallerParams) {\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n this.onFailedAttempt =\n params.onFailedAttempt ?? defaultFailedAttemptHandler;\n\n const PQueue = (\n \"default\" in PQueueMod ? PQueueMod.default : PQueueMod\n ) as typeof PQueueMod;\n this.queue = new PQueue({ concurrency: this.maxConcurrency });\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async call<A extends any[], T extends (...args: A) => Promise<any>>(\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n return this.queue.add(\n () =>\n pRetry(\n () =>\n callable(...args).catch((error) => {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n } else {\n throw new Error(error);\n }\n }),\n {\n onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error),\n retries: this.maxRetries,\n randomize: true,\n // If needed we can change some of the defaults here,\n // but they're quite sensible.\n }\n ),\n { throwOnTimeout: true }\n );\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions<A extends any[], T extends (...args: A) => Promise<any>>(\n options: AsyncCallerCallOptions,\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n // Note this doesn't cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n let listener: (() => void) | undefined;\n return Promise.race([\n this.call<A, T>(callable, ...args),\n new Promise<never>((_, reject) => {\n listener = () => {\n reject(getAbortSignalError(options.signal));\n };\n options.signal?.addEventListener(\"abort\", listener, { once: true });\n }),\n ]).finally(() => {\n if (options.signal && listener) {\n options.signal.removeEventListener(\"abort\", listener);\n }\n });\n }\n return this.call<A, T>(callable, ...args);\n }\n\n fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {\n return this.call(() =>\n fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))\n );\n }\n}\n"],"mappings":";;;;;;;;AAKA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;AAOD,MAAM,+BAA+B,UAAmB;AACtD,KAAI,OAAO,UAAU,YAAY,UAAU,KACzC;AAGF,KACG,aAAa,SACZ,OAAO,MAAM,YAAY,aACxB,MAAM,QAAQ,WAAW,SAAS,IACjC,MAAM,QAAQ,WAAW,aAAa,KACzC,UAAU,SACT,OAAO,MAAM,SAAS,YACtB,MAAM,SAAS,aAEjB,OAAM;AAER,KACE,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,MAAM,SAAS,eAEf,OAAM;CAER,MAAM,iBACJ,cAAc,SACd,OAAO,MAAM,aAAa,YAC1B,MAAM,aAAa,QACnB,YAAY,MAAM,YAClB,OAAO,MAAM,SAAS,WAAW,WAC7B,MAAM,SAAS,SACf,KAAA;CAGN,MAAM,eACJ,YAAY,SAAS,OAAO,M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,YAAQ,QAAQ,iBAAiB,SAAS,UAAU,EAAE,MAAM,MAAM,CAAC;KACnE,CACH,CAAC,CAAC,cAAc;AACf,QAAI,QAAQ,UAAU,SACpB,SAAQ,OAAO,oBAAoB,SAAS,SAAS;KAEvD;;AAEJ,SAAO,KAAK,KAAW,UAAU,GAAG,KAAK;;CAG3C,MAAM,GAAG,MAA0D;AACjE,SAAO,KAAK,WACV,MAAM,GAAG,KAAK,CAAC,MAAM,QAAS,IAAI,KAAK,MAAM,QAAQ,OAAO,IAAI,CAAE,CACnE"}
1
+ {"version":3,"file":"async_caller.cjs","names":["PQueueMod","pRetry","getAbortSignalError"],"sources":["../../src/utils/async_caller.ts"],"sourcesContent":["import PQueueMod from \"p-queue\";\n\nimport { getAbortSignalError } from \"./signal.js\";\nimport pRetry from \"./p-retry/index.js\";\n\nconst STATUS_NO_RETRY = [\n 400, // Bad Request\n 401, // Unauthorized\n 402, // Payment Required\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 407, // Proxy Authentication Required\n 409, // Conflict\n];\n\n/**\n * The default failed attempt handler for the AsyncCaller.\n * @param error - The error to handle.\n * @returns void\n */\nconst defaultFailedAttemptHandler = (error: unknown) => {\n if (typeof error !== \"object\" || error === null) {\n return;\n }\n\n if (\n (\"message\" in error &&\n typeof error.message === \"string\" &&\n (error.message.startsWith(\"Cancel\") ||\n error.message.startsWith(\"AbortError\"))) ||\n (\"name\" in error &&\n typeof error.name === \"string\" &&\n error.name === \"AbortError\")\n ) {\n throw error;\n }\n if (\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code === \"ECONNABORTED\"\n ) {\n throw error;\n }\n const responseStatus =\n \"response\" in error &&\n typeof error.response === \"object\" &&\n error.response !== null &&\n \"status\" in error.response &&\n typeof error.response.status === \"number\"\n ? error.response.status\n : undefined;\n\n // OpenAI SDK errors expose status directly on the error object\n const directStatus =\n \"status\" in error && typeof error.status === \"number\"\n ? error.status\n : undefined;\n\n const status = responseStatus ?? directStatus;\n if (status && STATUS_NO_RETRY.includes(+status)) {\n throw error;\n }\n\n const code =\n \"error\" in error &&\n typeof error.error === \"object\" &&\n error.error !== null &&\n \"code\" in error.error &&\n typeof error.error.code === \"string\"\n ? error.error.code\n : undefined;\n if (code === \"insufficient_quota\") {\n const err = new Error(\n \"message\" in error && typeof error.message === \"string\"\n ? error.message\n : \"Insufficient quota\"\n );\n err.name = \"InsufficientQuotaError\";\n throw err;\n }\n};\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type FailedAttemptHandler = (error: any) => any;\n\nexport interface AsyncCallerParams {\n /**\n * The maximum number of concurrent calls that can be made.\n * Defaults to `Infinity`, which means no limit.\n */\n maxConcurrency?: number;\n /**\n * The maximum number of retries that can be made for a single call,\n * with an exponential backoff between each attempt. Defaults to 6.\n */\n maxRetries?: number;\n /**\n * Custom handler to handle failed attempts. Takes the originally thrown\n * error object as input, and should itself throw an error if the input\n * error is not retryable.\n */\n onFailedAttempt?: FailedAttemptHandler;\n}\n\nexport interface AsyncCallerCallOptions {\n signal?: AbortSignal;\n}\n\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of \"expensive\" external resource,\n * be it because it's rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nexport class AsyncCaller {\n protected maxConcurrency: AsyncCallerParams[\"maxConcurrency\"];\n\n protected maxRetries: AsyncCallerParams[\"maxRetries\"];\n\n protected onFailedAttempt: AsyncCallerParams[\"onFailedAttempt\"];\n\n private queue: (typeof import(\"p-queue\"))[\"default\"][\"prototype\"];\n\n constructor(params: AsyncCallerParams) {\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n this.onFailedAttempt =\n params.onFailedAttempt ?? defaultFailedAttemptHandler;\n\n const PQueue = (\n \"default\" in PQueueMod ? PQueueMod.default : PQueueMod\n ) as typeof PQueueMod;\n this.queue = new PQueue({ concurrency: this.maxConcurrency });\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async call<A extends any[], T extends (...args: A) => Promise<any>>(\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n return this.queue.add(\n () =>\n pRetry(\n () =>\n callable(...args).catch((error) => {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n } else {\n throw new Error(error);\n }\n }),\n {\n onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error),\n retries: this.maxRetries,\n randomize: true,\n // If needed we can change some of the defaults here,\n // but they're quite sensible.\n }\n ),\n { throwOnTimeout: true }\n );\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions<A extends any[], T extends (...args: A) => Promise<any>>(\n options: AsyncCallerCallOptions,\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n // Note this doesn't cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n let listener: (() => void) | undefined;\n return Promise.race([\n this.call<A, T>(callable, ...args),\n new Promise<never>((_, reject) => {\n listener = () => {\n reject(getAbortSignalError(options.signal));\n };\n options.signal?.addEventListener(\"abort\", listener, { once: true });\n }),\n ]).finally(() => {\n if (options.signal && listener) {\n options.signal.removeEventListener(\"abort\", listener);\n }\n });\n }\n return this.call<A, T>(callable, ...args);\n }\n\n fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {\n return this.call(() =>\n fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))\n );\n }\n}\n"],"mappings":";;;;;;;;AAKA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;AAOD,MAAM,+BAA+B,UAAmB;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AAAA,cAEI,SAAS,GAAG,KAAK,CAAC,OAAO,UAAU;AAEjC,OAAI,iBAAiB,MACnB,OAAM;OAEN,OAAM,IAAI,MAAM,MAAM;IAExB,EACJ;GACE,kBAAkB,EAAE,YAAY,KAAK,kBAAkB,MAAM;GAC7D,SAAS,KAAK;GACd,WAAW;GAGZ,CACF,EACH,EAAE,gBAAgB,MAAM,CACzB;;CAIH,gBACE,SACA,UACA,GAAG,MAC8B;AAGjC,MAAI,QAAQ,QAAQ;GAClB,IAAI;AACJ,UAAO,QAAQ,KAAK,CAClB,KAAK,KAAW,UAAU,GAAG,KAAK,EAClC,IAAI,SAAgB,GAAG,WAAW;AAChC,qBAAiB;AACf,YAAOC,eAAAA,oBAAoB,QAAQ,OAAO,CAAC;;AAE7C,YAAQ,QAAQ,iBAAiB,SAAS,UAAU,EAAE,MAAM,MAAM,CAAC;KACnE,CACH,CAAC,CAAC,cAAc;AACf,QAAI,QAAQ,UAAU,SACpB,SAAQ,OAAO,oBAAoB,SAAS,SAAS;KAEvD;;AAEJ,SAAO,KAAK,KAAW,UAAU,GAAG,KAAK;;CAG3C,MAAM,GAAG,MAA0D;AACjE,SAAO,KAAK,WACV,MAAM,GAAG,KAAK,CAAC,MAAM,QAAS,IAAI,KAAK,MAAM,QAAQ,OAAO,IAAI,CAAE,CACnE"}
@@ -56,7 +56,8 @@ var AsyncCaller = class {
56
56
  this.maxConcurrency = params.maxConcurrency ?? Infinity;
57
57
  this.maxRetries = params.maxRetries ?? 6;
58
58
  this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler;
59
- this.queue = new ("default" in PQueueMod ? PQueueMod.default : PQueueMod)({ concurrency: this.maxConcurrency });
59
+ const PQueue = "default" in PQueueMod ? PQueueMod.default : PQueueMod;
60
+ this.queue = new PQueue({ concurrency: this.maxConcurrency });
60
61
  }
61
62
  async call(callable, ...args) {
62
63
  return this.queue.add(() => pRetry(() => callable(...args).catch((error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"async_caller.js","names":[],"sources":["../../src/utils/async_caller.ts"],"sourcesContent":["import PQueueMod from \"p-queue\";\n\nimport { getAbortSignalError } from \"./signal.js\";\nimport pRetry from \"./p-retry/index.js\";\n\nconst STATUS_NO_RETRY = [\n 400, // Bad Request\n 401, // Unauthorized\n 402, // Payment Required\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 407, // Proxy Authentication Required\n 409, // Conflict\n];\n\n/**\n * The default failed attempt handler for the AsyncCaller.\n * @param error - The error to handle.\n * @returns void\n */\nconst defaultFailedAttemptHandler = (error: unknown) => {\n if (typeof error !== \"object\" || error === null) {\n return;\n }\n\n if (\n (\"message\" in error &&\n typeof error.message === \"string\" &&\n (error.message.startsWith(\"Cancel\") ||\n error.message.startsWith(\"AbortError\"))) ||\n (\"name\" in error &&\n typeof error.name === \"string\" &&\n error.name === \"AbortError\")\n ) {\n throw error;\n }\n if (\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code === \"ECONNABORTED\"\n ) {\n throw error;\n }\n const responseStatus =\n \"response\" in error &&\n typeof error.response === \"object\" &&\n error.response !== null &&\n \"status\" in error.response &&\n typeof error.response.status === \"number\"\n ? error.response.status\n : undefined;\n\n // OpenAI SDK errors expose status directly on the error object\n const directStatus =\n \"status\" in error && typeof error.status === \"number\"\n ? error.status\n : undefined;\n\n const status = responseStatus ?? directStatus;\n if (status && STATUS_NO_RETRY.includes(+status)) {\n throw error;\n }\n\n const code =\n \"error\" in error &&\n typeof error.error === \"object\" &&\n error.error !== null &&\n \"code\" in error.error &&\n typeof error.error.code === \"string\"\n ? error.error.code\n : undefined;\n if (code === \"insufficient_quota\") {\n const err = new Error(\n \"message\" in error && typeof error.message === \"string\"\n ? error.message\n : \"Insufficient quota\"\n );\n err.name = \"InsufficientQuotaError\";\n throw err;\n }\n};\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type FailedAttemptHandler = (error: any) => any;\n\nexport interface AsyncCallerParams {\n /**\n * The maximum number of concurrent calls that can be made.\n * Defaults to `Infinity`, which means no limit.\n */\n maxConcurrency?: number;\n /**\n * The maximum number of retries that can be made for a single call,\n * with an exponential backoff between each attempt. Defaults to 6.\n */\n maxRetries?: number;\n /**\n * Custom handler to handle failed attempts. Takes the originally thrown\n * error object as input, and should itself throw an error if the input\n * error is not retryable.\n */\n onFailedAttempt?: FailedAttemptHandler;\n}\n\nexport interface AsyncCallerCallOptions {\n signal?: AbortSignal;\n}\n\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of \"expensive\" external resource,\n * be it because it's rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nexport class AsyncCaller {\n protected maxConcurrency: AsyncCallerParams[\"maxConcurrency\"];\n\n protected maxRetries: AsyncCallerParams[\"maxRetries\"];\n\n protected onFailedAttempt: AsyncCallerParams[\"onFailedAttempt\"];\n\n private queue: (typeof import(\"p-queue\"))[\"default\"][\"prototype\"];\n\n constructor(params: AsyncCallerParams) {\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n this.onFailedAttempt =\n params.onFailedAttempt ?? defaultFailedAttemptHandler;\n\n const PQueue = (\n \"default\" in PQueueMod ? PQueueMod.default : PQueueMod\n ) as typeof PQueueMod;\n this.queue = new PQueue({ concurrency: this.maxConcurrency });\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async call<A extends any[], T extends (...args: A) => Promise<any>>(\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n return this.queue.add(\n () =>\n pRetry(\n () =>\n callable(...args).catch((error) => {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n } else {\n throw new Error(error);\n }\n }),\n {\n onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error),\n retries: this.maxRetries,\n randomize: true,\n // If needed we can change some of the defaults here,\n // but they're quite sensible.\n }\n ),\n { throwOnTimeout: true }\n );\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions<A extends any[], T extends (...args: A) => Promise<any>>(\n options: AsyncCallerCallOptions,\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n // Note this doesn't cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n let listener: (() => void) | undefined;\n return Promise.race([\n this.call<A, T>(callable, ...args),\n new Promise<never>((_, reject) => {\n listener = () => {\n reject(getAbortSignalError(options.signal));\n };\n options.signal?.addEventListener(\"abort\", listener, { once: true });\n }),\n ]).finally(() => {\n if (options.signal && listener) {\n options.signal.removeEventListener(\"abort\", listener);\n }\n });\n }\n return this.call<A, T>(callable, ...args);\n }\n\n fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {\n return this.call(() =>\n fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))\n );\n }\n}\n"],"mappings":";;;;;;AAKA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;AAOD,MAAM,+BAA+B,UAAmB;AACtD,KAAI,OAAO,UAAU,YAAY,UAAU,KACzC;AAGF,KACG,aAAa,SACZ,OAAO,MAAM,YAAY,aACxB,MAAM,QAAQ,WAAW,SAAS,IACjC,MAAM,QAAQ,WAAW,aAAa,KACzC,UAAU,SACT,OAAO,MAAM,SAAS,YACtB,MAAM,SAAS,aAEjB,OAAM;AAER,KACE,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,MAAM,SAAS,eAEf,OAAM;CAER,MAAM,iBACJ,cAAc,SACd,OAAO,MAAM,aAAa,YAC1B,MAAM,aAAa,QACnB,YAAY,MAAM,YAClB,OAAO,MAAM,SA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oBAAoB,QAAQ,OAAO,CAAC;;AAE7C,YAAQ,QAAQ,iBAAiB,SAAS,UAAU,EAAE,MAAM,MAAM,CAAC;KACnE,CACH,CAAC,CAAC,cAAc;AACf,QAAI,QAAQ,UAAU,SACpB,SAAQ,OAAO,oBAAoB,SAAS,SAAS;KAEvD;;AAEJ,SAAO,KAAK,KAAW,UAAU,GAAG,KAAK;;CAG3C,MAAM,GAAG,MAA0D;AACjE,SAAO,KAAK,WACV,MAAM,GAAG,KAAK,CAAC,MAAM,QAAS,IAAI,KAAK,MAAM,QAAQ,OAAO,IAAI,CAAE,CACnE"}
1
+ {"version":3,"file":"async_caller.js","names":[],"sources":["../../src/utils/async_caller.ts"],"sourcesContent":["import PQueueMod from \"p-queue\";\n\nimport { getAbortSignalError } from \"./signal.js\";\nimport pRetry from \"./p-retry/index.js\";\n\nconst STATUS_NO_RETRY = [\n 400, // Bad Request\n 401, // Unauthorized\n 402, // Payment Required\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 407, // Proxy Authentication Required\n 409, // Conflict\n];\n\n/**\n * The default failed attempt handler for the AsyncCaller.\n * @param error - The error to handle.\n * @returns void\n */\nconst defaultFailedAttemptHandler = (error: unknown) => {\n if (typeof error !== \"object\" || error === null) {\n return;\n }\n\n if (\n (\"message\" in error &&\n typeof error.message === \"string\" &&\n (error.message.startsWith(\"Cancel\") ||\n error.message.startsWith(\"AbortError\"))) ||\n (\"name\" in error &&\n typeof error.name === \"string\" &&\n error.name === \"AbortError\")\n ) {\n throw error;\n }\n if (\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code === \"ECONNABORTED\"\n ) {\n throw error;\n }\n const responseStatus =\n \"response\" in error &&\n typeof error.response === \"object\" &&\n error.response !== null &&\n \"status\" in error.response &&\n typeof error.response.status === \"number\"\n ? error.response.status\n : undefined;\n\n // OpenAI SDK errors expose status directly on the error object\n const directStatus =\n \"status\" in error && typeof error.status === \"number\"\n ? error.status\n : undefined;\n\n const status = responseStatus ?? directStatus;\n if (status && STATUS_NO_RETRY.includes(+status)) {\n throw error;\n }\n\n const code =\n \"error\" in error &&\n typeof error.error === \"object\" &&\n error.error !== null &&\n \"code\" in error.error &&\n typeof error.error.code === \"string\"\n ? error.error.code\n : undefined;\n if (code === \"insufficient_quota\") {\n const err = new Error(\n \"message\" in error && typeof error.message === \"string\"\n ? error.message\n : \"Insufficient quota\"\n );\n err.name = \"InsufficientQuotaError\";\n throw err;\n }\n};\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport type FailedAttemptHandler = (error: any) => any;\n\nexport interface AsyncCallerParams {\n /**\n * The maximum number of concurrent calls that can be made.\n * Defaults to `Infinity`, which means no limit.\n */\n maxConcurrency?: number;\n /**\n * The maximum number of retries that can be made for a single call,\n * with an exponential backoff between each attempt. Defaults to 6.\n */\n maxRetries?: number;\n /**\n * Custom handler to handle failed attempts. Takes the originally thrown\n * error object as input, and should itself throw an error if the input\n * error is not retryable.\n */\n onFailedAttempt?: FailedAttemptHandler;\n}\n\nexport interface AsyncCallerCallOptions {\n signal?: AbortSignal;\n}\n\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of \"expensive\" external resource,\n * be it because it's rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nexport class AsyncCaller {\n protected maxConcurrency: AsyncCallerParams[\"maxConcurrency\"];\n\n protected maxRetries: AsyncCallerParams[\"maxRetries\"];\n\n protected onFailedAttempt: AsyncCallerParams[\"onFailedAttempt\"];\n\n private queue: (typeof import(\"p-queue\"))[\"default\"][\"prototype\"];\n\n constructor(params: AsyncCallerParams) {\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n this.onFailedAttempt =\n params.onFailedAttempt ?? defaultFailedAttemptHandler;\n\n const PQueue = (\n \"default\" in PQueueMod ? PQueueMod.default : PQueueMod\n ) as typeof PQueueMod;\n this.queue = new PQueue({ concurrency: this.maxConcurrency });\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async call<A extends any[], T extends (...args: A) => Promise<any>>(\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n return this.queue.add(\n () =>\n pRetry(\n () =>\n callable(...args).catch((error) => {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n } else {\n throw new Error(error);\n }\n }),\n {\n onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error),\n retries: this.maxRetries,\n randomize: true,\n // If needed we can change some of the defaults here,\n // but they're quite sensible.\n }\n ),\n { throwOnTimeout: true }\n );\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions<A extends any[], T extends (...args: A) => Promise<any>>(\n options: AsyncCallerCallOptions,\n callable: T,\n ...args: Parameters<T>\n ): Promise<Awaited<ReturnType<T>>> {\n // Note this doesn't cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n let listener: (() => void) | undefined;\n return Promise.race([\n this.call<A, T>(callable, ...args),\n new Promise<never>((_, reject) => {\n listener = () => {\n reject(getAbortSignalError(options.signal));\n };\n options.signal?.addEventListener(\"abort\", listener, { once: true });\n }),\n ]).finally(() => {\n if (options.signal && listener) {\n options.signal.removeEventListener(\"abort\", listener);\n }\n });\n }\n return this.call<A, T>(callable, ...args);\n }\n\n fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {\n return this.call(() =>\n fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))\n );\n }\n}\n"],"mappings":";;;;;;AAKA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;AAOD,MAAM,+BAA+B,UA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,CAAC,OAAO,UAAU;AAEjC,OAAI,iBAAiB,MACnB,OAAM;OAEN,OAAM,IAAI,MAAM,MAAM;IAExB,EACJ;GACE,kBAAkB,EAAE,YAAY,KAAK,kBAAkB,MAAM;GAC7D,SAAS,KAAK;GACd,WAAW;GAGZ,CACF,EACH,EAAE,gBAAgB,MAAM,CACzB;;CAIH,gBACE,SACA,UACA,GAAG,MAC8B;AAGjC,MAAI,QAAQ,QAAQ;GAClB,IAAI;AACJ,UAAO,QAAQ,KAAK,CAClB,KAAK,KAAW,UAAU,GAAG,KAAK,EAClC,IAAI,SAAgB,GAAG,WAAW;AAChC,qBAAiB;AACf,YAAO,oBAAoB,QAAQ,OAAO,CAAC;;AAE7C,YAAQ,QAAQ,iBAAiB,SAAS,UAAU,EAAE,MAAM,MAAM,CAAC;KACnE,CACH,CAAC,CAAC,cAAc;AACf,QAAI,QAAQ,UAAU,SACpB,SAAQ,OAAO,oBAAoB,SAAS,SAAS;KAEvD;;AAEJ,SAAO,KAAK,KAAW,UAAU,GAAG,KAAK;;CAG3C,MAAM,GAAG,MAA0D;AACjE,SAAO,KAAK,WACV,MAAM,GAAG,KAAK,CAAC,MAAM,QAAS,IAAI,KAAK,MAAM,QAAQ,OAAO,IAAI,CAAE,CACnE"}
@@ -38,13 +38,6 @@ async function getBytes(stream, onChunk) {
38
38
  ].join("\n"));
39
39
  }
40
40
  }
41
- var ControlChars = /* @__PURE__ */ function(ControlChars) {
42
- ControlChars[ControlChars["NewLine"] = 10] = "NewLine";
43
- ControlChars[ControlChars["CarriageReturn"] = 13] = "CarriageReturn";
44
- ControlChars[ControlChars["Space"] = 32] = "Space";
45
- ControlChars[ControlChars["Colon"] = 58] = "Colon";
46
- return ControlChars;
47
- }(ControlChars || {});
48
41
  /**
49
42
  * Parses arbitary byte chunks into EventSource line buffers.
50
43
  * Each line should be of the format "field: value" and ends with \r, \n, or \r\n.
@@ -70,16 +63,16 @@ function getLines(onLine) {
70
63
  let lineStart = 0;
71
64
  while (position < bufLength) {
72
65
  if (discardTrailingNewline) {
73
- if (buffer[position] === ControlChars.NewLine) lineStart = ++position;
66
+ if (buffer[position] === 10) lineStart = ++position;
74
67
  discardTrailingNewline = false;
75
68
  }
76
69
  let lineEnd = -1;
77
70
  for (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) {
78
- case ControlChars.Colon:
71
+ case 58:
79
72
  if (fieldLength === -1) fieldLength = position - lineStart;
80
73
  break;
81
- case ControlChars.CarriageReturn: discardTrailingNewline = true;
82
- case ControlChars.NewLine:
74
+ case 13: discardTrailingNewline = true;
75
+ case 10:
83
76
  lineEnd = position;
84
77
  break;
85
78
  }
@@ -118,7 +111,7 @@ function getMessages(onMessage, onId, onRetry) {
118
111
  message = newMessage();
119
112
  } else if (fieldLength > 0) {
120
113
  const field = decoder.decode(line.subarray(0, fieldLength));
121
- const valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);
114
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
122
115
  const value = decoder.decode(line.subarray(valueOffset));
123
116
  switch (field) {
124
117
  case "data":
@@ -1 +1 @@
1
- {"version":3,"file":"event_source_parse.cjs","names":["IterableReadableStream"],"sources":["../../src/utils/event_source_parse.ts"],"sourcesContent":["/* oxlint-disable prefer-template */\n/* oxlint-disable default-case */\n// Adapted from https://github.com/gfortaine/fetch-event-source/blob/main/src/parse.ts\n// due to a packaging issue in the original.\n// MIT License\nimport { IterableReadableStream } from \"./stream.js\";\n\nexport const EventStreamContentType = \"text/event-stream\";\n\n/**\n * Represents a message sent in an event stream\n * https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format\n */\nexport interface EventSourceMessage {\n /** The event ID to set the EventSource object's last event ID value. */\n id: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\n/**\n * Converts a ReadableStream into a callback pattern.\n * @param stream The input ReadableStream.\n * @param onChunk A function that will be called on each new byte chunk in the stream.\n * @returns {Promise<void>} A promise that will be resolved when the stream closes.\n */\nexport async function getBytes(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n stream: ReadableStream<Uint8Array> | AsyncIterable<any>,\n onChunk: (arr: Uint8Array, flush?: boolean) => void\n) {\n // TODO: Use Async iteration for both cases?\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (stream instanceof ReadableStream) {\n const reader = stream.getReader();\n // CHANGED: Introduced a \"flush\" mechanism to process potential pending messages when the stream ends.\n // This change is essential to ensure that we capture every last piece of information from streams,\n // such as those from Azure OpenAI, which may not terminate with a blank line. Without this\n // mechanism, we risk ignoring a possibly significant last message.\n // See https://github.com/langchain-ai/langchainjs/issues/1299 for details.\n while (true) {\n const result = await reader.read();\n if (result.done) {\n onChunk(new Uint8Array(), true);\n break;\n }\n onChunk(result.value);\n }\n } else {\n try {\n // Handle Node.js Readable streams with async iteration\n for await (const chunk of stream) {\n onChunk(new Uint8Array(chunk));\n }\n onChunk(new Uint8Array(), true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(\n [\n \"Parsing event source stream failed.\",\n \"Ensure your implementation of fetch returns a web or Node readable stream.\",\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n}\n\nconst enum ControlChars {\n NewLine = 10,\n CarriageReturn = 13,\n Space = 32,\n Colon = 58,\n}\n\n/**\n * Parses arbitary byte chunks into EventSource line buffers.\n * Each line should be of the format \"field: value\" and ends with \\r, \\n, or \\r\\n.\n * @param onLine A function that will be called on each new EventSource line.\n * @returns A function that should be called for each incoming byte chunk.\n */\nexport function getLines(\n onLine: (line: Uint8Array, fieldLength: number, flush?: boolean) => void\n) {\n let buffer: Uint8Array | undefined;\n let position: number; // current read position\n let fieldLength: number; // length of the `field` portion of the line\n let discardTrailingNewline = false;\n\n // return a function that can process each incoming byte chunk:\n return function onChunk(arr: Uint8Array, flush?: boolean) {\n if (flush) {\n onLine(arr, 0, true);\n return;\n }\n\n if (buffer === undefined) {\n buffer = arr;\n position = 0;\n fieldLength = -1;\n } else {\n // we're still parsing the old line. Append the new bytes into buffer:\n buffer = concat(buffer, arr);\n }\n\n const bufLength = buffer.length;\n let lineStart = 0; // index where the current line starts\n while (position < bufLength) {\n if (discardTrailingNewline) {\n if (buffer[position] === ControlChars.NewLine) {\n lineStart = ++position; // skip to next char\n }\n\n discardTrailingNewline = false;\n }\n\n // start looking forward till the end of line:\n let lineEnd = -1; // index of the \\r or \\n char\n for (; position < bufLength && lineEnd === -1; ++position) {\n switch (buffer[position]) {\n case ControlChars.Colon:\n if (fieldLength === -1) {\n // first colon in line\n fieldLength = position - lineStart;\n }\n break;\n // @ts-expect-error \\r case below should fallthrough to \\n:\n case ControlChars.CarriageReturn:\n discardTrailingNewline = true;\n // oxlint-disable-next-line no-fallthrough\n case ControlChars.NewLine:\n lineEnd = position;\n break;\n }\n }\n\n if (lineEnd === -1) {\n // We reached the end of the buffer but the line hasn't ended.\n // Wait for the next arr and then continue parsing:\n break;\n }\n\n // we've reached the line end, send it out:\n onLine(buffer.subarray(lineStart, lineEnd), fieldLength);\n lineStart = position; // we're now on the next line\n fieldLength = -1;\n }\n\n if (lineStart === bufLength) {\n buffer = undefined; // we've finished reading it\n } else if (lineStart !== 0) {\n // Create a new view into buffer beginning at lineStart so we don't\n // need to copy over the previous lines when we get the new arr:\n buffer = buffer.subarray(lineStart);\n position -= lineStart;\n }\n };\n}\n\n/**\n * Parses line buffers into EventSourceMessages.\n * @param onId A function that will be called on each `id` field.\n * @param onRetry A function that will be called on each `retry` field.\n * @param onMessage A function that will be called on each message.\n * @returns A function that should be called for each incoming line buffer.\n */\nexport function getMessages(\n onMessage?: (msg: EventSourceMessage) => void,\n onId?: (id: string) => void,\n onRetry?: (retry: number) => void\n) {\n let message = newMessage();\n const decoder = new TextDecoder();\n\n // return a function that can process each incoming line buffer:\n return function onLine(\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) {\n if (flush) {\n if (!isEmpty(message)) {\n onMessage?.(message);\n message = newMessage();\n }\n return;\n }\n\n if (line.length === 0) {\n // empty line denotes end of message. Trigger the callback and start a new message:\n onMessage?.(message);\n message = newMessage();\n } else if (fieldLength > 0) {\n // exclude comments and lines with no values\n // line is of format \"<field>:<value>\" or \"<field>: <value>\"\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n const field = decoder.decode(line.subarray(0, fieldLength));\n const valueOffset =\n fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);\n const value = decoder.decode(line.subarray(valueOffset));\n\n switch (field) {\n case \"data\":\n // if this message already has data, append the new value to the old.\n // otherwise, just set to the new value:\n message.data = message.data ? message.data + \"\\n\" + value : value; // otherwise,\n break;\n case \"event\":\n message.event = value;\n break;\n case \"id\":\n onId?.((message.id = value));\n break;\n case \"retry\": {\n const retry = parseInt(value, 10);\n if (!Number.isNaN(retry)) {\n // per spec, ignore non-integers\n onRetry?.((message.retry = retry));\n }\n break;\n }\n }\n }\n };\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array) {\n const res = new Uint8Array(a.length + b.length);\n res.set(a);\n res.set(b, a.length);\n return res;\n}\n\nfunction newMessage(): EventSourceMessage {\n // data, event, and id must be initialized to empty strings:\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n // retry should be initialized to undefined so we return a consistent shape\n // to the js engine all the time: https://mathiasbynens.be/notes/shapes-ics#takeaways\n return {\n data: \"\",\n event: \"\",\n id: \"\",\n retry: undefined,\n };\n}\n\nexport function convertEventStreamToIterableReadableDataStream(\n stream: ReadableStream,\n onMetadataEvent?: (e: unknown) => unknown\n) {\n const dataStream = new ReadableStream({\n async start(controller) {\n const enqueueLine = getMessages((msg) => {\n if (msg.event === \"error\") {\n throw new Error(msg.data ?? \"Unspecified event streaming error.\");\n } else if (msg.event === \"metadata\") {\n onMetadataEvent?.(msg);\n } else {\n if (msg.data) controller.enqueue(msg.data);\n }\n });\n const onLine = (\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) => {\n enqueueLine(line, fieldLength, flush);\n if (flush) controller.close();\n };\n await getBytes(stream, getLines(onLine));\n },\n });\n return IterableReadableStream.fromReadableStream(dataStream);\n}\n\nfunction isEmpty(message: EventSourceMessage): boolean {\n return (\n message.data === \"\" &&\n message.event === \"\" &&\n message.id === \"\" &&\n message.retry === undefined\n );\n}\n"],"mappings":";;;;;;;;;;;AAOA,MAAa,yBAAyB;;;;;;;AAuBtC,eAAsB,SAEpB,QACA,SACA;AAGA,KAAI,kBAAkB,gBAAgB;EACpC,MAAM,SAAS,OAAO,WAAW;AAMjC,SAAO,MAAM;GACX,MAAM,SAAS,MAAM,OAAO,MAAM;AAClC,OAAI,OAAO,MAAM;AACf,YAAQ,IAAI,YAAY,EAAE,KAAK;AAC/B;;AAEF,WAAQ,OAAO,MAAM;;OAGvB,KAAI;AAEF,aAAW,MAAM,SAAS,OACxB,SAAQ,IAAI,WAAW,MAAM,CAAC;AAEhC,UAAQ,IAAI,YAAY,EAAE,KAAK;UAExB,GAAQ;AACf,QAAM,IAAI,MACR;GACE;GACA;GACA,UAAU,EAAE;GACb,CAAC,KAAK,KAAK,CACb;;;AAKP,IAAW,eAAX,yBAAA,cAAA;AACE,cAAA,aAAA,aAAA,MAAA;AACA,cAAA,aAAA,oBAAA,MAAA;AACA,cAAA,aAAA,WAAA,MAAA;AACA,cAAA,aAAA,WAAA,MAAA;;EAJS,gBAAA,EAAA,CAKV;;;;;;;AAQD,SAAgB,SACd,QACA;CACA,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,yBAAyB;AAG7B,QAAO,SAAS,QAAQ,KAAiB,OAAiB;AACxD,MAAI,OAAO;AACT,UAAO,KAAK,GAAG,KAAK;AACpB;;AAGF,MAAI,WAAW,KAAA,GAAW;AACxB,YAAS;AACT,cAAW;AACX,iBAAc;QAGd,UAAS,OAAO,QAA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ACH,YAAQ,QAAQ,KAAK,MAAO;AAC5B;IACF,KAAK,SAAS;KACZ,MAAM,QAAQ,SAAS,OAAO,GAAG;AACjC,SAAI,CAAC,OAAO,MAAM,MAAM,CAEtB,WAAW,QAAQ,QAAQ,MAAO;AAEpC;;;;;;AAOV,SAAS,OAAO,GAAe,GAAe;CAC5C,MAAM,MAAM,IAAI,WAAW,EAAE,SAAS,EAAE,OAAO;AAC/C,KAAI,IAAI,EAAE;AACV,KAAI,IAAI,GAAG,EAAE,OAAO;AACpB,QAAO;;AAGT,SAAS,aAAiC;AAKxC,QAAO;EACL,MAAM;EACN,OAAO;EACP,IAAI;EACJ,OAAO,KAAA;EACR;;AAGH,SAAgB,+CACd,QACA,iBACA;CACA,MAAM,aAAa,IAAI,eAAe,EACpC,MAAM,MAAM,YAAY;EACtB,MAAM,cAAc,aAAa,QAAQ;AACvC,OAAI,IAAI,UAAU,QAChB,OAAM,IAAI,MAAM,IAAI,QAAQ,qCAAqC;YACxD,IAAI,UAAU,WACvB,mBAAkB,IAAI;YAElB,IAAI,KAAM,YAAW,QAAQ,IAAI,KAAK;IAE5C;EACF,MAAM,UACJ,MACA,aACA,UACG;AACH,eAAY,MAAM,aAAa,MAAM;AACrC,OAAI,MAAO,YAAW,OAAO;;AAE/B,QAAM,SAAS,QAAQ,SAAS,OAAO,CAAC;IAE3C,CAAC;AACF,QAAOA,qBAAAA,uBAAuB,mBAAmB,WAAW;;AAG9D,SAAS,QAAQ,SAAsC;AACrD,QACE,QAAQ,SAAS,MACjB,QAAQ,UAAU,MAClB,QAAQ,OAAO,MACf,QAAQ,UAAU,KAAA"}
1
+ {"version":3,"file":"event_source_parse.cjs","names":["IterableReadableStream"],"sources":["../../src/utils/event_source_parse.ts"],"sourcesContent":["/* oxlint-disable prefer-template */\n/* oxlint-disable default-case */\n// Adapted from https://github.com/gfortaine/fetch-event-source/blob/main/src/parse.ts\n// due to a packaging issue in the original.\n// MIT License\nimport { IterableReadableStream } from \"./stream.js\";\n\nexport const EventStreamContentType = \"text/event-stream\";\n\n/**\n * Represents a message sent in an event stream\n * https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format\n */\nexport interface EventSourceMessage {\n /** The event ID to set the EventSource object's last event ID value. */\n id: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\n/**\n * Converts a ReadableStream into a callback pattern.\n * @param stream The input ReadableStream.\n * @param onChunk A function that will be called on each new byte chunk in the stream.\n * @returns {Promise<void>} A promise that will be resolved when the stream closes.\n */\nexport async function getBytes(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n stream: ReadableStream<Uint8Array> | AsyncIterable<any>,\n onChunk: (arr: Uint8Array, flush?: boolean) => void\n) {\n // TODO: Use Async iteration for both cases?\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (stream instanceof ReadableStream) {\n const reader = stream.getReader();\n // CHANGED: Introduced a \"flush\" mechanism to process potential pending messages when the stream ends.\n // This change is essential to ensure that we capture every last piece of information from streams,\n // such as those from Azure OpenAI, which may not terminate with a blank line. Without this\n // mechanism, we risk ignoring a possibly significant last message.\n // See https://github.com/langchain-ai/langchainjs/issues/1299 for details.\n while (true) {\n const result = await reader.read();\n if (result.done) {\n onChunk(new Uint8Array(), true);\n break;\n }\n onChunk(result.value);\n }\n } else {\n try {\n // Handle Node.js Readable streams with async iteration\n for await (const chunk of stream) {\n onChunk(new Uint8Array(chunk));\n }\n onChunk(new Uint8Array(), true);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(\n [\n \"Parsing event source stream failed.\",\n \"Ensure your implementation of fetch returns a web or Node readable stream.\",\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n}\n\nconst enum ControlChars {\n NewLine = 10,\n CarriageReturn = 13,\n Space = 32,\n Colon = 58,\n}\n\n/**\n * Parses arbitary byte chunks into EventSource line buffers.\n * Each line should be of the format \"field: value\" and ends with \\r, \\n, or \\r\\n.\n * @param onLine A function that will be called on each new EventSource line.\n * @returns A function that should be called for each incoming byte chunk.\n */\nexport function getLines(\n onLine: (line: Uint8Array, fieldLength: number, flush?: boolean) => void\n) {\n let buffer: Uint8Array | undefined;\n let position: number; // current read position\n let fieldLength: number; // length of the `field` portion of the line\n let discardTrailingNewline = false;\n\n // return a function that can process each incoming byte chunk:\n return function onChunk(arr: Uint8Array, flush?: boolean) {\n if (flush) {\n onLine(arr, 0, true);\n return;\n }\n\n if (buffer === undefined) {\n buffer = arr;\n position = 0;\n fieldLength = -1;\n } else {\n // we're still parsing the old line. Append the new bytes into buffer:\n buffer = concat(buffer, arr);\n }\n\n const bufLength = buffer.length;\n let lineStart = 0; // index where the current line starts\n while (position < bufLength) {\n if (discardTrailingNewline) {\n if (buffer[position] === ControlChars.NewLine) {\n lineStart = ++position; // skip to next char\n }\n\n discardTrailingNewline = false;\n }\n\n // start looking forward till the end of line:\n let lineEnd = -1; // index of the \\r or \\n char\n for (; position < bufLength && lineEnd === -1; ++position) {\n switch (buffer[position]) {\n case ControlChars.Colon:\n if (fieldLength === -1) {\n // first colon in line\n fieldLength = position - lineStart;\n }\n break;\n // @ts-expect-error \\r case below should fallthrough to \\n:\n case ControlChars.CarriageReturn:\n discardTrailingNewline = true;\n // oxlint-disable-next-line no-fallthrough\n case ControlChars.NewLine:\n lineEnd = position;\n break;\n }\n }\n\n if (lineEnd === -1) {\n // We reached the end of the buffer but the line hasn't ended.\n // Wait for the next arr and then continue parsing:\n break;\n }\n\n // we've reached the line end, send it out:\n onLine(buffer.subarray(lineStart, lineEnd), fieldLength);\n lineStart = position; // we're now on the next line\n fieldLength = -1;\n }\n\n if (lineStart === bufLength) {\n buffer = undefined; // we've finished reading it\n } else if (lineStart !== 0) {\n // Create a new view into buffer beginning at lineStart so we don't\n // need to copy over the previous lines when we get the new arr:\n buffer = buffer.subarray(lineStart);\n position -= lineStart;\n }\n };\n}\n\n/**\n * Parses line buffers into EventSourceMessages.\n * @param onId A function that will be called on each `id` field.\n * @param onRetry A function that will be called on each `retry` field.\n * @param onMessage A function that will be called on each message.\n * @returns A function that should be called for each incoming line buffer.\n */\nexport function getMessages(\n onMessage?: (msg: EventSourceMessage) => void,\n onId?: (id: string) => void,\n onRetry?: (retry: number) => void\n) {\n let message = newMessage();\n const decoder = new TextDecoder();\n\n // return a function that can process each incoming line buffer:\n return function onLine(\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) {\n if (flush) {\n if (!isEmpty(message)) {\n onMessage?.(message);\n message = newMessage();\n }\n return;\n }\n\n if (line.length === 0) {\n // empty line denotes end of message. Trigger the callback and start a new message:\n onMessage?.(message);\n message = newMessage();\n } else if (fieldLength > 0) {\n // exclude comments and lines with no values\n // line is of format \"<field>:<value>\" or \"<field>: <value>\"\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n const field = decoder.decode(line.subarray(0, fieldLength));\n const valueOffset =\n fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);\n const value = decoder.decode(line.subarray(valueOffset));\n\n switch (field) {\n case \"data\":\n // if this message already has data, append the new value to the old.\n // otherwise, just set to the new value:\n message.data = message.data ? message.data + \"\\n\" + value : value; // otherwise,\n break;\n case \"event\":\n message.event = value;\n break;\n case \"id\":\n onId?.((message.id = value));\n break;\n case \"retry\": {\n const retry = parseInt(value, 10);\n if (!Number.isNaN(retry)) {\n // per spec, ignore non-integers\n onRetry?.((message.retry = retry));\n }\n break;\n }\n }\n }\n };\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array) {\n const res = new Uint8Array(a.length + b.length);\n res.set(a);\n res.set(b, a.length);\n return res;\n}\n\nfunction newMessage(): EventSourceMessage {\n // data, event, and id must be initialized to empty strings:\n // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation\n // retry should be initialized to undefined so we return a consistent shape\n // to the js engine all the time: https://mathiasbynens.be/notes/shapes-ics#takeaways\n return {\n data: \"\",\n event: \"\",\n id: \"\",\n retry: undefined,\n };\n}\n\nexport function convertEventStreamToIterableReadableDataStream(\n stream: ReadableStream,\n onMetadataEvent?: (e: unknown) => unknown\n) {\n const dataStream = new ReadableStream({\n async start(controller) {\n const enqueueLine = getMessages((msg) => {\n if (msg.event === \"error\") {\n throw new Error(msg.data ?? \"Unspecified event streaming error.\");\n } else if (msg.event === \"metadata\") {\n onMetadataEvent?.(msg);\n } else {\n if (msg.data) controller.enqueue(msg.data);\n }\n });\n const onLine = (\n line: Uint8Array,\n fieldLength: number,\n flush?: boolean\n ) => {\n enqueueLine(line, fieldLength, flush);\n if (flush) controller.close();\n };\n await getBytes(stream, getLines(onLine));\n },\n });\n return IterableReadableStream.fromReadableStream(dataStream);\n}\n\nfunction isEmpty(message: EventSourceMessage): boolean {\n return (\n message.data === \"\" &&\n message.event === \"\" &&\n message.id === \"\" &&\n message.retry === undefined\n );\n}\n"],"mappings":";;;;;;;;;;;AAOA,MAAa,yBAAyB;;;;;;;AAuBtC,eAAsB,SAEpB,QACA,SACA;AAGA,KAAI,kBAAkB,gBAAgB;EACpC,MAAM,SAAS,OAAO,WAAW;AAMjC,SAAO,MAAM;GACX,MAAM,SAAS,MAAM,OAAO,MAAM;AAClC,OAAI,OAAO,MAAM;AACf,YAAQ,IAAI,YAAY,EAAE,KAAK;AAC/B;;AAEF,WAAQ,OAAO,MAAM;;OAGvB,KAAI;AAEF,aAAW,MAAM,SAAS,OACxB,SAAQ,IAAI,WAAW,MAAM,CAAC;AAEhC,UAAQ,IAAI,YAAY,EAAE,KAAK;UAExB,GAAQ;AACf,QAAM,IAAI,MACR;GACE;GACA;GACA,UAAU,EAAE;GACb,CAAC,KAAK,KAAK,CACb;;;;;;;;;AAkBP,SAAgB,SACd,QACA;CACA,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,yBAAyB;AAG7B,QAAO,SAAS,QAAQ,KAAiB,OAAiB;AACxD,MAAI,OA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