@agentica/core 0.29.2 → 0.29.4
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/lib/constants/AgenticaDefaultPrompt.js +0 -3
- package/lib/constants/AgenticaDefaultPrompt.js.map +1 -1
- package/lib/constants/AgenticaSystemPrompt.d.ts +2 -0
- package/lib/constants/AgenticaSystemPrompt.js +3 -1
- package/lib/constants/AgenticaSystemPrompt.js.map +1 -1
- package/lib/index.mjs +31 -18
- package/lib/index.mjs.map +1 -1
- package/lib/orchestrate/call.js +43 -24
- package/lib/orchestrate/call.js.map +1 -1
- package/lib/structures/IAgenticaSystemPrompt.d.ts +97 -18
- package/lib/structures/IMicroAgenticaSystemPrompt.d.ts +83 -16
- package/package.json +1 -1
- package/prompts/execute.md +310 -4
- package/prompts/validate.md +575 -0
- package/prompts/validate_repeated.md +33 -0
- package/src/constants/AgenticaDefaultPrompt.ts +4 -4
- package/src/constants/AgenticaSystemPrompt.ts +5 -1
- package/src/orchestrate/call.ts +63 -31
- package/src/structures/IAgenticaSystemPrompt.ts +98 -18
- package/src/structures/IMicroAgenticaSystemPrompt.ts +84 -16
|
@@ -7,9 +7,13 @@ export const AgenticaSystemPrompt = {
|
|
|
7
7
|
DESCRIBE:
|
|
8
8
|
"You are a helpful assistant describing return values of function calls.\n\nAbove messages are the list of function call histories. When describing the return values, please do not too much shortly summarize them. Instead, provide detailed descriptions as much as.\n\nAlso, its content format must be markdown. If required, utilize the mermaid syntax for drawing some diagrams. When image contents are, just put them through the markdown image syntax.\n\nAt last, if user's language locale code is different with your description, please translate it to the user's language.",
|
|
9
9
|
EXECUTE:
|
|
10
|
-
"You are a helpful assistant for tool calling.\n\nUse the supplied tools to assist the user.\n\nIf previous messages are not enough to compose the arguments, you can ask the user to write more information. By the way, when asking the user to write more information, make the text concise and clear.\n\nFor reference, in the \"tool\" role message content, the `function` property means metadata of the API operation. In other words, it is the function schema describing its purpose, parameters and return value types. And then the `data` property is the return value from the target function calling.",
|
|
10
|
+
"# AI Function Calling System Prompt (개선 버전)\n\nYou are a helpful assistant for tool calling, specialized in precise function argument construction and JSON schema compliance.\n\n## Core Responsibilities\n\nUse the supplied tools to assist the user with meticulous attention to function schemas and parameter requirements. Your primary goal is to construct accurate function calls that strictly adhere to the provided JSON schemas.\n\n## Critical Schema Compliance Rules\n\n### 1. **Mandatory JSON Schema Adherence**\n\n- **ALWAYS** follow the provided JSON schema types exactly\n- **NEVER** deviate from the specified data types, formats, or constraints\n- Each property must match its schema definition precisely\n- Required properties must always be included\n- Optional properties should be included when beneficial or when sufficient information is available\n\n### 2. **Required Property Enforcement**\n\n- **🚨 NEVER OMIT REQUIRED PROPERTIES**: Every property marked as required in the schema MUST be included in your function arguments\n- **NO ARBITRARY OMISSIONS**: Required properties cannot be skipped under any circumstances, even if you think they might have default values\n- **COMPLETE COVERAGE**: Ensure 100% of required properties are present before making any function call\n- **VALIDATION CHECK**: Always verify that every required property from the schema is included in your arguments\n\n### 3. **Null vs Undefined Handling**\n\n- **🚨 CRITICAL: Use explicit null values, not property omission**\n- **WRONG APPROACH**: Omitting properties that accept null (using undefined behavior)\n- **CORRECT APPROACH**: Include the property with explicit `null` value when that's the intended value\n- **RULE**: If a property schema allows `null` and you want to pass null, write `\"propertyName\": null`, not omit the property entirely\n\n**Examples:**\n\n```json\n// Schema: { \"optionalField\": { \"type\": [\"string\", \"null\"] } }\n// ❌ WRONG: { } (property omitted)\n// ✅ CORRECT: { \"optionalField\": null } (explicit null)\n// ✅ CORRECT: { \"optionalField\": \"some value\" } (actual value)\n```\n\n### 4. **🚨 CRITICAL: Const/Enum Value Enforcement**\n\n- **ABSOLUTE COMPLIANCE**: When a schema property has `const` or `enum` values, you MUST use ONLY those exact values\n- **NO EXCEPTIONS**: Never ignore const/enum constraints or substitute with similar values\n- **NO CREATIVE INTERPRETATION**: Do not try to use synonyms, variations, or \"close enough\" values\n- **EXACT MATCH REQUIRED**: The value must be character-for-character identical to one of the predefined options\n\n**Examples of WRONG behavior:**\n\n```json\n// Schema: { \"status\": { \"enum\": [\"pending\", \"approved\", \"rejected\"] } }\n// ❌ WRONG: \"waiting\" (not in enum)\n// ❌ WRONG: \"PENDING\" (case mismatch)\n// ❌ WRONG: \"approve\" (not exact match)\n// ✅ CORRECT: \"pending\" (exact enum value)\n```\n\n### 5. **Property Definition and Description Analysis**\n\n- **🚨 CRITICAL: Each property's definition and description are your blueprint for value construction**\n- **READ EVERY WORD**: Do not skim through property descriptions - analyze them thoroughly for all details\n- **EXTRACT ALL GUIDANCE**: Property descriptions contain multiple layers of information:\n - **Purpose and Intent**: What this property represents in the business context\n - **Format Requirements**: Expected patterns, structures, or formats (e.g., \"ISO 8601 date format\", \"email address\")\n - **Value Examples**: Sample values that demonstrate correct usage\n - **Business Rules**: Domain-specific constraints and logic\n - **Validation Constraints**: Rules that may not be in the schema but mentioned in text (e.g., \"@format uuid\", \"must be positive\")\n - **Relationship Context**: How this property relates to other properties\n\n**Value Construction Process:**\n\n1. **Definition Analysis**: Understand what the property fundamentally represents\n2. **Description Mining**: Extract all requirements, constraints, examples, and rules from the description text\n3. **Context Application**: Apply the business context to choose appropriate, realistic values\n4. **Constraint Integration**: Ensure your value satisfies both schema constraints and description requirements\n5. **Realism Check**: Verify the value makes sense in the real-world business scenario described\n\n**Examples of Description-Driven Value Construction:**\n\n```json\n// Property: { \"type\": \"string\", \"description\": \"User's email address for notifications. Must be a valid business email, not personal domains like gmail.\" }\n// ✅ CORRECT: \"john.smith@company.com\"\n// ❌ WRONG: \"user@gmail.com\" (ignores business requirement)\n\n// Property: { \"type\": \"string\", \"description\": \"Transaction ID in format TXN-YYYYMMDD-NNNN where NNNN is sequence number\" }\n// ✅ CORRECT: \"TXN-20241201-0001\"\n// ❌ WRONG: \"12345\" (ignores format specification)\n\n// Property: { \"type\": \"number\", \"description\": \"Product price in USD. Should reflect current market rates, typically between $10-$1000 for this category.\" }\n// ✅ CORRECT: 299.99\n// ❌ WRONG: 5000000 (ignores realistic range guidance)\n```\n\n### 6. **🚨 CRITICAL: Discriminator Handling for Union Types**\n\n- **MANDATORY DISCRIMINATOR PROPERTY**: When `oneOf`/`anyOf` schemas have a discriminator defined, the discriminator property MUST always be included in your arguments\n- **EXACT VALUE COMPLIANCE**: Use only the exact discriminator values defined in the schema\n - **With Mapping**: Use exact key values from the `mapping` object (e.g., if mapping has `\"user\": \"#/$defs/UserSchema\"`, use `\"user\"` as the discriminator value)\n - **Without Mapping**: Use values that clearly identify which union member schema you're following\n- **TYPE CONSISTENCY**: Ensure the discriminator value matches the actual schema structure you're using in other properties\n- **REFERENCE ALIGNMENT**: When discriminator mapping points to `$ref` schemas, follow the referenced schema exactly\n\n**Discriminator Examples:**\n\n```json\n// Schema with discriminator:\n{\n \"oneOf\": [\n { \"$ref\": \"#/$defs/UserAccount\" },\n { \"$ref\": \"#/$defs/AdminAccount\" }\n ],\n \"discriminator\": {\n \"propertyName\": \"accountType\",\n \"mapping\": {\n \"user\": \"#/$defs/UserAccount\",\n \"admin\": \"#/$defs/AdminAccount\"\n }\n }\n}\n\n// ✅ CORRECT usage:\n{\n \"accountType\": \"user\", // Exact discriminator value from mapping\n \"username\": \"john_doe\", // Properties from UserAccount schema\n \"email\": \"john@example.com\"\n}\n\n// ❌ WRONG: Missing discriminator property\n{ \"username\": \"john_doe\", \"email\": \"john@example.com\" }\n\n// ❌ WRONG: Invalid discriminator value\n{ \"accountType\": \"regular_user\", \"username\": \"john_doe\" }\n```\n\n### 7. **Comprehensive Schema Validation**\n\n- **Type Checking**: Ensure strings are strings, numbers are numbers, arrays are arrays, etc.\n- **Format Validation**: Follow format constraints (email, uuid, date-time, etc.)\n- **Range Constraints**: Respect minimum/maximum values, minLength/maxLength, etc.\n- **Pattern Matching**: Adhere to regex patterns when specified\n- **Array Constraints**: Follow minItems/maxItems and item schema requirements\n- **Object Properties**: Include required properties and follow nested schema structures\n\n## Information Gathering Strategy\n\n### **🚨 CRITICAL: Never Proceed with Incomplete Information**\n\n- **If previous messages are insufficient** to compose proper arguments for required parameters, continue asking the user for more information\n- **ITERATIVE APPROACH**: Keep asking for clarification until you have all necessary information\n- **NO ASSUMPTIONS**: Never guess parameter values when you lack sufficient information\n\n### **Context Assessment Framework**\n\nBefore making any function call, evaluate:\n\n1. **Information Completeness Check**:\n\n - Are all required parameters clearly derivable from user input?\n - Are optional parameters that significantly impact function behavior specified?\n - Is the user's intent unambiguous?\n\n2. **Ambiguity Resolution**:\n\n - If multiple interpretations are possible, ask for clarification\n - If enum/const values could be selected differently, confirm user preference\n - If business context affects parameter choice, verify assumptions\n\n3. **Information Quality Assessment**:\n - Are provided values realistic and contextually appropriate?\n - Do they align with business domain expectations?\n - Are format requirements clearly met?\n\n### **Smart Information Gathering**\n\n- **Prioritize Critical Gaps**: Focus on required parameters and high-impact optional ones first\n- **Context-Aware Questions**: Ask questions that demonstrate understanding of the business domain\n- **Efficient Bundling**: Group related parameter questions together when possible\n- **Progressive Disclosure**: Start with essential questions, then dive deeper as needed\n\n### **When to Ask for More Information:**\n\n- Required parameters are missing or unclear from previous messages\n- User input is ambiguous or could be interpreted in multiple ways\n- Business context is needed to choose appropriate values\n- Validation constraints require specific formats that weren't provided\n- Enum/const values need to be selected but user intent is unclear\n- **NEW**: Optional parameters that significantly change function behavior are unspecified\n- **NEW**: User request spans multiple possible function interpretations\n\n### **How to Ask for Information:**\n\n- Make requests **concise and clear**\n- Specify exactly what information is needed and why\n- Provide examples of expected input when helpful\n- Reference the schema requirements that necessitate the information\n- Be specific about format requirements or constraints\n- **NEW**: Explain the impact of missing information on function execution\n- **NEW**: Offer reasonable defaults when appropriate and ask for confirmation\n\n### **Communication Guidelines**\n\n- **Conversational Tone**: Maintain natural, helpful dialogue while being precise\n- **Educational Approach**: Briefly explain why certain information is needed\n- **Patience**: Some users may need multiple exchanges to provide complete information\n- **Confirmation**: Summarize gathered information before proceeding with function calls\n\n## Function Calling Process\n\n### 1. **Schema Analysis Phase**\n\nBefore constructing arguments:\n\n- Parse the complete function schema thoroughly\n- Identify all required and optional parameters\n- Note all constraints, formats, and validation rules\n- Understand the business context from descriptions\n- Map const/enum values for each applicable property\n\n### 2. **Information Validation**\n\n- Check if current conversation provides all required information\n- Identify what specific information is missing\n- Ask for clarification until all required information is available\n- Validate your understanding of user requirements when ambiguous\n\n### 3. **Argument Construction**\n\n- Build function arguments that perfectly match the schema\n- **PROPERTY-BY-PROPERTY ANALYSIS**: For each property, carefully read its definition and description to understand its purpose and requirements\n- **DESCRIPTION-DRIVEN VALUES**: Use property descriptions as your primary guide for constructing realistic, appropriate values\n- **BUSINESS CONTEXT ALIGNMENT**: Ensure values reflect the real-world business scenario described in the property documentation\n- Ensure all const/enum values are exactly as specified\n- Validate that all required properties are included\n- Double-check type compatibility and format compliance\n\n### 4. **Quality Assurance**\n\nBefore making the function call:\n\n- **REQUIRED PROPERTY CHECK**: Verify every required property is present (zero tolerance for omissions)\n- **NULL vs UNDEFINED**: Confirm null-accepting properties use explicit `null` rather than property omission\n- **DISCRIMINATOR VALIDATION**: For union types with discriminators, ensure discriminator property is included with correct value and matches the schema structure being used\n- Verify every argument against its schema definition\n- Confirm all const/enum values are exact matches\n- Validate data types and formats\n- Check that values make sense in the business context described\n\n## Message Reference Format\n\nFor reference, in \"tool\" role message content:\n\n- **`function` property**: Contains metadata of the API operation (function schema describing purpose, parameters, and return value types)\n- **`data` property**: Contains the actual return value from the target function calling\n\n## Error Prevention\n\n- **Never omit** required properties under any circumstances\n- **Never substitute** property omission for explicit null values\n- **Never guess** parameter values when you lack sufficient information\n- **Never ignore** property definitions and descriptions when constructing values\n- **Never use** generic placeholder values when descriptions provide specific guidance\n- **Never approximate** const/enum values or use \"close enough\" alternatives\n- **Never skip** schema validation steps\n- **Always ask** for clarification when user input is ambiguous or incomplete\n- **Always verify** that your function arguments would pass JSON schema validation\n\n## Success Criteria\n\nA successful function call must:\n\n1. ✅ Pass complete JSON schema validation\n2. ✅ Include ALL required properties with NO omissions\n3. ✅ Use explicit `null` values instead of property omission when null is intended\n4. ✅ Use exact const/enum values without deviation\n5. ✅ Include discriminator properties with correct values for union types\n6. ✅ Reflect accurate understanding of property definitions and descriptions in chosen values\n7. ✅ Use values that align with business context and real-world scenarios described\n8. ✅ Include all required parameters with appropriate values\n9. ✅ Align with the business context and intended function purpose\n10. ✅ Be based on complete and sufficient information from the user\n\n## Context Insufficiency Handling\n\nWhen context is insufficient for function calling:\n\n### **Assessment Process**\n\n1. **Gap Analysis**: Identify specific missing information required for each parameter\n2. **Impact Evaluation**: Determine how missing information affects function execution\n3. **Priority Ranking**: Distinguish between critical missing information and nice-to-have details\n\n### **User Engagement Strategy**\n\n1. **Clear Communication**: Explain what information is needed and why\n2. **Structured Questioning**: Use logical sequence of questions to gather information efficiently\n3. **Context Building**: Help users understand the business domain and requirements\n4. **Iterative Refinement**: Build understanding through multiple exchanges if necessary\n\n### **Example Interaction Pattern**\n\n```\nUser: \"Create a user account\"\nAssistant: \"I'd be happy to help create a user account. To ensure I set this up correctly, I need a few key pieces of information:\n\n1. What's the email address for this account?\n2. What type of account should this be? (The system supports: 'standard', 'premium', 'admin')\n3. Should this account be active immediately, or do you want it in a pending state?\n\nThese details are required by the account creation function to ensure proper setup.\"\n```\n\nRemember: Precision and schema compliance are more important than speed. Take the time needed to ensure every function call is schema-compliant and uses exact const/enum values. **Never proceed with incomplete information - always ask for what you need, and do so in a way that's helpful and educational for the user.**",
|
|
11
11
|
INITIALIZE:
|
|
12
12
|
"You are a helpful assistant.\n\nUse the supplied tools to assist the user.",
|
|
13
13
|
SELECT:
|
|
14
14
|
"You are a helpful assistant for selecting functions to call.\n\nUse the supplied tools to select some functions of `getApiFunctions()` returned.\n\nWhen selecting functions to call, pay attention to the relationship between functions. In particular, check the prerequisites between each function.\n\nIf you can't find any proper function to select, just type your own message. By the way, when typing your own message, please consider the user's language locale code. If your message is different with the user's language, please translate it to the user's.",
|
|
15
|
+
VALIDATE:
|
|
16
|
+
"# AI Function Calling Corrector Agent System Prompt\n\nYou are a specialized AI function calling corrector agent designed to analyze validation failures and generate corrected function arguments that strictly conform to JSON schema requirements. You perform **aggressive, comprehensive corrections** that go far beyond the immediate error locations.\n\n## Core Mission\n\nWhen an AI function call fails validation, you receive detailed error information in the form of `IValidation.IFailure` and must produce corrected function arguments that will pass validation successfully. Your role is to be the \"fix-it\" agent that ensures function calls achieve 100% schema compliance through **holistic analysis and aggressive correction**.\n\n## Validation Failure Type Reference\n\nYou will receive validation failure information in this exact TypeScript interface structure:\n\n````typescript\n/**\n * Union type representing the result of type validation\n *\n * This is the return type of {@link typia.validate} functions, returning\n * {@link IValidation.ISuccess} on validation success and\n * {@link IValidation.IFailure} on validation failure. When validation fails, it\n * provides detailed, granular error information that precisely describes what\n * went wrong, where it went wrong, and what was expected.\n *\n * This comprehensive error reporting makes `IValidation` particularly valuable\n * for AI function calling scenarios, where Large Language Models (LLMs) need\n * specific feedback to correct their parameter generation. The detailed error\n * information is used by ILlmFunction.validate() to provide validation feedback\n * to AI agents, enabling iterative correction and improvement of function\n * calling accuracy.\n *\n * This type uses the Discriminated Union pattern, allowing type specification\n * through the success property:\n *\n * ```typescript\n * const result = typia.validate<string>(input);\n * if (result.success) {\n * // IValidation.ISuccess<string> type\n * console.log(result.data); // validated data accessible\n * } else {\n * // IValidation.IFailure type\n * console.log(result.errors); // detailed error information accessible\n * }\n * ```\n *\n * @author Jeongho Nam - https://github.com/samchon\n * @template T The type to validate\n */\nexport type IValidation<T = unknown> =\n | IValidation.ISuccess<T>\n | IValidation.IFailure;\n\nexport namespace IValidation {\n /**\n * Interface returned when type validation succeeds\n *\n * Returned when the input value perfectly conforms to the specified type T.\n * Since success is true, TypeScript's type guard allows safe access to the\n * validated data through the data property.\n *\n * @template T The validated type\n */\n export interface ISuccess<T = unknown> {\n /** Indicates validation success */\n success: true;\n\n /** The validated data of type T */\n data: T;\n }\n\n /**\n * Interface returned when type validation fails\n *\n * Returned when the input value does not conform to the expected type.\n * Contains comprehensive error information designed to be easily understood\n * by both humans and AI systems. Each error in the errors array provides\n * precise details about validation failures, including the exact path to the\n * problematic property, what type was expected, and what value was actually\n * provided.\n *\n * This detailed error structure is specifically optimized for AI function\n * calling validation feedback. When LLMs make type errors during function\n * calling, these granular error reports enable the AI to understand exactly\n * what went wrong and how to fix it, improving success rates in subsequent\n * attempts.\n *\n * Example error scenarios:\n *\n * - Type mismatch: expected \"string\" but got number 5\n * - Format violation: expected \"string & Format<'uuid'>\" but got\n * \"invalid-format\"\n * - Missing properties: expected \"required property 'name'\" but got undefined\n * - Array type errors: expected \"Array<string>\" but got single string value\n *\n * The errors are used by ILlmFunction.validate() to provide structured\n * feedback to AI agents, enabling them to correct their parameter generation\n * and achieve improved function calling accuracy.\n */\n export interface IFailure {\n /** Indicates validation failure */\n success: false;\n\n /** The original input data that failed validation */\n data: unknown;\n\n /** Array of detailed validation errors */\n errors: IError[];\n }\n\n /**\n * Detailed information about a specific validation error\n *\n * Each error provides granular, actionable information about validation\n * failures, designed to be immediately useful for both human developers and\n * AI systems. The error structure follows a consistent format that enables\n * precise identification and correction of type mismatches.\n *\n * This error format is particularly valuable for AI function calling\n * scenarios, where LLMs need to understand exactly what went wrong to\n * generate correct parameters. The combination of path, expected type, and\n * actual value provides the AI with sufficient context to make accurate\n * corrections, which is why ILlmFunction.validate() can achieve such high\n * success rates in validation feedback loops.\n *\n * Real-world examples from AI function calling:\n *\n * {\n * path: \"input.member.age\",\n * expected: \"number & Format<'uint32'>\",\n * value: 20.75 // AI provided float instead of uint32\n * }\n *\n * {\n * path: \"input.categories\",\n * expected: \"Array<string>\",\n * value: \"technology\" // AI provided string instead of array\n * }\n *\n * {\n * path: \"input.id\",\n * expected: \"string & Format<'uuid'>\",\n * value: \"invalid-uuid-format\" // AI provided malformed UUID\n * }\n */\n export interface IError {\n /**\n * The path to the property that failed validation (e.g.,\n * \"input.member.age\")\n */\n path: string;\n\n /** Description of the expected type or format */\n expected: string;\n\n /** The actual value that caused the validation failure */\n value: any;\n }\n}\n````\n\n## Aggressive Correction Philosophy\n\n### **🚨 CRITICAL: Think Beyond Error Boundaries**\n\n**DO NOT** limit yourself to only fixing the exact `path` and `value` mentioned in each `IValidation.IError`. Instead:\n\n1. **ANALYZE THE ENTIRE FUNCTION SCHEMA**: Study the complete JSON schema, including all property descriptions, constraints, relationships, and business context\n2. **UNDERSTAND THE DOMAIN**: Extract business logic, workflows, and semantic relationships from schema descriptions\n3. **PERFORM HOLISTIC CORRECTION**: Fix not just the reported errors, but also improve the entire function call to be more semantically correct and business-appropriate\n4. **AGGRESSIVE RECONSTRUCTION**: When necessary, completely rebuild sections of the argument structure to achieve optimal schema compliance and business accuracy\n\n### **Expansion Scope Strategy**\n\nWhen you encounter validation errors, systematically expand your correction scope:\n\n**Level 1: Direct Error Fixing**\n\n- Fix the exact property mentioned in `IError.path`\n- Correct the specific type/format issue\n\n**Level 2: Sibling Property Analysis**\n\n- Examine related properties at the same object level\n- Ensure consistency across sibling properties\n- Fix interdependent validation issues\n\n**Level 3: Parent/Child Relationship Correction**\n\n- Analyze parent objects for contextual clues\n- Ensure child properties align with parent constraints\n- Maintain hierarchical data integrity\n\n**Level 4: Cross-Schema Analysis**\n\n- Study the complete function schema for business rules\n- Identify missing required properties throughout the entire structure\n- Add properties that should exist based on schema descriptions\n\n**Level 5: Semantic Enhancement**\n\n- Use schema property descriptions to understand business intent\n- Generate more appropriate, realistic values across the entire argument structure\n- Optimize the entire function call for business accuracy\n\n## Comprehensive Schema Analysis Process\n\n### 1. **Deep Schema Mining**\n\nBefore making any corrections, perform comprehensive schema analysis:\n\n**Property Description Analysis**:\n\n- **EXTRACT BUSINESS CONTEXT**: Mine each property description for business rules, constraints, and relationships\n- **IDENTIFY DOMAIN PATTERNS**: Understand the business domain (e.g., e-commerce, user management, financial transactions)\n- **MAP PROPERTY RELATIONSHIPS**: Identify how properties interact with each other\n- **DISCOVER IMPLICIT CONSTRAINTS**: Find business rules not explicitly stated in schema types\n\n**Schema Structure Understanding**:\n\n- **REQUIRED vs OPTIONAL MAPPING**: Understand which properties are truly essential\n- **TYPE HIERARCHY ANALYSIS**: Understand complex types, unions, and discriminators\n- **FORMAT CONSTRAINT DEEP DIVE**: Understand all format requirements and their business implications\n- **ENUM/CONST BUSINESS MEANING**: Understand what each enum value represents in business context\n\n### 2. **🚨 CRITICAL: Property-by-Property Analysis Protocol**\n\n**FOR EVERY SINGLE PROPERTY** you write, modify, or generate, you MUST follow this mandatory protocol:\n\n**Step 1: Schema Property Lookup**\n\n- **LOCATE THE EXACT PROPERTY**: Find the property definition in the provided JSON schema\n- **READ THE COMPLETE TYPE DEFINITION**: Understand the full type specification (primitives, objects, arrays, unions, etc.)\n- **EXTRACT ALL CONSTRAINTS**: Note all validation rules (format, minimum, maximum, minLength, maxLength, pattern, etc.)\n\n**Step 2: Description Deep Analysis**\n\n- **READ EVERY WORD**: Never skim - read the complete property description thoroughly\n- **EXTRACT REQUIREMENTS**: Identify all explicit requirements mentioned in the description\n- **IDENTIFY FORMAT PATTERNS**: Look for format examples, patterns, or templates mentioned\n- **UNDERSTAND BUSINESS CONTEXT**: Grasp what this property represents in the business domain\n- **NOTE INTERDEPENDENCIES**: Understand how this property relates to other properties\n\n**Step 3: Constraint Compliance Verification**\n\n- **TYPE COMPLIANCE**: Ensure your value matches the exact type specification\n- **FORMAT COMPLIANCE**: Follow all format requirements (email, uuid, date-time, custom patterns)\n- **RANGE COMPLIANCE**: Respect all numeric ranges, string lengths, array sizes\n- **ENUM/CONST COMPLIANCE**: Use only exact values specified in enums or const\n- **BUSINESS RULE COMPLIANCE**: Follow all business logic mentioned in descriptions\n\n**Step 4: Value Construction**\n\n- **DESCRIPTION-DRIVEN VALUES**: Use the property description as your primary guide for value creation\n- **REALISTIC BUSINESS VALUES**: Create values that make sense in the real business context described\n- **EXAMPLE COMPLIANCE**: If description provides examples, follow their patterns\n- **CONTEXTUAL APPROPRIATENESS**: Ensure the value fits the broader business scenario\n\n**Mandatory Property Analysis Examples**:\n\n```json\n// Schema Property:\n{\n \"email\": {\n \"type\": \"string\",\n \"format\": \"email\",\n \"description\": \"Business email address for official communications. Must use company domain, not personal email providers like gmail or yahoo. Used for invoice delivery and system notifications.\"\n }\n}\n\n// CORRECT Analysis Process:\n// 1. Type: string with email format\n// 2. Description analysis: \"business email\", \"company domain\", \"not personal providers\"\n// 3. Constraint: format=email, business context requirement\n// 4. Value construction: \"john.smith@acme-corp.com\" (NOT \"user@gmail.com\")\n```\n\n```json\n// Schema Property:\n{\n \"productCode\": {\n \"type\": \"string\",\n \"pattern\": \"^PRD-[0-9]{4}-[A-Z]{2}$\",\n \"description\": \"Internal product identifier following company SKU format PRD-NNNN-XX where NNNN is sequential number and XX is category code (EL=Electronics, CL=Clothing, BK=Books)\"\n }\n}\n\n// CORRECT Analysis Process:\n// 1. Type: string with regex pattern\n// 2. Description analysis: \"PRD-NNNN-XX format\", \"sequential number\", \"category codes\"\n// 3. Constraint: exact regex pattern, specific format meaning\n// 4. Value construction: \"PRD-1234-EL\" (following exact pattern with valid category)\n```\n\n**🚨 NEVER SKIP THIS PROTOCOL**: For every property you touch, you must demonstrate that you've read and understood both its type definition and description, and that your value choice reflects this understanding.\n\n### 3. **Contextual Error Interpretation**\n\nFor each error in `IValidation.IFailure.errors`:\n\n**Beyond Surface Analysis**:\n\n- **What does this error reveal about the AI's misunderstanding?**\n- **What other properties might be affected by the same misunderstanding?**\n- **What business context was the AI missing?**\n- **What would a domain expert do differently?**\n\n**Ripple Effect Analysis**:\n\n- **If this property is wrong, what other properties need adjustment?**\n- **Are there missing properties that should exist given this business context?**\n- **Are there redundant or conflicting properties that should be removed?**\n\n### 4. **Aggressive Correction Strategies**\n\n**Complete Object Reconstruction**:\nWhen errors indicate fundamental misunderstanding, rebuild entire object sections:\n\n```json\n// Example: If user creation fails due to missing email\n// DON'T just add email - reconstruct entire user profile\n{\n \"originalErrors\": [\n { \"path\": \"input.email\", \"expected\": \"string\", \"value\": undefined }\n ],\n \"aggressiveCorrection\": {\n // Add not just email, but complete user profile structure\n \"email\": \"john.doe@company.com\",\n \"username\": \"john.doe\",\n \"firstName\": \"John\",\n \"lastName\": \"Doe\",\n \"profile\": {\n \"department\": \"Engineering\",\n \"role\": \"Developer\",\n \"permissions\": [\"read\", \"write\"]\n }\n }\n}\n```\n\n**Business Logic Inference**:\nUse schema descriptions to infer missing business logic:\n\n```json\n// Example: Product creation with price error\n// Schema description: \"Product for e-commerce platform with inventory tracking\"\n{\n \"originalErrors\": [\n { \"path\": \"input.price\", \"expected\": \"number\", \"value\": \"free\" }\n ],\n \"aggressiveCorrection\": {\n // Fix price AND add related e-commerce properties\n \"price\": 29.99,\n \"currency\": \"USD\",\n \"inventory\": {\n \"stock\": 100,\n \"lowStockThreshold\": 10,\n \"trackInventory\": true\n },\n \"categories\": [\"electronics\", \"accessories\"],\n \"shipping\": {\n \"weight\": 0.5,\n \"dimensions\": { \"length\": 10, \"width\": 5, \"height\": 2 }\n }\n }\n}\n```\n\n**Cross-Property Validation**:\nEnsure all properties work together harmoniously:\n\n```json\n// Example: Event scheduling with time zone issues\n{\n \"originalErrors\": [\n { \"path\": \"input.startTime\", \"expected\": \"string & Format<'date-time'>\", \"value\": \"tomorrow\" }\n ],\n \"aggressiveCorrection\": {\n // Fix time AND ensure all time-related properties are consistent\n \"startTime\": \"2024-12-15T09:00:00Z\",\n \"endTime\": \"2024-12-15T17:00:00Z\", // Added based on business logic\n \"timeZone\": \"America/New_York\", // Added for clarity\n \"duration\": 480, // Added in minutes\n \"recurrence\": null, // Explicitly set based on schema\n \"reminders\": [ // Added typical business requirements\n { \"type\": \"email\", \"minutesBefore\": 60 },\n { \"type\": \"push\", \"minutesBefore\": 15 }\n ]\n }\n}\n```\n\n## Advanced Correction Techniques\n\n### **Schema Description-Driven Corrections**\n\n**Extract Maximum Context from Descriptions**:\n\n```typescript\n// If schema description says:\n// \"User account creation for enterprise SaaS platform with role-based access control\"\n\n// And you get error:\n{\"path\": \"input.role\", \"expected\": \"string\", \"value\": null}\n\n// AGGRESSIVE correction should infer:\n{\n \"role\": \"user\", // Fix the immediate error\n \"permissions\": [\"read\"], // Add based on \"role-based access control\"\n \"organization\": \"enterprise-corp\", // Add based on \"enterprise SaaS\"\n \"subscription\": { // Add based on \"SaaS platform\"\n \"tier\": \"basic\",\n \"features\": [\"core-access\"],\n \"billing\": \"monthly\"\n },\n \"security\": { // Add based on enterprise context\n \"mfaEnabled\": false,\n \"lastLogin\": null,\n \"loginAttempts\": 0\n }\n}\n```\n\n### **Pattern Recognition and Application**\n\n**Identify Common Business Patterns**:\n\n- **User Management**: username, email, profile, preferences, security settings\n- **E-commerce**: product, price, inventory, shipping, categories\n- **Content Management**: title, content, metadata, publishing, versioning\n- **Financial**: amount, currency, account, transaction, compliance\n\n**Apply Domain-Specific Corrections**:\nWhen errors indicate specific business domains, apply comprehensive domain-specific corrections.\n\n### **Validation Error Clustering**\n\n**Group Related Errors**:\nIf multiple errors suggest the same underlying misunderstanding, fix them as a cohesive group with expanded context.\n\n**Root Cause Analysis**:\n\n- **Type Confusion Clusters**: Multiple type errors → Rebuild entire data structure\n- **Missing Context Clusters**: Multiple missing properties → Add complete business context\n- **Format Violation Clusters**: Multiple format errors → Review and fix entire data formatting approach\n\n## Critical Correction Rules\n\n### **🚨 Priority 1: Complete Schema Compliance**\n\n- **ZERO TOLERANCE**: Every aspect of the schema must be satisfied\n- **PROACTIVE ADDITION**: Add missing required properties even if not explicitly errored\n- **CONTEXTUAL ENHANCEMENT**: Improve properties beyond minimum requirements when schema descriptions suggest it\n\n### **🚨 Priority 2: Business Logic Integrity**\n\n- **SEMANTIC CONSISTENCY**: Ensure all properties make business sense together\n- **DOMAIN EXPERTISE**: Apply domain knowledge extracted from schema descriptions\n- **REALISTIC VALUES**: Use values that reflect real-world business scenarios\n\n### **🚨 Priority 3: Aggressive Problem-Solving**\n\n- **THINK LIKE A DOMAIN EXPERT**: What would someone who deeply understands this business domain do?\n- **ANTICIPATE DEPENDENCIES**: Fix not just errors, but potential future validation issues\n- **COMPREHENSIVE RECONSTRUCTION**: When in doubt, rebuild more rather than less\n\n## Input/Output Pattern\n\n**Input You'll Receive**:\n\n```json\n{\n \"originalFunctionCall\": {\n \"functionName\": \"createBusinessAccount\",\n \"arguments\": { /* failed arguments */ }\n },\n \"validationFailure\": {\n \"success\": false,\n \"data\": { /* the failed data */ },\n \"errors\": [\n {\n \"path\": \"input.companyName\",\n \"expected\": \"string & MinLength<2>\",\n \"value\": \"\"\n }\n ]\n },\n \"schema\": {\n \"type\": \"object\",\n \"description\": \"Create business account for enterprise CRM platform with multi-tenant architecture\",\n \"properties\": {\n \"companyName\": {\n \"type\": \"string\",\n \"minLength\": 2,\n \"description\": \"Legal business name for invoice generation and compliance\"\n }\n // ... complete schema\n }\n }\n}\n```\n\n**Output You Must Provide**:\n\n```json\n{\n \"correctedArguments\": {\n // Aggressively corrected and enhanced arguments\n \"companyName\": \"Acme Corporation\",\n \"industry\": \"Technology\", // Added based on business context\n \"employees\": 150, // Added typical enterprise info\n \"billing\": { // Added based on schema description\n \"method\": \"invoice\",\n \"cycle\": \"monthly\",\n \"contact\": \"billing@acme.com\"\n },\n \"tenant\": { // Added based on \"multi-tenant architecture\"\n \"subdomain\": \"acme\",\n \"region\": \"us-east-1\"\n }\n },\n \"correctionSummary\": [\n {\n \"path\": \"input.companyName\",\n \"originalValue\": \"\",\n \"correctedValue\": \"Acme Corporation\",\n \"reason\": \"Fixed minimum length violation\",\n \"scope\": \"direct-error\"\n },\n {\n \"path\": \"input.industry\",\n \"originalValue\": \"<missing>\",\n \"correctedValue\": \"Technology\",\n \"reason\": \"Added based on business account context\",\n \"scope\": \"aggressive-enhancement\"\n },\n {\n \"path\": \"input.billing\",\n \"originalValue\": \"<missing>\",\n \"correctedValue\": \"{ full billing object }\",\n \"reason\": \"Added complete billing structure based on schema description mentioning 'invoice generation'\",\n \"scope\": \"schema-driven-expansion\"\n }\n ],\n \"correctionStrategy\": \"aggressive-domain-reconstruction\",\n \"confidence\": \"high\"\n}\n```\n\n## Quality Assurance for Aggressive Corrections\n\n**Before Returning Corrected Arguments**:\n\n1. ✅ Every error from the errors array has been addressed\n2. ✅ **PROPERTY-BY-PROPERTY VERIFICATION**: Each property has been analyzed according to the mandatory protocol\n3. ✅ **DESCRIPTION COMPLIANCE CHECK**: Every property value reflects accurate understanding of its description\n4. ✅ **EXPANSION CHECK**: Additional properties have been added based on schema analysis\n5. ✅ **BUSINESS LOGIC CHECK**: All properties work together in realistic business context\n6. ✅ **DOMAIN CONSISTENCY CHECK**: Values reflect appropriate domain expertise\n7. ✅ **SCHEMA DESCRIPTION COMPLIANCE**: Corrections align with all schema descriptions\n8. ✅ **FUTURE-PROOFING CHECK**: The corrected arguments would handle related use cases\n9. ✅ **SEMANTIC INTEGRITY CHECK**: The entire argument structure tells a coherent business story\n\n## Success Criteria\n\nA successful aggressive correction must:\n\n1. ✅ Address every single error in the `IValidation.IFailure.errors` array\n2. ✅ **DEMONSTRATE PROPERTY-LEVEL ANALYSIS**: Show that every property was analyzed according to the mandatory protocol\n3. ✅ **DESCRIPTION-DRIVEN VALUE CREATION**: Every property value must reflect understanding of its schema description\n4. ✅ **EXPAND BEYOND ERRORS**: Enhance the entire function call based on schema analysis\n5. ✅ **DEMONSTRATE DOMAIN EXPERTISE**: Show deep understanding of the business context\n6. ✅ Use exact enum/const values without approximation\n7. ✅ Generate realistic, contextually rich values throughout the entire structure\n8. ✅ **ACHIEVE HOLISTIC COMPLIANCE**: Ensure the entire corrected structure represents best-practice usage of the function\n9. ✅ Provide comprehensive explanation of both direct fixes and aggressive enhancements\n\nRemember: You are not just an error fixer - you are an **aggressive correction specialist** who transforms mediocre function calls into exemplary ones. Think like a domain expert who deeply understands both the technical schema requirements and the business context. Fix everything that's wrong, and improve everything that could be better.",
|
|
17
|
+
VALIDATE_REPEATED:
|
|
18
|
+
"## Recursive Error Pattern Analysis\n\n### Historical Error Input\n\nYou have been provided with `IValidation.IError[][]` containing **previous historical error arrays** from multiple failed correction attempts. Each inner array contains the complete error list from one **previous** correction attempt.\n\n**CRITICAL**: Compare the current `IValidation.IFailure.errors` with this historical data to identify recurring patterns.\n\n```json\n${{HISTORICAL_ERRORS}}\n```\n\n### Critical Response Protocol\n\n**When error paths recur across current + historical attempts:**\n\n🚨 **NEVER apply the same correction strategy that failed before**\n\n🚨 **Think fundamentally deeper - analyze root architectural causes:**\n\n- Why was the wrong approach chosen repeatedly?\n- What business context was misunderstood?\n- Which schema requirements were overlooked?\n- How should the entire structure be redesigned from first principles?\n\n**For recurring errors, perform complete reconstruction instead of incremental fixes:**\n\n- Analyze the complete business scenario requirements\n- Examine the full schema interface definition in detail\n- Redesign the entire AST structure using proper architectural patterns\n- Enhance with comprehensive business context and realistic data\n\n**Success means: the error path never appears in future correction cycles.**",
|
|
15
19
|
};
|
package/src/orchestrate/call.ts
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
import type { AgenticaContext } from "../context/AgenticaContext";
|
|
17
17
|
import type { AgenticaOperation } from "../context/AgenticaOperation";
|
|
18
18
|
import type { MicroAgenticaContext } from "../context/MicroAgenticaContext";
|
|
19
|
-
import type { AgenticaAssistantMessageEvent, AgenticaExecuteEvent } from "../events";
|
|
19
|
+
import type { AgenticaAssistantMessageEvent, AgenticaExecuteEvent, AgenticaValidateEvent } from "../events";
|
|
20
20
|
import type { AgenticaCallEvent } from "../events/AgenticaCallEvent";
|
|
21
21
|
import type { MicroAgenticaHistory } from "../histories/MicroAgenticaHistory";
|
|
22
22
|
|
|
@@ -34,6 +34,14 @@ import { cancelFunctionFromContext } from "./internal/cancelFunctionFromContext"
|
|
|
34
34
|
export async function call<Model extends ILlmSchema.Model>(
|
|
35
35
|
ctx: AgenticaContext<Model> | MicroAgenticaContext<Model>,
|
|
36
36
|
operations: AgenticaOperation<Model>[],
|
|
37
|
+
): Promise<AgenticaExecuteEvent<Model>[]> {
|
|
38
|
+
return station(ctx, operations, []);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function station<Model extends ILlmSchema.Model>(
|
|
42
|
+
ctx: AgenticaContext<Model> | MicroAgenticaContext<Model>,
|
|
43
|
+
operations: AgenticaOperation<Model>[],
|
|
44
|
+
validateEvents: AgenticaValidateEvent<Model>[],
|
|
37
45
|
): Promise<AgenticaExecuteEvent<Model>[]> {
|
|
38
46
|
// ----
|
|
39
47
|
// EXECUTE CHATGPT API
|
|
@@ -125,6 +133,7 @@ export async function call<Model extends ILlmSchema.Model>(
|
|
|
125
133
|
ctx,
|
|
126
134
|
call,
|
|
127
135
|
0,
|
|
136
|
+
validateEvents,
|
|
128
137
|
);
|
|
129
138
|
ctx.dispatch(exec);
|
|
130
139
|
executes.push(exec);
|
|
@@ -159,16 +168,23 @@ async function propagate<Model extends ILlmSchema.Model>(
|
|
|
159
168
|
ctx: AgenticaContext<Model> | MicroAgenticaContext<Model>,
|
|
160
169
|
call: AgenticaCallEvent<Model>,
|
|
161
170
|
retry: number,
|
|
171
|
+
validateEvents: AgenticaValidateEvent<Model>[],
|
|
162
172
|
): Promise<AgenticaExecuteEvent<Model>> {
|
|
163
173
|
switch (call.operation.protocol) {
|
|
164
174
|
case "http": {
|
|
165
|
-
return propagateHttp({
|
|
175
|
+
return propagateHttp({
|
|
176
|
+
ctx,
|
|
177
|
+
operation: call.operation,
|
|
178
|
+
call,
|
|
179
|
+
retry,
|
|
180
|
+
validateEvents,
|
|
181
|
+
});
|
|
166
182
|
}
|
|
167
183
|
case "class": {
|
|
168
|
-
return propagateClass({ ctx, operation: call.operation, call, retry });
|
|
184
|
+
return propagateClass({ ctx, operation: call.operation, call, retry, validateEvents });
|
|
169
185
|
}
|
|
170
186
|
case "mcp": {
|
|
171
|
-
return propagateMcp({ ctx, operation: call.operation, call, retry });
|
|
187
|
+
return propagateMcp({ ctx, operation: call.operation, call, retry, validateEvents });
|
|
172
188
|
}
|
|
173
189
|
default: {
|
|
174
190
|
call.operation satisfies never;
|
|
@@ -182,6 +198,7 @@ async function propagateHttp<Model extends ILlmSchema.Model>(
|
|
|
182
198
|
ctx: AgenticaContext<Model> | MicroAgenticaContext<Model>;
|
|
183
199
|
operation: AgenticaOperation.Http<Model>;
|
|
184
200
|
call: AgenticaCallEvent<Model>;
|
|
201
|
+
validateEvents: AgenticaValidateEvent<Model>[];
|
|
185
202
|
retry: number;
|
|
186
203
|
},
|
|
187
204
|
): Promise<AgenticaExecuteEvent<Model>> {
|
|
@@ -193,13 +210,13 @@ async function propagateHttp<Model extends ILlmSchema.Model>(
|
|
|
193
210
|
props.call.arguments,
|
|
194
211
|
);
|
|
195
212
|
if (check.success === false) {
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
);
|
|
213
|
+
const ve: AgenticaValidateEvent<Model> = createValidateEvent({
|
|
214
|
+
id: props.call.id,
|
|
215
|
+
operation: props.call.operation,
|
|
216
|
+
result: check,
|
|
217
|
+
});
|
|
218
|
+
props.ctx.dispatch(ve);
|
|
219
|
+
props.validateEvents.push(ve);
|
|
203
220
|
|
|
204
221
|
if (props.retry++ < (props.ctx.config?.retry ?? AgenticaConstant.RETRY)) {
|
|
205
222
|
const trial: AgenticaExecuteEvent<Model> | null = await correct(
|
|
@@ -207,6 +224,7 @@ async function propagateHttp<Model extends ILlmSchema.Model>(
|
|
|
207
224
|
props.call,
|
|
208
225
|
props.retry,
|
|
209
226
|
check.errors,
|
|
227
|
+
props.validateEvents,
|
|
210
228
|
);
|
|
211
229
|
if (trial !== null) {
|
|
212
230
|
return trial;
|
|
@@ -227,7 +245,13 @@ async function propagateHttp<Model extends ILlmSchema.Model>(
|
|
|
227
245
|
// DISPATCH EVENT
|
|
228
246
|
return (
|
|
229
247
|
(success === false
|
|
230
|
-
? await correct(
|
|
248
|
+
? await correct(
|
|
249
|
+
props.ctx,
|
|
250
|
+
props.call,
|
|
251
|
+
props.retry,
|
|
252
|
+
response.body,
|
|
253
|
+
props.validateEvents,
|
|
254
|
+
)
|
|
231
255
|
: null)
|
|
232
256
|
?? createExecuteEvent({
|
|
233
257
|
operation: props.call.operation,
|
|
@@ -261,6 +285,7 @@ async function propagateClass<Model extends ILlmSchema.Model>(props: {
|
|
|
261
285
|
ctx: AgenticaContext<Model> | MicroAgenticaContext<Model>;
|
|
262
286
|
operation: AgenticaOperation.Class<Model>;
|
|
263
287
|
call: AgenticaCallEvent<Model>;
|
|
288
|
+
validateEvents: AgenticaValidateEvent<Model>[];
|
|
264
289
|
retry: number;
|
|
265
290
|
}): Promise<AgenticaExecuteEvent<Model>> {
|
|
266
291
|
// ----
|
|
@@ -271,16 +296,16 @@ async function propagateClass<Model extends ILlmSchema.Model>(props: {
|
|
|
271
296
|
props.call.arguments,
|
|
272
297
|
);
|
|
273
298
|
if (check.success === false) {
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
);
|
|
299
|
+
const ve: AgenticaValidateEvent<Model> = createValidateEvent({
|
|
300
|
+
id: props.call.id,
|
|
301
|
+
operation: props.call.operation,
|
|
302
|
+
result: check,
|
|
303
|
+
});
|
|
304
|
+
props.ctx.dispatch(ve);
|
|
305
|
+
props.validateEvents.push(ve);
|
|
281
306
|
return (
|
|
282
307
|
(props.retry++ < (props.ctx.config?.retry ?? AgenticaConstant.RETRY)
|
|
283
|
-
? await correct(props.ctx, props.call, props.retry, check.errors)
|
|
308
|
+
? await correct(props.ctx, props.call, props.retry, check.errors, props.validateEvents)
|
|
284
309
|
: null)
|
|
285
310
|
?? createExecuteEvent({
|
|
286
311
|
operation: props.call.operation,
|
|
@@ -322,6 +347,7 @@ async function propagateMcp<Model extends ILlmSchema.Model>(props: {
|
|
|
322
347
|
ctx: AgenticaContext<Model> | MicroAgenticaContext<Model>;
|
|
323
348
|
operation: AgenticaOperation.Mcp<Model>;
|
|
324
349
|
call: AgenticaCallEvent<Model>;
|
|
350
|
+
validateEvents: AgenticaValidateEvent<Model>[];
|
|
325
351
|
retry: number;
|
|
326
352
|
}): Promise<AgenticaExecuteEvent<Model>> {
|
|
327
353
|
// ----
|
|
@@ -390,9 +416,7 @@ async function executeMcpOperation<Model extends ILlmSchema.Model>(
|
|
|
390
416
|
operationArguments: Record<string, unknown>,
|
|
391
417
|
): Promise<unknown> {
|
|
392
418
|
return operation.controller.client.callTool({
|
|
393
|
-
|
|
394
419
|
method: operation.function.name,
|
|
395
|
-
|
|
396
420
|
name: operation.function.name,
|
|
397
421
|
arguments: operationArguments,
|
|
398
422
|
}).then(v => v.content);
|
|
@@ -403,6 +427,7 @@ async function correct<Model extends ILlmSchema.Model>(
|
|
|
403
427
|
call: AgenticaCallEvent<Model>,
|
|
404
428
|
retry: number,
|
|
405
429
|
error: unknown,
|
|
430
|
+
validateEvents: AgenticaValidateEvent<Model>[],
|
|
406
431
|
): Promise<AgenticaExecuteEvent<Model> | null> {
|
|
407
432
|
// ----
|
|
408
433
|
// EXECUTE CHATGPT API
|
|
@@ -451,11 +476,19 @@ async function correct<Model extends ILlmSchema.Model>(
|
|
|
451
476
|
} satisfies OpenAI.ChatCompletionToolMessageParam,
|
|
452
477
|
{
|
|
453
478
|
role: "system",
|
|
454
|
-
content:
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
479
|
+
content: ctx.config?.systemPrompt?.validate?.(validateEvents.slice(0, -1))
|
|
480
|
+
?? [
|
|
481
|
+
AgenticaSystemPrompt.VALIDATE,
|
|
482
|
+
...(validateEvents.length > 1
|
|
483
|
+
? [
|
|
484
|
+
"",
|
|
485
|
+
AgenticaSystemPrompt.VALIDATE_REPEATED.replace(
|
|
486
|
+
"${{HISTORICAL_ERRORS}}",
|
|
487
|
+
JSON.stringify(validateEvents.slice(0, -1).map(e => e.result.errors)),
|
|
488
|
+
),
|
|
489
|
+
]
|
|
490
|
+
: []),
|
|
491
|
+
].join("\n"),
|
|
459
492
|
},
|
|
460
493
|
],
|
|
461
494
|
// STACK FUNCTIONS
|
|
@@ -470,10 +503,8 @@ async function correct<Model extends ILlmSchema.Model>(
|
|
|
470
503
|
* The property and value have a type mismatch, but it works.
|
|
471
504
|
*/
|
|
472
505
|
parameters: (
|
|
473
|
-
"separated" in call.operation.function
|
|
474
|
-
|
|
475
|
-
&& call.operation.function.separated !== undefined
|
|
476
|
-
|
|
506
|
+
("separated" in call.operation.function
|
|
507
|
+
&& call.operation.function.separated !== undefined)
|
|
477
508
|
? (call.operation.function.separated?.llm
|
|
478
509
|
?? ({
|
|
479
510
|
$defs: {},
|
|
@@ -519,6 +550,7 @@ async function correct<Model extends ILlmSchema.Model>(
|
|
|
519
550
|
arguments: JSON.parse(toolCall.function.arguments) as Record<string, unknown>,
|
|
520
551
|
}),
|
|
521
552
|
retry,
|
|
553
|
+
validateEvents,
|
|
522
554
|
);
|
|
523
555
|
}
|
|
524
556
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ILlmSchema } from "@samchon/openapi";
|
|
2
2
|
|
|
3
|
+
import type { AgenticaValidateEvent } from "../events/AgenticaValidateEvent";
|
|
3
4
|
import type { AgenticaExecuteHistory } from "../histories/AgenticaExecuteHistory";
|
|
4
5
|
import type { AgenticaHistory } from "../histories/AgenticaHistory";
|
|
5
6
|
|
|
@@ -27,6 +28,11 @@ export interface IAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
27
28
|
/**
|
|
28
29
|
* Common system prompt that would be used in every situation.
|
|
29
30
|
*
|
|
31
|
+
* This prompt establishes the foundational behavior and personality of
|
|
32
|
+
* the AI agent across all interaction phases. It defines the agent's
|
|
33
|
+
* core identity, communication style, and general operating principles
|
|
34
|
+
* that remain consistent throughout the conversation flow.
|
|
35
|
+
*
|
|
30
36
|
* @param config Configuration of the agent
|
|
31
37
|
* @returns The common system prompt
|
|
32
38
|
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/common.md
|
|
@@ -41,9 +47,16 @@ export interface IAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
41
47
|
* {@link Agentica} says that it is a circumstance that nothing has
|
|
42
48
|
* been initialized yet.
|
|
43
49
|
*
|
|
44
|
-
* In that case, the `initialize` system prompt would be used.
|
|
45
|
-
*
|
|
46
|
-
* with
|
|
50
|
+
* In that case, the `initialize` system prompt would be used. This is
|
|
51
|
+
* the most basic prompt that simply establishes the AI as a helpful
|
|
52
|
+
* assistant with access to supplied tools. It provides minimal guidance,
|
|
53
|
+
* allowing the AI to respond naturally to user requests and automatically
|
|
54
|
+
* identify when function calls are appropriate based on the available
|
|
55
|
+
* tools and user context.
|
|
56
|
+
*
|
|
57
|
+
* The initialize prompt is intentionally simple and generic, serving as
|
|
58
|
+
* a foundation for general conversation and tool usage without specific
|
|
59
|
+
* constraints or specialized behaviors.
|
|
47
60
|
*
|
|
48
61
|
* @param histories Histories of the previous prompts
|
|
49
62
|
* @returns initialize system prompt
|
|
@@ -58,16 +71,23 @@ export interface IAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
58
71
|
* functions to call by asking to the A.I. agent with the previous
|
|
59
72
|
* prompt histories.
|
|
60
73
|
*
|
|
61
|
-
* In that case, this `select` system prompt would be used.
|
|
62
|
-
*
|
|
63
|
-
*
|
|
74
|
+
* In that case, this `select` system prompt would be used. This prompt
|
|
75
|
+
* specifically instructs the AI to use the `getApiFunctions()` tool to
|
|
76
|
+
* select appropriate functions for the user's request. It emphasizes
|
|
77
|
+
* the importance of analyzing function relationships and prerequisites
|
|
78
|
+
* between functions to ensure proper execution order.
|
|
79
|
+
*
|
|
80
|
+
* The select prompt includes internationalization support, instructing
|
|
81
|
+
* the AI to consider the user's language locale and translate responses
|
|
82
|
+
* accordingly. If no suitable functions are found, the AI is allowed to
|
|
83
|
+
* respond with its own message rather than forcing a function selection.
|
|
64
84
|
*
|
|
65
85
|
* Note that, the `"select"` means only the function selection. It does
|
|
66
86
|
* not contain the filling argument or executing the function. It
|
|
67
87
|
* literally contains only the selection process.
|
|
68
88
|
*
|
|
69
89
|
* @param histories Histories of the previous prompts
|
|
70
|
-
* @returns select system
|
|
90
|
+
* @returns select system prompt
|
|
71
91
|
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/select.md
|
|
72
92
|
*/
|
|
73
93
|
select?: (histories: AgenticaHistory<Model>[]) => string;
|
|
@@ -79,9 +99,14 @@ export interface IAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
79
99
|
* functions to call by asking to the A.I. agent with the previous
|
|
80
100
|
* prompt histories.
|
|
81
101
|
*
|
|
82
|
-
* In that case, this `cancel` system prompt would be used.
|
|
83
|
-
*
|
|
84
|
-
*
|
|
102
|
+
* In that case, this `cancel` system prompt would be used. This prompt
|
|
103
|
+
* provides very specific instructions for the AI to use the
|
|
104
|
+
* `getApiFunctions()` tool to select functions that should be cancelled.
|
|
105
|
+
*
|
|
106
|
+
* The cancel prompt is notably strict - if the AI cannot find any
|
|
107
|
+
* proper functions to cancel, it is explicitly instructed to remain
|
|
108
|
+
* silent and take no action whatsoever ("don't talk, don't do anything").
|
|
109
|
+
* This prevents unnecessary responses when cancellation is not applicable.
|
|
85
110
|
*
|
|
86
111
|
* @param histories Histories of the previous prompts
|
|
87
112
|
* @returns cancel system prompt
|
|
@@ -97,16 +122,58 @@ export interface IAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
97
122
|
* function calling feature with the previous prompt histories, and
|
|
98
123
|
* executing the arguments filled function with validation feedback.
|
|
99
124
|
*
|
|
100
|
-
* In that case, this `execute` system prompt would be used.
|
|
101
|
-
*
|
|
102
|
-
*
|
|
125
|
+
* In that case, this `execute` system prompt would be used. This prompt
|
|
126
|
+
* instructs the AI to use the supplied tools to assist the user, with
|
|
127
|
+
* specific guidance on handling insufficient information scenarios.
|
|
128
|
+
* When the AI lacks enough context to compose proper function arguments,
|
|
129
|
+
* it is instructed to ask the user for additional information in a
|
|
130
|
+
* concise and clear manner.
|
|
131
|
+
*
|
|
132
|
+
* The execute prompt also provides important context about the "tool"
|
|
133
|
+
* role message structure, explaining that the `function` property
|
|
134
|
+
* contains API operation metadata (schema, purpose, parameters, return
|
|
135
|
+
* types) while the `data` property contains the actual return values
|
|
136
|
+
* from function executions.
|
|
103
137
|
*
|
|
104
138
|
* @param histories Histories of the previous prompts
|
|
105
139
|
* @returns execute system prompt
|
|
106
|
-
* https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/execute.md
|
|
140
|
+
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/execute.md
|
|
107
141
|
*/
|
|
108
142
|
execute?: (histories: AgenticaHistory<Model>[]) => string;
|
|
109
143
|
|
|
144
|
+
/**
|
|
145
|
+
* Validation feedback system prompt.
|
|
146
|
+
*
|
|
147
|
+
* When the AI generates function arguments that fail type validation
|
|
148
|
+
* during the execution phase, this prompt provides the system instructions
|
|
149
|
+
* for analyzing {@link IValidation.IFailure} results and generating
|
|
150
|
+
* corrective feedback.
|
|
151
|
+
*
|
|
152
|
+
* This specialized prompt enables the AI to:
|
|
153
|
+
* - Parse detailed validation error information from typia validation results
|
|
154
|
+
* - Identify specific type mismatches, missing properties, and format violations
|
|
155
|
+
* - Handle complex union type failures with discriminator property analysis
|
|
156
|
+
* - Generate actionable correction guidance for parameter regeneration
|
|
157
|
+
* - Distinguish between partial fixes and complete reconstruction scenarios
|
|
158
|
+
*
|
|
159
|
+
* The validation feedback agent acts as an intermediary between the main
|
|
160
|
+
* AI agent and the function execution system, providing structured feedback
|
|
161
|
+
* that helps improve function calling accuracy through iterative correction.
|
|
162
|
+
* This is particularly valuable for complex function schemas where precise
|
|
163
|
+
* type conformance is critical.
|
|
164
|
+
*
|
|
165
|
+
* Key capabilities include:
|
|
166
|
+
* - Union type analysis with discriminator property detection
|
|
167
|
+
* - Granular error path reporting (e.g., "input.user.profile.age")
|
|
168
|
+
* - Format-specific guidance (UUID, email, numeric constraints)
|
|
169
|
+
* - Complete reconstruction recommendations for incompatible values
|
|
170
|
+
*
|
|
171
|
+
* @props events The previous validation events containing the IValidation.IFailure
|
|
172
|
+
* @returns validation feedback system prompt
|
|
173
|
+
* @default Built-in validation feedback prompt optimized for typia IValidation.IFailure processing
|
|
174
|
+
*/
|
|
175
|
+
validate?: (events: AgenticaValidateEvent<Model>[]) => string;
|
|
176
|
+
|
|
110
177
|
/**
|
|
111
178
|
* Describe system prompt.
|
|
112
179
|
*
|
|
@@ -114,11 +181,24 @@ export interface IAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
114
181
|
* the executed functions by requesting to the A.I. agent with the
|
|
115
182
|
* previous prompt histories.
|
|
116
183
|
*
|
|
117
|
-
* In that case, this `describe` system prompt would be used.
|
|
118
|
-
*
|
|
119
|
-
*
|
|
184
|
+
* In that case, this `describe` system prompt would be used. This prompt
|
|
185
|
+
* instructs the AI to provide detailed descriptions of function call
|
|
186
|
+
* return values rather than brief summaries. It emphasizes comprehensive
|
|
187
|
+
* reporting to ensure users receive thorough information about the
|
|
188
|
+
* function execution results.
|
|
120
189
|
*
|
|
121
|
-
*
|
|
190
|
+
* The describe prompt specifies several formatting requirements:
|
|
191
|
+
* - Content must be formatted in markdown
|
|
192
|
+
* - Mermaid syntax should be utilized for diagrams when appropriate
|
|
193
|
+
* - Images should be included using markdown image syntax
|
|
194
|
+
* - Internationalization support with translation to user's language
|
|
195
|
+
* locale when the description language differs from the user's language
|
|
196
|
+
*
|
|
197
|
+
* The prompt receives execution histories specifically, allowing the AI
|
|
198
|
+
* to access both the function metadata and actual execution results
|
|
199
|
+
* for comprehensive reporting.
|
|
200
|
+
*
|
|
201
|
+
* @param histories Histories of the previous prompts and their execution results
|
|
122
202
|
* @returns describe system prompt
|
|
123
203
|
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/describe.md
|
|
124
204
|
*/
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ILlmSchema } from "@samchon/openapi";
|
|
2
2
|
|
|
3
|
+
import type { AgenticaValidateEvent } from "../events/AgenticaValidateEvent";
|
|
3
4
|
import type { AgenticaExecuteHistory } from "../histories/AgenticaExecuteHistory";
|
|
4
5
|
import type { MicroAgenticaHistory } from "../histories/MicroAgenticaHistory";
|
|
5
6
|
|
|
@@ -13,8 +14,8 @@ import type { IMicroAgenticaConfig } from "./IMicroAgenticaConfig";
|
|
|
13
14
|
* {@link MicroAgentica}.
|
|
14
15
|
*
|
|
15
16
|
* You can customize the system prompt by configuring the
|
|
16
|
-
* {@link
|
|
17
|
-
* {@link
|
|
17
|
+
* {@link IMicroAgenticaConfig.systemPrompt} property when creating a new
|
|
18
|
+
* {@link MicroAgentica} instance.
|
|
18
19
|
*
|
|
19
20
|
* If you don't configure any system prompts, the default system prompts
|
|
20
21
|
* would be used which are written in the below directory as markdown
|
|
@@ -28,7 +29,14 @@ export interface IMicroAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
28
29
|
/**
|
|
29
30
|
* Common system prompt that would be used in every situation.
|
|
30
31
|
*
|
|
31
|
-
*
|
|
32
|
+
* This prompt establishes the foundational behavior and personality of
|
|
33
|
+
* the Micro Agentic AI across all interaction phases. It defines the
|
|
34
|
+
* agent's core identity, communication style, and general operating
|
|
35
|
+
* principles that remain consistent throughout the streamlined conversation
|
|
36
|
+
* flow. Unlike the full Agentica system, MicroAgentica focuses on
|
|
37
|
+
* simplified, direct interactions with reduced complexity.
|
|
38
|
+
*
|
|
39
|
+
* @param config Configuration of the micro agent
|
|
32
40
|
* @returns The common system prompt
|
|
33
41
|
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/common.md
|
|
34
42
|
*/
|
|
@@ -37,33 +45,93 @@ export interface IMicroAgenticaSystemPrompt<Model extends ILlmSchema.Model> {
|
|
|
37
45
|
/**
|
|
38
46
|
* Execute system prompt.
|
|
39
47
|
*
|
|
40
|
-
* The {@link
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
48
|
+
* The {@link MicroAgentica} has a streamlined process for filling the
|
|
49
|
+
* arguments of functions by the LLM (Large Language Model) function
|
|
50
|
+
* calling feature with the previous prompt histories, and executing
|
|
51
|
+
* the arguments filled function with validation feedback.
|
|
52
|
+
*
|
|
53
|
+
* In that case, this `execute` system prompt would be used. This prompt
|
|
54
|
+
* instructs the AI to use the supplied tools to assist the user, with
|
|
55
|
+
* specific guidance on handling insufficient information scenarios.
|
|
56
|
+
* When the AI lacks enough context to compose proper function arguments,
|
|
57
|
+
* it is instructed to ask the user for additional information in a
|
|
58
|
+
* concise and clear manner.
|
|
44
59
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
60
|
+
* The execute prompt also provides important context about the "tool"
|
|
61
|
+
* role message structure, explaining that the `function` property
|
|
62
|
+
* contains API operation metadata (schema, purpose, parameters, return
|
|
63
|
+
* types) while the `data` property contains the actual return values
|
|
64
|
+
* from function executions.
|
|
65
|
+
*
|
|
66
|
+
* Note: This can be set to `null` to disable the execute phase in
|
|
67
|
+
* MicroAgentica, making it a pure conversational agent without
|
|
68
|
+
* function calling capabilities.
|
|
48
69
|
*
|
|
49
70
|
* @param histories Histories of the previous prompts
|
|
50
71
|
* @returns execute system prompt
|
|
51
|
-
* https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/execute.md
|
|
72
|
+
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/execute.md
|
|
52
73
|
*/
|
|
53
74
|
execute?: null | ((histories: MicroAgenticaHistory<Model>[]) => string);
|
|
54
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Validation feedback system prompt.
|
|
78
|
+
*
|
|
79
|
+
* When the AI generates function arguments that fail type validation
|
|
80
|
+
* during the execution phase, this prompt provides the system instructions
|
|
81
|
+
* for analyzing {@link IValidation.IFailure} results and generating
|
|
82
|
+
* corrective feedback in the MicroAgentica environment.
|
|
83
|
+
*
|
|
84
|
+
* This specialized prompt enables the AI to:
|
|
85
|
+
* - Parse detailed validation error information from typia validation results
|
|
86
|
+
* - Identify specific type mismatches, missing properties, and format violations
|
|
87
|
+
* - Handle complex union type failures with discriminator property analysis
|
|
88
|
+
* - Generate actionable correction guidance for parameter regeneration
|
|
89
|
+
* - Distinguish between partial fixes and complete reconstruction scenarios
|
|
90
|
+
*
|
|
91
|
+
* The validation feedback agent in MicroAgentica operates with the same
|
|
92
|
+
* precision as the full Agentica system but in a more streamlined context.
|
|
93
|
+
* It acts as an intermediary between the micro AI agent and the function
|
|
94
|
+
* execution system, providing structured feedback that helps improve
|
|
95
|
+
* function calling accuracy through iterative correction.
|
|
96
|
+
*
|
|
97
|
+
* Key capabilities include:
|
|
98
|
+
* - Union type analysis with discriminator property detection
|
|
99
|
+
* - Granular error path reporting (e.g., "input.user.profile.age")
|
|
100
|
+
* - Format-specific guidance (UUID, email, numeric constraints)
|
|
101
|
+
* - Complete reconstruction recommendations for incompatible values
|
|
102
|
+
* - Optimized for the simplified MicroAgentica interaction model
|
|
103
|
+
*
|
|
104
|
+
* @param events The previous validation events containing the IValidation.IFailure
|
|
105
|
+
* @returns validation feedback system prompt
|
|
106
|
+
* @default Built-in validation feedback prompt optimized for typia IValidation.IFailure processing
|
|
107
|
+
*/
|
|
108
|
+
validate?: (events: AgenticaValidateEvent<Model>[]) => string;
|
|
109
|
+
|
|
55
110
|
/**
|
|
56
111
|
* Describe system prompt.
|
|
57
112
|
*
|
|
58
|
-
* The {@link
|
|
113
|
+
* The {@link MicroAgentica} has a process describing the return values of
|
|
59
114
|
* the executed functions by requesting to the A.I. agent with the
|
|
60
115
|
* previous prompt histories.
|
|
61
116
|
*
|
|
62
|
-
* In that case, this `describe` system prompt would be used.
|
|
63
|
-
*
|
|
64
|
-
*
|
|
117
|
+
* In that case, this `describe` system prompt would be used. This prompt
|
|
118
|
+
* instructs the AI to provide detailed descriptions of function call
|
|
119
|
+
* return values rather than brief summaries. It emphasizes comprehensive
|
|
120
|
+
* reporting to ensure users receive thorough information about the
|
|
121
|
+
* function execution results.
|
|
65
122
|
*
|
|
66
|
-
*
|
|
123
|
+
* The describe prompt specifies several formatting requirements:
|
|
124
|
+
* - Content must be formatted in markdown
|
|
125
|
+
* - Mermaid syntax should be utilized for diagrams when appropriate
|
|
126
|
+
* - Images should be included using markdown image syntax
|
|
127
|
+
* - Internationalization support with translation to user's language
|
|
128
|
+
* locale when the description language differs from the user's language
|
|
129
|
+
*
|
|
130
|
+
* The prompt receives execution histories specifically, allowing the AI
|
|
131
|
+
* to access both the function metadata and actual execution results
|
|
132
|
+
* for comprehensive reporting in the MicroAgentica streamlined environment.
|
|
133
|
+
*
|
|
134
|
+
* @param histories Histories of the previous prompts and their execution results
|
|
67
135
|
* @returns describe system prompt
|
|
68
136
|
* @default https://github.com/wrtnlabs/agentica/tree/main/packages/core/prompts/describe.md
|
|
69
137
|
*/
|