nestjs-langchain 2.0.0 → 2.2.0

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 (112) hide show
  1. package/README.md +71 -6
  2. package/dist/agent.d.ts +21 -4
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +73 -33
  5. package/dist/agent.js.map +1 -1
  6. package/dist/constants.d.ts +16 -0
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +21 -0
  9. package/dist/constants.js.map +1 -1
  10. package/dist/errors/agent-aborted.error.d.ts +21 -0
  11. package/dist/errors/agent-aborted.error.d.ts.map +1 -0
  12. package/dist/errors/agent-aborted.error.js +22 -0
  13. package/dist/errors/agent-aborted.error.js.map +1 -0
  14. package/dist/errors/agent-recursion-limit.error.d.ts +23 -0
  15. package/dist/errors/agent-recursion-limit.error.d.ts.map +1 -0
  16. package/dist/errors/agent-recursion-limit.error.js +24 -0
  17. package/dist/errors/agent-recursion-limit.error.js.map +1 -0
  18. package/dist/errors/index.d.ts +5 -0
  19. package/dist/errors/index.d.ts.map +1 -1
  20. package/dist/errors/index.js +5 -0
  21. package/dist/errors/index.js.map +1 -1
  22. package/dist/errors/messages.d.ts +10 -0
  23. package/dist/errors/messages.d.ts.map +1 -1
  24. package/dist/errors/messages.js +24 -3
  25. package/dist/errors/messages.js.map +1 -1
  26. package/dist/errors/run-error.util.d.ts +21 -0
  27. package/dist/errors/run-error.util.d.ts.map +1 -0
  28. package/dist/errors/run-error.util.js +33 -0
  29. package/dist/errors/run-error.util.js.map +1 -0
  30. package/dist/errors/structured-output.error.d.ts +22 -0
  31. package/dist/errors/structured-output.error.d.ts.map +1 -0
  32. package/dist/errors/structured-output.error.js +23 -0
  33. package/dist/errors/structured-output.error.js.map +1 -0
  34. package/dist/errors/unwrap-middleware-error.util.d.ts +10 -0
  35. package/dist/errors/unwrap-middleware-error.util.d.ts.map +1 -0
  36. package/dist/errors/unwrap-middleware-error.util.js +17 -0
  37. package/dist/errors/unwrap-middleware-error.util.js.map +1 -0
  38. package/dist/index.d.ts +3 -1
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +2 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/interfaces/completed-run.interface.d.ts +1 -1
  43. package/dist/interfaces/completed-run.interface.d.ts.map +1 -1
  44. package/dist/interfaces/langchain-module-options.interface.d.ts +6 -0
  45. package/dist/interfaces/langchain-module-options.interface.d.ts.map +1 -1
  46. package/dist/interfaces/run-options.interface.d.ts +34 -0
  47. package/dist/interfaces/run-options.interface.d.ts.map +1 -0
  48. package/dist/interfaces/run-options.interface.js +2 -0
  49. package/dist/interfaces/run-options.interface.js.map +1 -0
  50. package/dist/output/index.d.ts +3 -0
  51. package/dist/output/index.d.ts.map +1 -0
  52. package/dist/output/index.js +3 -0
  53. package/dist/output/index.js.map +1 -0
  54. package/dist/output/run-output.d.ts +43 -0
  55. package/dist/output/run-output.d.ts.map +1 -0
  56. package/dist/output/run-output.js +107 -0
  57. package/dist/output/run-output.js.map +1 -0
  58. package/dist/output/structured-output.middleware.d.ts +22 -0
  59. package/dist/output/structured-output.middleware.d.ts.map +1 -0
  60. package/dist/output/structured-output.middleware.js +40 -0
  61. package/dist/output/structured-output.middleware.js.map +1 -0
  62. package/dist/run/answered-calls.util.d.ts +10 -0
  63. package/dist/run/answered-calls.util.d.ts.map +1 -0
  64. package/dist/run/answered-calls.util.js +12 -0
  65. package/dist/run/answered-calls.util.js.map +1 -0
  66. package/dist/run/index.d.ts +3 -0
  67. package/dist/run/index.d.ts.map +1 -1
  68. package/dist/run/index.js +3 -0
  69. package/dist/run/index.js.map +1 -1
  70. package/dist/run/recursion-limit.util.d.ts +10 -0
  71. package/dist/run/recursion-limit.util.d.ts.map +1 -0
  72. package/dist/run/recursion-limit.util.js +11 -0
  73. package/dist/run/recursion-limit.util.js.map +1 -0
  74. package/dist/run/run-summary.util.d.ts +10 -3
  75. package/dist/run/run-summary.util.d.ts.map +1 -1
  76. package/dist/run/run-summary.util.js +18 -6
  77. package/dist/run/run-summary.util.js.map +1 -1
  78. package/dist/run/usage-aside.d.ts +23 -0
  79. package/dist/run/usage-aside.d.ts.map +1 -0
  80. package/dist/run/usage-aside.js +33 -0
  81. package/dist/run/usage-aside.js.map +1 -0
  82. package/dist/tools/tool-errors.middleware.d.ts +7 -1
  83. package/dist/tools/tool-errors.middleware.d.ts.map +1 -1
  84. package/dist/tools/tool-errors.middleware.js +81 -16
  85. package/dist/tools/tool-errors.middleware.js.map +1 -1
  86. package/dist/tools/tool-name.util.d.ts.map +1 -1
  87. package/dist/tools/tool-name.util.js +1 -3
  88. package/dist/tools/tool-name.util.js.map +1 -1
  89. package/lib/agent.ts +119 -32
  90. package/lib/constants.ts +24 -0
  91. package/lib/errors/agent-aborted.error.ts +22 -0
  92. package/lib/errors/agent-recursion-limit.error.ts +24 -0
  93. package/lib/errors/index.ts +5 -0
  94. package/lib/errors/messages.ts +55 -3
  95. package/lib/errors/run-error.util.ts +57 -0
  96. package/lib/errors/structured-output.error.ts +23 -0
  97. package/lib/errors/unwrap-middleware-error.util.ts +19 -0
  98. package/lib/index.ts +9 -1
  99. package/lib/interfaces/completed-run.interface.ts +1 -1
  100. package/lib/interfaces/langchain-module-options.interface.ts +6 -0
  101. package/lib/interfaces/run-options.interface.ts +34 -0
  102. package/lib/output/index.ts +5 -0
  103. package/lib/output/run-output.ts +154 -0
  104. package/lib/output/structured-output.middleware.ts +44 -0
  105. package/lib/run/answered-calls.util.ts +16 -0
  106. package/lib/run/index.ts +3 -0
  107. package/lib/run/recursion-limit.util.ts +11 -0
  108. package/lib/run/run-summary.util.ts +33 -11
  109. package/lib/run/usage-aside.ts +41 -0
  110. package/lib/tools/tool-errors.middleware.ts +104 -10
  111. package/lib/tools/tool-name.util.ts +1 -4
  112. package/package.json +31 -12
