@jterrazz/intelligence 1.5.0 → 2.0.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 +199 -83
- package/dist/adapters/agents/{basic-agent.adapter.d.ts → chat-agent.adapter.d.ts} +6 -6
- package/dist/adapters/agents/{basic-agent.adapter.js → chat-agent.adapter.js} +54 -27
- package/dist/adapters/agents/chat-agent.adapter.js.map +1 -0
- package/dist/adapters/agents/{retryable-agent.adapter.d.ts → resilient-agent.adapter.d.ts} +4 -4
- package/dist/adapters/agents/{retryable-agent.adapter.js → resilient-agent.adapter.js} +22 -13
- package/dist/adapters/agents/resilient-agent.adapter.js.map +1 -0
- package/dist/adapters/agents/{autonomous-agent.adapter.d.ts → tool-agent.adapter.d.ts} +6 -6
- package/dist/adapters/agents/{autonomous-agent.adapter.js → tool-agent.adapter.js} +29 -18
- package/dist/adapters/agents/tool-agent.adapter.js.map +1 -0
- package/dist/adapters/models/openrouter-model.adapter.d.ts +17 -32
- package/dist/adapters/models/openrouter-model.adapter.js +84 -25
- package/dist/adapters/models/openrouter-model.adapter.js.map +1 -1
- package/dist/adapters/prompts/__tests__/presets.test.js +4 -4
- package/dist/adapters/prompts/__tests__/presets.test.js.map +1 -1
- package/dist/adapters/prompts/system-prompt.adapter.d.ts +2 -2
- package/dist/adapters/prompts/system-prompt.adapter.js +6 -6
- package/dist/adapters/prompts/system-prompt.adapter.js.map +1 -1
- package/dist/adapters/prompts/user-prompt.adapter.d.ts +2 -2
- package/dist/adapters/prompts/user-prompt.adapter.js +6 -6
- package/dist/adapters/prompts/user-prompt.adapter.js.map +1 -1
- package/dist/adapters/providers/openrouter-provider.adapter.d.ts +34 -0
- package/dist/adapters/providers/openrouter-provider.adapter.js +57 -0
- package/dist/adapters/providers/openrouter-provider.adapter.js.map +1 -0
- package/dist/adapters/tools/safe-tool.adapter.d.ts +2 -2
- package/dist/adapters/tools/safe-tool.adapter.js +6 -6
- package/dist/adapters/tools/safe-tool.adapter.js.map +1 -1
- package/dist/adapters/utils/__tests__/{ai-response-parser.test.js → structured-response-parser.test.js} +30 -30
- package/dist/adapters/utils/__tests__/structured-response-parser.test.js.map +1 -0
- package/dist/adapters/utils/{ai-response-parser-error.d.ts → structured-response-parser-error.d.ts} +2 -2
- package/dist/adapters/utils/{ai-response-parser-error.js → structured-response-parser-error.js} +9 -9
- package/dist/adapters/utils/structured-response-parser-error.js.map +1 -0
- package/dist/adapters/utils/{ai-response-parser.d.ts → structured-response-parser.d.ts} +1 -1
- package/dist/adapters/utils/{ai-response-parser.js → structured-response-parser.js} +13 -13
- package/dist/adapters/utils/structured-response-parser.js.map +1 -0
- package/dist/index.cjs +748 -342
- package/dist/index.d.ts +11 -8
- package/dist/index.js +29 -8
- package/dist/index.js.map +1 -1
- package/dist/ports/model.port.d.ts +30 -3
- package/dist/ports/model.port.js +1 -1
- package/dist/ports/model.port.js.map +1 -1
- package/dist/ports/provider.port.d.ts +13 -0
- package/dist/ports/provider.port.js +5 -0
- package/dist/ports/provider.port.js.map +1 -0
- package/package.json +11 -9
- package/dist/adapters/agents/autonomous-agent.adapter.js.map +0 -1
- package/dist/adapters/agents/basic-agent.adapter.js.map +0 -1
- package/dist/adapters/agents/retryable-agent.adapter.js.map +0 -1
- package/dist/adapters/utils/__tests__/ai-response-parser.test.js.map +0 -1
- package/dist/adapters/utils/ai-response-parser-error.js.map +0 -1
- package/dist/adapters/utils/ai-response-parser.js.map +0 -1
- /package/dist/adapters/utils/__tests__/{ai-response-parser.test.d.ts → structured-response-parser.test.d.ts} +0 -0
|
@@ -158,25 +158,25 @@ function _ts_generator(thisArg, body) {
|
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
160
|
/**
|
|
161
|
-
* A decorator agent that adds retry logic to an existing agent.
|
|
161
|
+
* A decorator agent that adds retry logic to an existing agent for resilient execution.
|
|
162
162
|
* @template TInput - The TypeScript type of the input
|
|
163
163
|
* @template TOutput - The TypeScript type of the output
|
|
164
|
-
*/ export var
|
|
164
|
+
*/ export var ResilientAgent = /*#__PURE__*/ function() {
|
|
165
165
|
"use strict";
|
|
166
|
-
function
|
|
166
|
+
function ResilientAgent(agent) {
|
|
167
167
|
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
|
|
168
|
-
_class_call_check(this,
|
|
168
|
+
_class_call_check(this, ResilientAgent);
|
|
169
169
|
_define_property(this, "agent", void 0);
|
|
170
170
|
_define_property(this, "name", void 0);
|
|
171
171
|
_define_property(this, "logger", void 0);
|
|
172
172
|
_define_property(this, "retries", void 0);
|
|
173
173
|
this.agent = agent;
|
|
174
174
|
var logger = options.logger, _options_retries = options.retries, retries = _options_retries === void 0 ? 1 : _options_retries;
|
|
175
|
-
this.name = "
|
|
175
|
+
this.name = "Resilient(".concat(agent.name, ")");
|
|
176
176
|
this.logger = logger;
|
|
177
177
|
this.retries = retries;
|
|
178
178
|
}
|
|
179
|
-
_create_class(
|
|
179
|
+
_create_class(ResilientAgent, [
|
|
180
180
|
{
|
|
181
181
|
key: "run",
|
|
182
182
|
value: function run(input) {
|
|
@@ -201,7 +201,9 @@ function _ts_generator(thisArg, body) {
|
|
|
201
201
|
,
|
|
202
202
|
5
|
|
203
203
|
]);
|
|
204
|
-
(_this_logger1 = this.logger) === null || _this_logger1 === void 0 ? void 0 : _this_logger1.debug("
|
|
204
|
+
(_this_logger1 = this.logger) === null || _this_logger1 === void 0 ? void 0 : _this_logger1.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts), {
|
|
205
|
+
agent: this.name
|
|
206
|
+
});
|
|
205
207
|
return [
|
|
206
208
|
4,
|
|
207
209
|
this.agent.run(input)
|
|
@@ -210,20 +212,25 @@ function _ts_generator(thisArg, body) {
|
|
|
210
212
|
result = _state.sent();
|
|
211
213
|
if (result !== null) {
|
|
212
214
|
;
|
|
213
|
-
(_this_logger3 = this.logger) === null || _this_logger3 === void 0 ? void 0 : _this_logger3.
|
|
215
|
+
(_this_logger3 = this.logger) === null || _this_logger3 === void 0 ? void 0 : _this_logger3.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts, " succeeded"), {
|
|
216
|
+
agent: this.name
|
|
217
|
+
});
|
|
214
218
|
return [
|
|
215
219
|
2,
|
|
216
220
|
result
|
|
217
221
|
];
|
|
218
222
|
}
|
|
219
|
-
(_this_logger2 = this.logger) === null || _this_logger2 === void 0 ? void 0 : _this_logger2.
|
|
223
|
+
(_this_logger2 = this.logger) === null || _this_logger2 === void 0 ? void 0 : _this_logger2.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts, " failed: agent returned null"), {
|
|
224
|
+
agent: this.name
|
|
225
|
+
});
|
|
220
226
|
return [
|
|
221
227
|
3,
|
|
222
228
|
5
|
|
223
229
|
];
|
|
224
230
|
case 4:
|
|
225
231
|
error = _state.sent();
|
|
226
|
-
(_this_logger4 = this.logger) === null || _this_logger4 === void 0 ? void 0 : _this_logger4.
|
|
232
|
+
(_this_logger4 = this.logger) === null || _this_logger4 === void 0 ? void 0 : _this_logger4.debug("Attempt ".concat(attempt, " of ").concat(maxAttempts, " failed with an error"), {
|
|
233
|
+
agent: this.name,
|
|
227
234
|
error: _instanceof(error, Error) ? error.message : 'Unknown error'
|
|
228
235
|
});
|
|
229
236
|
return [
|
|
@@ -237,7 +244,9 @@ function _ts_generator(thisArg, body) {
|
|
|
237
244
|
1
|
|
238
245
|
];
|
|
239
246
|
case 6:
|
|
240
|
-
(_this_logger = this.logger) === null || _this_logger === void 0 ? void 0 : _this_logger.error("
|
|
247
|
+
(_this_logger = this.logger) === null || _this_logger === void 0 ? void 0 : _this_logger.error("All ".concat(maxAttempts, " attempts failed"), {
|
|
248
|
+
agent: this.name
|
|
249
|
+
});
|
|
241
250
|
return [
|
|
242
251
|
2,
|
|
243
252
|
null
|
|
@@ -248,7 +257,7 @@ function _ts_generator(thisArg, body) {
|
|
|
248
257
|
}
|
|
249
258
|
}
|
|
250
259
|
]);
|
|
251
|
-
return
|
|
260
|
+
return ResilientAgent;
|
|
252
261
|
}();
|
|
253
262
|
|
|
254
|
-
//# sourceMappingURL=
|
|
263
|
+
//# sourceMappingURL=resilient-agent.adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/adapters/agents/resilient-agent.adapter.ts"],"sourcesContent":["import { type LoggerPort } from '@jterrazz/logger';\n\nimport { type AgentPort } from '../../ports/agent.port.js';\nimport type { PromptPort } from '../../ports/prompt.port.js';\n\nexport interface ResilientAgentOptions {\n logger?: LoggerPort;\n retries?: number;\n}\n\n/**\n * A decorator agent that adds retry logic to an existing agent for resilient execution.\n * @template TInput - The TypeScript type of the input\n * @template TOutput - The TypeScript type of the output\n */\nexport class ResilientAgent<TInput = PromptPort, TOutput = string>\n implements AgentPort<TInput, TOutput>\n{\n public readonly name: string;\n private readonly logger?: LoggerPort;\n private readonly retries: number;\n\n constructor(\n private readonly agent: AgentPort<TInput, TOutput>,\n options: ResilientAgentOptions = {},\n ) {\n const { logger, retries = 1 } = options;\n this.name = `Resilient(${agent.name})`;\n this.logger = logger;\n this.retries = retries;\n }\n\n async run(input?: TInput): Promise<null | TOutput> {\n const maxAttempts = this.retries + 1;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n this.logger?.debug(`Attempt ${attempt} of ${maxAttempts}`, { agent: this.name });\n const result = await this.agent.run(input);\n\n if (result !== null) {\n this.logger?.debug(`Attempt ${attempt} of ${maxAttempts} succeeded`, {\n agent: this.name,\n });\n return result;\n }\n\n this.logger?.debug(\n `Attempt ${attempt} of ${maxAttempts} failed: agent returned null`,\n { agent: this.name },\n );\n } catch (error) {\n this.logger?.debug(`Attempt ${attempt} of ${maxAttempts} failed with an error`, {\n agent: this.name,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n }\n }\n\n this.logger?.error(`All ${maxAttempts} attempts failed`, { agent: this.name });\n return null;\n }\n}\n"],"names":["ResilientAgent","agent","options","name","logger","retries","run","input","maxAttempts","attempt","result","error","debug","Error","message"],"m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,IAAI;oCACpB;oCACA;;wCAAOO;;gCACX;iCAEA,gBAAA,IAAI,CAACN,MAAM,cAAX,oCAAA,cAAaQ,KAAK,CACd,AAAC,WAAwBJ,OAAdC,SAAQ,QAAkB,OAAZD,aAAY,iCACrC;oCAAEP,OAAO,IAAI,CAACE,IAAI;gCAAC;;;;;;gCAElBQ;iCACL,gBAAA,IAAI,CAACP,MAAM,cAAX,oCAAA,cAAaQ,KAAK,CAAC,AAAC,WAAwBJ,OAAdC,SAAQ,QAAkB,OAAZD,aAAY,0BAAwB;oCAC5EP,OAAO,IAAI,CAACE,IAAI;oCAChBQ,OAAOA,AAAK,YAALA,OAAiBE,SAAQF,MAAMG,OAAO,GAAG;gCACpD;;;;;;gCApBsCL;;;;;;iCAwB9C,eAAA,IAAI,CAACL,MAAM,cAAX,mCAAA,aAAaO,KAAK,CAAC,AAAC,OAAkB,OAAZH,aAAY,qBAAmB;oCAAEP,OAAO,IAAI,CAACE,IAAI;gCAAC;gCAC5E;;oCAAO;;;;gBACX;;;;WA9CSH;IA+CZ"}
|
|
@@ -4,24 +4,24 @@ import { type AgentPort } from '../../ports/agent.port.js';
|
|
|
4
4
|
import type { ModelPort } from '../../ports/model.port.js';
|
|
5
5
|
import type { PromptPort } from '../../ports/prompt.port.js';
|
|
6
6
|
import type { ToolPort } from '../../ports/tool.port.js';
|
|
7
|
-
import type {
|
|
8
|
-
export interface
|
|
7
|
+
import type { SystemPrompt } from '../prompts/system-prompt.adapter.js';
|
|
8
|
+
export interface ToolAgentOptions<TOutput = string> {
|
|
9
9
|
logger?: LoggerPort;
|
|
10
10
|
model: ModelPort;
|
|
11
11
|
schema?: z.ZodSchema<TOutput>;
|
|
12
|
-
systemPrompt:
|
|
12
|
+
systemPrompt: SystemPrompt;
|
|
13
13
|
tools: ToolPort[];
|
|
14
14
|
verbose?: boolean;
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
17
|
+
* A tool-enabled agent that uses tools and a structured prompt to accomplish tasks.
|
|
18
18
|
* It can decide whether to respond or remain silent and supports schema-validated responses.
|
|
19
19
|
* @template TOutput - The TypeScript type of the output
|
|
20
20
|
*/
|
|
21
|
-
export declare class
|
|
21
|
+
export declare class ToolAgent<TOutput = string> implements AgentPort<PromptPort, TOutput> {
|
|
22
22
|
readonly name: string;
|
|
23
23
|
private readonly options;
|
|
24
|
-
constructor(name: string, options:
|
|
24
|
+
constructor(name: string, options: ToolAgentOptions<TOutput>);
|
|
25
25
|
run(input?: PromptPort): Promise<null | TOutput>;
|
|
26
26
|
private createExecutor;
|
|
27
27
|
private parseAgentOutput;
|
|
@@ -160,22 +160,22 @@ function _ts_generator(thisArg, body) {
|
|
|
160
160
|
import { ChatPromptTemplate } from '@langchain/core/prompts';
|
|
161
161
|
import { AgentExecutor, createStructuredChatAgent } from 'langchain/agents';
|
|
162
162
|
import { z } from 'zod/v4';
|
|
163
|
-
import {
|
|
163
|
+
import { StructuredResponseParser } from '../utils/structured-response-parser.js';
|
|
164
164
|
var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<GLOBAL_WRAPPER_OUTPUT_FORMAT>\nCRITICAL: The format instructions in this section are the ONLY valid way to structure your response. Your entire response MUST be a single JSON markdown code block. Any formatting guidelines within the <OBJECTIVE> section apply ONLY to the content inside the "RESPOND:" part of your final "action_input".\n\nREQUIRED: You have two ways to respond:\n\n1. **Call a tool** to gather information. For this, you MUST output a JSON blob with the tool\'s name and its input.\n *Valid tool names are: {tool_names}*\n ```json\n {{\n "action": "tool_name_to_use",\n "action_input": "the input for the tool, or an empty object {{}} if no input is needed"\n }}\n ```\n\n2. **Provide the Final Answer** once you have enough information. For this, you MUST output a JSON blob with the "Final Answer" action.\n The "action_input" for a "Final Answer" MUST be a string that begins with either "RESPOND: " for a message or "SILENT: " for no message. This prefix is a literal part of the output string and MUST NOT be omitted.\n - To send a message:\n ```json\n {{\n "action": "Final Answer",\n "action_input": "RESPOND: <your response message>"\n }}\n ```\n - To stay silent:\n ```json\n {{\n "action": "Final Answer",\n "action_input": "SILENT: <your reason for staying silent>"\n }}\n ```\n\n YOU MUST ALWAYS INCLUDE "RESPOND:" OR "SILENT:" IN YOUR FINAL ANSWER\'S "action_input". FAILURE TO DO SO WILL CAUSE AN ERROR.\n\n{schema_format}\n</OUTPUT_FORMAT>\n\n<EXECUTION_CONTEXT>\nThis is internal data for your reference.\n\n<TOOLS>\n{tools}\n</TOOLS>\n\n<WORKING_MEMORY>\nThis is your internal thought process and previous tool usage.\n{agent_scratchpad}\n</WORKING_MEMORY>\n</EXECUTION_CONTEXT>\n';
|
|
165
165
|
/**
|
|
166
|
-
*
|
|
166
|
+
* A tool-enabled agent that uses tools and a structured prompt to accomplish tasks.
|
|
167
167
|
* It can decide whether to respond or remain silent and supports schema-validated responses.
|
|
168
168
|
* @template TOutput - The TypeScript type of the output
|
|
169
|
-
*/ export var
|
|
169
|
+
*/ export var ToolAgent = /*#__PURE__*/ function() {
|
|
170
170
|
"use strict";
|
|
171
|
-
function
|
|
172
|
-
_class_call_check(this,
|
|
171
|
+
function ToolAgent(name, options) {
|
|
172
|
+
_class_call_check(this, ToolAgent);
|
|
173
173
|
_define_property(this, "name", void 0);
|
|
174
174
|
_define_property(this, "options", void 0);
|
|
175
175
|
this.name = name;
|
|
176
176
|
this.options = options;
|
|
177
177
|
}
|
|
178
|
-
_create_class(
|
|
178
|
+
_create_class(ToolAgent, [
|
|
179
179
|
{
|
|
180
180
|
key: "run",
|
|
181
181
|
value: function run(input) {
|
|
@@ -184,7 +184,9 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
184
184
|
return _ts_generator(this, function(_state) {
|
|
185
185
|
switch(_state.label){
|
|
186
186
|
case 0:
|
|
187
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug(
|
|
187
|
+
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug('Starting chat execution', {
|
|
188
|
+
agent: this.name
|
|
189
|
+
});
|
|
188
190
|
_state.label = 1;
|
|
189
191
|
case 1:
|
|
190
192
|
_state.trys.push([
|
|
@@ -208,7 +210,8 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
208
210
|
];
|
|
209
211
|
case 3:
|
|
210
212
|
result = _state.sent();
|
|
211
|
-
(_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug(
|
|
213
|
+
(_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Agent execution completed', {
|
|
214
|
+
agent: this.name,
|
|
212
215
|
hasOutput: 'output' in result
|
|
213
216
|
});
|
|
214
217
|
if (!result || typeof result.output !== 'string') {
|
|
@@ -223,7 +226,8 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
223
226
|
}
|
|
224
227
|
if (!agentResponse.shouldRespond) {
|
|
225
228
|
;
|
|
226
|
-
(_this_options_logger2 = this.options.logger) === null || _this_options_logger2 === void 0 ? void 0 : _this_options_logger2.
|
|
229
|
+
(_this_options_logger2 = this.options.logger) === null || _this_options_logger2 === void 0 ? void 0 : _this_options_logger2.debug('Agent chose to remain silent', {
|
|
230
|
+
agent: this.name,
|
|
227
231
|
reason: agentResponse.reason
|
|
228
232
|
});
|
|
229
233
|
return [
|
|
@@ -235,14 +239,18 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
235
239
|
if (this.options.schema) {
|
|
236
240
|
;
|
|
237
241
|
validatedResponse = this.validateResponseContent(message, this.options.schema);
|
|
238
|
-
(_this_options_logger3 = this.options.logger) === null || _this_options_logger3 === void 0 ? void 0 : _this_options_logger3.
|
|
242
|
+
(_this_options_logger3 = this.options.logger) === null || _this_options_logger3 === void 0 ? void 0 : _this_options_logger3.debug('Execution finished; response content validated.', {
|
|
243
|
+
agent: this.name
|
|
244
|
+
});
|
|
239
245
|
return [
|
|
240
246
|
2,
|
|
241
247
|
validatedResponse
|
|
242
248
|
];
|
|
243
249
|
} else {
|
|
244
250
|
;
|
|
245
|
-
(_this_options_logger4 = this.options.logger) === null || _this_options_logger4 === void 0 ? void 0 : _this_options_logger4.
|
|
251
|
+
(_this_options_logger4 = this.options.logger) === null || _this_options_logger4 === void 0 ? void 0 : _this_options_logger4.debug('Execution finished', {
|
|
252
|
+
agent: this.name
|
|
253
|
+
});
|
|
246
254
|
// When no schema is provided, we assume TOutput is string (default), so message is the result
|
|
247
255
|
return [
|
|
248
256
|
2,
|
|
@@ -255,7 +263,8 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
255
263
|
];
|
|
256
264
|
case 4:
|
|
257
265
|
error = _state.sent();
|
|
258
|
-
(_this_options_logger5 = this.options.logger) === null || _this_options_logger5 === void 0 ? void 0 : _this_options_logger5.error(
|
|
266
|
+
(_this_options_logger5 = this.options.logger) === null || _this_options_logger5 === void 0 ? void 0 : _this_options_logger5.error('Chat execution failed', {
|
|
267
|
+
agent: this.name,
|
|
259
268
|
error: _instanceof(error, Error) ? error.message : 'Unknown error'
|
|
260
269
|
});
|
|
261
270
|
return [
|
|
@@ -279,7 +288,7 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
279
288
|
return _ts_generator(this, function(_state) {
|
|
280
289
|
switch(_state.label){
|
|
281
290
|
case 0:
|
|
282
|
-
model = this.options.model.
|
|
291
|
+
model = this.options.model.getLangchainModel();
|
|
283
292
|
tools = this.options.tools.map(function(tool) {
|
|
284
293
|
return tool.getDynamicTool();
|
|
285
294
|
});
|
|
@@ -352,7 +361,8 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
352
361
|
shouldRespond: false
|
|
353
362
|
};
|
|
354
363
|
}
|
|
355
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error("
|
|
364
|
+
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error("Agent output was missing 'RESPOND:' or 'SILENT:' prefix.", {
|
|
365
|
+
agent: this.name,
|
|
356
366
|
rawOutput: output
|
|
357
367
|
});
|
|
358
368
|
return null;
|
|
@@ -371,10 +381,11 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
371
381
|
key: "validateResponseContent",
|
|
372
382
|
value: function validateResponseContent(content, schema) {
|
|
373
383
|
try {
|
|
374
|
-
return new
|
|
384
|
+
return new StructuredResponseParser(schema).parse(content);
|
|
375
385
|
} catch (error) {
|
|
376
386
|
var _this_options_logger;
|
|
377
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error(
|
|
387
|
+
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error('Failed to validate response content against schema.', {
|
|
388
|
+
agent: this.name,
|
|
378
389
|
error: _instanceof(error, Error) ? error.message : 'Unknown error',
|
|
379
390
|
rawContent: content
|
|
380
391
|
});
|
|
@@ -383,7 +394,7 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
|
|
|
383
394
|
}
|
|
384
395
|
}
|
|
385
396
|
]);
|
|
386
|
-
return
|
|
397
|
+
return ToolAgent;
|
|
387
398
|
}();
|
|
388
399
|
|
|
389
|
-
//# sourceMappingURL=
|
|
400
|
+
//# sourceMappingURL=tool-agent.adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/adapters/agents/tool-agent.adapter.ts"],"sourcesContent":["import { type LoggerPort } from '@jterrazz/logger';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\nimport { AgentExecutor, createStructuredChatAgent } from 'langchain/agents';\nimport { z } from 'zod/v4';\n\nimport { type AgentPort } from '../../ports/agent.port.js';\nimport type { ModelPort } from '../../ports/model.port.js';\nimport type { PromptPort } from '../../ports/prompt.port.js';\nimport type { ToolPort } from '../../ports/tool.port.js';\n\nimport { StructuredResponseParser } from '../utils/structured-response-parser.js';\n\nimport type { SystemPrompt } from '../prompts/system-prompt.adapter.js';\n\nexport interface ToolAgentOptions<TOutput = string> {\n logger?: LoggerPort;\n model: ModelPort;\n schema?: z.ZodSchema<TOutput>;\n systemPrompt: SystemPrompt;\n tools: ToolPort[];\n verbose?: boolean;\n}\n\nconst SYSTEM_PROMPT_TEMPLATE = `\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<GLOBAL_WRAPPER_OUTPUT_FORMAT>\nCRITICAL: The format instructions in this section are the ONLY valid way to structure your response. Your entire response MUST be a single JSON markdown code block. Any formatting guidelines within the <OBJECTIVE> section apply ONLY to the content inside the \"RESPOND:\" part of your final \"action_input\".\n\nREQUIRED: You have two ways to respond:\n\n1. **Call a tool** to gather information. For this, you MUST output a JSON blob with the tool's name and its input.\n *Valid tool names are: {tool_names}*\n \\`\\`\\`json\n {{\n \"action\": \"tool_name_to_use\",\n \"action_input\": \"the input for the tool, or an empty object {{}} if no input is needed\"\n }}\n \\`\\`\\`\n\n2. **Provide the Final Answer** once you have enough information. For this, you MUST output a JSON blob with the \"Final Answer\" action.\n The \"action_input\" for a \"Final Answer\" MUST be a string that begins with either \"RESPOND: \" for a message or \"SILENT: \" for no message. This prefix is a literal part of the output string and MUST NOT be omitted.\n - To send a message:\n \\`\\`\\`json\n {{\n \"action\": \"Final Answer\",\n \"action_input\": \"RESPOND: <your response message>\"\n }}\n \\`\\`\\`\n - To stay silent:\n \\`\\`\\`json\n {{\n \"action\": \"Final Answer\",\n \"action_input\": \"SILENT: <your reason for staying silent>\"\n }}\n \\`\\`\\`\n\n YOU MUST ALWAYS INCLUDE \"RESPOND:\" OR \"SILENT:\" IN YOUR FINAL ANSWER'S \"action_input\". FAILURE TO DO SO WILL CAUSE AN ERROR.\n\n{schema_format}\n</OUTPUT_FORMAT>\n\n<EXECUTION_CONTEXT>\nThis is internal data for your reference.\n\n<TOOLS>\n{tools}\n</TOOLS>\n\n<WORKING_MEMORY>\nThis is your internal thought process and previous tool usage.\n{agent_scratchpad}\n</WORKING_MEMORY>\n</EXECUTION_CONTEXT>\n`;\n\n/**\n * A tool-enabled agent that uses tools and a structured prompt to accomplish tasks.\n * It can decide whether to respond or remain silent and supports schema-validated responses.\n * @template TOutput - The TypeScript type of the output\n */\nexport class ToolAgent<TOutput = string> implements AgentPort<PromptPort, TOutput> {\n constructor(\n public readonly name: string,\n private readonly options: ToolAgentOptions<TOutput>,\n ) {}\n\n async run(input?: PromptPort): Promise<null | TOutput> {\n this.options.logger?.debug('Starting chat execution', { agent: this.name });\n\n try {\n const executor = await this.createExecutor();\n const userInput = this.resolveUserInput(input);\n\n const result = await executor.invoke({ input: userInput });\n\n this.options.logger?.debug('Agent execution completed', {\n agent: this.name,\n hasOutput: 'output' in result,\n });\n\n if (!result || typeof result.output !== 'string') {\n throw new Error('Agent returned an invalid result structure.');\n }\n\n const agentResponse = this.parseAgentOutput(result.output);\n\n if (!agentResponse) {\n return null;\n }\n\n if (!agentResponse.shouldRespond) {\n this.options.logger?.debug('Agent chose to remain silent', {\n agent: this.name,\n reason: agentResponse.reason,\n });\n return null;\n }\n\n const message = agentResponse.message ?? '';\n\n if (this.options.schema) {\n const validatedResponse = this.validateResponseContent(\n message,\n this.options.schema,\n );\n\n this.options.logger?.debug('Execution finished; response content validated.', {\n agent: this.name,\n });\n return validatedResponse;\n } else {\n this.options.logger?.debug('Execution finished', { agent: this.name });\n // When no schema is provided, we assume TOutput is string (default), so message is the result\n return message as TOutput;\n }\n } catch (error) {\n this.options.logger?.error('Chat execution failed', {\n agent: this.name,\n error: error instanceof Error ? error.message : 'Unknown error',\n });\n return null;\n }\n }\n\n private async createExecutor(): Promise<AgentExecutor> {\n const model = this.options.model.getLangchainModel();\n const tools = this.options.tools.map((tool) => tool.getDynamicTool());\n\n // Add schema format instructions if schema is provided\n let schemaFormatInstructions = '';\n if (this.options.schema) {\n const jsonSchema = z.toJSONSchema(this.options.schema);\n const isPrimitiveType = ['boolean', 'integer', 'number', 'string'].includes(\n jsonSchema.type as string,\n );\n const jsonSchemaString = JSON.stringify(jsonSchema, null, 2)\n .replace(/{/g, '{{')\n .replace(/}/g, '}}');\n\n if (isPrimitiveType) {\n schemaFormatInstructions = `\n\nSCHEMA VALIDATION: When providing a \"RESPOND:\" answer, the content after \"RESPOND: \" must be a ${jsonSchema.type} value that matches this schema description:\n\n\\`\\`\\`json\n${jsonSchemaString}\n\\`\\`\\`\n\nExample format:\n\\`\\`\\`json\n{{\n \"action\": \"Final Answer\",\n \"action_input\": \"RESPOND: your ${jsonSchema.type} value here\"\n}}\n\\`\\`\\`\n\nDo not wrap the ${jsonSchema.type} value in JSON - just provide the raw value after \"RESPOND: \".`;\n } else {\n schemaFormatInstructions = `\n\nSCHEMA VALIDATION: When providing a \"RESPOND:\" answer, the content after \"RESPOND: \" must be valid JSON that matches this JSON schema description:\n\n\\`\\`\\`json\n${jsonSchemaString}\n\\`\\`\\`\n\nExample format:\n\\`\\`\\`json\n{{\n \"action\": \"Final Answer\",\n \"action_input\": \"RESPOND: {{\\\\\"field1\\\\\": \\\\\"value1\\\\\", \\\\\"field2\\\\\": \\\\\"value2\\\\\"}}\"\n}}\n\\`\\`\\`\n`;\n }\n }\n\n const prompt = ChatPromptTemplate.fromMessages([\n [\n 'system',\n SYSTEM_PROMPT_TEMPLATE.replace(\n '{mission_prompt}',\n this.options.systemPrompt.generate(),\n ).replace('{schema_format}', schemaFormatInstructions),\n ],\n ['human', '{input}'],\n ]);\n\n const agent = await createStructuredChatAgent({\n llm: model,\n prompt,\n tools,\n });\n\n return AgentExecutor.fromAgentAndTools({\n agent,\n tools,\n verbose: this.options.verbose,\n });\n }\n\n private parseAgentOutput(output: string): null | {\n message?: string;\n reason?: string;\n shouldRespond: boolean;\n } {\n const text = output.trim();\n\n const respondMatch = text.match(/^RESPOND:\\s*([\\s\\S]+)$/i);\n if (respondMatch) {\n return { message: respondMatch[1].trim(), shouldRespond: true };\n }\n\n const silentMatch = text.match(/^SILENT:\\s*([\\s\\S]+)$/i);\n if (silentMatch) {\n return { reason: silentMatch[1].trim(), shouldRespond: false };\n }\n\n this.options.logger?.error(\"Agent output was missing 'RESPOND:' or 'SILENT:' prefix.\", {\n agent: this.name,\n rawOutput: output,\n });\n\n return null;\n }\n\n private resolveUserInput(input?: PromptPort): string {\n if (input) {\n return input.generate();\n }\n return 'Proceed with your instructions.';\n }\n\n private validateResponseContent<TResponse>(\n content: string,\n schema: z.ZodSchema<TResponse>,\n ): TResponse {\n try {\n return new StructuredResponseParser(schema).parse(content);\n } catch (error) {\n this.options.logger?.error('Failed to validate response content against schema.', {\n agent: this.name,\n error: error instanceof Error ? error.message : 'Unknown error',\n rawContent: content,\n });\n throw new Error('Invalid response content from model.');\n }\n }\n}\n"],"names":["ChatPromptTemplate","AgentExecutor","createStructuredChatAgent","z","StructuredResponseParser","SYSTEM_PROMPT_TEMPLATE","ToolAgent","name","options","run","input","executor","userInput","result","agentResponse","message","validatedResponse","error","logger","debug","agent","createExecutor","resolveUserInput","invoke","hasOutput","output","Error","parseAgentOutput","shouldRespond","reason","schema","validateResponseContent","model","tools","schemaFormatInstructions","jsonSchema","isPrimitiveType","jsonSchemaString","prompt","getLangchainModel","map","tool","getDynamicTool","toJSONSchema","includes","type","JSON","stringify","replace","fromMessages","systemPrompt","generate","llm","fromAgentAndTools","verbose","text","trim","respondMatch","match","silentMatch","rawOutput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|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
metadata?: OpenRouterMetadata;
|
|
16
|
-
/**
|
|
17
|
-
* The model to use (e.g., 'google/gemini-2.5-flash-preview-05-20:thinking')
|
|
18
|
-
*/
|
|
19
|
-
modelName: string;
|
|
20
|
-
}
|
|
21
|
-
export interface OpenRouterMetadata {
|
|
2
|
+
import type { LanguageModelV1 } from 'ai';
|
|
3
|
+
import type { ModelConfig, ModelPort } from '../../ports/model.port.js';
|
|
4
|
+
import type { OpenRouterConfig } from '../providers/openrouter-provider.adapter.js';
|
|
5
|
+
/**
|
|
6
|
+
* OpenRouter model wrapper supporting both LangChain and Vercel AI SDK
|
|
7
|
+
*/
|
|
8
|
+
export declare class OpenRouterModel implements ModelPort {
|
|
9
|
+
private readonly providerConfig;
|
|
10
|
+
private readonly modelName;
|
|
11
|
+
private readonly langchainModel;
|
|
12
|
+
private readonly modelConfig;
|
|
13
|
+
private readonly vercelModel;
|
|
14
|
+
constructor(providerConfig: OpenRouterConfig, modelName: string, modelConfig?: ModelConfig);
|
|
22
15
|
/**
|
|
23
|
-
*
|
|
16
|
+
* Get the configured LangChain language model instance
|
|
24
17
|
*/
|
|
25
|
-
|
|
18
|
+
getLangchainModel(): BaseLanguageModel;
|
|
26
19
|
/**
|
|
27
|
-
*
|
|
20
|
+
* Get the configured Vercel AI SDK language model instance
|
|
28
21
|
*/
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* OpenRouter adapter that provides access to various models through OpenRouter's API
|
|
33
|
-
*/
|
|
34
|
-
export declare class OpenRouterModelAdapter implements ModelPort {
|
|
35
|
-
private readonly model;
|
|
36
|
-
constructor(config: OpenRouterConfig);
|
|
37
|
-
getModel(): BaseLanguageModel;
|
|
22
|
+
getVercelModel(): LanguageModelV1;
|
|
38
23
|
}
|
|
@@ -45,45 +45,104 @@ function _object_spread(target) {
|
|
|
45
45
|
}
|
|
46
46
|
return target;
|
|
47
47
|
}
|
|
48
|
+
function ownKeys(object, enumerableOnly) {
|
|
49
|
+
var keys = Object.keys(object);
|
|
50
|
+
if (Object.getOwnPropertySymbols) {
|
|
51
|
+
var symbols = Object.getOwnPropertySymbols(object);
|
|
52
|
+
if (enumerableOnly) {
|
|
53
|
+
symbols = symbols.filter(function(sym) {
|
|
54
|
+
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
keys.push.apply(keys, symbols);
|
|
58
|
+
}
|
|
59
|
+
return keys;
|
|
60
|
+
}
|
|
61
|
+
function _object_spread_props(target, source) {
|
|
62
|
+
source = source != null ? source : {};
|
|
63
|
+
if (Object.getOwnPropertyDescriptors) {
|
|
64
|
+
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
|
|
65
|
+
} else {
|
|
66
|
+
ownKeys(Object(source)).forEach(function(key) {
|
|
67
|
+
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return target;
|
|
71
|
+
}
|
|
48
72
|
import { ChatOpenAI } from '@langchain/openai';
|
|
73
|
+
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
|
|
49
74
|
/**
|
|
50
|
-
* OpenRouter
|
|
51
|
-
*/ export var
|
|
75
|
+
* OpenRouter model wrapper supporting both LangChain and Vercel AI SDK
|
|
76
|
+
*/ export var OpenRouterModel = /*#__PURE__*/ function() {
|
|
52
77
|
"use strict";
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
this
|
|
78
|
+
function OpenRouterModel(providerConfig, modelName) {
|
|
79
|
+
var modelConfig = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
|
|
80
|
+
_class_call_check(this, OpenRouterModel);
|
|
81
|
+
var _this_providerConfig_metadata, _this_providerConfig_metadata1;
|
|
82
|
+
_define_property(this, "providerConfig", void 0);
|
|
83
|
+
_define_property(this, "modelName", void 0);
|
|
84
|
+
_define_property(this, "langchainModel", void 0);
|
|
85
|
+
_define_property(this, "modelConfig", void 0);
|
|
86
|
+
_define_property(this, "vercelModel", void 0);
|
|
87
|
+
this.providerConfig = providerConfig;
|
|
88
|
+
this.modelName = modelName;
|
|
89
|
+
this.modelConfig = _object_spread({
|
|
90
|
+
maxTokens: 256000,
|
|
91
|
+
reasoning: {
|
|
92
|
+
effort: 'high',
|
|
93
|
+
exclude: true
|
|
94
|
+
}
|
|
95
|
+
}, modelConfig);
|
|
96
|
+
// LangChain model setup
|
|
97
|
+
this.langchainModel = new ChatOpenAI(_object_spread_props(_object_spread({
|
|
59
98
|
configuration: {
|
|
60
99
|
baseURL: 'https://openrouter.ai/api/v1',
|
|
61
|
-
defaultHeaders: _object_spread({}, ((
|
|
62
|
-
'HTTP-Referer':
|
|
63
|
-
}, ((
|
|
64
|
-
'X-Title':
|
|
100
|
+
defaultHeaders: _object_spread({}, ((_this_providerConfig_metadata = this.providerConfig.metadata) === null || _this_providerConfig_metadata === void 0 ? void 0 : _this_providerConfig_metadata.website) && {
|
|
101
|
+
'HTTP-Referer': this.providerConfig.metadata.website
|
|
102
|
+
}, ((_this_providerConfig_metadata1 = this.providerConfig.metadata) === null || _this_providerConfig_metadata1 === void 0 ? void 0 : _this_providerConfig_metadata1.application) && {
|
|
103
|
+
'X-Title': this.providerConfig.metadata.application
|
|
65
104
|
})
|
|
66
105
|
},
|
|
67
|
-
maxTokens:
|
|
106
|
+
maxTokens: this.modelConfig.maxTokens
|
|
107
|
+
}, this.modelConfig.reasoning && {
|
|
68
108
|
modelKwargs: {
|
|
69
|
-
reasoning:
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
109
|
+
reasoning: this.modelConfig.reasoning
|
|
110
|
+
}
|
|
111
|
+
}), {
|
|
112
|
+
modelName: this.modelName,
|
|
113
|
+
openAIApiKey: this.providerConfig.apiKey
|
|
114
|
+
}));
|
|
115
|
+
// Vercel AI SDK model setup
|
|
116
|
+
var openrouter = createOpenRouter({
|
|
117
|
+
apiKey: this.providerConfig.apiKey
|
|
76
118
|
});
|
|
119
|
+
this.vercelModel = openrouter(this.modelName, _object_spread({}, this.modelConfig.maxTokens && {
|
|
120
|
+
maxTokens: this.modelConfig.maxTokens
|
|
121
|
+
}, this.modelConfig.reasoning && {
|
|
122
|
+
extraBody: {
|
|
123
|
+
reasoning: this.modelConfig.reasoning
|
|
124
|
+
}
|
|
125
|
+
}));
|
|
77
126
|
}
|
|
78
|
-
_create_class(
|
|
127
|
+
_create_class(OpenRouterModel, [
|
|
128
|
+
{
|
|
129
|
+
/**
|
|
130
|
+
* Get the configured LangChain language model instance
|
|
131
|
+
*/ key: "getLangchainModel",
|
|
132
|
+
value: function getLangchainModel() {
|
|
133
|
+
return this.langchainModel;
|
|
134
|
+
}
|
|
135
|
+
},
|
|
79
136
|
{
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Get the configured Vercel AI SDK language model instance
|
|
139
|
+
*/ key: "getVercelModel",
|
|
140
|
+
value: function getVercelModel() {
|
|
141
|
+
return this.vercelModel;
|
|
83
142
|
}
|
|
84
143
|
}
|
|
85
144
|
]);
|
|
86
|
-
return
|
|
145
|
+
return OpenRouterModel;
|
|
87
146
|
}();
|
|
88
147
|
|
|
89
148
|
//# sourceMappingURL=openrouter-model.adapter.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/adapters/models/openrouter-model.adapter.ts"],"sourcesContent":["import type { BaseLanguageModel } from '@langchain/core/language_models/base';\nimport { ChatOpenAI } from '@langchain/openai';\n\nimport type { ModelPort } from '../../ports/model.port.js';\n\
|
|
1
|
+
{"version":3,"sources":["../../../src/adapters/models/openrouter-model.adapter.ts"],"sourcesContent":["import type { BaseLanguageModel } from '@langchain/core/language_models/base';\nimport { ChatOpenAI } from '@langchain/openai';\nimport { createOpenRouter } from '@openrouter/ai-sdk-provider';\nimport type { LanguageModelV1 } from 'ai';\n\nimport type { ModelConfig, ModelPort } from '../../ports/model.port.js';\n\nimport type { OpenRouterConfig } from '../providers/openrouter-provider.adapter.js';\n\n/**\n * OpenRouter model wrapper supporting both LangChain and Vercel AI SDK\n */\nexport class OpenRouterModel implements ModelPort {\n private readonly langchainModel: BaseLanguageModel;\n private readonly modelConfig: ModelConfig;\n private readonly vercelModel: LanguageModelV1;\n\n constructor(\n private readonly providerConfig: OpenRouterConfig,\n private readonly modelName: string,\n modelConfig: ModelConfig = {},\n ) {\n this.modelConfig = {\n maxTokens: 256_000,\n reasoning: {\n effort: 'high',\n exclude: true,\n },\n ...modelConfig,\n };\n\n // LangChain model setup\n this.langchainModel = new ChatOpenAI({\n configuration: {\n baseURL: 'https://openrouter.ai/api/v1',\n defaultHeaders: {\n ...(this.providerConfig.metadata?.website && {\n 'HTTP-Referer': this.providerConfig.metadata.website,\n }),\n ...(this.providerConfig.metadata?.application && {\n 'X-Title': this.providerConfig.metadata.application,\n }),\n },\n },\n maxTokens: this.modelConfig.maxTokens,\n ...(this.modelConfig.reasoning && {\n modelKwargs: {\n reasoning: this.modelConfig.reasoning,\n },\n }),\n modelName: this.modelName,\n openAIApiKey: this.providerConfig.apiKey,\n });\n\n // Vercel AI SDK model setup\n const openrouter = createOpenRouter({\n apiKey: this.providerConfig.apiKey,\n });\n\n this.vercelModel = openrouter(this.modelName, {\n ...(this.modelConfig.maxTokens && { maxTokens: this.modelConfig.maxTokens }),\n ...(this.modelConfig.reasoning && {\n extraBody: {\n reasoning: this.modelConfig.reasoning,\n },\n }),\n });\n }\n\n /**\n * Get the configured LangChain language model instance\n */\n getLangchainModel(): BaseLanguageModel {\n return this.langchainModel;\n }\n\n /**\n * Get the configured Vercel AI SDK language model instance\n */\n getVercelModel(): LanguageModelV1 {\n return this.vercelModel;\n }\n}\n"],"names":["ChatOpenAI","createOpenRouter","OpenRouterModel","providerConfig","modelName","modelConfig","langchainModel","vercelModel","maxTokens","reasoning","effort","exclude","configuration","baseURL","defaultHeaders","metadata","website","application","modelKwargs","openAIApiKey","apiKey","openrouter","extraBody","getLangchainModel","getVercelModel"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,UAAU,QAAQ,oBAAoB;AAC/C,SAASC,gBAAgB,QAAQ,8BAA8B;AAO/D;;CAEC,GACD,OAAO,IAAA,AAAMC,gCAAN;;aAAMA,gBAML,AAAiBC,cAAgC,EACjD,AAAiBC,SAAiB;YAClCC,cAAAA,iEAA2B,CAAC;gCARvBH;YAwBW,+BAGA;;;QA1BpB,uBAAiBI,kBAAjB,KAAA;QACA,uBAAiBD,eAAjB,KAAA;QACA,uBAAiBE,eAAjB,KAAA;aAGqBJ,iBAAAA;aACAC,YAAAA;QAGjB,IAAI,CAACC,WAAW,GAAG;YACfG,WAAW;YACXC,WAAW;gBACPC,QAAQ;gBACRC,SAAS;YACb;WACGN;QAGP,wBAAwB;QACxB,IAAI,CAACC,cAAc,GAAG,IAAIN,WAAW;YACjCY,eAAe;gBACXC,SAAS;gBACTC,gBAAgB,mBACR,EAAA,gCAAA,IAAI,CAACX,cAAc,CAACY,QAAQ,cAA5B,oDAAA,8BAA8BC,OAAO,KAAI;oBACzC,gBAAgB,IAAI,CAACb,cAAc,CAACY,QAAQ,CAACC,OAAO;gBACxD,GACI,EAAA,iCAAA,IAAI,CAACb,cAAc,CAACY,QAAQ,cAA5B,qDAAA,+BAA8BE,WAAW,KAAI;oBAC7C,WAAW,IAAI,CAACd,cAAc,CAACY,QAAQ,CAACE,WAAW;gBACvD;YAER;YACAT,WAAW,IAAI,CAACH,WAAW,CAACG,SAAS;WACjC,IAAI,CAACH,WAAW,CAACI,SAAS,IAAI;YAC9BS,aAAa;gBACTT,WAAW,IAAI,CAACJ,WAAW,CAACI,SAAS;YACzC;QACJ;YACAL,WAAW,IAAI,CAACA,SAAS;YACzBe,cAAc,IAAI,CAAChB,cAAc,CAACiB,MAAM;;QAG5C,4BAA4B;QAC5B,IAAMC,aAAapB,iBAAiB;YAChCmB,QAAQ,IAAI,CAACjB,cAAc,CAACiB,MAAM;QACtC;QAEA,IAAI,CAACb,WAAW,GAAGc,WAAW,IAAI,CAACjB,SAAS,EAAE,mBACtC,IAAI,CAACC,WAAW,CAACG,SAAS,IAAI;YAAEA,WAAW,IAAI,CAACH,WAAW,CAACG,SAAS;QAAC,GACtE,IAAI,CAACH,WAAW,CAACI,SAAS,IAAI;YAC9Ba,WAAW;gBACPb,WAAW,IAAI,CAACJ,WAAW,CAACI,SAAS;YACzC;QACJ;;kBArDCP;;YAyDT;;KAEC,GACDqB,KAAAA;mBAAAA,SAAAA;gBACI,OAAO,IAAI,CAACjB,cAAc;YAC9B;;;YAEA;;KAEC,GACDkB,KAAAA;mBAAAA,SAAAA;gBACI,OAAO,IAAI,CAACjB,WAAW;YAC3B;;;WArESL;IAsEZ"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { describe, expect, it } from '@jterrazz/test';
|
|
2
2
|
import { PROMPT_LIBRARY } from '../library/index.js';
|
|
3
|
-
import {
|
|
3
|
+
import { SystemPrompt } from '../system-prompt.adapter.js';
|
|
4
4
|
describe('Prompt Library Presets', function() {
|
|
5
5
|
it('should generate the correct prompt for DISCORD_COMMUNITY_ANIMATOR', function() {
|
|
6
6
|
// Given - a Discord community animator preset
|
|
7
|
-
var prompt = new
|
|
7
|
+
var prompt = new SystemPrompt(PROMPT_LIBRARY.PRESETS.COMMUNITY_ANIMATOR);
|
|
8
8
|
// When - generating the prompt
|
|
9
9
|
var result = prompt.generate();
|
|
10
10
|
// Then - it should match the expected snapshot
|
|
@@ -12,7 +12,7 @@ describe('Prompt Library Presets', function() {
|
|
|
12
12
|
});
|
|
13
13
|
it('should generate the correct prompt for EMPATHETIC_SUPPORT_AGENT', function() {
|
|
14
14
|
// Given - an empathetic support agent preset
|
|
15
|
-
var prompt = new
|
|
15
|
+
var prompt = new SystemPrompt(PROMPT_LIBRARY.PRESETS.EMPATHETIC_SUPPORT_AGENT);
|
|
16
16
|
// When - generating the prompt
|
|
17
17
|
var result = prompt.generate();
|
|
18
18
|
// Then - it should match the expected snapshot
|
|
@@ -20,7 +20,7 @@ describe('Prompt Library Presets', function() {
|
|
|
20
20
|
});
|
|
21
21
|
it('should generate the correct prompt for CREATIVE_BRAINSTORMER', function() {
|
|
22
22
|
// Given - a creative brainstormer preset
|
|
23
|
-
var prompt = new
|
|
23
|
+
var prompt = new SystemPrompt(PROMPT_LIBRARY.PRESETS.CREATIVE_BRAINSTORMER);
|
|
24
24
|
// When - generating the prompt
|
|
25
25
|
var result = prompt.generate();
|
|
26
26
|
// Then - it should match the expected snapshot
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/adapters/prompts/__tests__/presets.test.ts"],"sourcesContent":["import { describe, expect, it } from '@jterrazz/test';\n\nimport { PROMPT_LIBRARY } from '../library/index.js';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/adapters/prompts/__tests__/presets.test.ts"],"sourcesContent":["import { describe, expect, it } from '@jterrazz/test';\n\nimport { PROMPT_LIBRARY } from '../library/index.js';\nimport { SystemPrompt } from '../system-prompt.adapter.js';\n\ndescribe('Prompt Library Presets', () => {\n it('should generate the correct prompt for DISCORD_COMMUNITY_ANIMATOR', () => {\n // Given - a Discord community animator preset\n const prompt = new SystemPrompt(PROMPT_LIBRARY.PRESETS.COMMUNITY_ANIMATOR);\n\n // When - generating the prompt\n const result = prompt.generate();\n\n // Then - it should match the expected snapshot\n expect(result).toMatchSnapshot();\n });\n\n it('should generate the correct prompt for EMPATHETIC_SUPPORT_AGENT', () => {\n // Given - an empathetic support agent preset\n const prompt = new SystemPrompt(PROMPT_LIBRARY.PRESETS.EMPATHETIC_SUPPORT_AGENT);\n\n // When - generating the prompt\n const result = prompt.generate();\n\n // Then - it should match the expected snapshot\n expect(result).toMatchSnapshot();\n });\n\n it('should generate the correct prompt for CREATIVE_BRAINSTORMER', () => {\n // Given - a creative brainstormer preset\n const prompt = new SystemPrompt(PROMPT_LIBRARY.PRESETS.CREATIVE_BRAINSTORMER);\n\n // When - generating the prompt\n const result = prompt.generate();\n\n // Then - it should match the expected snapshot\n expect(result).toMatchSnapshot();\n });\n});\n"],"names":["describe","expect","it","PROMPT_LIBRARY","SystemPrompt","prompt","PRESETS","COMMUNITY_ANIMATOR","result","generate","toMatchSnapshot","EMPATHETIC_SUPPORT_AGENT","CREATIVE_BRAINSTORMER"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,iBAAiB;AAEtD,SAASC,cAAc,QAAQ,sBAAsB;AACrD,SAASC,YAAY,QAAQ,8BAA8B;AAE3DJ,SAAS,0BAA0B;IAC/BE,GAAG,qEAAqE;QACpE,8CAA8C;QAC9C,IAAMG,SAAS,IAAID,aAAaD,eAAeG,OAAO,CAACC,kBAAkB;QAEzE,+BAA+B;QAC/B,IAAMC,SAASH,OAAOI,QAAQ;QAE9B,+CAA+C;QAC/CR,OAAOO,QAAQE,eAAe;IAClC;IAEAR,GAAG,mEAAmE;QAClE,6CAA6C;QAC7C,IAAMG,SAAS,IAAID,aAAaD,eAAeG,OAAO,CAACK,wBAAwB;QAE/E,+BAA+B;QAC/B,IAAMH,SAASH,OAAOI,QAAQ;QAE9B,+CAA+C;QAC/CR,OAAOO,QAAQE,eAAe;IAClC;IAEAR,GAAG,gEAAgE;QAC/D,yCAAyC;QACzC,IAAMG,SAAS,IAAID,aAAaD,eAAeG,OAAO,CAACM,qBAAqB;QAE5E,+BAA+B;QAC/B,IAAMJ,SAASH,OAAOI,QAAQ;QAE9B,+CAA+C;QAC/CR,OAAOO,QAAQE,eAAe;IAClC;AACJ"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { PromptPort } from '../../ports/prompt.port.js';
|
|
2
2
|
/**
|
|
3
|
-
* System prompt
|
|
3
|
+
* System prompt that generates a system prompt from a list of strings
|
|
4
4
|
*/
|
|
5
|
-
export declare class
|
|
5
|
+
export declare class SystemPrompt implements PromptPort {
|
|
6
6
|
private readonly finalPrompt;
|
|
7
7
|
constructor(...prompts: readonly (readonly string[] | string)[]);
|
|
8
8
|
generate(): string;
|