@jterrazz/intelligence 1.4.0 → 1.4.1

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.
@@ -275,7 +275,7 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
275
275
  key: "createExecutor",
276
276
  value: function createExecutor() {
277
277
  return _async_to_generator(function() {
278
- var model, tools, schemaFormatInstructions, jsonSchema, isPrimitiveType, prompt, agent;
278
+ var model, tools, schemaFormatInstructions, jsonSchema, isPrimitiveType, jsonSchemaString, prompt, agent;
279
279
  return _ts_generator(this, function(_state) {
280
280
  switch(_state.label){
281
281
  case 0:
@@ -287,17 +287,17 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
287
287
  schemaFormatInstructions = '';
288
288
  if (this.options.schema) {
289
289
  jsonSchema = z.toJSONSchema(this.options.schema);
290
- console.log(jsonSchema.type);
291
290
  isPrimitiveType = [
292
291
  'boolean',
293
292
  'integer',
294
293
  'number',
295
294
  'string'
296
295
  ].includes(jsonSchema.type);
296
+ jsonSchemaString = JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}');
297
297
  if (isPrimitiveType) {
298
- schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be a '.concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(JSON.stringify(jsonSchema, null, 2), '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: your ').concat(jsonSchema.type, ' value here"\n}}\n```\n\nDo not wrap the ').concat(jsonSchema.type, ' value in JSON - just provide the raw value after "RESPOND: ".');
298
+ schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be a '.concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: your ').concat(jsonSchema.type, ' value here"\n}}\n```\n\nDo not wrap the ').concat(jsonSchema.type, ' value in JSON - just provide the raw value after "RESPOND: ".');
299
299
  } else {
300
- schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be valid JSON that matches this exact schema:\n\n```json\n'.concat(JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}'), '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: {{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}"\n}}\n```\n');
300
+ schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be valid JSON that matches this exact schema:\n\n```json\n'.concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: {{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}"\n}}\n```\n');
301
301
  }
302
302
  }
303
303
  prompt = ChatPromptTemplate.fromMessages([
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/adapters/agents/autonomous-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 { AIResponseParser } from '../utils/ai-response-parser.js';\n\nimport type { SystemPromptAdapter } from '../prompts/system-prompt.adapter.js';\n\nexport interface AutonomousAgentOptions<TOutput = string> {\n logger?: LoggerPort;\n model: ModelPort;\n schema?: z.ZodSchema<TOutput>;\n systemPrompt: SystemPromptAdapter;\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 * An autonomous 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 AutonomousAgentAdapter<TOutput = string> implements AgentPort<PromptPort, TOutput> {\n constructor(\n public readonly name: string,\n private readonly options: AutonomousAgentOptions<TOutput>,\n ) {}\n\n async run(input?: PromptPort): Promise<null | TOutput> {\n this.options.logger?.debug(`[${this.name}] Starting chat execution.`);\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(`[${this.name}] Agent execution completed.`, {\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?.info(`[${this.name}] Agent chose to remain silent.`, {\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?.info(\n `[${this.name}] Execution finished; response content validated.`,\n );\n return validatedResponse;\n } else {\n this.options.logger?.info(`[${this.name}] Execution finished.`);\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(`[${this.name}] Chat execution failed.`, {\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.getModel();\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 console.log(jsonSchema.type);\n const isPrimitiveType = ['boolean', 'integer', 'number', 'string'].includes(\n jsonSchema.type as string,\n );\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:\n\n\\`\\`\\`json\n${JSON.stringify(jsonSchema, null, 2)}\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 exact schema:\n\n\\`\\`\\`json\n${JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}')}\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(\n `[${this.name}] Agent output was missing 'RESPOND:' or 'SILENT:' prefix.`,\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 AIResponseParser(schema).parse(content);\n } catch (error) {\n this.options.logger?.error(\n `[${this.name}] Failed to validate response content against schema.`,\n {\n error: error instanceof Error ? error.message : 'Unknown error',\n rawContent: content,\n },\n );\n throw new Error('Invalid response content from model.');\n }\n }\n}\n"],"names":["ChatPromptTemplate","AgentExecutor","createStructuredChatAgent","z","AIResponseParser","SYSTEM_PROMPT_TEMPLATE","AutonomousAgentAdapter","name","options","run","input","executor","userInput","result","agentResponse","message","validatedResponse","error","logger","debug","createExecutor","resolveUserInput","invoke","hasOutput","output","Error","parseAgentOutput","shouldRespond","info","reason","schema","validateResponseContent","model","tools","schemaFormatInstructions","jsonSchema","isPrimitiveType","prompt","agent","getModel","map","tool","getDynamicTool","toJSONSchema","console","log","type","includes","JSON","stringify","replace","fromMessages","systemPrompt","generate","llm","fromAgentAndTools","verbose","text","trim","respondMatch","match","silentMatch","rawOutput","content","parse","rawContent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,kBAAkB,QAAQ,0BAA0B;AAC7D,SAASC,aAAa,EAAEC,yBAAyB,QAAQ,mBAAmB;AAC5E,SAASC,CAAC,QAAQ,SAAS;AAO3B,SAASC,gBAAgB,QAAQ,iCAAiC;AAalE,IAAMC,yBAA0B;AAuDhC;;;;CAIC,GACD,OAAO,IAAA,AAAMC,uCAAN;;aAAMA,uBAEL,AAAgBC,IAAY,EAC5B,AAAiBC,OAAwC;gCAHpDF;;;aAEWC,OAAAA;aACCC,UA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gBAAO;gBAGxB,OAAO;YACX;;;YAEQH,KAAAA;mBAAR,SAAQA,iBAAiBX,KAAkB;gBACvC,IAAIA,OAAO;oBACP,OAAOA,MAAM2C,QAAQ;gBACzB;gBACA,OAAO;YACX;;;YAEQtB,KAAAA;mBAAR,SAAQA,wBACJgC,OAAe,EACfjC,MAA8B;gBAE9B,IAAI;oBACA,OAAO,IAAI1B,iBAAiB0B,QAAQkC,KAAK,CAACD;gBAC9C,EAAE,OAAO9C,OAAO;wBACZ;qBAAA,uBAAA,IAAI,CAACT,OAAO,CAACU,MAAM,cAAnB,2CAAA,qBAAqBD,KAAK,CACtB,AAAC,IAAa,OAAV,IAAI,CAACV,IAAI,EAAC,0DACd;wBACIU,OAAOA,AAAK,YAALA,OAAiBQ,SAAQR,MAAMF,OAAO,GAAG;wBAChDkD,YAAYF;oBAChB;oBAEJ,MAAM,IAAItC,MAAM;gBACpB;YACJ;;;WAxLSnB;IAyLZ"}
1
+ {"version":3,"sources":["../../../src/adapters/agents/autonomous-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 { AIResponseParser } from '../utils/ai-response-parser.js';\n\nimport type { SystemPromptAdapter } from '../prompts/system-prompt.adapter.js';\n\nexport interface AutonomousAgentOptions<TOutput = string> {\n logger?: LoggerPort;\n model: ModelPort;\n schema?: z.ZodSchema<TOutput>;\n systemPrompt: SystemPromptAdapter;\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 * An autonomous 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 AutonomousAgentAdapter<TOutput = string> implements AgentPort<PromptPort, TOutput> {\n constructor(\n public readonly name: string,\n private readonly options: AutonomousAgentOptions<TOutput>,\n ) {}\n\n async run(input?: PromptPort): Promise<null | TOutput> {\n this.options.logger?.debug(`[${this.name}] Starting chat execution.`);\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(`[${this.name}] Agent execution completed.`, {\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?.info(`[${this.name}] Agent chose to remain silent.`, {\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?.info(\n `[${this.name}] Execution finished; response content validated.`,\n );\n return validatedResponse;\n } else {\n this.options.logger?.info(`[${this.name}] Execution finished.`);\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(`[${this.name}] Chat execution failed.`, {\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.getModel();\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:\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 exact schema:\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(\n `[${this.name}] Agent output was missing 'RESPOND:' or 'SILENT:' prefix.`,\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 AIResponseParser(schema).parse(content);\n } catch (error) {\n this.options.logger?.error(\n `[${this.name}] Failed to validate response content against schema.`,\n {\n error: error instanceof Error ? error.message : 'Unknown error',\n rawContent: content,\n },\n );\n throw new Error('Invalid response content from model.');\n }\n }\n}\n"],"names":["ChatPromptTemplate","AgentExecutor","createStructuredChatAgent","z","AIResponseParser","SYSTEM_PROMPT_TEMPLATE","AutonomousAgentAdapter","name","options","run","input","executor","userInput","result","agentResponse","message","validatedResponse","error","logger","debug","createExecutor","resolveUserInput","invoke","hasOutput","output","Error","parseAgentOutput","shouldRespond","info","reason","schema","validateResponseContent","model","tools","schemaFormatInstructions","jsonSchema","isPrimitiveType","jsonSchemaString","prompt","agent","getModel","map","tool","getDynamicTool","toJSONSchema","includes","type","JSON","stringify","replace","fromMessages","systemPrompt","generate","llm","fromAgentAndTools","verbose","text","trim","respondMatch","match","silentMatch","rawOutput","content","parse","rawContent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAASA,kBAAkB,QAAQ,0BAA0B;AAC7D,SAASC,aAAa,EAAEC,yBAAyB,QAAQ,mBAAmB;AAC5E,SAASC,CAAC,QAAQ,SAAS;AAO3B,SAASC,gBAAgB,QAAQ,iCAAiC;AAalE,IAAMC,yBAA0B;AAuDhC;;;;CAIC,GACD,OAAO,IAAA,AAAMC,uCAAN;;aAAMA,uBAEL,AAAgBC,IAAY,EAC5B,AAAiBC,OAAwC;gCAHpDF;;;aAEWC,OAAAA;aACCC,UAAAA;;kBAHZF;;YAMHG,KAAAA;mBAAN,SAAMA,IAAIC,KAAkB;;wBACxB,sBAQI,uBALMC,UACAC,WAEAC,QAUAC,eAOF,uBAMYA,wBAAVC,SAQF,u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wBACJ+B,OAAe,EACfhC,MAA8B;gBAE9B,IAAI;oBACA,OAAO,IAAI1B,iBAAiB0B,QAAQiC,KAAK,CAACD;gBAC9C,EAAE,OAAO7C,OAAO;wBACZ;qBAAA,uBAAA,IAAI,CAACT,OAAO,CAACU,MAAM,cAAnB,2CAAA,qBAAqBD,KAAK,CACtB,AAAC,IAAa,OAAV,IAAI,CAACV,IAAI,EAAC,0DACd;wBACIU,OAAOA,AAAK,YAALA,OAAiBQ,SAAQR,MAAMF,OAAO,GAAG;wBAChDiD,YAAYF;oBAChB;oBAEJ,MAAM,IAAIrC,MAAM;gBACpB;YACJ;;;WA1LSnB;IA2LZ"}
package/dist/index.cjs CHANGED
@@ -733,7 +733,7 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
733
733
  key: "createExecutor",
734
734
  value: function createExecutor() {
735
735
  return _async_to_generator$2(function() {
736
- var model, tools, schemaFormatInstructions, jsonSchema, isPrimitiveType, prompt, agent;
736
+ var model, tools, schemaFormatInstructions, jsonSchema, isPrimitiveType, jsonSchemaString, prompt, agent;
737
737
  return _ts_generator$2(this, function(_state) {
738
738
  switch(_state.label){
739
739
  case 0:
@@ -745,17 +745,17 @@ var SYSTEM_PROMPT_TEMPLATE = '\n<OBJECTIVE>\n{mission_prompt}\n</OBJECTIVE>\n\n<
745
745
  schemaFormatInstructions = '';
746
746
  if (this.options.schema) {
747
747
  jsonSchema = v4.z.toJSONSchema(this.options.schema);
748
- console.log(jsonSchema.type);
749
748
  isPrimitiveType = [
750
749
  'boolean',
751
750
  'integer',
752
751
  'number',
753
752
  'string'
754
753
  ].includes(jsonSchema.type);
754
+ jsonSchemaString = JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}');
755
755
  if (isPrimitiveType) {
756
- schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be a '.concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(JSON.stringify(jsonSchema, null, 2), '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: your ').concat(jsonSchema.type, ' value here"\n}}\n```\n\nDo not wrap the ').concat(jsonSchema.type, ' value in JSON - just provide the raw value after "RESPOND: ".');
756
+ schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be a '.concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: your ').concat(jsonSchema.type, ' value here"\n}}\n```\n\nDo not wrap the ').concat(jsonSchema.type, ' value in JSON - just provide the raw value after "RESPOND: ".');
757
757
  } else {
758
- schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be valid JSON that matches this exact schema:\n\n```json\n'.concat(JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}'), '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: {{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}"\n}}\n```\n');
758
+ schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be valid JSON that matches this exact schema:\n\n```json\n'.concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: {{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}"\n}}\n```\n');
759
759
  }
760
760
  }
761
761
  prompt = prompts.ChatPromptTemplate.fromMessages([
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jterrazz/intelligence",
3
3
  "author": "Jean-Baptiste Terrazzoni <contact@jterrazz.com>",
4
- "version": "1.4.0",
4
+ "version": "1.4.1",
5
5
  "exports": {
6
6
  ".": {
7
7
  "require": "./dist/index.cjs",