@@ -0,0 +1,154 @@
1
+ import { toJsonSchema } from '@langchain/core/utils/json_schema';
2
+ import {
3
+ MultipleStructuredOutputsError,
4
+ StructuredOutputParsingError,
5
+ toolStrategy,
6
+ TypedToolStrategy,
7
+ } from 'langchain';
8
+ import z, { ZodType } from 'zod';
9
+ import { OUTPUT_TOOL } from '../constants.js';
10
+ import { AgentRunError, StructuredOutputError } from '../errors/index.js';
11
+ import {
12
+ agentPrefix,
13
+ noOutputJsonSchemaForm,
14
+ outputNotAnObject,
15
+ structuredOutputInvalid,
16
+ structuredOutputMissing,
17
+ structuredOutputMultiple,
18
+ } from '../errors/messages.js';
19
+ import { messageOf } from '../logging/index.js';
20
+
21
+ // The default of LangChain's own retry middlewares. See #151.
22
+ const MAX_RETRIES = 2;
23
+
24
+ // LangChain's default for a Zod schema, which its JSON Schema path leaves
25
+ // empty. See #282.
26
+ const OUTPUT_DESCRIPTION =
27
+ "Tool for extracting structured output from the model's response.";
28
+
29
+ /**
30
+ * The structured output one run asked for: the strategy its model calls use,
31
+ * and the answer parsed by the schema.
32
+ *
33
+ * @internal
34
+ */
35
+ export class RunOutput {
36
+ /**
37
+ * Through a tool, whatever the model (see #274). One per run, which counts
38
+ * its own retries (see #151).
39
+ */
40
+ readonly strategy: TypedToolStrategy;
41
+ /** The tool the model answers through. */
42
+ readonly toolName = OUTPUT_TOOL;
43
+ #retries = 0;
44
+ private readonly prefix: string;
45
+
46
+ /**
47
+ * @param schema The run's `output` schema.
48
+ * @param agent The agent's name, for the errors.
49
+ * @throws AgentRunError when the schema has no JSON Schema form, or is not
50
+ * an object with named fields.
51
+ */
52
+ constructor(
53
+ private readonly schema: ZodType,
54
+ private readonly agent: string,
55
+ ) {
56
+ this.prefix = agentPrefix(agent);
57
+
58
+ // LangChain's own conversion, run before any model call.
59
+ let json: Record<string, unknown>;
60
+
61
+ try {
62
+ json = toJsonSchema(schema);
63
+ } catch (error) {
64
+ throw new AgentRunError(
65
+ noOutputJsonSchemaForm(this.prefix, messageOf(error)),
66
+ agent,
67
+ { cause: error },
68
+ );
69
+ }
70
+
71
+ // A tool's parameters. LangChain takes them as a JSON Schema with
72
+ // `properties` at every version, as a Zod schema other than an object at
73
+ // recent ones only. See #282.
74
+ if (json.type !== 'object' || !('properties' in json)) {
75
+ throw new AgentRunError(outputNotAnObject(this.prefix), agent);
76
+ }
77
+
78
+ // LangChain names the tool after the title.
79
+ this.strategy = toolStrategy(
80
+ {
81
+ ...json,
82
+ type: 'object',
83
+ title: OUTPUT_TOOL,
84
+ description: json.description ?? OUTPUT_DESCRIPTION,
85
+ },
86
+ { handleError: (error) => this.retry(error) },
87
+ );
88
+ }
89
+
90
+ // What LangChain sends back by default, until the retries run out.
91
+ private retry(error: Error): string {
92
+ this.#retries += 1;
93
+
94
+ if (this.#retries > MAX_RETRIES) {
95
+ throw error;
96
+ }
97
+
98
+ return error.message;
99
+ }
100
+
101
+ /**
102
+ * @param error What a model call threw.
103
+ * @returns A `StructuredOutputError` for LangChain's parsing failures, the
104
+ * error itself otherwise.
105
+ */
106
+ failure(error: unknown): unknown {
107
+ // Never LangChain's messages, which name the internal tool.
108
+ if (error instanceof StructuredOutputParsingError) {
109
+ return this.invalid(error.errors.join(' '), error);
110
+ }
111
+
112
+ if (error instanceof MultipleStructuredOutputsError) {
113
+ return new StructuredOutputError(
114
+ structuredOutputMultiple(this.prefix, error.toolNames.length),
115
+ this.agent,
116
+ { cause: error },
117
+ );
118
+ }
119
+
120
+ return error;
121
+ }
122
+
123
+ /**
124
+ * @param structuredResponse What the run left in `structuredResponse`.
125
+ * @returns The answer, as the schema parses it.
126
+ * @throws StructuredOutputError when the answer is missing or invalid.
127
+ */
128
+ read(structuredResponse: unknown): unknown {
129
+ if (structuredResponse === undefined) {
130
+ throw new StructuredOutputError(
131
+ structuredOutputMissing(this.prefix),
132
+ this.agent,
133
+ );
134
+ }
135
+
136
+ // LangChain checks the JSON Schema only: Zod also applies transforms and
137
+ // refinements. See #151.
138
+ const parsed = this.schema.safeParse(structuredResponse);
139
+
140
+ if (!parsed.success) {
141
+ throw this.invalid(z.prettifyError(parsed.error), parsed.error);
142
+ }
143
+
144
+ return parsed.data;
145
+ }
146
+
147
+ private invalid(reason: string, cause: unknown): StructuredOutputError {
148
+ return new StructuredOutputError(
149
+ structuredOutputInvalid(this.prefix, reason),
150
+ this.agent,
151
+ { cause },
152
+ );
153
+ }
154
+ }
@@ -0,0 +1,44 @@
1
+ import { createMiddleware } from 'langchain';
2
+ import { RunOutput } from './run-output.js';
3
+
4
+ // The run's output travels under our own key in `configurable`, which
5
+ // LangGraph keeps out of the trace metadata and checkpoints. See #151.
6
+ const OUTPUT_KEY = 'nestjs-langchain:output';
7
+
8
+ /**
9
+ * The `configurable` entry that hands a run's output to the middleware. A
10
+ * text run sets it to `null`, or it would inherit the output of the run it is
11
+ * nested in, which LangChain hands down. See #295.
12
+ *
13
+ * @internal
14
+ * @param output The run's output, if it asked for one.
15
+ * @returns The entry to put in `configurable`.
16
+ */
17
+ export const outputConfig = (output: RunOutput | undefined) => ({
18
+ [OUTPUT_KEY]: output ?? null,
19
+ });
20
+
21
+ /**
22
+ * Sets the `responseFormat` of each model call of a run that asked for an
23
+ * `output`, so that one compiled agent serves text and structured runs.
24
+ * LangChain's parsing failures come out as a `StructuredOutputError`.
25
+ *
26
+ * @internal
27
+ */
28
+ export const structuredOutput = () =>
29
+ createMiddleware({
30
+ name: 'structuredOutput',
31
+ wrapModelCall: async (request, handler) => {
32
+ const output = request.runtime.configurable?.[OUTPUT_KEY];
33
+
34
+ if (!(output instanceof RunOutput)) {
35
+ return handler(request);
36
+ }
37
+
38
+ try {
39
+ return await handler({ ...request, responseFormat: output.strategy });
40
+ } catch (error) {
41
+ throw output.failure(error);
42
+ }
43
+ },
44
+ });
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The ids of the tool calls the messages answer: the tool node answers every
3
+ * call it runs. Structural rather than `BaseMessage`. See #52.
4
+ *
5
+ * @internal
6
+ * @param messages A run's messages.
7
+ * @returns The ids their `tool_call_id`s answer.
8
+ */
9
+ export const answeredCalls = (messages: readonly object[]): Set<string> =>
10
+ new Set(
11
+ messages.flatMap((message) =>
12
+ 'tool_call_id' in message && typeof message.tool_call_id === 'string'
13
+ ? [message.tool_call_id]
14
+ : [],
15
+ ),
16
+ );
package/lib/run/index.ts CHANGED
@@ -1,2 +1,5 @@
1
+ export { answeredCalls } from './answered-calls.util.js';
2
+ export { isRecursionLimit } from './recursion-limit.util.js';
1
3
  export { summariseRun } from './run-summary.util.js';
