langchain 1.0.0-alpha.2 → 1.0.0-alpha.4

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 (73) hide show
  1. package/dist/agents/ReactAgent.cjs +1 -1
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.d.cts +3 -3
  4. package/dist/agents/ReactAgent.d.cts.map +1 -1
  5. package/dist/agents/ReactAgent.d.ts +3 -3
  6. package/dist/agents/ReactAgent.d.ts.map +1 -1
  7. package/dist/agents/ReactAgent.js +2 -2
  8. package/dist/agents/ReactAgent.js.map +1 -1
  9. package/dist/agents/annotation.cjs +122 -2
  10. package/dist/agents/annotation.cjs.map +1 -1
  11. package/dist/agents/annotation.d.cts +18 -14
  12. package/dist/agents/annotation.d.cts.map +1 -1
  13. package/dist/agents/annotation.d.ts +18 -14
  14. package/dist/agents/annotation.d.ts.map +1 -1
  15. package/dist/agents/annotation.js +121 -2
  16. package/dist/agents/annotation.js.map +1 -1
  17. package/dist/agents/errors.cjs +1 -1
  18. package/dist/agents/errors.cjs.map +1 -1
  19. package/dist/agents/errors.js +1 -1
  20. package/dist/agents/errors.js.map +1 -1
  21. package/dist/agents/index.cjs +2 -2
  22. package/dist/agents/index.cjs.map +1 -1
  23. package/dist/agents/index.d.cts +15 -15
  24. package/dist/agents/index.d.cts.map +1 -1
  25. package/dist/agents/index.d.ts +15 -15
  26. package/dist/agents/index.d.ts.map +1 -1
  27. package/dist/agents/index.js +2 -2
  28. package/dist/agents/index.js.map +1 -1
  29. package/dist/agents/nodes/AgentNode.cjs +8 -3
  30. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  31. package/dist/agents/nodes/AgentNode.js +8 -3
  32. package/dist/agents/nodes/AgentNode.js.map +1 -1
  33. package/dist/agents/nodes/ToolNode.cjs +2 -2
  34. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  35. package/dist/agents/nodes/ToolNode.d.cts +1 -1
  36. package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
  37. package/dist/agents/nodes/ToolNode.d.ts +1 -1
  38. package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
  39. package/dist/agents/nodes/ToolNode.js +2 -2
  40. package/dist/agents/nodes/ToolNode.js.map +1 -1
  41. package/dist/agents/responses.cjs +2 -3
  42. package/dist/agents/responses.cjs.map +1 -1
  43. package/dist/agents/responses.d.cts +6 -1
  44. package/dist/agents/responses.d.cts.map +1 -1
  45. package/dist/agents/responses.d.ts +6 -1
  46. package/dist/agents/responses.d.ts.map +1 -1
  47. package/dist/agents/responses.js +2 -3
  48. package/dist/agents/responses.js.map +1 -1
  49. package/dist/agents/types.d.cts +28 -10
  50. package/dist/agents/types.d.cts.map +1 -1
  51. package/dist/agents/types.d.ts +28 -10
  52. package/dist/agents/types.d.ts.map +1 -1
  53. package/dist/agents/utils.cjs +1 -1
  54. package/dist/agents/utils.cjs.map +1 -1
  55. package/dist/agents/utils.js +1 -1
  56. package/dist/agents/utils.js.map +1 -1
  57. package/dist/agents/withAgentName.cjs +1 -1
  58. package/dist/agents/withAgentName.cjs.map +1 -1
  59. package/dist/agents/withAgentName.js +1 -1
  60. package/dist/agents/withAgentName.js.map +1 -1
  61. package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
  62. package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
  63. package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
  64. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  65. package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
  66. package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
  67. package/dist/index.cjs +52 -3
  68. package/dist/index.cjs.map +1 -1
  69. package/dist/index.d.cts +4 -4
  70. package/dist/index.d.ts +4 -4
  71. package/dist/index.js +12 -5
  72. package/dist/index.js.map +1 -1
  73. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"responses.js","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n }","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat: InteropZodType<any> | JsonSchemaFormat"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | Record<string, unknown>,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? options?.name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(),\n strict: options?.strict,\n description:\n options?.description ??\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema,\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n name: getFunctionName(),\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n private constructor(public readonly schema: Record<string, unknown>) {}\n\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n\n static fromSchema(\n schema: Record<string, unknown>\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | Record<string, unknown>\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * return if the response doesn't contain valid content\n */\n if (typeof response.content !== \"string\" || response.content === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(response.content);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch (error) {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateReactAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, undefined, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" && item !== null && !isInteropZodObject(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, undefined, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject or plain JSON schema objects.`\n );\n }\n\n if (isInteropZodObject(responseFormat)) {\n return [ToolStrategy.fromSchema(responseFormat, undefined, options)];\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return [\n ToolStrategy.fromSchema(\n responseFormat as JsonSchemaFormat,\n undefined,\n options\n ),\n ];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown>\n extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Define how to transform the response format from a tool call.\n *\n * @param responseFormat - The response format to transform\n * @param options - The options to use for the transformation\n * @param options.handleError - Whether to handle errors from the tool call\n * @returns The transformed response format\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\nexport function providerStrategy<T extends InteropZodType<any>>(\n responseFormat: T\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat: JsonSchemaFormat\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat: InteropZodType<any> | JsonSchemaFormat\n): ProviderStrategy<any> {\n return ProviderStrategy.fromSchema(\n responseFormat as any\n ) as ProviderStrategy<any>;\n}\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n"],"mappings":";;;;;;;;AAmBA,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIUA,QAKAC,MAQAC,SAChB;EAdgB;EAKA;EAQA;CACd;CAEJ,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;CAC3B;CAsBD,OAAO,WACLC,QACAC,SAKAC,eACmB;;;;;EAKnB,SAAS,gBAAgBC,MAAe;AACtC,UAAO,QAAQ,SAAS,QAAQ,CAAC,QAAQ,EAAE,EAAE,mBAAmB;EACjE;AAED,MAAI,mBAAmB,OAAO,EAAE;GAC9B,MAAMC,iBAAe,aAAa,OAAO;GACzC,MAAMC,SAAO;IACX,MAAM;IACN,UAAU;KACR,MAAM,iBAAiB;KACvB,QAAQ,SAAS;KACjB,aACE,SAAS,eACTD,eAAa,eACb;KACF,YAAYA;IACb;GACF;AACD,UAAO,IAAI,aAAaA,gBAAcC,QAAM;EAC7C;EAED,IAAIC;AACJ,MACE,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAAO,cAAc,MAErB,qBAAqB;OAErB,qBAAqB;GACnB,MAAM,gBAAgB,OAAO,MAAgB;GAC7C,aAAc,OAAO,eAA0B;GAC/C,YAAY;EACb;EAEH,MAAM,eAAe,aAAa,OAA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E,eAAe,MACb,CAAC,SACC,OAAO,SAAS,YAAY,SAAS,QAAQ,CAAC,mBAAmB,KAAK,CACzE,CAED,QAAO,eAAe,IAAI,CAAC,SACzB,aAAa,WAAW,MAA0B,QAAW,QAAQ,CACtE;AAGH,QAAM,IAAI,MACR;CAGH;AAED,KAAI,mBAAmB,eAAe,CACpC,QAAO,CAAC,aAAa,WAAW,gBAAgB,QAAW,QAAQ,AAAC;AAGtE,KACE,0BAA0B,gBAC1B,0BAA0B,iBAE1B,QAAO,CAAC,cAAe;;;;AAMzB,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,gBAAgB,eAEhB,QAAO,CACL,aAAa,WACX,gBACA,QACA,QACD,AACF;AAGH,OAAM,IAAI,MAAM,CAAC,yBAAyB,EAAE,OAAO,eAAe,EAAE;AACrE;;;;;;;;;AA0DD,SAAgB,aACdY,gBAKAZ,SACmB;AACnB,QAAO,wBAAwB,gBAAgB,QAAQ;AACxD;AAQD,SAAgB,iBACda,gBACuB;AACvB,QAAO,iBAAiB,WACtB,eACD;AACF"}
1
+ {"version":3,"file":"responses.js","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n }","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat: InteropZodType<any> | JsonSchemaFormat"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | Record<string, unknown>,\n options?: {\n name?: string;\n description?: string;\n strict?: boolean;\n },\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? options?.name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(),\n strict: options?.strict,\n description:\n options?.description ??\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n private constructor(public readonly schema: Record<string, unknown>) {}\n\n static fromSchema<T>(schema: InteropZodType<T>): ProviderStrategy<T>;\n\n static fromSchema(\n schema: Record<string, unknown>\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | Record<string, unknown>\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * return if the response doesn't contain valid content\n */\n if (typeof response.content !== \"string\" || response.content === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(response.content);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch (error) {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, undefined, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" && item !== null && !isInteropZodObject(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, undefined, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject or plain JSON schema objects.`\n );\n }\n\n if (isInteropZodObject(responseFormat)) {\n return [ToolStrategy.fromSchema(responseFormat, undefined, options)];\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return [\n ToolStrategy.fromSchema(\n responseFormat as JsonSchemaFormat,\n undefined,\n options\n ),\n ];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown>\n extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Define how to transform the response format from a tool call.\n *\n * @param responseFormat - The response format to transform\n * @param options - The options to use for the transformation\n * @param options.handleError - Whether to handle errors from the tool call\n * @returns The transformed response format\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\nexport function providerStrategy<T extends InteropZodType<any>>(\n responseFormat: T\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat: JsonSchemaFormat\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat: InteropZodType<any> | JsonSchemaFormat\n): ProviderStrategy<any> {\n return ProviderStrategy.fromSchema(\n responseFormat as any\n ) as ProviderStrategy<any>;\n}\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n"],"mappings":";;;;;;;;AAmBA,I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I,MAAM,CAAC,yBAAyB,EAAE,OAAO,eAAe,EAAE;AACrE;;;;;;;;;AA+DD,SAAgB,aACdY,gBAKAZ,SACmB;AACnB,QAAO,wBAAwB,gBAAgB,QAAQ;AACxD;AAQD,SAAgB,iBACda,gBACuB;AACvB,QAAO,iBAAiB,WACtB,eACD;AACF"}
@@ -7,7 +7,7 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
7
7
  import { BaseMessage, BaseMessageLike, SystemMessage } from "@langchain/core/messages";
8
8
  import { BaseChatModel } from "@langchain/core/language_models/chat_models";
9
9
  import { DynamicTool, StructuredToolInterface } from "@langchain/core/tools";
10
- import { LangGraphRunnableConfig, Runtime, START } from "@langchain/langgraph";
10
+ import { LangGraphRunnableConfig, START } from "@langchain/langgraph";
11
11
  import { All, BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
12
12
 
13
13
  //#region src/agents/types.d.ts
@@ -28,7 +28,25 @@ type ServerTool = Record<string, unknown>;
28
28
  type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;
29
29
  type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>["State"] & PreHookAnnotation["State"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>["State"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;
30
30
  type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>["State"] & PreHookAnnotation["State"];
31
- type CreateReactAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,
31
+ interface AgentRuntime<ContextType = Record<string, unknown>> {
32
+ /**
33
+ * The context of the agent.
34
+ */
35
+ context?: ContextType;
36
+ /**
37
+ * The store passed to the agent.
38
+ */
39
+ store?: BaseStore;
40
+ /**
41
+ * The writer of the agent to write to the output stream.
42
+ */
43
+ writer?: (chunk: unknown) => void;
44
+ /**
45
+ * An optional abort signal that indicates that the overall operation should be aborted.
46
+ */
47
+ signal?: AbortSignal;
48
+ }
49
+ type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,
32
50
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
51
  StructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {
34
52
  /** The chat model that can utilize OpenAI-style tool calling. */
@@ -40,7 +58,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
40
58
  * @uses {@link initChatModel}
41
59
  * @example
42
60
  * ```ts
43
- * const agent = createReactAgent({
61
+ * const agent = createAgent({
44
62
  * model: "anthropic:claude-3-7-sonnet-latest",
45
63
  * // ...
46
64
  * });
@@ -85,7 +103,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
85
103
  * // Context schema defines runtime parameters passed per invocation
86
104
  * const contextSchema = z.object({ ... });
87
105
  *
88
- * const agent = createReactAgent({
106
+ * const agent = createAgent({
89
107
  * llm: model,
90
108
  * tools: [updatePreferences, addTask],
91
109
  * stateSchema, // Persisted: preferences, e.g. task history, workflow state
@@ -120,7 +138,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
120
138
  *
121
139
  * @example
122
140
  * ```ts
123
- * const agent = createReactAgent({
141
+ * const agent = createAgent({
124
142
  * llm: model,
125
143
  * tools: [getWeather],
126
144
  * contextSchema: z.object({
@@ -164,7 +182,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
164
182
  * Can be passed in as:
165
183
  * - Zod schema
166
184
  * ```ts
167
- * const agent = createReactAgent({
185
+ * const agent = createAgent({
168
186
  * responseFormat: z.object({
169
187
  * capital: z.string(),
170
188
  * }),
@@ -173,7 +191,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
173
191
  * ```
174
192
  * - JSON schema
175
193
  * ```ts
176
- * const agent = createReactAgent({
194
+ * const agent = createAgent({
177
195
  * responseFormat: {
178
196
  * type: "json_schema",
179
197
  * schema: {
@@ -190,7 +208,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
190
208
  * - Create React Agent ResponseFormat
191
209
  * ```ts
192
210
  * import { providerStrategy, toolStrategy } from "langchain";
193
- * const agent = createReactAgent({
211
+ * const agent = createAgent({
194
212
  * responseFormat: providerStrategy(
195
213
  * z.object({
196
214
  * capital: z.string(),
@@ -255,7 +273,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
255
273
  /**
256
274
  * @deprecated likely to be removed in the next version of the agent
257
275
  */
258
- type DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>["State"] & PreHookAnnotation["State"], runtime: Runtime<ToAnnotationRoot<ContextSchema>["State"]>) => Promise<LanguageModelLike> | LanguageModelLike;
276
+ type DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>["State"] & PreHookAnnotation["State"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>["State"]>) => Promise<LanguageModelLike> | LanguageModelLike;
259
277
  //#endregion
260
- export { AgentState, ClientTool, CreateReactAgentParams, ExtractZodArrayTypes, N, Prompt, ServerTool };
278
+ export { AgentRuntime, AgentState, ClientTool, CreateAgentParams, ExtractZodArrayTypes, N, Prompt, ServerTool };
261
279
  //# sourceMappingURL=types.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","Runtime","StateGraph","LanguageModelLike","BaseChatModel","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","CreateReactAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","AbortSignal","ConfigurableModelInterface","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, Runtime, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport type AgentRuntime<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = Runtime<ToAnnotationRoot<AnnotationRoot>[\"State\"]>;\nexport type CreateReactAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nStructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createReactAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createReactAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createReactAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createReactAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createReactAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createReactAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _model: () => Promise<BaseChatModel>;\n}\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: Runtime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport {};\n"],"mappings":";;;;;;;;;;;;;KAYY8B,CAAAA,UAAW3B;AAAvB;AA0CA;;;;AAaka;AACla;AAAsB,KAdVkC,oBAcU,CAAA,UAAA,SAd8BpC,cAc9B,CAAA,GAAA,CAAA,EAAA,CAAA,GAduDkC,CAcvD,SAAA,SAAA,CAd2ElC,cAc3E,CAAA,KAAA,EAAA,CAAA,EAAA,GAAA,KAAA,KAAA,CAAA,GAdqHqC,IAcrH,SAAA,SAd2IrC,cAc3I,CAAA,GAAA,CAAA,EAAA,GAdmKsC,CAcnK,GAduKF,oBAcvK,CAd4LC,IAc5L,CAAA,GAdoMC,CAcpM,GAAA,KAAA;;;;;AAEqDvC,KAL/D2C,UAAAA,GAAaX,MAKkDhC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;AAAmBqB,KAJlFuB,UAAAA,GAAa7B,uBAIqEM,GAJ3CP,WAI2CO,GAJ7BH,gBAI6BG;AAE/DW,KALnBa,MAKmBb,CAAAA,oBALQX,iBAKRW,GAL4BhC,gBAK5BgC,GAL+CX,iBAK/CW,EAAAA,sBALwFX,iBAKxFW,GAL4GhC,gBAK5GgC,GAL+HX,iBAK/HW,CAAAA,GALoJxB,aAKpJwB,GAAAA,MAAAA,GAAAA,CAAAA,CAAAA,KAAA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C,aAF0J9C,CAAAA;EAAc;;;;;;;;;;;;;EAE3J,KAA7CqD,CAAAA,EAAAA,MAAAA;EAAkB;EAgB7B,KAAIX,EAAZxB,QAAYwB,GAAAA,CAAAA,UAAAA,GAAaC,UAAbD,CAAAA,EAAAA;EAAU;;;;;;;;;;;;;;;;EAqLe,MAAyBvB,CAAAA,EApK5DyB,MAoK4DzB,CApKrD0B,WAoKqD1B,EApKxC2B,aAoKwC3B,CAAAA;EAAiB;;;;;;;;;;;;;;;;;;AASlE;AAuB2K;;;;;;;;;;;;;;;;;AAI+K;;;;;;;;;gBA1JhW0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;oBAEEnC;;iBAEHA;;oBAEGkB,MAAMnB;;mBAEPmB,MAAMnB;UACfE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS0C;;;;;;;;;;;;;;;;;;;;;iBAqBFtC,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BlB,wBAAwBoB,iBAAiByB;;;;;kBAKjM9B,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BlB,wBAAwBoB,iBAAiByB;;;;WAIzMS;;;;;;;;;;;;;;;;;KA2BRF,uCAAuCjC,oBAAoBrB,mBAAmBqB,yCAAyCA,oBAAoBrB,mBAAmBqB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqChB,QAAQkB,iBAAiByB,6BAA6BC,QAAQ1C,qBAAqBA"}
1
+ {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","StateGraph","LanguageModelLike","BaseChatModel","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","ContextType","AbortSignal","CreateAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","ConfigurableModelInterface","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport interface AgentRuntime<ContextType = Record<string, unknown>> {\n /**\n * The context of the agent.\n */\n context?: ContextType;\n /**\n * The store passed to the agent.\n */\n store?: BaseStore;\n /**\n * The writer of the agent to write to the output stream.\n */\n writer?: (chunk: unknown) => void;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n}\nexport type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nStructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _model: () => Promise<BaseChatModel>;\n}\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport {};\n"],"mappings":";;;;;;;;;;;;;KAYY6B,CAAAA,UAAW1B;AAAvB;AA0CA;;;;AAaka;AACla;AAAsB,KAdViC,oBAcU,CAAA,UAAA,SAd8BnC,cAc9B,CAAA,GAAA,CAAA,EAAA,CAAA,GAduDiC,CAcvD,SAAA,SAAA,CAd2EjC,cAc3E,CAAA,KAAA,EAAA,CAAA,EAAA,GAAA,KAAA,KAAA,CAAA,GAdqHoC,IAcrH,SAAA,SAd2IpC,cAc3I,CAAA,GAAA,CAAA,EAAA,GAdmKqC,CAcnK,GAduKF,oBAcvK,CAd4LC,IAc5L,CAAA,GAdoMC,CAcpM,GAAA,KAAA;;;;;AAKRa,KARFT,UAAAA,GAAaX,MAQXoB,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;AAIFvC,KAXA+B,UAAAA,GAAa7B,uBAWbF,GAXuCC,WAWvCD,GAXqDK,gBAWrDL;AAQCwC,KAlBDR,MAkBCQ,CAAAA,oBAlB0BhC,iBAkB1BgC,GAlB8CpD,gBAkB9CoD,GAlBiEhC,iBAkBjEgC,EAAAA,sBAlB0GhC,iBAkB1GgC,GAlB8HpD,gBAkB9HoD,GAlBiJhC,iBAkBjJgC,CAAAA,GAlBsK7C,aAkBtK6C,GAAAA,MAAAA,GAAAA,CAAAA,CAAAA,KAAAA,EAlBwM/B,gBAkBxM+B,CAlByNP,WAkBzNO,CAAAA,CAAAA,OAAAA,CAAAA,GAlBiPjC,iBAkBjPiC,CAAAA,OAAAA,CAAAA,EAAAA,MAAAA,EAlBqRlD,uBAkBrRkD,CAlB6S/B,gBAkB7S+B,CAlB8T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} from "@langchain/core/mes
5
5
  import { BaseChatModel } from "@langchain/core/language_models/chat_models";
6
6
  import { Runnable, RunnableLike, RunnableToolLike } from "@langchain/core/runnables";
7
7
  import { DynamicTool, StructuredToolInterface } from "@langchain/core/tools";
8
- import { LangGraphRunnableConfig, Runtime, START, StateGraph } from "@langchain/langgraph";
8
+ import { LangGraphRunnableConfig, START, StateGraph } from "@langchain/langgraph";
9
9
  import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
10
10
  import { LanguageModelLike } from "@langchain/core/language_models/base";
11
11
  import { All, BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
@@ -28,7 +28,25 @@ type ServerTool = Record<string, unknown>;
28
28
  type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;
29
29
  type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>["State"] & PreHookAnnotation["State"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>["State"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;
30
30
  type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>["State"] & PreHookAnnotation["State"];
31
- type CreateReactAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,
31
+ interface AgentRuntime<ContextType = Record<string, unknown>> {
32
+ /**
33
+ * The context of the agent.
34
+ */
35
+ context?: ContextType;
36
+ /**
37
+ * The store passed to the agent.
38
+ */
39
+ store?: BaseStore;
40
+ /**
41
+ * The writer of the agent to write to the output stream.
42
+ */
43
+ writer?: (chunk: unknown) => void;
44
+ /**
45
+ * An optional abort signal that indicates that the overall operation should be aborted.
46
+ */
47
+ signal?: AbortSignal;
48
+ }
49
+ type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,
32
50
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
51
  StructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {
34
52
  /** The chat model that can utilize OpenAI-style tool calling. */
@@ -40,7 +58,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
40
58
  * @uses {@link initChatModel}
41
59
  * @example
42
60
  * ```ts
43
- * const agent = createReactAgent({
61
+ * const agent = createAgent({
44
62
  * model: "anthropic:claude-3-7-sonnet-latest",
45
63
  * // ...
46
64
  * });
@@ -85,7 +103,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
85
103
  * // Context schema defines runtime parameters passed per invocation
86
104
  * const contextSchema = z.object({ ... });
87
105
  *
88
- * const agent = createReactAgent({
106
+ * const agent = createAgent({
89
107
  * llm: model,
90
108
  * tools: [updatePreferences, addTask],
91
109
  * stateSchema, // Persisted: preferences, e.g. task history, workflow state
@@ -120,7 +138,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
120
138
  *
121
139
  * @example
122
140
  * ```ts
123
- * const agent = createReactAgent({
141
+ * const agent = createAgent({
124
142
  * llm: model,
125
143
  * tools: [getWeather],
126
144
  * contextSchema: z.object({
@@ -164,7 +182,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
164
182
  * Can be passed in as:
165
183
  * - Zod schema
166
184
  * ```ts
167
- * const agent = createReactAgent({
185
+ * const agent = createAgent({
168
186
  * responseFormat: z.object({
169
187
  * capital: z.string(),
170
188
  * }),
@@ -173,7 +191,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
173
191
  * ```
174
192
  * - JSON schema
175
193
  * ```ts
176
- * const agent = createReactAgent({
194
+ * const agent = createAgent({
177
195
  * responseFormat: {
178
196
  * type: "json_schema",
179
197
  * schema: {
@@ -190,7 +208,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
190
208
  * - Create React Agent ResponseFormat
191
209
  * ```ts
192
210
  * import { providerStrategy, toolStrategy } from "langchain";
193
- * const agent = createReactAgent({
211
+ * const agent = createAgent({
194
212
  * responseFormat: providerStrategy(
195
213
  * z.object({
196
214
  * capital: z.string(),
@@ -255,7 +273,7 @@ StructuredResponseType extends Record<string, any> = Record<string, any>, Contex
255
273
  /**
256
274
  * @deprecated likely to be removed in the next version of the agent
257
275
  */
258
- type DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>["State"] & PreHookAnnotation["State"], runtime: Runtime<ToAnnotationRoot<ContextSchema>["State"]>) => Promise<LanguageModelLike> | LanguageModelLike;
276
+ type DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>["State"] & PreHookAnnotation["State"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>["State"]>) => Promise<LanguageModelLike> | LanguageModelLike;
259
277
  //#endregion
260
- export { AgentState, ClientTool, CreateReactAgentParams, ExtractZodArrayTypes, N, Prompt, ServerTool };
278
+ export { AgentRuntime, AgentState, ClientTool, CreateAgentParams, ExtractZodArrayTypes, N, Prompt, ServerTool };
261
279
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","Runtime","StateGraph","LanguageModelLike","BaseChatModel","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","CreateReactAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","AbortSignal","ConfigurableModelInterface","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, Runtime, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport type AgentRuntime<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = Runtime<ToAnnotationRoot<AnnotationRoot>[\"State\"]>;\nexport type CreateReactAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nStructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createReactAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createReactAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createReactAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createReactAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createReactAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createReactAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _model: () => Promise<BaseChatModel>;\n}\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: Runtime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport {};\n"],"mappings":";;;;;;;;;;;;;KAYY8B,CAAAA,UAAW3B;AAAvB;AA0CA;;;;AAaka;AACla;AAAsB,KAdVkC,oBAcU,CAAA,UAAA,SAd8BpC,cAc9B,CAAA,GAAA,CAAA,EAAA,CAAA,GAduDkC,CAcvD,SAAA,SAAA,CAd2ElC,cAc3E,CAAA,KAAA,EAAA,CAAA,EAAA,GAAA,KAAA,KAAA,CAAA,GAdqHqC,IAcrH,SAAA,SAd2IrC,cAc3I,CAAA,GAAA,CAAA,EAAA,GAdmKsC,CAcnK,GAduKF,oBAcvK,CAd4LC,IAc5L,CAAA,GAdoMC,CAcpM,GAAA,KAAA;;;;;AAEqDvC,KAL/D2C,UAAAA,GAAaX,MAKkDhC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;AAAmBqB,KAJlFuB,UAAAA,GAAa7B,uBAIqEM,GAJ3CP,WAI2CO,GAJ7BH,gBAI6BG;AAE/DW,KALnBa,MAKmBb,CAAAA,oBALQX,iBAKRW,GAL4BhC,gBAK5BgC,GAL+CX,iBAK/CW,EAAAA,sBALwFX,iBAKxFW,GAL4GhC,gBAK5GgC,GAL+HX,iBAK/HW,CAAAA,GALoJxB,aAKpJwB,GAAAA,MAAAA,GAAAA,CAAAA,CAAAA,KAAAA,EALsLV,gBAKtLU,CALuMc,WAKvMd,CAAAA,CAAAA,OAAAA,CAAAA,GAL+NZ,iBAK/NY,CAAAA,OAAAA,CAAAA,EAAAA,MAAAA,EALmQ9B,uBAKnQ8B,CAL2RV,gBAK3RU,CAL4Se,aAK5Sf,CAAAA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;;;;;;;;EAqLe,MAAyBvB,CAAAA,EApK5DyB,MAoK4DzB,CApKrD0B,WAoKqD1B,EApKxC2B,aAoKwC3B,CAAAA;EAAiB;;;;;;;;;;;;;;;;;;AASlE;AAuB2K;;;;;;;;;;;;;;;;;AAI+K;;;;;;;;;gBA1JhW0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;oBAEEnC;;iBAEHA;;oBAEGkB,MAAMnB;;mBAEPmB,MAAMnB;UACfE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS0C;;;;;;;;;;;;;;;;;;;;;iBAqBFtC,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BlB,wBAAwBoB,iBAAiByB;;;;;kBAKjM9B,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BlB,wBAAwBoB,iBAAiByB;;;;WAIzMS;;;;;;;;;;;;;;;;;KA2BRF,uCAAuCjC,oBAAoBrB,mBAAmBqB,yCAAyCA,oBAAoBrB,mBAAmBqB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqChB,QAAQkB,iBAAiByB,6BAA6BC,QAAQ1C,qBAAqBA"}
1
+ {"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","StateGraph","LanguageModelLike","BaseChatModel","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","ContextType","AbortSignal","CreateAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","ConfigurableModelInterface","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport interface AgentRuntime<ContextType = Record<string, unknown>> {\n /**\n * The context of the agent.\n */\n context?: ContextType;\n /**\n * The store passed to the agent.\n */\n store?: BaseStore;\n /**\n * The writer of the agent to write to the output stream.\n */\n writer?: (chunk: unknown) => void;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n}\nexport type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nStructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _model: () => Promise<BaseChatModel>;\n}\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRo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pB,CAAAA;EAAuB;;;;;;;;;;;;;EAqHzZ,KAEtBf,CAAAA,EAAAA,MAAAA;EAAmB;EAEf,KAAKD,EAvGjBQ,QAuGiBR,GAAAA,CAvGLgC,UAuGKhC,GAvGQiC,UAuGRjC,CAAAA,EAAAA;EAAG;;;;;;;;;;;;;;;;EAmFkB,MAAyBS,CAAAA,EAzK7DyB,MAyK6DzB,CAzKtD0B,WAyKsD1B,EAzKzC2B,aAyKyC3B,CAAAA;EAAiB;;;;;;;;AAInE;AAuB2K;;;;;;;;;;;;;;;;;AAIoL;;;;;;;;;;;;;;;;;;;gBA1JrW0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;oBAEEnC;;iBAEHA;;oBAEGkB,MAAMnB;;mBAEPmB,MAAMnB;UACfE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS4C;;;;;;;;;;;;;;;;;;;;;iBAqBFxC,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BjB,wBAAwBmB,iBAAiByB;;;;;kBAKjM9B,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BjB,wBAAwBmB,iBAAiByB;;;;WAIzMM;;;;;;;;;;;;;;;;;KA2BRG,uCAAuCnC,oBAAoBpB,mBAAmBoB,yCAAyCA,oBAAoBpB,mBAAmBoB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqC+B,aAAa7B,iBAAiByB,6BAA6BC,QAAQ1C,qBAAqBA"}
@@ -13,7 +13,7 @@ const CONTENT_PATTERN = /<content>(.*?)<\/content>/s;
13
13
  * This is useful for making a message history with multiple agents more coherent.
14
14
  *
15
15
  * NOTE: agent name is consumed from the message.name field.
16
- * If you're using an agent built with createReactAgent, name is automatically set.
16
+ * If you're using an agent built with createAgent, name is automatically set.
17
17
  * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.
18
18
  *
19
19
  * @param message - Message to add agent name formatting to