nestjs-langchain 1.0.2 → 2.0.0-rc.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 (151) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +344 -254
  3. package/dist/agent.d.ts +63 -0
  4. package/dist/agent.d.ts.map +1 -0
  5. package/dist/agent.js +189 -0
  6. package/dist/agent.js.map +1 -0
  7. package/dist/constants.d.ts +5 -0
  8. package/dist/constants.d.ts.map +1 -0
  9. package/dist/constants.js +14 -0
  10. package/dist/constants.js.map +1 -0
  11. package/dist/decorators/index.d.ts +4 -2
  12. package/dist/decorators/index.d.ts.map +1 -0
  13. package/dist/decorators/index.js +3 -18
  14. package/dist/decorators/index.js.map +1 -0
  15. package/dist/decorators/inject-agent.decorator.d.ts +12 -0
  16. package/dist/decorators/inject-agent.decorator.d.ts.map +1 -0
  17. package/dist/decorators/inject-agent.decorator.js +15 -7
  18. package/dist/decorators/inject-agent.decorator.js.map +1 -0
  19. package/dist/decorators/tool.decorator.d.ts +54 -6
  20. package/dist/decorators/tool.decorator.d.ts.map +1 -0
  21. package/dist/decorators/tool.decorator.js +40 -16
  22. package/dist/decorators/tool.decorator.js.map +1 -0
  23. package/dist/errors/agent-run.error.d.ts +27 -0
  24. package/dist/errors/agent-run.error.d.ts.map +1 -0
  25. package/dist/errors/agent-run.error.js +26 -0
  26. package/dist/errors/agent-run.error.js.map +1 -0
  27. package/dist/errors/index.d.ts +3 -0
  28. package/dist/errors/index.d.ts.map +1 -0
  29. package/dist/errors/index.js +3 -0
  30. package/dist/errors/index.js.map +1 -0
  31. package/dist/errors/messages.d.ts +26 -0
  32. package/dist/errors/messages.d.ts.map +1 -0
  33. package/dist/errors/messages.js +67 -0
  34. package/dist/errors/messages.js.map +1 -0
  35. package/dist/errors/tool-configuration.error.d.ts +23 -0
  36. package/dist/errors/tool-configuration.error.d.ts.map +1 -0
  37. package/dist/errors/tool-configuration.error.js +27 -0
  38. package/dist/errors/tool-configuration.error.js.map +1 -0
  39. package/dist/index.d.ts +10 -3
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +8 -19
  42. package/dist/index.js.map +1 -0
  43. package/dist/interfaces/agent-observer.interface.d.ts +107 -0
  44. package/dist/interfaces/agent-observer.interface.d.ts.map +1 -0
  45. package/dist/interfaces/agent-observer.interface.js +2 -0
  46. package/dist/interfaces/agent-observer.interface.js.map +1 -0
  47. package/dist/interfaces/completed-run.interface.d.ts +14 -0
  48. package/dist/interfaces/completed-run.interface.d.ts.map +1 -0
  49. package/dist/interfaces/completed-run.interface.js +2 -0
  50. package/dist/interfaces/completed-run.interface.js.map +1 -0
  51. package/dist/interfaces/langchain-module-options.interface.d.ts +73 -5
  52. package/dist/interfaces/langchain-module-options.interface.d.ts.map +1 -0
  53. package/dist/interfaces/langchain-module-options.interface.js +2 -2
  54. package/dist/interfaces/langchain-module-options.interface.js.map +1 -0
  55. package/dist/langchain.module-definition.d.ts +26 -6
  56. package/dist/langchain.module-definition.d.ts.map +1 -0
  57. package/dist/langchain.module-definition.js +26 -13
  58. package/dist/langchain.module-definition.js.map +1 -0
  59. package/dist/langchain.module.d.ts +60 -3
  60. package/dist/langchain.module.d.ts.map +1 -0
  61. package/dist/langchain.module.js +87 -24
  62. package/dist/langchain.module.js.map +1 -0
  63. package/dist/logging/index.d.ts +3 -0
  64. package/dist/logging/index.d.ts.map +1 -0
  65. package/dist/logging/index.js +3 -0
  66. package/dist/logging/index.js.map +1 -0
  67. package/dist/logging/observe-tool-call.util.d.ts +13 -0
  68. package/dist/logging/observe-tool-call.util.d.ts.map +1 -0
  69. package/dist/logging/observe-tool-call.util.js +34 -0
  70. package/dist/logging/observe-tool-call.util.js.map +1 -0
  71. package/dist/logging/run-reporter.d.ts +26 -0
  72. package/dist/logging/run-reporter.d.ts.map +1 -0
  73. package/dist/logging/run-reporter.js +39 -0
  74. package/dist/logging/run-reporter.js.map +1 -0
  75. package/dist/run/index.d.ts +3 -0
  76. package/dist/run/index.d.ts.map +1 -0
  77. package/dist/run/index.js +2 -0
  78. package/dist/run/index.js.map +1 -0
  79. package/dist/run/run-summary.util.d.ts +31 -0
  80. package/dist/run/run-summary.util.d.ts.map +1 -0
  81. package/dist/run/run-summary.util.js +28 -0
  82. package/dist/run/run-summary.util.js.map +1 -0
  83. package/dist/tools/index.d.ts +3 -0
  84. package/dist/tools/index.d.ts.map +1 -0
  85. package/dist/tools/index.js +3 -0
  86. package/dist/tools/index.js.map +1 -0
  87. package/dist/tools/tool-discovery.service.d.ts +31 -0
  88. package/dist/tools/tool-discovery.service.d.ts.map +1 -0
  89. package/dist/tools/tool-discovery.service.js +132 -0
  90. package/dist/tools/tool-discovery.service.js.map +1 -0
  91. package/dist/tools/tool-errors.middleware.d.ts +21 -0
  92. package/dist/tools/tool-errors.middleware.d.ts.map +1 -0
  93. package/dist/tools/tool-errors.middleware.js +55 -0
  94. package/dist/tools/tool-errors.middleware.js.map +1 -0
  95. package/dist/tools/tool-method.util.d.ts +21 -0
  96. package/dist/tools/tool-method.util.d.ts.map +1 -0
  97. package/dist/tools/tool-method.util.js +39 -0
  98. package/dist/tools/tool-method.util.js.map +1 -0
  99. package/dist/tools/tool-modules.util.d.ts +14 -0
  100. package/dist/tools/tool-modules.util.d.ts.map +1 -0
  101. package/dist/tools/tool-modules.util.js +61 -0
  102. package/dist/tools/tool-modules.util.js.map +1 -0
  103. package/dist/tools/tool-name.util.d.ts +10 -0
  104. package/dist/tools/tool-name.util.d.ts.map +1 -0
  105. package/dist/tools/tool-name.util.js +35 -0
  106. package/dist/tools/tool-name.util.js.map +1 -0
  107. package/dist/tools/tool-schema.factory.d.ts +4 -0
  108. package/dist/tools/tool-schema.factory.d.ts.map +1 -0
  109. package/dist/tools/tool-schema.factory.js +87 -0
  110. package/dist/tools/tool-schema.factory.js.map +1 -0
  111. package/dist/tools/tool.factory.d.ts +9 -0
  112. package/dist/tools/tool.factory.d.ts.map +1 -0
  113. package/dist/tools/tool.factory.js +34 -0
  114. package/dist/tools/tool.factory.js.map +1 -0
  115. package/lib/agent.ts +257 -0
  116. package/lib/constants.ts +15 -0
  117. package/lib/decorators/index.ts +3 -0
  118. package/lib/decorators/inject-agent.decorator.ts +15 -0
  119. package/lib/decorators/tool.decorator.ts +86 -0
  120. package/lib/errors/agent-run.error.ts +29 -0
  121. package/lib/errors/index.ts +2 -0
  122. package/lib/errors/messages.ts +158 -0
  123. package/lib/errors/tool-configuration.error.ts +24 -0
  124. package/lib/index.ts +26 -0
  125. package/lib/interfaces/agent-observer.interface.ts +113 -0
  126. package/lib/interfaces/completed-run.interface.ts +14 -0
  127. package/lib/interfaces/langchain-module-options.interface.ts +91 -0
  128. package/lib/langchain.module-definition.ts +36 -0
  129. package/lib/langchain.module.ts +138 -0
  130. package/lib/logging/index.ts +2 -0
  131. package/lib/logging/observe-tool-call.util.ts +59 -0
  132. package/lib/logging/run-reporter.ts +56 -0
  133. package/lib/run/index.ts +2 -0
  134. package/lib/run/run-summary.util.ts +51 -0
  135. package/lib/tools/index.ts +2 -0
  136. package/lib/tools/tool-discovery.service.ts +191 -0
  137. package/lib/tools/tool-errors.middleware.ts +68 -0
  138. package/lib/tools/tool-method.util.ts +81 -0
  139. package/lib/tools/tool-modules.util.ts +104 -0
  140. package/lib/tools/tool-name.util.ts +57 -0
  141. package/lib/tools/tool-schema.factory.ts +142 -0
  142. package/lib/tools/tool.factory.ts +56 -0
  143. package/package.json +112 -91
  144. package/dist/factories/message.factory.d.ts +0 -7
  145. package/dist/factories/message.factory.js +0 -28
  146. package/dist/langchain.service.d.ts +0 -18
  147. package/dist/langchain.service.js +0 -69
  148. package/dist/tool-discovery.service.d.ts +0 -11
  149. package/dist/tool-discovery.service.js +0 -79
  150. package/dist/types/message.d.ts +0 -69
  151. package/dist/types/message.js +0 -104
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Martin-Bruel
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Martin-Bruel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,254 +1,344 @@
1
- <p align="center">
2
- <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
3
- </p>
4
-
5
- <p align="center">
6
- A <a href="https://nestjs.com/">Nest</a> module wrapper for building AI agent with <a href="https://www.langchain.com/">LangChain</a>.
7
- </p>
8
-
9
- <p align="center">
10
- <a href="https://github.com/Martin-Bruel/nestjs-langchain/pulse"><img src="https://img.shields.io/github/commit-activity/m/Martin-Bruel/nestjs-langchain" alt="GitHub commit activity"></a>
11
- <a href="https://github.com/Martin-Bruel/nestjs-langchain/graphs/contributors"><img src="https://img.shields.io/github/contributors/Martin-Bruel/nestjs-langchain" alt="Contributors"></a>
12
- </p>
13
-
14
- <p align="center">
15
- <img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/Martin-Bruel/nestjs-langchain">
16
- <a href="https://github.com/Martin-Bruel/nestjs-langchain/issues"><img alt="GitHub issues" src="https://img.shields.io/github/issues/Martin-Bruel/nestjs-langchain.svg"></a>
17
- <a href="https://github.com/Martin-Bruel/nestjs-langchain/pulls"><img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/Martin-Bruel/nestjs-langchain"></a>
18
- </p>
19
- </p>
20
-
21
- **Table of Contents**
22
-
23
- - [Description](#description)
24
- - [Installation](#installation)
25
- - [Quick start](#quick-start)
26
- - [Defining tools](#defining-tools)
27
- - [Multi-agent support](#multi-agent-support)
28
- - [Async configuration](#async-configuration)
29
- - [Contributing](#contributing)
30
- - [License](#license)
31
-
32
- ## Description
33
-
34
- **nestjs-langchain** is a powerful, decorator-driven wrapper that integrates LangChain agents seamlessly into the NestJS ecosystem. It allows you to transform standard NestJS services into AI tools and manage multiple isolated agents with distinct roles and configurations.
35
-
36
- ## Installation
37
-
38
- ```bash
39
- npm install --save nestjs-langchain langchain @langchain/<ai-provider>
40
- ```
41
-
42
- Having troubles configuring `nestjs-langchain`? Clone this repository and `cd` in a sample:
43
-
44
- ```bash
45
- cd samples/chat
46
- npm install
47
- npm run start
48
- ```
49
-
50
- ## Quick start
51
-
52
- ### 1. Register the module
53
-
54
- You can register the `LangChainModule` in your `AppModule` or any specific feature module.
55
-
56
- ```ts
57
- import { LangChainModule } from 'nestjs-langchain';
58
-
59
- @Module({
60
- imports: [
61
- LangChainModule.register({
62
- model: {
63
- model: 'your-model-name', // Syntax: provider:model-name
64
- apiKey: 'your-api-key',
65
- },
66
- systemPrompt: 'your-system-prompt',
67
- }),
68
- ],
69
- controllers: [AppController],
70
- providers: [AppService],
71
- })
72
- export class AppModule {}
73
- ```
74
-
75
- > **_NOTE:_** The model property allows you to select your AI engine based on the provider (OpenAI, Anthropic, Google, etc.). You can find the list of all available integrations here:
76
- > 👉 [LangChain Chat Integrations](https://docs.langchain.com/oss/javascript/integrations/chat/index)
77
-
78
- ### 2. Usage
79
-
80
- Once registered, simply inject the `LangChainService` to interact with your agent.
81
-
82
- ```ts
83
- @Injectable()
84
- export class AppService {
85
- constructor(private readonly agent: LangChainService) {}
86
-
87
- async ask(question: string) {
88
- return await this.agent.run(question);
89
- }
90
- }
91
- ```
92
-
93
- ## Defining Tools
94
-
95
- Tools allow your AI agents to interact with the real world, fetch live data, and perform complex tasks, significantly enriching their responses beyond their static training data.
96
-
97
- ### 1. Define the tool
98
-
99
- You can easily turn any NestJS service method into an AI tool using the @Tool() decorator.
100
-
101
- ```ts
102
- import { Tool, ToolParam } from 'nestjs-langchain';
103
-
104
- @Injectable()
105
- export class MathService {
106
- @Tool({ description: 'Adds two numbers together.' })
107
- add(
108
- @ToolParam({
109
- name: 'a',
110
- description: 'The first number to add.',
111
- type: 'number',
112
- })
113
- a: number,
114
- @ToolParam({
115
- name: 'b',
116
- description: 'The second number to add.',
117
- type: 'number',
118
- })
119
- b: number,
120
- ): number {
121
- return a + b;
122
- }
123
- }
124
- ```
125
-
126
- ### 2. Attach tool to the agent
127
-
128
- To make tools available to your agent, simply add the corresponding module to the tools array option of the LangChainModule during the registration.
129
-
130
- ```ts
131
- import { LangChainModule } from 'nestjs-langchain';
132
- import { MathModule } from './math/math.module';
133
-
134
- @Module({
135
- imports: [
136
- LangChainModule.register({
137
- model: {
138
- model: 'your-model-name', // Syntax: provider:model-name
139
- apiKey: 'your-api-key',
140
- },
141
- systemPrompt: 'your-system-prompt',
142
- tools: [MathModule],
143
- }),
144
- MathModule,
145
- ],
146
- controllers: [AppController],
147
- providers: [AppService],
148
- })
149
- export class AppModule {}
150
- ```
151
-
152
- > **_NOTE:_** Any module passed to the tools array of LangChainModule must also be imported into the NestJS context (usually in the same @Module decorator). This ensures that the services containing your @Tool() decorators are correctly instantiated and managed by the NestJS dependency injection system.
153
-
154
- ## Multi-Agent Support
155
-
156
- If you need multiple agents with different roles in the same application, you can register them with unique names. Each agent is a distinct instance with its own configuration, system prompt, and specific set of tools. This isolation prevents "tool confusion" where an agent might try to use irrelevant tools for a given task, improving accuracy and reducing token costs.
157
-
158
- For example, you can have a "Support Agent" with access to your database and a "Math Agent" with access to calculation tools.
159
-
160
- ### 1. Register a specific agent
161
-
162
- To register a specific agent you must define a name:
163
-
164
- ```ts
165
- import { LangChainModule } from 'nestjs-langchain';
166
- import { MathModule } from './math/math.module';
167
- import { MongoModule } from './mongo/mongo.module';
168
-
169
- @Module({
170
- imports: [
171
- LangChainModule.register({
172
- name: 'MATH_AGENT',
173
- model: {
174
- model: 'your-model-name', // Syntax: provider:model-name
175
- apiKey: 'your-api-key',
176
- },
177
- systemPrompt: 'your-system-prompt',
178
- tools: [MathModule],
179
- }),
180
- LangChainModule.register({
181
- name: 'MONGO_AGENT',
182
- model: {
183
- model: 'your-model-name', // Syntax: provider:model-name
184
- apiKey: 'your-api-key',
185
- },
186
- systemPrompt: 'your-system-prompt',
187
- tools: [MongoModule],
188
- }),
189
- MathModule,
190
- MongoModule,
191
- ],
192
- controllers: [AppController],
193
- providers: [AppService],
194
- })
195
- export class AppModule {}
196
- ```
197
-
198
- ### 2. Use a specific agent
199
-
200
- o use a specific agent in your services, use the @InjectAgent() decorator with the corresponding name:
201
-
202
- ```ts
203
- @Injectable()
204
- export class AppService {
205
- constructor(
206
- @InjectAgent('MATH_AGENT') private readonly mathAgent: LangChainService,
207
- @InjectAgent('SUPPORT_AGENT')
208
- private readonly supportAgent: LangChainService,
209
- ) {}
210
-
211
- async solveProblem(query: string) {
212
- return this.mathAgent.run(query);
213
- }
214
- }
215
- ```
216
-
217
- ## Async Configuration
218
-
219
- To inject configuration from a ConfigService or other providers, use registerAsync:
220
-
221
- ```ts
222
- import { LangChainModule } from 'nestjs-langchain';
223
- import { MathModule } from './math/math.module';
224
- import { MongoModule } from './mongo/mongo.module';
225
-
226
- @Module({
227
- imports: [
228
- LangChainModule.registerAsync({
229
- imports: [ConfigModule],
230
- useFactory: (configService: ConfigService) => ({
231
- model: {
232
- model: 'openai:gpt-5-mini',
233
- apiKey: configService.get<string>('OPENAI_API_KEY'),
234
- },
235
- systemPrompt: 'your-system-prompt',
236
- tools: [MongoModule],
237
- }),
238
- inject: [ConfigService],
239
- name: 'MONGO',
240
- }),
241
- ],
242
- })
243
- export class AppModule {}
244
- ```
245
-
246
- > **_NOTE:_** The name property is required at the root of registerAsync because it defines the injection token used by @InjectAgent(). It cannot be determined dynamically inside the factory.
247
-
248
- ## Contributing
249
-
250
- All types of contributions are encouraged and valued. See the Contributing guidelines, the community looks forward to your contributions!
251
-
252
- ## License
253
-
254
- This project is released under the under terms of the MIT License.
1
+ <p align="center">
2
+ <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
3
+ </p>
4
+
5
+ <p align="center">
6
+ A <a href="https://nestjs.com/">Nest</a> module wrapper for building AI agents with <a href="https://www.langchain.com/">LangChain</a>.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://github.com/Martin-Bruel/nestjs-langchain/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/Martin-Bruel/nestjs-langchain/actions/workflows/ci.yml/badge.svg?branch=main"></a>
11
+ <a href="https://www.npmjs.com/package/nestjs-langchain"><img alt="npm version" src="https://img.shields.io/npm/v/nestjs-langchain"></a>
12
+ <a href="https://www.npmjs.com/package/nestjs-langchain"><img alt="npm downloads" src="https://img.shields.io/npm/dm/nestjs-langchain"></a>
13
+ <a href="https://github.com/Martin-Bruel/nestjs-langchain/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/npm/l/nestjs-langchain"></a>
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://github.com/Martin-Bruel/nestjs-langchain/commits/main"><img alt="Last commit" src="https://img.shields.io/github/last-commit/Martin-Bruel/nestjs-langchain"></a>
18
+ <a href="https://github.com/Martin-Bruel/nestjs-langchain/graphs/contributors"><img alt="Contributors" src="https://img.shields.io/github/contributors/Martin-Bruel/nestjs-langchain"></a>
19
+ <a href="https://github.com/Martin-Bruel/nestjs-langchain/issues"><img alt="Open issues" src="https://img.shields.io/github/issues/Martin-Bruel/nestjs-langchain"></a>
20
+ </p>
21
+
22
+ **Table of Contents**
23
+
24
+ - [Description](#description)
25
+ - [Installation](#installation)
26
+ - [Quick start](#quick-start)
27
+ - [Defining tools](#defining-tools)
28
+ - [Multi-agent support](#multi-agent-support)
29
+ - [Async configuration](#async-configuration)
30
+ - [Testing](#testing)
31
+ - [Logging and observing](#logging-and-observing)
32
+ - [Contributing](#contributing)
33
+ - [License](#license)
34
+
35
+ ## Description
36
+
37
+ **nestjs-langchain** is a powerful, decorator-driven wrapper that integrates LangChain agents seamlessly into the NestJS ecosystem. It allows you to transform standard NestJS services into AI tools and manage multiple isolated agents with distinct roles and configurations.
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ npm install nestjs-langchain @langchain/<ai-provider>
43
+ ```
44
+
45
+ Requires **NestJS 11.1.18+ or 12.0.1+**, **`langchain` 1.5.4+**, **Zod 4**, **Node 22.12+** and
46
+ **TypeScript 5.8+**.
47
+
48
+ > **_NOTE:_** Yarn does not install `langchain`, `@langchain/core` and `zod` as peer dependencies, so add them explicitly:
49
+ >
50
+ > ```bash
51
+ > yarn add nestjs-langchain @langchain/<ai-provider> langchain @langchain/core zod
52
+ > ```
53
+
54
+ Having troubles configuring `nestjs-langchain`? Clone this repository and run a sample, whose
55
+ README says what it needs:
56
+
57
+ ```bash
58
+ npm install
59
+ npm run build
60
+ cd samples/chat
61
+ npm run start
62
+ ```
63
+
64
+ Requirements in detail, CommonJS applications and Jest: [docs/setup.md](docs/setup.md).
65
+
66
+ ## Quick start
67
+
68
+ ### 1. Register an agent
69
+
70
+ ```ts
71
+ import { Module } from '@nestjs/common';
72
+ import { LangChainModule } from 'nestjs-langchain';
73
+ import { AppService } from './app.service.js';
74
+
75
+ @Module({
76
+ imports: [
77
+ LangChainModule.register({
78
+ // `provider:model`. Without an `apiKey`, the provider reads its own
79
+ // environment variable, here OPENAI_API_KEY.
80
+ model: { model: 'openai:gpt-5-mini' },
81
+ systemPrompt: 'You are a helpful assistant.',
82
+ }),
83
+ ],
84
+ providers: [AppService],
85
+ })
86
+ export class AppModule {}
87
+ ```
88
+
89
+ > **_NOTE:_** The model property allows you to select your AI engine based on the provider (OpenAI, Anthropic, Google, etc.). You can find the list of all available integrations here:
90
+ > 👉 [LangChain Chat Integrations](https://docs.langchain.com/oss/javascript/integrations/chat/index)
91
+
92
+ > **_NOTE:_** `model` also accepts a chat model you built yourself, such as
93
+ > `new ChatOpenAI({ ... })`, for what the configuration cannot express: a proxy, an Azure
94
+ > deployment, a fake in tests.
95
+
96
+ Model options and providers: [docs/models.md](docs/models.md).
97
+
98
+ ### 2. Inject the agent
99
+
100
+ Inject `Agent` and run it:
101
+
102
+ ```ts
103
+ import { Injectable } from '@nestjs/common';
104
+ import { Agent } from 'nestjs-langchain';
105
+
106
+ @Injectable()
107
+ export class AppService {
108
+ constructor(private readonly agent: Agent) {}
109
+
110
+ async ask(question: string): Promise<string> {
111
+ const { output } = await this.agent.run(question);
112
+ return output;
113
+ }
114
+ }
115
+ ```
116
+
117
+ ## Defining Tools
118
+
119
+ ### 1. Define the tool
120
+
121
+ Turn a service method into a tool with `@Tool()`, and describe its parameters with `@ToolParam()`:
122
+
123
+ ```ts
124
+ import { Injectable } from '@nestjs/common';
125
+ import { Tool, ToolParam } from 'nestjs-langchain';
126
+
127
+ @Injectable()
128
+ export class MathService {
129
+ @Tool({ description: 'Adds two numbers.' })
130
+ add(
131
+ @ToolParam({ name: 'a', description: 'The first number.' }) a: number,
132
+ @ToolParam({ name: 'b', description: 'The second number.' }) b: number,
133
+ ): number {
134
+ return a + b;
135
+ }
136
+ }
137
+ ```
138
+
139
+ The tool is named after the method, unless `@Tool()` takes a `name`.
140
+
141
+ ### 2. Declare the parameter types
142
+
143
+ Use a Zod `schema` for any parameter that is not a `string`, `number` or `boolean`.
144
+
145
+ ```ts
146
+ import { z } from 'zod';
147
+
148
+ @Tool({ description: 'Searches the catalogue.' })
149
+ search(
150
+ @ToolParam({ name: 'query' }) query: string,
151
+ @ToolParam({
152
+ name: 'filter',
153
+ description: 'Restricts the results.',
154
+ schema: z.object({ field: z.string(), value: z.string() }),
155
+ })
156
+ filter: { field: string; value: string },
157
+ @ToolParam({ name: 'limit', optional: true }) limit?: number,
158
+ ): Promise<Result[]> {
159
+ // ...
160
+ }
161
+ ```
162
+
163
+ ### 3. Attach tool to the agent
164
+
165
+ List the module that declares the service in `tools`, and import it:
166
+
167
+ ```ts
168
+ import { Module } from '@nestjs/common';
169
+ import { LangChainModule } from 'nestjs-langchain';
170
+ import { MathModule } from './math/math.module.js';
171
+
172
+ @Module({
173
+ imports: [
174
+ MathModule,
175
+ LangChainModule.register({
176
+ model: { model: 'openai:gpt-5-mini' },
177
+ tools: [MathModule],
178
+ }),
179
+ ],
180
+ })
181
+ export class AppModule {}
182
+ ```
183
+
184
+ Naming, parameter types, tool modules and the checks at bootstrap: [docs/tools.md](docs/tools.md).
185
+ Before exposing tools to users, read [docs/security.md](docs/security.md).
186
+
187
+ ## Multi-Agent Support
188
+
189
+ Give each agent a `name`, and inject it with `@InjectAgent()`.
190
+
191
+ ### 1. Register a specific agent
192
+
193
+ ```ts
194
+ @Module({
195
+ imports: [
196
+ MathModule,
197
+ MongoModule,
198
+ LangChainModule.register({
199
+ name: 'MATH_AGENT',
200
+ model: { model: 'openai:gpt-5-mini' },
201
+ tools: [MathModule],
202
+ }),
203
+ LangChainModule.register({
204
+ name: 'MONGO_AGENT',
205
+ model: { model: 'openai:gpt-5-mini' },
206
+ tools: [MongoModule],
207
+ }),
208
+ ],
209
+ providers: [AppService],
210
+ })
211
+ export class AppModule {}
212
+ ```
213
+
214
+ ### 2. Use a specific agent
215
+
216
+ ```ts
217
+ @Injectable()
218
+ export class AppService {
219
+ constructor(
220
+ @InjectAgent('MATH_AGENT') private readonly math: Agent,
221
+ @InjectAgent('MONGO_AGENT') private readonly mongo: Agent,
222
+ ) {}
223
+ }
224
+ ```
225
+
226
+ `Agent` without `@InjectAgent()` is the agent registered without a name.
227
+
228
+ ## Async Configuration
229
+
230
+ Build the options from other providers with `registerAsync`:
231
+
232
+ ```ts
233
+ import { ConfigModule, ConfigService } from '@nestjs/config';
234
+
235
+ LangChainModule.registerAsync({
236
+ // Outside the factory: it names the token `@InjectAgent()` resolves.
237
+ name: 'MATH_AGENT',
238
+ imports: [ConfigModule],
239
+ inject: [ConfigService],
240
+ useFactory: (config: ConfigService) => ({
241
+ model: {
242
+ model: 'openai:gpt-5-mini',
243
+ apiKey: config.getOrThrow<string>('OPENAI_API_KEY'),
244
+ },
245
+ tools: [MathModule],
246
+ }),
247
+ });
248
+ ```
249
+
250
+ `useClass` and `useExisting` take a class implementing `LangChainOptionsFactory`.
251
+
252
+ `useClass`, `name` and agent names in detail: [docs/setup.md](docs/setup.md#registerasync).
253
+
254
+ ## Testing
255
+
256
+ Replace an agent with `overrideProvider`: `Agent` for the agent registered without a name,
257
+ `getAgentToken(name)` for a named one.
258
+
259
+ ```ts
260
+ import { Test } from '@nestjs/testing';
261
+ import { getAgentToken } from 'nestjs-langchain';
262
+
263
+ const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
264
+ .overrideProvider(getAgentToken('MATH_AGENT'))
265
+ .useValue({
266
+ run: async () => ({ status: 'completed', output: '42', tools: [], durationMs: 0 }),
267
+ })
268
+ .compile();
269
+ ```
270
+
271
+ Or run the real agent and its tools against LangChain's `fakeModel()`, which replays the answers
272
+ and tool calls you queue:
273
+
274
+ ```ts
275
+ import { Test } from '@nestjs/testing';
276
+ import { AIMessage } from '@langchain/core/messages';
277
+ import { fakeModel } from '@langchain/core/testing';
278
+ import { Agent, LangChainModule } from 'nestjs-langchain';
279
+ import { MathModule } from './math/math.module.js';
280
+
281
+ const model = fakeModel()
282
+ .respondWithTools([{ name: 'add', args: { a: 1, b: 2 } }])
283
+ .respond(new AIMessage('The result is 3.'));
284
+
285
+ const moduleRef = await Test.createTestingModule({
286
+ imports: [MathModule, LangChainModule.register({ model, tools: [MathModule] })],
287
+ }).compile();
288
+ // The agent is built on init, which `compile()` does not run.
289
+ await moduleRef.init();
290
+
291
+ const { output } = await moduleRef.get(Agent).run('1 + 2?');
292
+ ```
293
+
294
+ Testing with Jest: [docs/setup.md](docs/setup.md#testing-with-jest).
295
+
296
+ ## Logging and observing
297
+
298
+ Record what a run does through `observer`:
299
+
300
+ ```ts
301
+ LangChainModule.register({
302
+ model: { model: 'openai:gpt-5-mini' },
303
+ tools: [MathModule],
304
+ observer: {
305
+ onToolStart: ({ tool, args }) => console.log(`${tool} called with`, args),
306
+ onToolError: ({ tool, reason, error }) =>
307
+ console.error(`${tool} failed (${reason})`, error),
308
+ onRunFinish: ({ durationMs, tools, tokens }) =>
309
+ console.log({ durationMs, tools, tokens }),
310
+ },
311
+ });
312
+ ```
313
+
314
+ With `LANGSMITH_TRACING=true` and `LANGSMITH_API_KEY` set, every run is also traced in LangSmith.
315
+
316
+ Every event, the errors, the log lines and `callbacks`: [docs/observing.md](docs/observing.md).
317
+
318
+ ### Errors
319
+
320
+ Everything `run()` throws is an `AgentRunError`, with the `agent` that failed and the original
321
+ error in `cause`:
322
+
323
+ ```ts
324
+ import { AgentRunError } from 'nestjs-langchain';
325
+
326
+ try {
327
+ await agent.run(question);
328
+ } catch (error) {
329
+ if (error instanceof AgentRunError) {
330
+ console.error(error.agent, error.message, error.cause);
331
+ }
332
+ }
333
+ ```
334
+
335
+ ## Contributing
336
+
337
+ Contributions are welcome. Read the
338
+ [contributing guidelines](https://github.com/Martin-Bruel/nestjs-langchain/blob/main/CONTRIBUTING.md)
339
+ and the [code of conduct](https://github.com/Martin-Bruel/nestjs-langchain/blob/main/CODE_OF_CONDUCT.md)
340
+ first.
341
+
342
+ ## License
343
+
344
+ This project is released under the terms of the MIT License.