4
+ export { UsageAside } from './usage-aside.js';
2
5
  export type { RunSummary } from './run-summary.util.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Whether a `recursionLimit` is one LangGraph applies: it rejects a limit
3
+ * below 1, but runs on with `NaN`. See #194.
4
+ *
5
+ * @internal
6
+ * @param limit The option as given, from untyped JavaScript too.
7
+ * @returns `true` for an integer of at least 1, or no limit.
8
+ */
9
+ export const isRecursionLimit = (limit: unknown): boolean =>
10
+ limit === undefined ||
11
+ (typeof limit === 'number' && Number.isInteger(limit) && limit >= 1);
@@ -1,14 +1,19 @@
1
1
  import { mergeUsageMetadata, UsageMetadata } from '@langchain/core/messages';
2
+ import { answeredCalls } from './answered-calls.util.js';
2
3
 
3
4
  // Structural rather than `BaseMessage`. See #52.
4
5
  interface MessageLike {
5
6
  usage_metadata?: UsageMetadata;
6
- tool_calls?: { name: string }[];
7
+ tool_calls?: { name: string; id?: string }[];
8
+ tool_call_id?: string;
7
9
  }
8
10
 
9
11
  /** What a run did and cost. */
10
12
  export interface RunSummary {
11
- /** Every tool call the model made, failed and unknown ones included. */
13
+ /**
14
+ * Every tool call that reached the agent's tools, failed and unknown ones
15
+ * included, but not the one returning a structured output.
16
+ */
12
17
  tools: string[];
13
18
  /**
14
19
  * Summed over the run's model calls; absent when the provider reports no
@@ -22,16 +27,33 @@ export interface RunSummary {
22
27
  *
23
28
  * @internal
24
29
  * @param messages The messages of the finished run.
25
- * @returns The tool calls the model made, and the tokens if reported.
30
+ * @param outputTool The tool the model returned a structured output through.
31
+ * @param aside The usage of the replies the run left out of its messages.
32
+ * @returns The tool calls that reached the tools, and the tokens if reported.
26
33
  */
27
- export const summariseRun = (messages: readonly MessageLike[]): RunSummary => {
28
- const tools = messages.flatMap((message) =>
29
- (message.tool_calls ?? []).map((call) => call.name),
30
- );
31
-
32
- const reported = messages
33
- .map((message) => message.usage_metadata)
34
- .filter((usage) => usage !== undefined);
34
+ export const summariseRun = (
35
+ messages: readonly MessageLike[],
36
+ outputTool?: string,
37
+ aside: readonly UsageMetadata[] = [],
38
+ ): RunSummary => {
39
+ // One that did not run has no answer (see #290). One with no id cannot be
40
+ // told, and counts (see #295).
41
+ const answered = answeredCalls(messages);
42
+
43
+ const tools = messages
44
+ .flatMap((message) => message.tool_calls ?? [])
45
+ .filter(
46
+ ({ name, id }) =>
47
+ name !== outputTool && (id === undefined || answered.has(id)),
48
+ )
49
+ .map((call) => call.name);
50
+
51
+ const reported = [
52
+ ...messages
53
+ .map((message) => message.usage_metadata)
54
+ .filter((usage) => usage !== undefined),
55
+ ...aside,
56
+ ];
35
57
 
36
58
  if (reported.length === 0) {
37
59
  return { tools };
@@ -0,0 +1,41 @@
1
+ import { UsageMetadata } from '@langchain/core/messages';
2
+
3
+ // Our own key in `configurable`, like the run's output. See #296.
4
+ const USAGE_ASIDE_KEY = 'nestjs-langchain:usage-aside';
5
+
6
+ /**
7
+ * The usage of the model's replies a run leaves out of its messages, which its
8
+ * `tokens` still count: those the `unknownTools` re-ask asks again about. One
9
+ * per run, handed to the middlewares in `configurable`. See #296.
10
+ *
11
+ * @internal
12
+ */
13
+ export class UsageAside {
14
+ readonly usage: UsageMetadata[] = [];
15
+
16
+ /** The `configurable` entry that hands it to the middlewares. */
17
+ get config(): Record<string, UsageAside> {
18
+ return { [USAGE_ASIDE_KEY]: this };
19
+ }
20
+
21
+ /**
22
+ * @param usage A left-out reply's usage, when the provider reported it.
23
+ */
24
+ add(usage: UsageMetadata | undefined): void {
25
+ if (usage) {
26
+ this.usage.push(usage);
27
+ }
28
+ }
29
+
30
+ /**
31
+ * @param configurable A middleware's `runtime.configurable`.
32
+ * @returns The run's aside, when it set one.
33
+ */
34
+ static of(
35
+ configurable: Record<string, unknown> | undefined,
36
+ ): UsageAside | undefined {
37
+ const aside = configurable?.[USAGE_ASIDE_KEY];
38
+
39
+ return aside instanceof UsageAside ? aside : undefined;
40
+ }
41
+ }
@@ -1,10 +1,33 @@
1
+ import {
2
+ AIMessage,
3
+ BaseMessage,
4
+ ToolCall,
5
+ ToolMessage,
6
+ } from '@langchain/core/messages';
1
7
  import {
2
8
  createMiddleware,
3
9
  toolErrorMiddleware,
4
10
  ToolInvocationError,
5
11
  } from 'langchain';
6
- import { unknownTool } from '../errors/messages.js';
12
+ import { OUTPUT_TOOL, STRUCTURED_OUTPUT_PREFIX } from '../constants.js';
13
+ import { invalidTool, toolNotRun, unknownTool } from '../errors/messages.js';
7
14
  import { reportToolError, RunReporter } from '../logging/index.js';
15
+ import { answeredCalls, UsageAside } from '../run/index.js';
16
+
17
+ // The default of LangChain's own retry middlewares. See #151.
18
+ const MAX_REASKS = 2;
19
+
20
+ // LangChain routes every `extract-` call to structured output, never to the
21
+ // tools: one the model invents, which is not the run's output, neither runs
22
+ // nor gets an answer. See #264.
23
+ const isInvented = ({ name }: ToolCall): boolean =>
24
+ name.startsWith(STRUCTURED_OUTPUT_PREFIX) && name !== OUTPUT_TOOL;
25
+
26
+ const invented = (calls: readonly ToolCall[]): ToolCall[] =>
27
+ calls.filter(isInvented);
28
+
29
+ const callsOf = (message: BaseMessage | undefined): ToolCall[] =>
30
+ AIMessage.isInstance(message) ? (message.tool_calls ?? []) : [];
8
31
 
9
32
  /**
10
33
  * Turns a failed tool call into the text the model receives, LangChain's own,
@@ -48,21 +71,92 @@ export const toolErrors = (reporter: RunReporter) =>
48
71
  /**
49
72
  * Reports a call to a tool the agent does not have. LangChain's tool node
50
73
  * answers the model itself, without throwing, so `toolErrors` never sees it.
74
+ * One the model invents with the `extract-` prefix never reaches the tool
75
+ * node: it is answered here, as the tool node answers any other, and so is
76
+ * any call LangChain leaves unanswered.
77
+ *
78
+ * @param reporter The agent's reporter.
79
+ * @param tools The names of the agent's tools, which the answer lists.
51
80
  */
52
- export const unknownTools = (reporter: RunReporter) =>
53
- createMiddleware({
81
+ export const unknownTools = (reporter: RunReporter, tools: string[]) => {
82
+ const report = ({ name, id }: ToolCall) =>
83
+ reportToolError(reporter, {
84
+ tool: name,
85
+ callId: id ?? '',
86
+ reason: 'unknown-tool',
87
+ error: new Error(unknownTool()),
88
+ durationMs: 0,
89
+ });
90
+
91
+ const answer = (call: ToolCall) =>
92
+ new ToolMessage({
93
+ content: isInvented(call)
94
+ ? invalidTool(call.name, tools)
95
+ : toolNotRun(call.name),
96
+ tool_call_id: call.id ?? '',
97
+ name: call.name,
98
+ status: 'error',
99
+ });
100
+
101
+ // Every call without an answer gets one right after its message, which
102
+ // providers require: an invented one (see #264), or one LangChain left out
103
+ // next to the output (see #290). In the request, which the output's retry
104
+ // reaches without `beforeModel`; rebuilt on every model call, so only the
105
+ // reply just made is reported. See #297.
106
+ const answerLeft = (messages: BaseMessage[]): BaseMessage[] => {
107
+ const done = answeredCalls(messages);
108
+ const left = (message: BaseMessage | undefined) =>
109
+ callsOf(message).filter(({ id }) => id !== undefined && !done.has(id));
110
+
111
+ invented(left(messages.findLast((m) => AIMessage.isInstance(m)))).forEach(
112
+ report,
113
+ );
114
+
115
+ return messages.flatMap((message) => [
116
+ message,
117
+ ...left(message).map(answer),
118
+ ]);
119
+ };
120
+
121
+ return createMiddleware({
54
122
  name: 'unknownTools',
123
+ // Alone, LangChain would end the run: answered, and the model asked again,
124
+ // as `modelRetryMiddleware` asks it again. See #264.
125
+ wrapModelCall: async (request, handler) => {
126
+ let current = { ...request, messages: answerLeft(request.messages) };
127
+
128
+ for (let asked = 0; ; asked += 1) {
129
+ const reply = await handler(current);
130
+ const calls = callsOf(reply);
131
+ const left = invented(calls);
132
+
133
+ if (calls.length === 0 || left.length < calls.length) {
134
+ return reply;
135
+ }
136
+
137
+ left.forEach(report);
138
+
139
+ if (asked === MAX_REASKS) {
140
+ return reply;
141
+ }
142
+
143
+ // Left out of the run's messages, but paid for. See #296.
144
+ UsageAside.of(request.runtime.configurable)?.add(
145
+ AIMessage.isInstance(reply) ? reply.usage_metadata : undefined,
146
+ );
147
+
148
+ current = {
149
+ ...current,
150
+ messages: [...current.messages, reply, ...left.map(answer)],
151
+ };
152
+ }
153
+ },
55
154
  wrapToolCall: (request, handler) => {
56
155
  if (!request.tool) {
57
- reportToolError(reporter, {
58
- tool: request.toolCall.name,
59
- callId: request.toolCall.id ?? '',
60
- reason: 'unknown-tool',
61
- error: new Error(unknownTool()),
62
- durationMs: 0,
63
- });
156
+ report(request.toolCall);
64
157
  }
65
158
 
66
159
  return handler(request);
67
160
  },
68
161
  });
162
+ };
@@ -1,3 +1,4 @@
1
+ import { STRUCTURED_OUTPUT_PREFIX } from '../constants.js';
1
2
  import {
2
3
  duplicateToolName,
3
4
  invalidToolName,
@@ -8,10 +9,6 @@ import {
8
9
  // it. See #90.
9
10
  const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
10
11
 
11
- // The agent routes a call with this prefix to structured output, never to the
12
- // tool. Restated: LangChain does not export it. See #213.
13
- const STRUCTURED_OUTPUT_PREFIX = 'extract-';
14
-
15
12
  export const resolveToolName = (
16
13
  declared: string | undefined,
17
14
  method: string,
package/package.json CHANGED
@@ -1,13 +1,32 @@
1
1
  {
2
2
  "name": "nestjs-langchain",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "type": "module",
5
- "description": "NestJS library to build agents with LangChain",
5
+ "description": "AI agents for NestJS, powered by LangChain: declare agents as modules, give them your services as tools.",
6
6
  "keywords": [
7
7
  "nestjs",
8
+ "nest",
9
+ "nestjs-module",
8
10
  "langchain",
11
+ "langchainjs",
12
+ "ai",
13
+ "agent",
9
14
  "agents",
10
- "ai"
15
+ "ai-agent",
16
+ "ai-agents",
17
+ "llm",
18
+ "tools",
19
+ "tool-calling",
20
+ "function-calling",
21
+ "structured-output",
22
+ "openai",
23
+ "anthropic",
24
+ "mistral",
25
+ "gemini",
26
+ "ollama",
27
+ "zod",
28
+ "decorators",
29
+ "typescript"
11
30
  ],
12
31
  "author": "Martin Bruel",
13
32
  "license": "MIT",
@@ -51,7 +70,7 @@
51
70
  "format": "prettier --write \"{lib,tests,scripts}/**/*.{ts,mjs}\" vitest.config.ts",
52
71
  "lint": "oxlint --type-aware lib/ tests/ scripts/ vitest.config.ts --fix",
53
72
  "lint:check": "oxlint --type-aware lib/ tests/ scripts/ vitest.config.ts",
54
- "test": "vitest run --typecheck",
73
+ "test": "vitest run && tsc --noEmit",
55
74
  "test:watch": "vitest",
56
75
  "release": "release-it",
57
76
  "release:rc": "release-it --preRelease=rc --no-plugins.@release-it/conventional-changelog.infile",
@@ -64,20 +83,20 @@
64
83
  },
65
84
  "devDependencies": {
66
85
  "@arethetypeswrong/cli": "^0.18.5",
67
- "@commitlint/cli": "21.2.3",
86
+ "@commitlint/cli": "21.2.4",
68
87
  "@commitlint/config-conventional": "^21.2.3",
69
88
  "@langchain/core": "^1.2.3",
70
89
  "@langchain/openai": "^1.2.10",
71
- "@nestjs/common": "^11.1.18",
72
- "@nestjs/core": "^11.1.18",
73
- "@nestjs/testing": "^11.1.18",
90
+ "@nestjs/common": "^12.0.1",
91
+ "@nestjs/core": "^12.0.1",
92
+ "@nestjs/testing": "^12.0.1",
74
93
  "@release-it/conventional-changelog": "12.0.2",
75
- "@types/node": "^25.1.0",
76
- "@vitest/coverage-v8": "^4.1.11",
94
+ "@types/node": "^26.6.4",
95
+ "@vitest/coverage-v8": "^5.0.5",
77
96
  "eslint-plugin-jsdoc": "^65.2.0",
78
97
  "husky": "9.1.7",
79
98
  "langchain": "^1.5.4",
80
- "lint-staged": "16.4.0",
99
+ "lint-staged": "17.6.0",
81
100
  "oxlint": "^1.83.0",
82
101
  "oxlint-tsgolint": "^7.0.2001",
83
102
  "prettier": "^3.8.1",
@@ -88,7 +107,7 @@
88
107
  "rxjs": "^7.8.2",
89
108
  "semver": "^7.8.5",
90
109
  "typescript": "^6.0.3",
91
- "vitest": "^4.1.11",
110
+ "vitest": "^5.0.5",
92
111
  "zod": "^4.0.0"
93
112
  },
94
113
  "peerDependencies": {