@node-llm/core 1.10.0 → 1.11.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.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @node-llm/core
2
2
 
3
3
  <p align="left">
4
- <a href="https://node-llm.eshaiju.com/">
5
- <img src="https://node-llm.eshaiju.com/assets/images/logo.jpg" alt="NodeLLM logo" width="300" />
4
+ <a href="https://nodellm.dev/">
5
+ <img src="https://nodellm.dev/assets/images/logo.jpg" alt="NodeLLM logo" width="300" />
6
6
  </a>
7
7
  </p>
8
8
 
@@ -139,6 +139,54 @@ const safetyMiddleware = {
139
139
 
140
140
  ---
141
141
 
142
+ ## 🤖 Agent Class
143
+
144
+ Define reusable, class-configured agents with a declarative DSL:
145
+
146
+ ```ts
147
+ import { Agent, Tool, z } from "@node-llm/core";
148
+
149
+ class LookupOrderTool extends Tool<{ orderId: string }> {
150
+ name = "lookup_order";
151
+ description = "Look up an order by ID";
152
+ schema = z.object({ orderId: z.string() });
153
+
154
+ async execute({ orderId }: { orderId: string }) {
155
+ return { status: "shipped", eta: "Tomorrow" };
156
+ }
157
+ }
158
+
159
+ class SupportAgent extends Agent {
160
+ static model = "gpt-4.1";
161
+ static instructions = "You are a helpful support agent.";
162
+ static tools = [LookupOrderTool];
163
+ static temperature = 0.2;
164
+ }
165
+
166
+ // Use anywhere in your app
167
+ const agent = new SupportAgent();
168
+ const response = await agent.ask("Where is order #123?");
169
+ console.log(response.content);
170
+ ```
171
+
172
+ ### ToolHalt - Early Loop Termination
173
+
174
+ Stop the agentic loop early when a definitive answer is found:
175
+
176
+ ```ts
177
+ class FinalAnswerTool extends Tool<{ answer: string }> {
178
+ name = "final_answer";
179
+ description = "Return the final answer to the user";
180
+ schema = z.object({ answer: z.string() });
181
+
182
+ async execute({ answer }: { answer: string }) {
183
+ return this.halt(answer); // Stops the loop, returns this result
184
+ }
185
+ }
186
+ ```
187
+
188
+ ---
189
+
142
190
  ## 💾 Ecosystem
143
191
 
144
192
  Looking for persistence? use **[@node-llm/orm](https://www.npmjs.com/package/@node-llm/orm)**.
@@ -150,11 +198,11 @@ Looking for persistence? use **[@node-llm/orm](https://www.npmjs.com/package/@no
150
198
 
151
199
  ## 📚 Full Documentation
152
200
 
153
- Visit **[node-llm.eshaiju.com](https://node-llm.eshaiju.com/)** for:
201
+ Visit **[nodellm.dev](https://nodellm.dev/)** for:
154
202
 
155
- - [Deep Dive into Tool Calling](https://node-llm.eshaiju.com/core-features/tools)
156
- - [Multi-modal Vision & Audio Guide](https://node-llm.eshaiju.com/core-features/multimodal)
157
- - [Custom Provider Plugin System](https://node-llm.eshaiju.com/advanced/custom-providers)
203
+ - [Deep Dive into Tool Calling](https://nodellm.dev/core-features/tools)
204
+ - [Multi-modal Vision & Audio Guide](https://nodellm.dev/core-features/multimodal)
205
+ - [Custom Provider Plugin System](https://nodellm.dev/advanced/custom-providers)
158
206
 
159
207
  ---
160
208
 
@@ -0,0 +1,191 @@
1
+ import { z } from "zod";
2
+ import { Chat, AskOptions } from "../chat/Chat.js";
3
+ import { ChatOptions } from "../chat/ChatOptions.js";
4
+ import { ChatResponseString } from "../chat/ChatResponse.js";
5
+ import { ToolResolvable } from "../chat/Tool.js";
6
+ import { ThinkingConfig, ThinkingResult } from "../providers/Provider.js";
7
+ import { Schema } from "../schema/Schema.js";
8
+ import { NodeLLMCore } from "../llm.js";
9
+ /**
10
+ * Configuration options that can be defined as static properties on Agent subclasses.
11
+ */
12
+ export interface AgentConfig {
13
+ /** The model ID to use (e.g., "gpt-4o", "claude-sonnet-4-20250514") */
14
+ model?: string;
15
+ /** The provider to use (e.g., "openai", "anthropic") */
16
+ provider?: string;
17
+ /** System instructions for the agent */
18
+ instructions?: string;
19
+ /** Tools available to the agent */
20
+ tools?: ToolResolvable[];
21
+ /** Temperature for response generation (0.0 - 1.0) */
22
+ temperature?: number;
23
+ /** Extended thinking configuration */
24
+ thinking?: ThinkingConfig;
25
+ /** Output schema for structured responses */
26
+ schema?: z.ZodType | Schema | Record<string, unknown>;
27
+ /** Provider-specific parameters */
28
+ params?: Record<string, unknown>;
29
+ /** Custom headers for requests */
30
+ headers?: Record<string, string>;
31
+ /** Maximum tokens in response */
32
+ maxTokens?: number;
33
+ /** Maximum tool call iterations */
34
+ maxToolCalls?: number;
35
+ /** Assume model exists without validation */
36
+ assumeModelExists?: boolean;
37
+ /** Optional LLM instance to use instead of global NodeLLM */
38
+ llm?: NodeLLMCore;
39
+ }
40
+ /**
41
+ * Base class for creating reusable, class-configured agents.
42
+ *
43
+ * Define your agent configuration using static properties, then instantiate
44
+ * and use it anywhere in your application.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * class SupportAgent extends Agent {
49
+ * static model = "gpt-4o";
50
+ * static instructions = "You are a helpful support agent";
51
+ * static tools = [SearchDocs, LookupAccount];
52
+ * static temperature = 0.2;
53
+ * }
54
+ *
55
+ * const agent = new SupportAgent();
56
+ * const response = await agent.ask("How can I reset my password?");
57
+ * ```
58
+ *
59
+ * @example Override configuration per instance:
60
+ * ```typescript
61
+ * const agent = new SupportAgent({ model: "gpt-4o-mini" });
62
+ * ```
63
+ */
64
+ export declare abstract class Agent<S extends Record<string, unknown> = Record<string, unknown>> {
65
+ static model?: string;
66
+ static provider?: string;
67
+ static instructions?: string;
68
+ static tools?: ToolResolvable[];
69
+ static temperature?: number;
70
+ static thinking?: ThinkingConfig;
71
+ static schema?: z.ZodType | Schema | Record<string, unknown>;
72
+ static params?: Record<string, unknown>;
73
+ static headers?: Record<string, string>;
74
+ static maxTokens?: number;
75
+ static maxToolCalls?: number;
76
+ static assumeModelExists?: boolean;
77
+ /**
78
+ * Hook called when the agent starts a new session (ask/stream).
79
+ * @param context - Initial context including messages/options
80
+ */
81
+ static onStart(_context: {
82
+ messages: unknown[];
83
+ }): void | Promise<void>;
84
+ /**
85
+ * Hook called when the agent generates a reasoning trace (thinking).
86
+ * @param thinking - The content of the thinking trace
87
+ * @param result - The full response object containing the thinking
88
+ */
89
+ static onThinking(_thinking: ThinkingResult, _result: ChatResponseString): void | Promise<void>;
90
+ /**
91
+ * Hook called when a tool execution starts.
92
+ * @param toolCall - The tool call object (id, function name, arguments)
93
+ */
94
+ static onToolStart(_toolCall: unknown): void | Promise<void>;
95
+ /**
96
+ * Hook called when a tool execution ends.
97
+ * @param toolCall - The tool call object
98
+ * @param result - The result of the tool execution
99
+ */
100
+ static onToolEnd(_toolCall: unknown, _result: unknown): void | Promise<void>;
101
+ /**
102
+ * Hook called when a tool execution encounters an error.
103
+ * @param toolCall - The tool call object
104
+ * @param error - The error that occurred
105
+ */
106
+ static onToolError(_toolCall: unknown, _error: Error): void | Promise<void>;
107
+ /**
108
+ * Hook called when the agent completes a response turn.
109
+ * @param result - The final response object
110
+ */
111
+ static onComplete(_result: ChatResponseString): void | Promise<void>;
112
+ /**
113
+ * Run the agent immediately with a prompt.
114
+ * Creates a new instance of the agent, runs the prompt, and disposes it.
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const result = await TravelAgent.ask("Find flights to Paris");
119
+ * ```
120
+ */
121
+ static ask(message: string, options?: AskOptions): Promise<ChatResponseString>;
122
+ /**
123
+ * Stream the agent response immediately.
124
+ * Creates a new instance of the agent and streams the response.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * for await (const chunk of TravelAgent.stream("Write a poem")) {
129
+ * process.stdout.write(chunk.content);
130
+ * }
131
+ * ```
132
+ */
133
+ static stream(message: string, options?: AskOptions): import("../index.js").Stream<import("../providers/Provider.js").ChatChunk>;
134
+ /** The underlying Chat instance */
135
+ protected readonly chat: Chat<S>;
136
+ /**
137
+ * Create a new agent instance.
138
+ * @param overrides - Optional configuration to override static properties
139
+ */
140
+ constructor(overrides?: Partial<AgentConfig & ChatOptions>);
141
+ /**
142
+ * Send a message to the agent and get a response.
143
+ * @param message - The user message
144
+ * @param options - Optional request options
145
+ */
146
+ ask(message: string, options?: AskOptions): Promise<ChatResponseString>;
147
+ /**
148
+ * Alias for ask()
149
+ */
150
+ say(message: string, options?: AskOptions): Promise<ChatResponseString>;
151
+ /**
152
+ * Stream a response from the agent.
153
+ * @param message - The user message
154
+ * @param options - Optional request options
155
+ */
156
+ stream(message: string, options?: AskOptions): import("../index.js").Stream<import("../providers/Provider.js").ChatChunk>;
157
+ /**
158
+ * Get the conversation history.
159
+ */
160
+ get history(): readonly import("../index.js").Message[];
161
+ /**
162
+ * Get the model ID being used.
163
+ */
164
+ get modelId(): string;
165
+ /**
166
+ * Get aggregate token usage across the conversation.
167
+ */
168
+ get totalUsage(): import("../providers/Provider.js").Usage;
169
+ /**
170
+ * Access the underlying Chat instance for advanced operations.
171
+ */
172
+ get underlyingChat(): Chat<S>;
173
+ }
174
+ /**
175
+ * Helper function to define an agent inline without creating a class.
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * const SupportAgent = defineAgent({
180
+ * model: "gpt-4o",
181
+ * instructions: "You are a helpful support agent",
182
+ * tools: [SearchDocs, LookupAccount],
183
+ * temperature: 0.2
184
+ * });
185
+ *
186
+ * const agent = new SupportAgent();
187
+ * const response = await agent.ask("Help me!");
188
+ * ```
189
+ */
190
+ export declare function defineAgent<S extends Record<string, unknown> = Record<string, unknown>>(config: AgentConfig): new (overrides?: Partial<AgentConfig & ChatOptions>) => Agent<S>;
191
+ //# sourceMappingURL=Agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Agent.d.ts","sourceRoot":"","sources":["../../src/agent/Agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,cAA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WAAW,GAAG,WAAW,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,CAelE"}
@@ -0,0 +1,272 @@
1
+ import { NodeLLM } from "../llm.js";
2
+ /**
3
+ * Base class for creating reusable, class-configured agents.
4
+ *
5
+ * Define your agent configuration using static properties, then instantiate
6
+ * and use it anywhere in your application.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * class SupportAgent extends Agent {
11
+ * static model = "gpt-4o";
12
+ * static instructions = "You are a helpful support agent";
13
+ * static tools = [SearchDocs, LookupAccount];
14
+ * static temperature = 0.2;
15
+ * }
16
+ *
17
+ * const agent = new SupportAgent();
18
+ * const response = await agent.ask("How can I reset my password?");
19
+ * ```
20
+ *
21
+ * @example Override configuration per instance:
22
+ * ```typescript
23
+ * const agent = new SupportAgent({ model: "gpt-4o-mini" });
24
+ * ```
25
+ */
26
+ export class Agent {
27
+ // Static configuration properties - override these in subclasses
28
+ static model;
29
+ static provider;
30
+ static instructions;
31
+ static tools;
32
+ static temperature;
33
+ static thinking;
34
+ static schema;
35
+ static params;
36
+ static headers;
37
+ static maxTokens;
38
+ static maxToolCalls;
39
+ static assumeModelExists;
40
+ /**
41
+ * Hook called when the agent starts a new session (ask/stream).
42
+ * @param context - Initial context including messages/options
43
+ */
44
+ static onStart(_context) {
45
+ // Override in subclass
46
+ }
47
+ /**
48
+ * Hook called when the agent generates a reasoning trace (thinking).
49
+ * @param thinking - The content of the thinking trace
50
+ * @param result - The full response object containing the thinking
51
+ */
52
+ static onThinking(_thinking, _result) {
53
+ // Override in subclass
54
+ }
55
+ /**
56
+ * Hook called when a tool execution starts.
57
+ * @param toolCall - The tool call object (id, function name, arguments)
58
+ */
59
+ static onToolStart(_toolCall) {
60
+ // Override in subclass
61
+ }
62
+ /**
63
+ * Hook called when a tool execution ends.
64
+ * @param toolCall - The tool call object
65
+ * @param result - The result of the tool execution
66
+ */
67
+ static onToolEnd(_toolCall, _result) {
68
+ // Override in subclass
69
+ }
70
+ /**
71
+ * Hook called when a tool execution encounters an error.
72
+ * @param toolCall - The tool call object
73
+ * @param error - The error that occurred
74
+ */
75
+ static onToolError(_toolCall, _error) {
76
+ // Override in subclass
77
+ }
78
+ /**
79
+ * Hook called when the agent completes a response turn.
80
+ * @param result - The final response object
81
+ */
82
+ static onComplete(_result) {
83
+ // Override in subclass
84
+ }
85
+ // --- Static Execution API ---
86
+ /**
87
+ * Run the agent immediately with a prompt.
88
+ * Creates a new instance of the agent, runs the prompt, and disposes it.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const result = await TravelAgent.ask("Find flights to Paris");
93
+ * ```
94
+ */
95
+ static async ask(message, options) {
96
+ const Ctor = this;
97
+ const agent = new Ctor({});
98
+ return agent.ask(message, options);
99
+ }
100
+ /**
101
+ * Stream the agent response immediately.
102
+ * Creates a new instance of the agent and streams the response.
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * for await (const chunk of TravelAgent.stream("Write a poem")) {
107
+ * process.stdout.write(chunk.content);
108
+ * }
109
+ * ```
110
+ */
111
+ static stream(message, options) {
112
+ const Ctor = this;
113
+ const agent = new Ctor({});
114
+ return agent.stream(message, options);
115
+ }
116
+ /** The underlying Chat instance */
117
+ chat;
118
+ /**
119
+ * Create a new agent instance.
120
+ * @param overrides - Optional configuration to override static properties
121
+ */
122
+ constructor(overrides = {}) {
123
+ const ctor = this.constructor;
124
+ // Build chat options from static properties + overrides
125
+ const chatOptions = {
126
+ provider: overrides.provider ?? ctor.provider,
127
+ assumeModelExists: overrides.assumeModelExists ?? ctor.assumeModelExists,
128
+ temperature: overrides.temperature ?? ctor.temperature,
129
+ maxTokens: overrides.maxTokens ?? ctor.maxTokens,
130
+ maxToolCalls: overrides.maxToolCalls ?? ctor.maxToolCalls,
131
+ headers: { ...ctor.headers, ...overrides.headers },
132
+ params: { ...ctor.params, ...overrides.params },
133
+ thinking: overrides.thinking ?? ctor.thinking,
134
+ messages: overrides.messages // Allow history injection
135
+ };
136
+ // Determine model
137
+ const model = overrides.model ?? ctor.model;
138
+ if (!model) {
139
+ throw new Error(`[Agent] No model specified. Set static model property or pass model in constructor.`);
140
+ }
141
+ // Use provided LLM instance or fall back to global NodeLLM
142
+ const llm = overrides.llm ?? NodeLLM;
143
+ this.chat = llm.chat(model, chatOptions);
144
+ // Apply instructions
145
+ const instructions = overrides.instructions ?? ctor.instructions;
146
+ if (instructions) {
147
+ this.chat.withInstructions(instructions);
148
+ }
149
+ // Apply tools
150
+ const tools = overrides.tools ?? ctor.tools;
151
+ if (tools && tools.length > 0) {
152
+ this.chat.withTools(tools);
153
+ }
154
+ // Apply schema
155
+ const schema = overrides.schema ?? ctor.schema;
156
+ if (schema) {
157
+ this.chat.withSchema(schema);
158
+ }
159
+ // Wire up global/static telemetry hooks
160
+ // Trigger onStart immediately
161
+ if (ctor.onStart) {
162
+ this.chat.beforeRequest(async (messages) => {
163
+ if (ctor.onStart) {
164
+ await ctor.onStart({ messages });
165
+ }
166
+ });
167
+ }
168
+ if (ctor.onToolStart) {
169
+ this.chat.onToolCallStart(async (toolCall) => {
170
+ await ctor.onToolStart(toolCall);
171
+ });
172
+ }
173
+ if (ctor.onToolEnd) {
174
+ this.chat.onToolCallEnd(async (toolCall, result) => {
175
+ await ctor.onToolEnd(toolCall, result);
176
+ });
177
+ }
178
+ if (ctor.onToolError) {
179
+ this.chat.onToolCallError(async (toolCall, error) => {
180
+ await ctor.onToolError(toolCall, error);
181
+ });
182
+ }
183
+ if (ctor.onComplete || ctor.onThinking) {
184
+ this.chat.onEndMessage(async (msg) => {
185
+ if (msg.thinking && ctor.onThinking) {
186
+ await ctor.onThinking(msg.thinking, msg);
187
+ }
188
+ if (ctor.onComplete) {
189
+ await ctor.onComplete(msg);
190
+ }
191
+ });
192
+ }
193
+ }
194
+ /**
195
+ * Send a message to the agent and get a response.
196
+ * @param message - The user message
197
+ * @param options - Optional request options
198
+ */
199
+ async ask(message, options) {
200
+ return this.chat.ask(message, options);
201
+ }
202
+ /**
203
+ * Alias for ask()
204
+ */
205
+ async say(message, options) {
206
+ return this.ask(message, options);
207
+ }
208
+ /**
209
+ * Stream a response from the agent.
210
+ * @param message - The user message
211
+ * @param options - Optional request options
212
+ */
213
+ stream(message, options) {
214
+ return this.chat.stream(message, options);
215
+ }
216
+ /**
217
+ * Get the conversation history.
218
+ */
219
+ get history() {
220
+ return this.chat.history;
221
+ }
222
+ /**
223
+ * Get the model ID being used.
224
+ */
225
+ get modelId() {
226
+ return this.chat.modelId;
227
+ }
228
+ /**
229
+ * Get aggregate token usage across the conversation.
230
+ */
231
+ get totalUsage() {
232
+ return this.chat.totalUsage;
233
+ }
234
+ /**
235
+ * Access the underlying Chat instance for advanced operations.
236
+ */
237
+ get underlyingChat() {
238
+ return this.chat;
239
+ }
240
+ }
241
+ /**
242
+ * Helper function to define an agent inline without creating a class.
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * const SupportAgent = defineAgent({
247
+ * model: "gpt-4o",
248
+ * instructions: "You are a helpful support agent",
249
+ * tools: [SearchDocs, LookupAccount],
250
+ * temperature: 0.2
251
+ * });
252
+ *
253
+ * const agent = new SupportAgent();
254
+ * const response = await agent.ask("Help me!");
255
+ * ```
256
+ */
257
+ export function defineAgent(config) {
258
+ return class extends Agent {
259
+ static model = config.model;
260
+ static provider = config.provider;
261
+ static instructions = config.instructions;
262
+ static tools = config.tools;
263
+ static temperature = config.temperature;
264
+ static thinking = config.thinking;
265
+ static schema = config.schema;
266
+ static params = config.params;
267
+ static headers = config.headers;
268
+ static maxTokens = config.maxTokens;
269
+ static maxToolCalls = config.maxToolCalls;
270
+ static assumeModelExists = config.assumeModelExists;
271
+ };
272
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"Chat.d.ts","sourceRoot":"","sources":["../../src/chat/Chat.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACL,WAAW,EAGX,cAAc,EACf,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,WAAW,EAAE,MA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AAE,CAAC,QAAQ,EAAE,kBAAkB,KAAK,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,GAC5E,IAAI;IAKP;;OAEG;IACG,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,EAAE,EAAE,OAAO,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,kBAAkB,CAAC;IA2X7F;;OAEG;IACH,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,EAAE,EAAE,OAAO,GAAE,UAAe,GAAG,MAAM,CAAC,SAAS,CAAC;IAWpF;;OAEG;IACH,OAAO,CAAC,aAAa;CAoDtB"}
package/dist/chat/Chat.js CHANGED
@@ -423,7 +423,8 @@ export class Chat {
423
423
  }
424
424
  const maxToolCalls = options?.maxToolCalls ?? this.options.maxToolCalls ?? 5;
425
425
  let stepCount = 0;
426
- while (response.tool_calls && response.tool_calls.length > 0) {
426
+ let haltTriggered = false;
427
+ while (response.tool_calls && response.tool_calls.length > 0 && !haltTriggered) {
427
428
  // Dry-run mode: stop after proposing tools
428
429
  if (!ToolHandler.shouldExecuteTools(response.tool_calls, this.options.toolExecution)) {
429
430
  break;
@@ -448,6 +449,16 @@ export class Chat {
448
449
  // 3. onToolCallEnd Hook
449
450
  await runMiddleware(this.middlewares, "onToolCallEnd", context, toolCall, toolResult.content);
450
451
  this.messages.push(this.provider.formatToolResultMessage(toolResult.tool_call_id, toolResult.content));
452
+ // Check if tool signaled a halt - stop the agentic loop
453
+ if (toolResult.halted) {
454
+ haltTriggered = true;
455
+ // Create final response from halt content
456
+ assistantMessage = new ChatResponseString(toolResult.content, totalUsage, this.model, this.provider.id, undefined, undefined, undefined, "tool_halt");
457
+ if (this.options.onEndMessage) {
458
+ this.options.onEndMessage(assistantMessage);
459
+ }
460
+ break; // Exit the for loop
461
+ }
451
462
  }
452
463
  catch (error) {
453
464
  let currentError = error;
@@ -489,6 +500,10 @@ export class Chat {
489
500
  logger.error(`Tool execution failed for '${toolCall.function.name}':`, currentError);
490
501
  }
491
502
  }
503
+ // If halt was triggered, exit the while loop immediately
504
+ if (haltTriggered) {
505
+ break;
506
+ }
492
507
  response = await this.executor.executeChat({
493
508
  model: this.model,
494
509
  messages: [...this.systemMessages, ...this.messages], // Use updated history
@@ -14,7 +14,32 @@ export interface ToolDefinition {
14
14
  description?: string;
15
15
  parameters: Record<string, unknown>;
16
16
  };
17
- handler?: (args: unknown) => Promise<string>;
17
+ handler?: (args: unknown) => Promise<string | ToolHalt>;
18
+ }
19
+ /**
20
+ * Stops the agentic tool execution loop and returns the content as the final response.
21
+ * Return this from a tool's execute() method to immediately end the conversation turn.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * class PaymentTool extends Tool {
26
+ * async execute({ amount }) {
27
+ * if (amount > 10000) {
28
+ * return this.halt("Payment requires manager approval. Please contact support.");
29
+ * }
30
+ * return processPayment(amount);
31
+ * }
32
+ * }
33
+ * ```
34
+ */
35
+ export declare class ToolHalt {
36
+ readonly content: string;
37
+ constructor(content: string);
38
+ toString(): string;
39
+ toJSON(): {
40
+ halt: true;
41
+ content: string;
42
+ };
18
43
  }
19
44
  /**
20
45
  * Anything that can be resolved into a ToolDefinition.
@@ -44,11 +69,27 @@ export declare abstract class Tool<T = Record<string, unknown>> {
44
69
  * 'args' will be parsed and validated based on 'schema'.
45
70
  */
46
71
  abstract execute(args: T): Promise<unknown>;
72
+ /**
73
+ * Stop the agentic loop and return this message as the final tool result.
74
+ * Use this when you want to end the conversation turn immediately.
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * async execute({ amount }) {
79
+ * if (amount > 10000) {
80
+ * return this.halt("Payment requires manager approval.");
81
+ * }
82
+ * return processPayment(amount);
83
+ * }
84
+ * ```
85
+ */
86
+ protected halt(message: string): ToolHalt;
47
87
  /**
48
88
  * Internal handler to bridge with LLM providers.
49
89
  * Converts any result to a string (usually JSON).
90
+ * Preserves ToolHalt instances for the execution loop to detect.
50
91
  */
51
- handler(args: T): Promise<string>;
92
+ handler(args: T): Promise<string | ToolHalt>;
52
93
  /**
53
94
  * Converts the tool definition and logic into a standard ToolDefinition interface.
54
95
  * This is called automatically by NodeLLM when registering tools.
@@ -1 +1 @@
1
- {"version":3,"file":"Tool.d.ts","sourceRoot":"","sources":["../../src/chat/Tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAC;QACb,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACrC,CAAC;IACF,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9C;AAED;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,IAAI,GAAG;IAAE,QAAQ,IAAI,CAAA;CAAE,GAAG,cAAc,CAAC;AAEtE;;GAEG;AACH,8BAAsB,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACpD;;OAEG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC;;;OAGG;IACH,SAAgB,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE7E;;;OAGG;aACa,OAAO,CAAC,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IAElD;;;OAGG;I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AEpC;;;OAGG;IACH,SAAgB,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE7E;;;OAGG;aACa,OAAO,CAAC,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC;IAElD;;;;;;;;;;;;;OAaG;IACH,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ;IAIzC;;;;OAIG;IACU,OAAO,CAAC,IAAI,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,CAAC;IAYzD;;;OAGG;IACI,SAAS,IAAI,cAAc;CAuBnC"}
package/dist/chat/Tool.js CHANGED
@@ -1,14 +1,64 @@
1
1
  import { toJsonSchema } from "../schema/to-json-schema.js";
2
+ /**
3
+ * Stops the agentic tool execution loop and returns the content as the final response.
4
+ * Return this from a tool's execute() method to immediately end the conversation turn.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * class PaymentTool extends Tool {
9
+ * async execute({ amount }) {
10
+ * if (amount > 10000) {
11
+ * return this.halt("Payment requires manager approval. Please contact support.");
12
+ * }
13
+ * return processPayment(amount);
14
+ * }
15
+ * }
16
+ * ```
17
+ */
18
+ export class ToolHalt {
19
+ content;
20
+ constructor(content) {
21
+ this.content = content;
22
+ }
23
+ toString() {
24
+ return this.content;
25
+ }
26
+ toJSON() {
27
+ return { halt: true, content: this.content };
28
+ }
29
+ }
2
30
  /**
3
31
  * Subclass this to create tools with auto-generated schemas and type safety.
4
32
  */
5
33
  export class Tool {
34
+ /**
35
+ * Stop the agentic loop and return this message as the final tool result.
36
+ * Use this when you want to end the conversation turn immediately.
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * async execute({ amount }) {
41
+ * if (amount > 10000) {
42
+ * return this.halt("Payment requires manager approval.");
43
+ * }
44
+ * return processPayment(amount);
45
+ * }
46
+ * ```
47
+ */
48
+ halt(message) {
49
+ return new ToolHalt(message);
50
+ }
6
51
  /**
7
52
  * Internal handler to bridge with LLM providers.
8
53
  * Converts any result to a string (usually JSON).
54
+ * Preserves ToolHalt instances for the execution loop to detect.
9
55
  */
10
56
  async handler(args) {
11
57
  const result = await this.execute(args);
58
+ // Preserve ToolHalt for the execution loop to handle
59
+ if (result instanceof ToolHalt) {
60
+ return result;
61
+ }
12
62
  if (result === undefined || result === null)
13
63
  return "";
14
64
  return typeof result === "string" ? result : JSON.stringify(result);
@@ -1,12 +1,17 @@
1
1
  import { ToolExecutionMode } from "../constants.js";
2
2
  import { ToolCall, ToolDefinition } from "./Tool.js";
3
+ /**
4
+ * Result of a tool execution, including halt status
5
+ */
6
+ export interface ToolExecutionResult {
7
+ role: "tool";
8
+ tool_call_id: string;
9
+ content: string;
10
+ halted: boolean;
11
+ }
3
12
  export declare class ToolHandler {
4
13
  static shouldExecuteTools(toolCalls: ToolCall[] | undefined, mode?: ToolExecutionMode): boolean;
5
14
  static requestToolConfirmation(toolCall: ToolCall, onConfirm?: (call: ToolCall) => Promise<boolean> | boolean): Promise<boolean>;
6
- static execute(toolCall: ToolCall, tools: ToolDefinition[] | undefined, onStart?: (call: ToolCall) => void, onEnd?: (call: ToolCall, result: unknown) => void): Promise<{
7
- role: "tool";
8
- tool_call_id: string;
9
- content: string;
10
- }>;
15
+ static execute(toolCall: ToolCall, tools: ToolDefinition[] | undefined, onStart?: (call: ToolCall) => void, onEnd?: (call: ToolCall, result: unknown) => void): Promise<ToolExecutionResult>;
11
16
  }
12
17
  //# sourceMappingURL=ToolHandler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ToolHandler.d.ts","sourceRoot":"","sources":["../../src/chat/ToolHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAErD,qBAAa,WAAW;IACtB,MAAM,CAAC,kBA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AAG,OAAO,GACzD,OAAO,CAAC,OAAO,CAAC;WAMN,OAAO,CAClB,QAAQ,EAAE,QAAQ,EAClB,KAAK,EAAE,cAAc,EAAE,GAAG,SAAS,EACnC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,KAAK,IAAI,EAClC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,KAAK,IAAI,GAChD,OAAO,CAAC,mBAAmB,CAAC;CAgChC"}
@@ -1,5 +1,6 @@
1
1
  import { ToolExecutionMode } from "../constants.js";
2
2
  import { ToolError } from "../errors/index.js";
3
+ import { ToolHalt } from "./Tool.js";
3
4
  export class ToolHandler {
4
5
  static shouldExecuteTools(toolCalls, mode) {
5
6
  if (!toolCalls || toolCalls.length === 0)
@@ -21,13 +22,20 @@ export class ToolHandler {
21
22
  if (tool?.handler) {
22
23
  const args = JSON.parse(toolCall.function.arguments);
23
24
  const result = await tool.handler(args);
24
- const safeResult = typeof result === "string" ? result : JSON.stringify(result);
25
+ // Check if this is a halt signal
26
+ const isHalt = typeof result === "object" && result !== null && result instanceof ToolHalt;
27
+ const content = isHalt
28
+ ? result.content
29
+ : typeof result === "string"
30
+ ? result
31
+ : JSON.stringify(result);
25
32
  if (onEnd)
26
33
  onEnd(toolCall, result);
27
34
  return {
28
35
  role: "tool",
29
36
  tool_call_id: toolCall.id,
30
- content: safeResult
37
+ content,
38
+ halted: isHalt
31
39
  };
32
40
  }
33
41
  else {
package/dist/index.d.ts CHANGED
@@ -7,6 +7,8 @@ export * from "./chat/Chat.js";
7
7
  export * from "./chat/ChatStream.js";
8
8
  export * from "./streaming/Stream.js";
9
9
  export * from "./errors/index.js";
10
+ export { Agent, defineAgent } from "./agent/Agent.js";
11
+ export type { AgentConfig } from "./agent/Agent.js";
10
12
  export type { Middleware, MiddlewareContext } from "./types/Middleware.js";
11
13
  export * from "./middlewares/index.js";
12
14
  export { z } from "zod";
@@ -1 +1 @@
1
- {"version":3,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Aa,EACb,oBAAoB,EACpB,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EACtB,uBAAuB,EACvB,cAAc,EACf,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ export * from "./chat/Chat.js";
7
7
  export * from "./chat/ChatStream.js";
8
8
  export * from "./streaming/Stream.js";
9
9
  export * from "./errors/index.js";
10
+ export { Agent, defineAgent } from "./agent/Agent.js";
10
11
  export * from "./middlewares/index.js";
11
12
  export { z } from "zod";
12
13
  export { NodeLLM, LegacyNodeLLM, createLLM, NodeLLMCore, Transcription, Moderation, Embedding, ModelRegistry, PricingRegistry } from "./llm.js";
package/dist/llm.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"llm.d.ts","sourceRoot":"","sources":["../src/llm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAW9D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAE9D,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,MAAM,4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chat/Message.js";
2
2
  import { ChatOptions } from "../chat/ChatOptions.js";
3
3
  import { ChatResponseString } from "../chat/ChatResponse.js";
4
4
  import { ToolCall } from "../chat/Tool.js";
5
+ import { GeneratedImage } from "../image/GeneratedImage.js";
6
+ import { Transcription } from "../transcription/Transcription.js";
7
+ import { Moderation } from "../moderation/Moderation.js";
8
+ import { Embedding } from "../embedding/Embedding.js";
9
+ /**
10
+ * All possible response types that can be returned by NodeLLM.
11
+ */
12
+ export type NodeLLMResponse = ChatResponseString | GeneratedImage | Transcription | Moderation | Embedding;
5
13
  /**
6
14
  * Context passed to all middleware hooks.
7
15
  * This object is shared across the lifecycle of a single request.
@@ -36,19 +44,19 @@ export interface MiddlewareContext {
36
44
  /**
37
45
  * Options passed to the embedding request (Embedding only).
38
46
  */
39
- embeddingOptions?: Record<string, any>;
47
+ embeddingOptions?: Record<string, unknown>;
40
48
  /**
41
49
  * Options passed to the transcription request (Transcription only).
42
50
  */
43
- transcriptionOptions?: Record<string, any>;
51
+ transcriptionOptions?: Record<string, unknown>;
44
52
  /**
45
53
  * Options passed to the moderation request (Moderation only).
46
54
  */
47
- moderationOptions?: Record<string, any>;
55
+ moderationOptions?: Record<string, unknown>;
48
56
  /**
49
57
  * Options passed to the image generation request (Paint only).
50
58
  */
51
- imageOptions?: Record<string, any>;
59
+ imageOptions?: Record<string, unknown>;
52
60
  /**
53
61
  * Shared state storage for passing data between middleware hooks.
54
62
  * Example: Storing start time in `onRequest` and reading it in `onResponse`.
@@ -75,7 +83,7 @@ export interface Middleware {
75
83
  /**
76
84
  * Called after a successful response from the provider.
77
85
  */
78
- onResponse?(ctx: MiddlewareContext, result: ChatResponseString): Promise<void>;
86
+ onResponse?(ctx: MiddlewareContext, result: NodeLLMResponse): Promise<void>;
79
87
  /**
80
88
  * Called if an error occurs during execution.
81
89
  */
@@ -1 +1 @@
1
- {"version":3,"file":"Middleware.d.ts","sourceRoot":"","sources":["../../src/types/Middleware.ts"],"names":[],"mappings":"AAAA,O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AAC;IAE9D;;;OAGG;IACH,eAAe,CAAC,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAExE;;OAEG;IACH,aAAa,CAAC,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvF;;;OAGG;IACH,eAAe,CAAC,CACd,GAAG,EAAE,iBAAiB,EACtB,IAAI,EAAE,QAAQ,EACd,KAAK,EAAE,KAAK,GACX,OAAO,CAAC,kBAAkB,CAAC,CAAC;CAChC"}
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-runner.d.ts","sourceRoot":"","sources":["../../src/utils/middleware-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEvE;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,GAAG,IAAI,EAC1C,WAAW,EAAE,UAAU,EAAE,EACzB,QAAQ,EAAE,MAAM,UAAU,EAC1B,OAAO,EAAE,iBAAiB,EAC1B,GAAG,IAAI,EAAE,GAAG,EAAE,GACb,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAiBxB"}
1
+ {"version":3,"file":"middleware-runner.d.ts","sourceRoot":"","sources":["../../src/utils/middleware-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEvE;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,GAAG,IAAI,EAC1C,WAAW,EAAE,UAAU,EAAE,EACzB,QAAQ,EAAE,MAAM,UAAU,EAC1B,OAAO,EAAE,iBAAiB,EAC1B,GAAG,IAAI,EAAE,GAAG,EAAE,GACb,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAuBxB"}
@@ -5,8 +5,11 @@
5
5
  export async function runMiddleware(middlewares, hookName, context, ...args) {
6
6
  if (!middlewares || middlewares.length === 0)
7
7
  return undefined;
8
+ // Response and error hooks run in reverse order (stack model)
9
+ const isReverse = ["onResponse", "onError", "onToolCallEnd", "onToolCallError"].includes(hookName);
10
+ const chain = isReverse ? [...middlewares].reverse() : middlewares;
8
11
  let finalResult;
9
- for (const middleware of middlewares) {
12
+ for (const middleware of chain) {
10
13
  if (typeof middleware[hookName] === "function") {
11
14
  // @ts-ignore
12
15
  const result = await middleware[hookName](context, ...args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@node-llm/core",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -11,6 +11,9 @@
11
11
  }
12
12
  },
13
13
  "description": "A provider-agnostic LLM core for Node.js, inspired by ruby-llm.",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
14
17
  "keywords": [
15
18
  "llm",
16
19
  "large-language-models",
@@ -40,7 +43,7 @@
40
43
  "url": "https://github.com/node-llm/node-llm",
41
44
  "directory": "packages/core"
42
45
  },
43
- "homepage": "https://node-llm.eshaiju.com",
46
+ "homepage": "https://nodellm.dev",
44
47
  "bugs": {
45
48
  "url": "https://github.com/node-llm/node-llm/issues"
46
49
  },
@@ -67,6 +70,7 @@
67
70
  "dev": "tsc -w",
68
71
  "lint": "tsc --noEmit",
69
72
  "test": "vitest run",
73
+ "test:docs": "vitest run test/docs",
70
74
  "test:watch": "vitest"
71
75
  }
72
76
  }