Tool invocation error correction method and system for large language model agent
Patent Information
- Application Number
- CN202611129594.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-28
- Publication Date
- 2026-10-27
AI Technical Summary
[0005]本发明旨在解决现有大语言模型智能体在调用数据库查询工具、脚本工具、文件处理工具及外部服务接口执行任务时,历史失败信息通常仅以日志或自然语言反思形式保存,难以被任务规划器直接复用;
本发明将任务计划、调用参数、上下文摘要、运行环境及调用结果共同组织为执行轨迹,并将失败轨迹转化为包含适用前提、纠错约束和参数模板的结构化反思记忆,使历史失败不再仅作为事后日志保存,而能够被任务规划器直接解析并作用于后续工具调用。由于反思记忆同时保留失败发生时的工具类型、权限状态、依赖关系和环境条件,纠错经验能够在满足适用前提时被定向调用,从而避免仅依据文本语义相似而将一种工具或环境下的修复方式错误迁移至另一任务。由此实现了失败经验由不可直接复用的记录向具有适用边界的可执行纠错规则的转变。
Smart Images

Figure CN122985264A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of artificial intelligence and computer task execution control technology, specifically to a method and system for correcting tool invocation errors in a large language model intelligent agent. Background Technology
[0002] With the application of large language model agents in data analysis, code processing, automated operation and maintenance, and business process automation, the agents need to generate task plans based on task objectives and call database query tools, script tools, file processing tools, and external service interfaces to complete the tasks. The tool invocation process involves parameter configuration, step dependencies, execution permissions, runtime environment, and preceding output transmission. An abnormality in any of these links may lead to tool invocation failure or task results that do not meet expectations.
[0003] Existing intelligent agent systems typically handle errors by saving error logs, regenerating task plans, or retrying failed steps using error-handling tools. This approach primarily focuses on post-event correction for the current task. The error conditions, environmental states, and repair methods contained in historical failure trajectories are difficult to translate into error-correction information that can be directly invoked in subsequent tasks. Therefore, similar tasks may still experience recurring issues such as missing parameters, incorrect tool order, insufficient permissions, or missing context.
[0004] Some systems generate reflective content in natural language form using large language models. However, natural language reflection typically lacks clear applicable preconditions, conditional action rules, and parameter structures, making it difficult for task planners to execute directly. Furthermore, directly incorporating unverified reflective content into subsequent task plans may introduce new step conflicts or parameter errors. Therefore, it is necessary to structure historical failure trajectories and verify the applicability and effectiveness of the error correction content for the current task before actual execution. Summary of the Invention
[0005] This invention aims to address the problem that when existing large language model intelligent agents call database query tools, script tools, file processing tools, and external service interfaces to execute tasks, historical failure information is usually only saved in the form of logs or natural language reflection, which is difficult to be directly reused by task planners.
[0006] Meanwhile, unverified error correction content may be incorrectly injected into subsequent task plans, leading to problems such as incorrect parameters, incorrect call order, incorrect permissions, missing context, or abnormal output structure.
[0007] To address the aforementioned technical problems, this invention provides a method for correcting tool invocation errors in a large language model agent, comprising: Record task plans, call parameters, output, errors, context summaries, and environment states to form an execution trajectory; The failure trajectory is filtered and the failure type is determined. Applicable premises, error correction constraints and parameter templates are generated by the large language model and structured into reflective memory. The reflective memory is injected into the tool call chain reconstructed from the failure trajectory. The replay is performed in an isolated environment and the initial credibility is determined. Before executing a task, extract the task objective, tool sequence, key entities and environmental status, weighted match the failure trajectory, select the reflection memory that matches the applicable premise and whose credibility reaches the preset credibility threshold, and write the error correction constraints and parameter templates into the task plan and call parameters to form the tool call chain after repair. After verification and repair, the parameters, dependencies and permissions of the tool call chain are isolated and simulated. If the verification fails, adjustments are made and the verification is repeated. If the termination condition is met and the verification still fails, the actual execution is stopped. If the verification passes, the actual execution is performed. After completing the actual execution, the tools, parameters, and output structures of the simulated execution and the actual execution are compared to determine the execution consistency. The credibility of the selected reflective memory is updated based on the replay verification results, the actual execution status, and the execution consistency. The selected reflective memory is retained or archived based on the updated credibility, and the actual execution result or verification failure information is output.
[0008] Furthermore, the formation of the execution trajectory includes: Create a trajectory record for each tool call, aggregated by task identifier and sorted by step number; Write the plan snapshot, tool name, tool version, and input parameters to the call input area; write the call output and error code to the call result area; and write permissions, dependency versions, network status, and resource level to the environment status area. Extract the task objective, key entities, and references to the results obtained from the dialogue history and intermediate results generated up to the start of the current call to form a context summary; The call input area, call result area, environment status area, and context summary are associated by task identifier for failure trajectory filtering and matching.
[0009] Furthermore, the filtering of failed trajectories and determination of failure types includes: When the error code, exception stack, parameter verification result, output structure, or task result meets the failure judgment conditions, the corresponding step and its predecessor dependencies are determined as the failure trajectory. The failure trajectory is matched with the preset failure rules. When a match is found, the corresponding failure type is output. When a match is not found, the tool sequence, previous output, context summary and environment state are input into the classification model. When the classification confidence reaches the automatic classification threshold, the failure type output by the classification model is saved. When the automatic classification threshold is not reached, the failure trajectory is sent to the verification interface, and the failure type returned by the verification interface is used to replace the classification model output.
[0010] Furthermore, the process of forming reflective memories and determining initial credibility includes: Input the failure trajectory and failure type into the large language model to generate applicable premises, error correction constraints and parameter templates; Convert applicable prerequisites into key-value pairs, error correction constraints into conditional action records, and parameter templates into parameter skeletons with placeholders. Verify the parsability of the conditional action record and the parameter structure of the parameter skeleton; When the verification passes, a reflective memory is formed. The reflective memory is injected into the tool call chain reconstructed from the failure trajectory to form a pre-verification call chain. It is replayed in an isolated environment, and the initial credibility is determined based on the error elimination status, constraint satisfaction status, and output structure conformity status. Reflective memories are linked to failure trajectories and stored together.
[0011] Furthermore, the weighted matching failure trajectory includes: Build keyword inverted index and semantic vector index for failed trajectories, and recall candidate failed trajectories based on the two types of indexes; Calculate the semantic similarity of the task target, the similarity of the tool sequence, the overlap of entities, and the matching degree of the environment. Sum the computable features according to the normalized weights to form a comprehensive similarity. When the overall similarity reaches a preset similarity threshold, an injection candidate is formed; when it is lower than the preset similarity threshold but reaches the recall threshold, a bypass prompt is formed, and the bypass prompt is sent to the task planner without being written into the task plan. Exclude injection candidates that do not meet the applicable premises or whose credibility does not reach the preset credibility threshold, and determine the reflective memory corresponding to the remaining injection candidates as the selected reflective memory.
[0012] Furthermore, the step of writing the error correction constraints and parameter templates into the task plan and invocation parameters includes: Analyze the conditional action records and write the actions that meet the conditions for the task to be executed as pre-check items, adjustment items, or prohibited items in the task plan; Match the placeholders in the parameter skeleton with the entities and input values of the task to be executed, and merge the filled parameter skeleton that has passed the parameter structure validation into the call parameters; Add a reflective memory marker to the written content; When a static verification exception or simulation execution exception is detected due to written content, the same source written content is deleted according to the reflection memory identifier, and the task plan and calling parameters before the write are restored.
[0013] Furthermore, the verification and repair of the tool call chain parameters, dependencies, and permissions, and the isolation simulation, include: Based on the tool parameter structure, preceding outputs, and permission records, verify parameters, dependencies, and permissions. If the verification fails, output the failure steps. If the verification passes, the repaired tool call chain is executed in a container isolation environment with a running image that is identical to the actual execution environment; Read-only tools connect to read-only data copies or desensitized snapshots. The writing tools, script tools, and external interfaces are generated by the isolation adaptation layer based on the tool interface definition and the success trajectory in the historical execution trajectory, and the simulated output is constructed according to the interface contract. The simulation will terminate and output the failed steps if the preset time limit is exceeded. When the simulation is completed, the simulation execution results of each step will be output.
[0014] Furthermore, the re-verification after adjustment when failing includes: Check the required parameters, parameter types, prerequisites, permissions, output structure, and error correction constraint satisfaction status of the tool call chain after repair. Calculate the output score from the simulated input-output discrimination model and determine the current verification failure type based on the check results and the output score. Based on the current verification failure type, perform parameter completion, step rearrangement, context supplementation, or tool replacement to form a new repaired tool call chain and re-verify; When the number of re-verifications reaches the preset number of re-verifications, or when the number of consecutive occurrences of the same verification failure type reaches the preset number of repetitions, the termination condition is determined to be met, the actual execution is stopped, and verification failure information is output.
[0015] Furthermore, the update of the credibility of the selected reflective memory includes: When the replay verification passes and the actual execution is completed, the tools, parameters, and output structures of the simulated execution and the actual execution are compared, and a weighted average is used to form the execution consistency. The credibility is increased when the execution is successful and the execution consistency reaches the consistency threshold; the credibility is decreased when the execution fails or the execution consistency does not reach the consistency threshold. If the replay verification fails even after reaching the termination condition, the credibility is reduced based on the verification failure result. When the selected reflective memory is not matched within a preset period, its credibility is reduced by the idle coefficient. Based on the updated credibility, the selected reflective memories are added to the injection candidate set, retained, or archived.
[0016] The present invention also provides a tool call error correction system for a large language model intelligent agent, including a trajectory formation module, a reflective memory construction module, a retrieval injection module, a replay execution module, and a credibility update module.
[0017] The trajectory formation module is used to record task plans, call parameters, outputs, errors, context summaries, and environmental states to form an execution trajectory.
[0018] The reflexive memory construction module is used to filter failure trajectories and determine failure types. It generates applicable premises, error correction constraints, and parameter templates from a large language model and structures them into reflexive memories. The reflexive memories are injected into the tool call chain reconstructed from the failure trajectories, and replayed in an isolated environment to determine the initial credibility.
[0019] The retrieval and injection module is used to extract task objectives, tool sequences, key entities and environmental states before the task to be executed, weighted match failure trajectories, select reflective memories that match applicable premises and whose credibility reaches a preset credibility threshold, and write error correction constraints and parameter templates into the task plan and call parameters to form a repaired tool call chain.
[0020] The replay execution module is used to verify the parameters, dependencies, and permissions of the tool call chain after repair and to isolate and simulate them. If it fails, it is adjusted and re-verified. If it still fails after reaching the termination condition, it stops the real execution. If it passes, it is executed in real.
[0021] The credibility update module is used to compare the tools, parameters and output structure of the simulated execution and the actual execution after the actual execution to form an execution consistency. It updates the credibility of the selected reflection memory based on the replay verification results, the actual execution status and the execution consistency. Based on the updated credibility, it retains or archives the selected reflection memory and outputs the actual execution result or verification failure information.
[0022] The beneficial effects of this invention are: This invention organizes task plans, call parameters, context summaries, runtime environment, and call results into an execution trajectory. It transforms the failure trajectory into a structured reflective memory containing applicable prerequisites, error-correcting constraints, and parameter templates. This allows historical failures to be directly parsed by the task planner and applied to subsequent tool calls, rather than merely being saved as a post-event log. Because the reflective memory simultaneously retains the tool type, permission status, dependencies, and environmental conditions at the time of failure, error-correcting experience can be invoked when applicable prerequisites are met. This avoids incorrectly migrating repair methods from one tool or environment to another task based solely on semantic similarity. Thus, it transforms failure experience from unreusable records into executable error-correcting rules with applicable boundaries.
[0023] This invention combines similar failure trajectory retrieval, applicable prerequisite gating, and credibility gating. Before actual execution, it writes eligible error-correction constraints and parameter templates into the task plan and call parameters, and verifies the repaired tool call chain through static verification and isolation simulation. This process does not simply retry the original steps after an error occurs; instead, it proactively detects missing parameters, incorrect call order, insufficient permissions, data inconsistencies between steps, and abnormal output structures before actual data writing, file modification, or changes in external service status occur, and prevents actual execution when termination conditions are met. Therefore, this invention shifts the detection point of tool call errors from after actual execution to before, while simultaneously balancing the actual verification of read-only tools and the side-effect-free simulation of write tools, reducing the possibility of irreversible business impacts from erroneous calls.
[0024] This invention further updates the credibility of reflective memories based on replay verification results, actual execution status, and the consistency between simulated and actual execution, allowing the retention, automatic injection, or archiving of reflective memories to be determined by continuous execution feedback. Reflective memories that have been repeatedly verified to be effective can have their credibility increased and be stably reused in similar tasks; reflective memories that cause new errors, fail replay verification, or deviate significantly from actual execution have their credibility reduced and are removed from the automatic injection scope. The structured reflective memories, pre-replay verification, and credibility updates work together to enable the system not only to reuse historical error correction experience but also to continuously identify and isolate failed experiences, forming a closed-loop error correction mechanism with error prevention, effect verification, and memory self-cleaning capabilities. This effect cannot be directly obtained by using failure logs, natural language reflection, or post-trial retries alone. Attached Figure Description
[0025] Other features, objects, and advantages of this application will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings: Figure 1 This is the main flowchart of the error correction method called by the large language model intelligent agent tool in the first embodiment of the present invention; Figure 2 This is a flowchart of the process of reflective memory formation and initial credibility determination in the first embodiment of the present invention; Figure 3 This is a flowchart of the isolation simulation, adjustment and verification, and actual execution process of the repaired tool call chain in the first embodiment of the present invention; Figure 4 This is an architectural block diagram of the error correction system for the large language model intelligent agent tool call according to the second embodiment of the present invention. Detailed Implementation
[0026] The present invention will be further described below with reference to the accompanying drawings and embodiments. It should be noted that the following embodiments are used to illustrate the technical solutions of the present invention, and are not intended to limit the scope of protection of the present invention. Unless otherwise specified, the various embodiments and the technical features within them can be combined with each other.
[0027] This invention applies to large language model agents capable of invoking external tools. The large language model agent can generate task plans based on task objectives and invoke database query tools, scripting tools, retrieval tools, file processing tools, business interfaces, or other external services according to the task plans. The large language model agent can be deployed on servers, workstations, or service clusters composed of multiple computing nodes. Its operating environment includes an operating system, runtime environment, dependency libraries, tool adapters, permission management components, network connectivity components, and isolated execution components.
[0028] The execution trajectory, as referred to in this invention, is time-series data formed from the beginning of task plan creation, recording plan snapshots, tool information, call parameters, context summary, environment state, call output, and error information according to the tool call sequence. The failure trajectory refers to an execution trajectory that includes call errors, parameter validation errors, abnormal output structure, unsatisfactory task results, or other failure states, or a continuous trajectory segment within the execution trajectory that has an input dependency on the failed step.
[0029] The reflective memory referred to in this invention does not directly store the natural language reflective text output by the large language model. Instead, it transforms the error-correction knowledge extracted from the failure trajectory into applicable prerequisites, error-correction constraints, and parameter templates that can be read and executed by the task planner. The applicable prerequisites are used to determine whether a reflective memory can be applied to the task to be executed. The error-correction constraints are used to specify the actions that should be executed or prohibited under the corresponding conditions. The parameter templates are used to provide the field structure, required status, data type, and positions to be filled for the tool call parameters.
[0030] The replay verification referred to in this invention refers to performing static verification based on the repaired tool call chain before making a real tool call, and simulating execution in an isolated environment to determine whether the parameters, dependencies, permissions, data transfer between steps, and output structure meet the task execution conditions. For tools that may involve business data modification, file modification, or changes in the status of external services, replay verification does not perform actual write operations, but instead constructs simulated output through an isolation adaptation layer.
[0031] The execution trajectory includes a plan snapshot, call parameters, and the environment state at the start of the call, all written before the corresponding tool call begins. Call output and error messages are added after the tool call ends or terminates abnormally. The context summary uses only dialogue content, task plans, and intermediate results generated up to the start of the current call, excluding subsequent results not yet generated at the current processing point. These timing constraints prevent the use of future data during failure classification, similar trajectory matching, and replay verification.
[0032] The first embodiment of this invention proposes a method for correcting tool invocation errors in a large language model intelligent agent. For example... Figure 1 As shown, the method includes the following steps: Step S10: Record the task plan, call parameters, output, errors, context summary, and environment status to form the execution trajectory; Step S20: Filter failure trajectories and determine failure types. Generate applicable premises, error correction constraints and parameter templates from the large language model and structure them into reflective memory. Inject the reflective memory into the tool call chain reconstructed from the failure trajectory, replay it in an isolated environment and determine the initial credibility. Step S30: Before the task to be executed is executed, extract the task objective, tool sequence, key entities and environmental status, weight match the failure trajectory, select the reflection memory with applicable premise matching and credibility reaching the preset credibility threshold, write the error correction constraints and parameter template into the task plan and call parameters, and form the tool call chain after repair. Step S40: Verify the parameters, dependencies, and permissions of the tool call chain after the repair and isolate the simulation. If it fails, adjust and re-verify. If it still fails after reaching the termination condition, stop the actual execution. If it passes, execute the actual execution. Step S50: After completing the actual execution, compare the tools, parameters, and output structure of the simulated execution with those of the actual execution to determine the execution consistency. Step S60: Update the credibility of the selected reflective memory based on the replay verification results, the actual execution status, and the execution consistency. Based on the updated credibility, retain or archive the selected reflective memory and output the actual execution result or verification failure information.
[0033] The above steps are executed in the order of data generation and use. The execution trajectory formed in step S10 is used for the failure trajectory screening in step S20 and for similar trajectory matching in step S30; the reflective memory formed in step S20 is used for retrieval and injection in step S30; the repaired tool call chain formed in step S30 is used for static verification, isolation simulation and real execution in step S40; the simulation execution results, real execution results and verification status generated in step S40 are used in steps S50 and S60.
[0034] Step S10: Record the task plan, call parameters, output, errors, context summary, and environment status to form the execution trajectory; In this embodiment, step S10 includes steps S11 to S14.
[0035] Step S11: Create a trajectory record for each tool call, aggregate it by task identifier and sort it according to the step number; When the task planner identifies a tool to be invoked, the trajectory formation component generates a trajectory identifier and records the task identifier, step number, plan snapshot, tool name, tool version, input parameters, invocation start time, and invocation start status before the tool actually executes. After the tool returns a result, an exception occurs, or the invocation time limit is exceeded, the trajectory formation component appends the invocation output, error code, error message, and invocation delay to the same trajectory record.
[0036] Multiple tool calls within the same task share the same task identifier, and the call order is determined by the step sequence number. When the same step is called again, the original step sequence number is retained, and a retry sequence number or plan version number is added, without overwriting the previous call record. This allows for the differentiation between the initial tool call, verification calls after task plan adjustments, isolated simulation calls, and actual execution calls.
[0037] A trajectory record can be stored using a structured record, whose fields include trajectory identifier, task identifier, step number, plan snapshot, tool name, tool version, input parameters, context summary, call output, error code, error message, environment status, timestamp, and call delay.
[0038] The plan snapshot records at least the task objectives, tool sequence, and dependencies between tools determined before the current step is executed. Input parameters record the parameter name, type, value, and source. The parameter source indicates whether the parameter was provided by user input, extracted by the task parser, output by preceding tools, or from a parameter template in reflective memory.
[0039] The call output can be structured data, file references, result summaries, or status codes. When the amount of call output data exceeds the preset storage capacity, the trajectory record saves the output summary, output storage location, and content verification value, and retrieves the original output through the output storage location, and verifies whether the original output has changed through the content verification value.
[0040] Step S12: Write the planned snapshot, tool name, tool version and input parameters into the call input area, write the call output and error code into the call result area, and write the permissions, dependency versions, network status and resource level into the environment status area. The call input area is frozen before the tool actually executes. Freezing means that the plan snapshot, tool information, and input parameters corresponding to the call input area will not be overwritten by subsequent task plans. When the task plan is adjusted, a new plan version is created, and the adjusted call input is saved in the new trajectory record.
[0041] The call result area is written when the tool returns normally, when an error occurs, or when the tool call exceeds the time limit. If no normal output is received, the call result area still records the empty output status, error code, and error message; the absence of records does not indicate a successful call.
[0042] The environment status area is collected by the environment probe before the tool is invoked. The environment status includes the operating system and version, runtime version, dependent libraries and versions, execution identity, permission level, database role, file system read and write permissions, external interface access scope, network connectivity status, proxy configuration, target service version, target service availability status, memory level, disk level, and whether it is in an isolated environment.
[0043] For environment fields that cannot be obtained at the start of the call, mark the environment field as unavailable and record the reason for the collection failure. Do not use null values or zero values to replace the normal state. If changes in permissions, network status, or target service status are detected before the current step is executed, the corresponding fields are collected again to avoid using the environment status of previous steps.
[0044] Step S13: Extract the task objective, key entities, and references to obtained results from the dialogue history and intermediate results generated up to the start of the current call to form a context summary; The context summary is generated by an independent context summarization unit, rather than directly using the summary text generated by the large language model agent during task execution. The context summarization unit extracts task objectives, time ranges, data objects, file objects, account or permission entities, target services, output format requirements, and references to obtained results from the generated user instructions, task plans, and intermediate results.
[0045] The obtained result reference includes at least the step number that produced the result, the result storage location, and the content verification value, so that subsequent tools can obtain the actual intermediate result based on the reference, rather than relying solely on the natural language summary.
[0046] The input scope of the context summary is defined by the start time of the current tool call. For dialogues exceeding the input length of the summary model, retention priorities are determined in the following order: content containing the task objective, results of the most recent tool call, content containing key entities, and references to obtained results. After the summary model outputs, an entity validator compares the entities in the summary with the input content. If an entity not present in the input content appears in the summary, the entity is deleted and the verification result is recorded. If a necessary entity for task execution is missing due to summary compression, the entity and its source location are refilled from the original input.
[0047] In one implementation, the maximum input length of the summarization model is 4096 tags, and the maximum output length is 256 Chinese characters. These values can be adjusted based on the model's context capacity and trajectory storage capacity. When the summarization model is unavailable, field extraction and sentence sorting are used to combine the task objective, key entities, and references to obtained results into a context summary according to a preset field order.
[0048] Step S14: Associate the call input area, call result area, environment status area, and context summary according to the task identifier for failure trajectory filtering and similar trajectory matching reading.
[0049] Track records can be aggregated into task-level track documents according to task identifiers, or appended to the event stream according to the invocation events and aggregated after the task ends. When using event streams, the plan formation event, invocation start event, invocation end event, and environment change event are all timestamped, and the aggregation component eliminates out-of-order events based on task identifiers, step numbers, and event times.
[0050] Task-level trajectory documents and single-step trajectory records are associated with trajectory identifiers, task identifiers, and step numbers. The failed trajectory filtering component reads the complete trajectory of the same task based on the task identifier and reads the preceding outputs corresponding to the failed steps based on step dependencies. The similar trajectory retrieval component obtains the task objectives, tool sequences, key entities, and environmental states of historical tasks through trajectory identifiers.
[0051] Step S20: Filter failure trajectories and determine failure types. Generate applicable premises, error correction constraints and parameter templates from the large language model and structure them into reflective memory. Inject the reflective memory into the tool call chain reconstructed from the failure trajectory, replay it in an isolated environment and determine the initial credibility. like Figure 2 As shown, in this embodiment, step S20 includes steps S21 to S28.
[0052] Step S21: When the error code, exception stack, parameter verification result, output structure or task result meets the failure judgment condition, the corresponding step and its predecessor dependencies are determined as the failure trajectory. Failure criteria include: the tool returns an error code indicating a failed call; the exception stack is not empty; the input parameters fail the tool parameter structure validation; the tool call exceeds the preset time limit; the tool output lacks required fields in the interface definition, or the field types are inconsistent with the interface definition; the task result does not meet the output structure, output object, or completion status specified in the task objective.
[0053] When any failure condition is met, the trajectory filtering component determines the directly failing step and, based on the dependencies in the plan snapshot, traces back to generate the preceding steps that would be the input for that step. The directly failing step and its preceding dependencies constitute the failure trajectory.
[0054] The failure trajectory simultaneously retains the input parameters, error messages, environment state, and call output of the failed step, as well as the preceding output that generated the input parameters. This allows us to determine whether the error originated directly from the failed step, or was caused by the order of preceding tools, abnormal preceding output, or missing context.
[0055] Step S22: Match the failure trajectory with the preset failure rules, and output the corresponding failure type when the preset failure rules are matched; The default failure rules consist of a decision field, a comparison relationship, a decision value, a rule priority, and a failure type. Failure types include parameter errors, sequence errors, permission errors, missing context, and external service exceptions.
[0056] Parameter errors refer to missing parameters required for tool invocation, incorrect parameter types, parameter values exceeding the allowed range, or invalid parameter values. Parameter errors can be identified through parameter structure validation results, parameter class error codes, or information returned by the tool interface.
[0057] A sequence error occurs when a tool call requires a prerequisite step that has not been executed, or when a previous output referenced by the current step has not yet been generated. Sequence errors can be identified through dependencies in the task plan, executed steps, and result reference status.
[0058] A permission error means that the currently executing identity does not have the required permissions to operate the target tool or object. Permission errors can be identified through authentication results, database roles, file system permissions, interface access scope, and permission error codes.
[0059] Contextual missing refers to situations where the entities required for a task are not obtained from user instructions, context summaries, or preceding output, or where the referents in the dialogue are not resolved. Contextual missing can be determined through a list of required entities, a context summary, and unresolved referent states.
[0060] External service exceptions refer to situations where the target service on which the tool depends is unreachable, the target service returns an error to the server, consecutive calls time out, or the target service status probe shows that it is unavailable.
[0061] When a failure path hits multiple failure rules simultaneously, the primary failure type is determined based on rule priority and the location of the error, and the remaining hit types are recorded as secondary failure types. Parameter errors and permission errors directly corresponding to the location of the error take precedence over general service errors caused by them; when the target service probe explicitly indicates unreachability, external service exceptions take precedence over empty output.
[0062] Step S23: When the preset failure rule is not hit, input the tool sequence, previous output, context summary and environment state into the classification model; The categorized inputs include tool sequence encoding, preceding output structure encoding, contextual summary semantic features, and environment state encoding. Tool sequence encoding records the tool name, tool version, and relative order; preceding output structure encoding records field names, field types, null value status, and exception flags; and environment state encoding records permissions, dependent versions, network status, target service status, and resource level.
[0063] The classification model outputs the category score corresponding to each failure type. Let the first... The category score for each failure type is: The corresponding failure type probability is ,but: ; The summation range covers all candidate failure types. The failure type with the highest probability is selected as the failure type output by the classification model, and its corresponding probability is used as the classification confidence score. Before calculating the index, the highest category score can be subtracted from the scores of each category to reduce the risk of numerical overflow.
[0064] When the classification confidence reaches the preset automatic classification threshold, the failure type output by the classification model is saved. When the classification confidence does not reach the preset automatic classification threshold, the failure trajectory, candidate failure types, the probability of each candidate failure type, and the reason for rule mismatch are sent to the verification interface. The failure type returned by the verification interface is received, and the failure type returned by the verification interface is used to replace the classification model output.
[0065] The verification interface can connect to a manual verification terminal or a verification model independent of the classification model. When using a manual verification terminal, verifiers determine the failure type based on the original trajectory, error location, and candidate type. When using a verification model, the verification model uses different input combinations or model parameters than the classification model, and returns the verification result after it meets preset verification conditions.
[0066] In one implementation, the automatic classification threshold is 0.80. This value can be set according to the false positive cost of different failure types.
[0067] Step S24: Input the failure trajectory and failure type into the large language model to generate applicable premises, error correction constraints and parameter templates; The failure trajectory of the input large language model includes the task objective, tool sequence, plan snapshot, input parameters, previous output references, error code, error message, exception stack, context summary, and environment state. To reduce information irrelevant to the current error, the failure trajectory is traced back and pruned according to the input dependencies of the directly failing steps. The pruned input retains the steps that explain the cause of the error and the conditions for repair.
[0068] The large language model outputs applicable prerequisites, error correction constraints, and parameter templates, and can also output root cause descriptions. Root cause descriptions are used to record error fields, the steps in which the error occurred, and the relationship between the preceding states and the error, but root cause descriptions are not directly used as machine actions.
[0069] The applicable prerequisites include at least one of the following: tool type, tool version range, data source type, permission level, task category, network status, and isolation status. These prerequisites are used to determine whether a reflective memory is applicable to the task to be performed.
[0070] Error correction constraints are expressed using a correspondence between conditions and actions. Conditions include tool type, tool parameters, environment state, and judgment conditions for preceding outputs or task entities; actions include adding pre-checks, adjusting the order of steps, supplementing parameters, adding context, prohibiting tool calls, or replacing tools.
[0071] The parameter template includes the parameter field name, parameter type, required status, parameter value range, and the position to be filled. The position to be filled is represented by a placeholder associated with the entity type. For example, a date range placeholder can only be filled by a date type entity, and a data table placeholder can only be filled by a data table entity that has been verified by the data source.
[0072] Step S25: Convert the applicable premises into key-value pairs, convert the error correction constraints into conditional action records, and convert the parameter template into a parameter skeleton with placeholders. The structured extractor processes the output of the large language model according to a preset structure. Applicable prerequisite key-value pairs include prerequisite fields, comparison methods, and prerequisite values. Conditional action records include condition fields, comparison relationships, condition values, action types, action targets, and action parameters. The parameter skeleton uses a data structure consistent with the target tool's parameter interface, and stores placeholder types, required / unrestricted values, and allowed value ranges in the fields to be filled.
[0073] For example, the conditional action record of a database query tool can be represented as follows: when the date range parameter is missing, the query is prohibited, and the start date and end date are obtained from the date entity of the current task; when there is no data table structure reading step in the task plan, the data table structure reading step is inserted before the database query step.
[0074] The structured extractor can also convert the suggested repair actions output by the large language model into action types and action parameters, and write them into the corresponding conditional action records for use in subsequent task planning and parameter correction.
[0075] Step S26: Verify the parsability of the conditional action record and the parameter structure of the parameter skeleton; The resolvability check includes: checking whether the condition field is a field that can be read from the task, tool, parameter, preceding output or environment state; checking whether the comparison relationship is an equal to, not equal to, contain, missing, numerical comparison or state matching relationship supported by the system; checking whether the action type has a corresponding executor; checking whether the action target points to the tool step or tool parameter in the task plan; and checking whether the action parameters meet the data structure of the action executor.
[0076] The parameter structure validation checks the field name, field type, required fields, nesting level, value range, and placeholder type according to the parameter definition of the target tool.
[0077] If validation fails, the erroneous fields, error locations, and expected structure are returned to the structure extractor for re-transformation. If validation still fails after a preset number of transformations, the output of the large language model is saved as a record to be verified, without forming a reflective memory that can be automatically injected.
[0078] Step S27: When the verification is successful, a reflection memory is formed, and the reflection memory is associated with and stored with the failure trajectory; A reflective memory should include at least the memory identifier, failure type, applicable prerequisites, conditional action record, parameter skeleton, associated trajectory identifier, basic credibility, verification status, hit count, replay verification count, actual successful execution count, and most recent usage time. It can also save root cause descriptions and semantic vectors.
[0079] Reflective memories are linked to the original failure trajectory through associated trajectory identifiers. When retrieving, verifying, or updating the credibility of reflective memories, their source of evidence can be retrieved based on the associated trajectory identifiers.
[0080] Step S28: The reflective memory is injected into the tool call chain reconstructed from the failure trajectory to form a pre-verification call chain, which is then replayed in an isolated environment, and the initial credibility is determined based on the error elimination state, constraint satisfaction state, and output structure conformity state.
[0081] First, the original tool call chain is reconstructed based on the plan snapshot, tool information, input parameters, and step dependencies in the failure trajectory. Then, the conditional action records and parameter skeletons from reflective memory are applied to the original tool call chain to form a pre-validation call chain.
[0082] The pre-verification call chain does not directly perform actual business writes. For read-only tools, it connects to a read-only data copy or a de-identified snapshot for execution; for write tools, script tools, and external interfaces, it constructs simulated output through an isolation adaptation layer. After pre-verification, it is determined whether the errors corresponding to the original failure trajectory have been eliminated, whether the error correction constraints in the replay memory have been met, and whether the output structure of the pre-verification call chain conforms to the tool interface definition and the original task expectations.
[0083] In one implementation, a base confidence level of 0.60 is initially assigned after the reflective memory is formed. When all three conditions are met, the initial confidence level is set to a preset confidence threshold, which can be 0.75, allowing the reflective memory to enter the subsequent automatic injection candidate range. When the error is eliminated but the error correction constraint or output structure has items to be confirmed, the initial confidence level remains at 0.60, and the reflective memory is only used for bypass hints or subsequent offline verification. When the error is not eliminated or a new deterministic error is generated, the initial confidence level is reduced to below a preset retention threshold and archived.
[0084] The specific value of the initial trust level can be set according to the tool's risk level and the degree of pre-verification integrity. High-risk write tools can use a higher preset trust threshold than ordinary read-only tools.
[0085] Step S30: Before the task to be executed is executed, extract the task objective, tool sequence, key entities and environmental status, weight match the failure trajectory, select the reflection memory with applicable premise matching and credibility reaching the preset credibility threshold, write the error correction constraints and parameter template into the task plan and call parameters, and form the tool call chain after repair. In this embodiment, step S30 includes steps S31 to S38.
[0086] Step S31: Before the task to be executed begins to be actually executed, extract the task objective, tool sequence, key entities and current environment state from the user instructions and initial task plan; The task objective represents the processing objects, processing actions, and output requirements that the task to be executed needs to complete. The tool sequence represents the tools expected to be called in the initial task plan and their calling order. Key entities include time range, data objects, file objects, accounts, target services, output formats, and task constraints. The current environment state is re-collected by the environment probe and does not use the environment state from historical failure tracks.
[0087] Step S32: Build a keyword inverted index and a semantic vector index for the failed trajectories, and recall candidate failed trajectories based on the two types of indexes; The keyword inverted index uses tool name, error code, failure type, key entity, dependency version, and permission level as index items, with index values pointing to trajectory identifiers and step numbers. The semantic vector index inputs historical task objectives and context summaries into the semantic encoder to obtain historical task semantic vectors, and then associates these historical task semantic vectors with trajectory identifiers.
[0088] When recalling candidate failed trajectories, the keyword inverted index is queried based on the tool name, key entities, and environment fields of the task to be executed, and the semantic vector index is queried based on the semantic vector of the task to be executed. The trajectory identifiers returned by the two types of indexes are deduplicated to form a set of candidate failed trajectories.
[0089] Step S33: Calculate the semantic similarity of the task target, the similarity of the tool sequence, the entity overlap, and the environment matching degree; Let the semantic vector of the task target of the task to be executed be... The task objective semantic vector of the candidate failed trajectory is The semantic similarity between the task and the target is ,but: ; in, To prevent positive numbers with a denominator of zero, the semantic vectors are normalized using the L2 norm, mapping the semantic similarity of the task target to the range of 0 to 1. If any semantic vector is unavailable, the semantic features of the task target are marked as uncomputable.
[0090] Let the sequence of tools for the task to be executed be... The tool sequence for candidate failure trajectories is The edit distance between the two is The tool sequence similarity is ,but: ; in, and These represent the number of tools in the two tool sequences. Edit distance is calculated based on the number of tool insertions, deletions, and replacements. When both tool sequences are empty, the tool sequence features are marked as uncomputable, and their similarity is not set to 1.
[0091] Let the set of key entities for the task to be executed be... The key entity set of candidate failed trajectories is The degree of overlap of entities is ,but: ; Before entity comparison, date format, data object identifier, file path, and service identifier are standardized. When the entity union is empty, entity features are marked as uncomputable.
[0092] Environment compatibility is calculated item by item based on tool version compatibility, data source type, permission level, network status, and isolation status. Let the first... The matching value of each environment field is The field weight is The environmental matching degree is ,but: ; When a perfect match is achieved, Set to 1; if a mismatch is determined, Set to 0; when the tool version is within the compatibility range. Use a compatible value between 0 and 1. Only calculate environment fields that are available in both the task to be executed and the candidate failure trajectory. If no comparable environment field exists, mark the environment feature as uncalculated.
[0093] Step S34: Sum the computable features according to normalized weights to form a comprehensive similarity; When all four types of features mentioned above can be calculated, the overall similarity is... for: ; Among them, task target semantic similarity is used to reflect task intent, tool sequence similarity is used to reflect execution path, entity overlap is used to reflect processing objects, and environment matching degree is used to reflect the probability of historical failure conditions occurring in the current environment. Each weight can be adjusted according to historical verification results, but the sum of the adjusted weights is 1, and the corresponding weight version is saved.
[0094] For cases where some features cannot be calculated, the overall similarity is calculated in the following way.
[0095] First, the system checks whether the task objective semantic vector, tool sequences, key entities, and environmental states have computable inputs, and then forms a feature availability identifier. Features are considered uncomputable when the vector norm is zero, both tool sequences are empty, the entity union is empty, or there is no common environmental field.
[0096] Let the first The availability identifier of class features is When computable Take 1, when it cannot be calculated. Take 0; the first The original preset weights of the class features are Normalized weights are ,but: ; Normalization is performed when the denominator is greater than zero. When all features are uncomputable, no comprehensive similarity is formed, and automatic injection of reflective memory is not allowed.
[0097] Comprehensive similarity under missing feature conditions for: ; For example, if the environmental state is not comparable but the other three features are computable, 0.4, 0.3, and 0.2 are divided by 0.9 respectively to form the corresponding normalized weights. The calculation record saves the original weights, feature availability identifiers, normalized weights, and calculated values of each feature to facilitate auditing of the matching results.
[0098] In one implementation, the preset integrity condition is that at least two types of features are computable, and at least one type of feature is computable, either the semantic features of the task objective or the sequence features of the tool. If the integrity condition is not met, even if the calculated overall similarity is high, automatic injection will not be performed; instead, the corresponding reflective memory will be used as a bypass cue.
[0099] Step S35: Generate injection candidates or bypass suggestions based on comprehensive similarity; When the overall similarity reaches a preset similarity threshold, the candidate failed trajectory is identified as an injection candidate. When the overall similarity is below the preset similarity threshold but reaches the preset recall threshold, the corresponding reflection memory is identified as a bypass prompt, and the bypass prompt is sent to the task planner or verification terminal, but not written into the task plan and calling parameters. When the overall similarity does not reach the preset recall threshold, the corresponding candidate failed trajectory is excluded.
[0100] In one implementation, the preset similarity threshold is 0.75, and the preset recall threshold is 0.60. When the number of candidates exceeds the preset number, they are first sorted in descending order of overall similarity, and then sorted by reflective memory credibility and most recent verification time.
[0101] Step S36: Match the applicable premises of the injected candidate reflective memory with the task to be executed, and check the credibility of the reflective memory; If the tool type, data source type, and permission level listed in the applicable prerequisites are mandatory, the task to be executed must meet the corresponding conditions. Tool versions are compared according to the version range specified in the applicable prerequisites. Network status, resource level, or isolation status are compared according to status values or allowed ranges.
[0102] If the applicable premises do not match, the corresponding reflective memory will be excluded even if the overall similarity reaches the preset similarity threshold. If the credibility of a reflective memory does not reach the preset credibility threshold, it will not be automatically injected, but can be used as a bypass prompt based on its overall similarity. Reflective memories that match the applicable premises and whose credibility reaches the preset credibility threshold will be selected as the chosen reflective memories.
[0103] When multiple reflective memories apply to the same task plan field or call parameter, and their corresponding actions conflict, the reflective memory with higher credibility, most recently verified playback, and a tool version closer to the current version is prioritized. If the conflict still cannot be resolved, the conflicting reflective memories are converted to bypass suggestions, and the task plan is not automatically modified.
[0104] Step S37: Write the error correction constraints and parameter templates from the selected reflective memory into the task plan and call parameters to form a tool call chain after repair; First, the conditional action record is parsed, and the conditions are matched with the tools, parameters, preceding outputs, and environment states of the task to be executed. When a condition is matched, the corresponding action is written into the task plan.
[0105] Actions such as permission checks, data structure reading, and dependency checks should be written as prerequisite checks; actions such as step insertion, step deletion, step rearrangement, and tool replacement should be written as adjustment items; actions such as prohibiting full queries when a date range is missing and prohibiting write operations by read-only users should be written as prohibited items.
[0106] Subsequently, the placeholders in the parameter skeleton are matched with the entities and input values of the task to be executed. The date placeholder is obtained from the time entity of the task to be executed, the data object placeholder is obtained from the data object that has been verified by the data source, and the preceding result placeholder is obtained from the reference of the obtained result.
[0107] When a placeholder has multiple candidate values, the selection is based on the following order: explicit user input, explicit fields in the task objective, confirmation results from preceding tools, and results extracted from the context summary. If a unique value cannot be determined, the placeholder is marked as pending supplementation, and no parameter value is automatically generated.
[0108] The populated parameter skeleton is validated according to the parameter structure of the target tool. Once validation passes, the parameter skeleton is merged into the corresponding tool's call parameters. When the original call parameters conflict with the parameter template, the parameters explicitly entered by the user and validated by the tool's parameter structure are retained. The parameter template is used to supplement missing fields or apply already triggered prohibition constraints.
[0109] In one implementation, a prompt-level injection method can also be used to assist in constraining the task planner. Specifically, the root cause description is converted into prompt content containing error conditions, prohibited behaviors, and correct actions, and this prompt content is written into the task planner's prompt information. This prompt content is used to assist the task planner in generating task plans; it does not replace conditional action records and parameter skeletons, nor is it directly used as tool call parameters.
[0110] Step S38: Attach a reflective memory identifier to the written content and perform a source rollback when an anomaly is detected.
[0111] The pre-checks, adjustments, and prohibited items written to the task plan, as well as the parameter fields written to the call parameters, are all appended with source reflection memory identifiers. The system simultaneously saves the task plan version and call parameter version before writing, and the task plan version and call parameter version after writing.
[0112] After the repaired tool call chain is formed, check for plan dependency loops, parameter structure conflicts, missing tools, abnormally high permission requirements, or other static validation anomalies caused by written content. During the isolation simulation, also check for new simulation execution anomalies caused by written content.
[0113] When an anomaly is detected corresponding to a reflective memory, the pre-write checks, adjustments, prohibitions, and parameter fields of that reflective memory are deleted based on the reflective memory identifier, and the task schedule and call parameters before the write are restored. When multiple reflective memories act on the same field, only the write content that caused the conflict is rolled back based on the field-level source record.
[0114] Step S40: Verify the parameters, dependencies, and permissions of the tool call chain after the repair and isolate the simulation. If it fails, adjust and re-verify. If it still fails after reaching the termination condition, stop the actual execution. If it passes, execute the actual execution. like Figure 3 As shown, in this embodiment, step S40 includes steps S41 to S48.
[0115] Step S41: Verify the parameters, dependencies, and permissions of the repaired tool call chain based on the tool parameter structure, preceding output, and permission records. Parameter validation checks required parameters, parameter types, parameter value ranges, field names, and nesting levels according to the parameter definitions of the target tool. For parameters derived from previous outputs, it checks whether the previous steps exist, whether the corresponding output fields exist, and whether the output field types can be converted to the target parameter types.
[0116] Dependency checks examine the step order and data dependencies in the plan. Dependency checks fail if the preceding output required by the current step has not yet been generated, or if the preceding step that generates the output occurs after the current step.
[0117] The permission check compares the permissions required by the tool with the permission records of the currently executing identity. If the current executing identity lacks the permissions required by the target tool or target object, the permission check fails, and the system simulates output to bypass the permission requirements.
[0118] If any validation fails, output the failed step, failed field, expected conditions, actual status and associated reflection memory identifier, and proceed to step S47 to adjust the task plan.
[0119] Step S42: When the parameters, dependencies and permissions are verified, execute the repaired tool call chain in a container isolation environment with a running image that is the same as the real execution environment. The isolated environment uses the same operating system image, runtime version, dependency library versions, and tool adapter versions as the real execution environment. Before starting the isolation simulation, the isolated environment image identifier is compared with the real execution environment's runtime manifest. If no matching image exists, replay verification stops and an environment inconsistency status is output.
[0120] The container isolation environment is configured with an independent file system, network policy, resource quotas, and temporary credentials. Actual write credentials are not passed to the container isolation environment. After the fix, the tool call chain executes step-by-step in sequence, with each subsequent step only reading the simulated output of the preceding steps.
[0121] Step S43: The read-only tool connects to a read-only data copy or a de-identified snapshot; Database query tools, retrieval tools, and other read-only tools that do not alter business status can connect to read-only data copies or anonymized snapshots for simulated execution. The read-only data copy or anonymized snapshot records the generation time, data version, and data structure version.
[0122] If a snapshot exceeds its preset validity period, or if the snapshot's data structure version is inconsistent with the actual execution environment, the corresponding snapshot will not be used. The snapshot validity period can be set according to the data update frequency; when the data structure changes, the old snapshot will be immediately marked as invalid.
[0123] Step S44: The writing tool, script tool and external interface are generated by the isolation adaptation layer based on the tool interface definition and the success trajectory in the historical execution trajectory, and the simulated output is constructed according to the interface contract; Step S441: Group the historical tracks of actual successful execution according to the tool name and tool version, and extract the parameter structure, environment field and output field structure from each group of historical tracks to form an interface contract; An interface contract should include at least the tool name, tool version range, parameter fields, parameter types, required parameters, applicable environment fields, output field names, output field types, output nesting levels, nullable states, numerical boundaries, normal status codes, and abnormal states.
[0124] The output structure in the interface contract is derived from the tool interface definition and the historical trajectory of actual successful execution. The specific business data in the historical trajectory is not directly reused as the simulation result; only the field structure, value range, and state relationships are extracted.
[0125] Step S442: Match the parameter structure of the repaired tool call chain and the current environment state with the interface contract, and select the interface contract that meets the contract conditions to construct the simulated output. When matching API contracts, first check if the tool name and main version are consistent, then check the parameter fields, required parameters, data source type, permission level, and target service status. If multiple API contracts meet the conditions, sort them according to version similarity, environment field matching degree, and the most recent actual successful execution time.
[0126] When constructing simulated output, output values consistent with field types are generated according to the interface contract, and required fields, nullable states, and abnormal states are retained. The isolation adaptation layer can construct normal output, boundary output, and interface abnormal output separately to check the ability of the tool call chain to handle different output states after repair.
[0127] In step S443, if no interface contract meets the contract conditions, instead of replacing the simulation output with a fixed success response, stop the current playback verification, output the tool name, tool version, parameter structure and unmatched environment fields, and return to the task plan adjustment; if an interface contract meets the contract conditions, save the interface contract identifier, contract version and simulation output branch in the simulation step record.
[0128] If the simulated execution results are inconsistent with the actual execution results, the interface contract identifier can be used to determine whether the interface contract has expired or whether the applicable conditions are set inaccurately.
[0129] Step S45: Set step time limits and call chain time limits for the isolation simulation; When a tool step exceeds its timeout period, the current step is terminated and the timed-out step, completed steps, the current tool, resource level, and the last intermediate result are output. When the entire tool call chain exceeds its call chain timeout, the current isolated instance is terminated.
[0130] In one implementation, the time limit for a single tool step is 30 seconds, and the time limit for the entire tool call chain is 120 seconds. These time limits are set based on the tool type, historical call latency, and resource limits, and are not required to be the same for all tools.
[0131] When the isolation simulation is complete, output the simulation input, simulation output, tool version, parameter summary, output structure, interface contract used, constraint check status, and step execution status for each step.
[0132] Step S46: Check the required parameters, parameter types, prerequisites, permissions, output structure, and error correction constraint satisfaction status of the repaired tool call chain, and generate an output score from the simulated output-input discrimination model; Explicit checks include missing required parameters, incorrect parameter types, unmet prerequisites, insufficient permissions, empty output, abnormal output structure, and conflicts with error correction constraints.
[0133] For cases where the output is empty, the system distinguishes between valid empty results and abnormal empty results based on the tool interface definition and task objectives. If the task allows for no matching records, an empty result is not considered a failure condition; if the task explicitly requires non-empty statistical results, an empty result is considered an output exception.
[0134] The discrimination model receives the field structure, null value ratio, numerical range, expected task structure, interface contract status, and explicit exception flags of the simulated output, and outputs an output score from 0 to 1.
[0135] Let the output value of the discriminant model be The output score is ,but: ; When the output score reaches the preset score threshold, it indicates that the simulated output meets the task expectations in terms of structure and value range. When the output score does not reach the preset score threshold, it indicates that there is an anomaly in the simulated output that cannot be determined solely by explicit rules.
[0136] In one implementation, the preset scoring threshold is 0.70. The discrimination model is only used to supplement the identification of the reasonableness of the output and does not cover the already identified parameter errors, permission errors, or dependency errors.
[0137] Step S47: Determine the current verification failure type based on the explicit inspection results and output scores, and adjust the tool call chain after repair. If a required parameter is missing, the parameter type is incorrect, or the parameter value is invalid, the current verification failure type is determined to be a parameter error, and parameter completion or parameter modification is performed.
[0138] If a prerequisite step is missing, the step order does not meet data dependencies, or the preceding output has not yet been formed, the current verification failure type is determined to be an order error, and step insertion or step reordering is performed.
[0139] If the entity required for the task cannot be obtained from the task input, context summary, or preceding output, the current validation failure type is determined to be context missing, and context supplementation is performed.
[0140] If the target tool is unavailable in the current environment, there is no matching interface contract, or a functionally equivalent tool exists, the execution tool will be substituted. If permissions are insufficient, execution privileges will not be automatically elevated; instead, an alternative tool permitted by current permissions will be selected, or actual execution will be stopped.
[0141] After forming a new, repaired tool call chain, the parameter, dependency, and permission checks are re-executed from step S41, not only re-executing the original failed steps. This checks whether the task schedule adjustment has affected preceding dependencies.
[0142] Step S48: Determine whether the re-verification passed and whether the termination condition was met.
[0143] If all explicit check conditions are not met and the output score reaches the preset score threshold, the replay verification passes. Before actual execution, recheck the tool version, permission records, and critical environment status. If the verification results are consistent with those during isolation simulation, remove the adaptation configuration used only for isolation simulation and execute the actual program according to the tool sequence and calling parameters that passed the replay verification.
[0144] The termination condition is met when the preset number of re-verification attempts is reached, or when the same current verification failure type occurs consecutively a preset number of times. If the replay verification still fails even after the termination condition is met, the actual execution stops, verification failure information is output, and the adjusted task plan version, failure steps, and current verification failure type are written to the verification record.
[0145] In one implementation, the preset number of re-verification attempts is 3, and the preset number of repetitions for the same current verification failure type is 2. For high-risk tools with capabilities such as data deletion, fund manipulation, or modification of critical configurations, the number of re-verification attempts can be set to a lower value, and a manual authorization step can be added after the replay verification passes.
[0146] If significant changes occur in the tool version, permission status, or target service status during actual execution, stop subsequent dependent steps, save the actual execution results and abnormal statuses that have been generated, and send the corresponding statuses to step S60.
[0147] Step S50: After completing the actual execution, compare the tools, parameters, and output structure of the simulated execution with those of the actual execution to determine the execution consistency. Step S50 is executed after the replay verification passes and the actual execution is completed. If the replay verification fails to pass the termination condition and the actual execution is not performed, the execution consistency between the simulated execution and the actual execution is not calculated.
[0148] Step S51: Compare the tools and their order used in the simulated execution and the actual execution to form a tool consistency value; When the tool name, tool version, and calling order are all consistent, the tool consistency value is 1. When a tool is replaced, the tool version is out of compatibility range, or the tool order changes, the tool consistency value is between 0 and 1, depending on the number of consistent tools and the order deviation.
[0149] Step S52: Compare the key parameters of the simulated execution and the actual execution to form a parameter similarity. Before comparing parameters, exclude fields that allow changes, such as timestamps, temporary tokens, random identifiers, and isolated environment paths. For enumerated and text parameters, compare whether the parameter values are consistent; for numeric parameters, calculate the similarity of parameters based on the allowable error range; for structured parameters, compare field names, field types, and nesting levels.
[0150] Step S53: Compare the output structures of the simulated output and the actual output to form an output structure similarity. The output structure comparison includes field names, field types, nesting levels, nullable states, and result states. Simulated business values do not need to be exactly the same as real business values, but the output fields and their structure should be able to support subsequent tool calls and task result generation.
[0151] Let the tool consistency value be The parameter similarity is The output structural similarity is The execution consistency is ,but: ; The sum of the three weights is 1. When a true output is missing, the output structure similarity is marked as uncomputable, and the execution consistency is recalculated based on the tool consistency value and parameter similarity according to the available feature normalization method in step S34. However, the state of a true execution failure is still used as the basis for reducing the credibility in step S60.
[0152] Step S60: Update the credibility of the selected reflective memory based on the replay verification results, the actual execution status, and the execution consistency. Based on the updated credibility, retain or archive the selected reflective memory and output the actual execution result or verification failure information. In this embodiment, step S60 includes steps S61 to S65.
[0153] Step S61: When the replay verification is passed, the actual execution is successful, and the execution consistency reaches the preset consistency threshold, the credibility of the selected reflective memory is increased. Let the current credibility be The credibility limit is 1, and the promotion ratio is... The updated credibility is ,but: ; In one implementation, when the consistency is not less than 0.90, the promotion ratio is... Set the value to 0.20. When the execution consistency is between 0.70 and 0.90, the promotion ratio decreases linearly according to the execution consistency, i.e.: ; The credibility score is limited to between 0 and 1 after the update. Each update records the credibility score before the update, the execution consistency score, the credibility score after the update, the reason for the update, and the corresponding actual execution trajectory.
[0154] When the confidence level is higher than 0.85, the reflective memory is added to the priority injection set. In subsequent matching cases where the conditions are the same, reflective memories from the priority injection set are selected first.
[0155] Step S62: When the actual execution fails or the execution consistency does not reach the preset consistency threshold, the credibility of the selected reflective memory is reduced. Let the preset attenuation coefficient be ,but: ; In one implementation, when the execution consistency is below 0.70, actual execution fails, or new deterministic errors occur after using reflective memory, Take 0.60.
[0156] When it can be clearly determined from network probes, target service status, or runtime logs that the actual execution failure is unrelated to reflective memory, the external cause is recorded and credibility decay is temporarily slowed down. When the cause of failure cannot be determined, credibility decay is implemented.
[0157] Step S63: If the playback verification fails to pass the termination condition, the credibility of the selected reflective memory is reduced based on the verification failure result. If the replay verification fails and no actual execution is performed, no execution consistency score is generated. In this case, the reliability score is determined based on the source relationship between the failed step and the content written in the reflex memory.
[0158] When a failure step is directly caused by a conditional action record or parameter field written to a reflective memory, the credibility of the corresponding reflective memory is reduced according to a preset attenuation coefficient. When the failure is related to a defect in the original task plan itself and is unrelated to the reflective memory, the cause is recorded, and the credibility of the reflective memory is not reduced. When multiple reflective memories act on the failure field, the update result of each reflective memory is determined separately based on the field-level source record.
[0159] Step S64: If the selected reflective memory is not matched within a preset period, its credibility is reduced according to the idle coefficient. Let the idle coefficient be ,but: ; In one implementation, the preset period is 90 days, and the idle coefficient is... Set the value to 0.90. An update is performed after each complete idle period. The most recent hit time is obtained from the trajectory record. Archived reflective memories are not subject to idle decay.
[0160] Step S65: Retain or archive the reflective memory based on the updated credibility, and output the task results.
[0161] When the credibility reaches the preset credibility threshold, the reflective memory is added to the automatic injection candidate set; when the credibility is lower than the preset credibility threshold but reaches the preset retention threshold, the reflective memory continues to be retained for bypass prompts or subsequent offline verification; when the credibility is lower than the preset retention threshold, the reflective memory is archived.
[0162] In one implementation, the preset trust threshold is 0.75, and the preset retention threshold is 0.30. Archiving is not permanent deletion. Archived records retain reflective memory content, associated failure trajectories, hit records, verification records, trust changes, and reasons for failure. When similar or highly similar reflective memories are subsequently formed, archived records are queried to avoid repeatedly creating invalid corrective knowledge.
[0163] Upon successful execution, output the actual execution result, task identifier, plan version, and execution status. Upon failure, output the completed steps, the failed steps, and error messages. If replay verification fails even after meeting the termination conditions, output verification failure information; do not substitute simulated output for the actual execution result.
[0164] The above method is illustrated below using a data analysis agent that can automatically call database query tools and statistical script tools as an example.
[0165] The historical task required calculating sales figures for each month within a specified date range. The original task plan included a database query tool and a statistical scripting tool, but it failed to read the data table structure before querying the database, and the database query parameters did not include start and end dates. The database query tool performed a full scan and returned a timeout error after reaching its time limit.
[0166] The trajectory generation component records the task identifier, task objective, tool sequence, database query tool version and input parameters, as well as timeout error codes, call latency, database role, network status, and target database availability. The context summary contains the sales data table and expected output fields, but does not include the start and end dates.
[0167] The trajectory filtering component identifies database query steps and the preceding plans that generated their inputs as failed trajectories. Failure rules detect date ranges that are required parameters but are currently missing, and also detect steps in the task plan that do not include a data table structure reading step, thus identifying parameter errors and sequence errors respectively. Since the directly failing steps lack required parameters, parameter errors are classified as the primary failure type, while sequence errors are recorded as a secondary failure type.
[0168] The large language model generates applicable prerequisites, error-correcting constraints, and parameter templates based on failure trajectories and failure types. Applicable prerequisites include database query tools, relational data sources, read-only permissions, and network reachability. Error-correcting constraints include disabling query execution when the date range is missing, and calling the data table structure reading tool first when the data table structure is not obtained. Parameter templates include start date placeholders, end date placeholders, data table placeholders, and a list of query fields.
[0169] The structure extractor converts error-correction constraints into conditional action records and parameter templates into parameter skeletons. Once the parameter structure passes validation, a reflective memory is formed. The system reconstructs the original tool call chain based on historical failure trajectories, inserts the data table structure reading step before the database query step, and writes date range placeholders into the database query parameters, forming a pre-validation call chain.
[0170] In the isolated environment, data table structure reading and database queries were performed using anonymized data snapshots. Pre-validation results showed that the original timeout error was eliminated, all error correction constraints were met, and the query output structure conformed to the tool interface definition. Therefore, the initial confidence level of this reflective memory was set at 0.75.
[0171] The new task requires calculating sales figures for each month from January 2026 to March 2026. The task parser extracts the task objective, date entity, sales data table entity, tool sequence, and current environment state.
[0172] The semantic similarity between the task to be executed and the historical failure trajectory is 0.90, the tool sequence similarity is 0.80, the entity overlap is 0.75, and the environment matching degree is 1.00. Therefore, the comprehensive similarity is: ; The overall similarity is higher than 0.75, the applicable premise of reflective memory matches the current task, and the credibility reaches 0.75. Therefore, this reflective memory is selected.
[0173] Before the database query step, the task planner writes the data table structure reading step, fills the start date with January 1, 2026, fills the end date with March 31, 2026, and writes a constraint that prohibits queries when the date range is empty, forming the repaired tool call chain.
[0174] Static validation confirmed that the date parameters were complete and of the correct type, the data table structure reading step preceded the database query step, and the current read-only role had query permissions. During the initial execution of the isolation simulation, it was found that the statistical script required the output fields "month" and "sales amount," while the database query step output the corresponding fields "transaction month" and "sales amount." Therefore, the current validation failure type was determined to be an output structure anomaly.
[0175] The task planner adjusted the field mappings of the database query steps, forming a new, repaired tool call chain and re-verifying it. In the second isolation simulation, all explicit check conditions were not met, and the discriminant model output a score of 0.91, higher than 0.70, indicating that the replay verification passed.
[0176] The actual execution follows the validated tool sequence to read the data table structure, query data within a specified date range, aggregate by month, and output the "month" and "sales amount" fields.
[0177] The simulated execution and the actual execution used the same tools and called in the same order, resulting in a tool similarity score of 1.00; excluding temporary timestamps, the parameter similarity was 0.95; the output field names, field types, and nesting levels were identical, resulting in an output structure similarity score of 1.00. The execution consistency score was: ; The replay verification passed, the actual execution was successful, and the execution consistency was higher than 0.90, therefore a promotion ratio of 0.20 was adopted. If the confidence level before the update was 0.75, then the confidence level after the update is: ; If the updated credibility is higher than the preset credibility threshold, the reflective memory will continue to be retained in the automatic injection candidate set.
[0178] In this embodiment, the summary model, failure classification model, large language model, and output discriminant model can be trained separately, or pre-trained models adapted to the corresponding task data can be used.
[0179] The training data for the summarizing model consists of completed and verified dialogue history, intermediate results, and corresponding context summaries. The input to the training samples only includes data that already existed at the start of the corresponding step, avoiding the mixing of subsequent results into the summarizing model's input. Evaluation metrics for the summarizing model include task objective coverage, key entity coverage, and the proportion of entities without a source.
[0180] The training data for the failure classification model comes from historical failure trajectories. Manual verification results serve as priority labels, while trajectories with evidence of deterministic failure rules can use the corresponding failure type as the label. Training data is divided into training and evaluation sets according to task identifiers to prevent different steps of the same task from simultaneously entering both sets.
[0181] Large language models can directly use pre-trained models and generate applicable premises, error correction constraints, and parameter templates through structured output constraints. When adaptation training is required, the training samples consist of verified failure trajectories and corresponding reflective memories. Evaluation criteria include the completeness of applicable premise fields, the parsing rate of conditional action records, and the parameter skeleton validation pass rate; the fluency of natural language expression is not the sole evaluation criterion.
[0182] The training samples for the output discrimination model come from historical simulated outputs, corresponding real execution results, and task expectations. The inputs include output field types, the proportion of null values, numerical ranges, task expectation structure, and interface contract status. Labels indicate whether the output meets the task expectations.
[0183] Each model is initialized with a preset state at the start of a task. Data that needs to be reused between tasks is passed through execution trajectories, reflective memories, and indexes, without relying on unrecorded hidden states of the models.
[0184] When a reflective memory is selected, written content is rolled back, replay verification ends, actual execution ends, or credibility changes, the audit component generates a structured record. The audit record includes the trajectory identifier, task identifier, plan version, reflective memory identifier, overall similarity, feature availability identifier, applicable prerequisite matching result, written fields, static validation result, simulated execution summary, interface contract identifier, actual execution summary, execution consistency, credibility before update, credibility after update, and reason for archiving.
[0185] Audit logs are appended and do not overwrite historical records. Verifiers can read audit logs by tracking markers or reflective memory markers to verify whether reflective memories have been matched, injected, rolled back, validated, and updated.
[0186] The second embodiment of this invention proposes a tool invocation error correction system for large language model intelligent agents. For example... Figure 4 As shown, the system includes a trajectory formation module, a reflective memory construction module, a retrieval injection module, a replay execution module, and a credibility update module.
[0187] The system in the second embodiment uses the same data processing rules, parameter definitions, and judgment conditions as the method in the first embodiment. The descriptions of each step in the first embodiment also apply to the modules performing the corresponding processing in the second embodiment.
[0188] The trajectory generation module is used to record task plans, call parameters, output, errors, context summaries, and environment states to form an execution trajectory.
[0189] The trajectory formation module includes an event acquisition unit, an environment probe, a context summary unit, and a trajectory storage unit.
[0190] The event collection unit records the planned snapshot, tool name, tool version, and input parameters before the tool is called, and records the call output, error code, error message, and call delay after the tool returns or terminates abnormally.
[0191] Environment probes are used to collect information on permissions, dependency versions, network status, target service status, and resource levels, and write the environment status into the corresponding trajectory record.
[0192] The context summary unit is used to extract the task objective, key entities, and references to the results obtained from the dialogue history and intermediate results generated up to the start of the current call, forming a context summary.
[0193] The trajectory storage unit is used to associate the call input area, call result area, environment status area and context summary according to the task identifier, and to save the temporal relationship and dependency relationship between each tool call through trajectory identifier and step number.
[0194] The Reflective Memory Building Module is used to filter failure trajectories and determine failure types. It generates applicable premises, error correction constraints, and parameter templates from the large language model and structures them into reflective memories. The reflective memories are then injected into the tool call chain reconstructed from the failure trajectories, and replayed in an isolated environment to determine the initial credibility.
[0195] The reflection memory construction module includes a failure trajectory filtering unit, a failure classification unit, a large language model invocation unit, a structure extraction unit, a structure verification unit, and a pre-verification unit.
[0196] The failure trajectory filtering unit is used to determine the failure steps based on the error code, exception stack, parameter verification results, output structure and task results, and to obtain the pre-order dependencies of the failure steps according to the step dependencies, thus forming a failure trajectory.
[0197] The failure classification unit first matches the failure trajectory with the preset failure rules; when the preset failure rules are not matched, the tool sequence, previous output, context summary and environment status are input into the classification model; when the classification confidence does not reach the preset automatic classification threshold, the verification failure type is obtained through the verification interface.
[0198] The large language model invocation unit is used to input failure trajectories and failure types into the large language model to obtain applicable prerequisites, error correction constraints, and parameter templates.
[0199] The structured extraction unit is used to convert applicable premises into key-value pairs, error correction constraints into conditional action records, and parameter templates into parameter skeletons with placeholders.
[0200] The structure verification unit is used to verify the parsability of conditional action records and the parameter structure of the parameter skeleton. When the verification passes, the structure extraction unit outputs a reflection memory; when the verification fails, the error fields and error locations are returned to the structure extraction unit for reprocessing.
[0201] The pre-verification unit reconstructs the tool call chain based on the failure trajectory, injects reflective memories into the tool call chain to form a pre-verification call chain, and replays it in an isolated environment. The pre-verification unit determines the initial confidence level of the reflective memories based on the error elimination state, constraint satisfaction state, and output structure compliance state.
[0202] The retrieval and injection module is used to extract task objectives, tool sequences, key entities and environmental states before the task to be executed, weighted match failure trajectories, select reflective memories that match applicable premises and whose credibility reaches a preset credibility threshold, and write error correction constraints and parameter templates into the task plan and call parameters to form a repaired tool call chain.
[0203] The retrieval injection module includes an indexing unit, a task feature extraction unit, a similarity calculation unit, an applicable prerequisite matching unit, and a content writing unit.
[0204] The index unit is used to build keyword inverted indexes and semantic vector indexes for failed trajectories, and to recall candidate failed trajectories based on the tool name, key entities and task semantic vector of the task to be executed.
[0205] The task feature extraction unit is used to extract task objectives, tool sequences, key entities, and current environmental states from the task to be executed.
[0206] The similarity calculation unit calculates the semantic similarity of the task target, the similarity of tool sequences, the overlap of entities, and the matching degree of the environment, and forms a comprehensive similarity according to normalized weights. When some features are not computable, the similarity calculation unit removes the uncomputable features from the summation process and normalizes the weights of the remaining features. If the feature integrity condition is not met, the similarity calculation unit does not output the automatic injection result.
[0207] The applicable premise matching unit is used to generate injection candidates or bypass hints based on comprehensive similarity, and to exclude injection candidates that do not match the applicable premise or whose credibility does not reach the preset credibility threshold.
[0208] The content writing unit parses conditional action records, writes actions that meet the conditions into the task plan, matches placeholders in the parameter skeleton with the entities and input values of the task to be executed, and merges the parameter skeleton that passes parameter structure validation into the call parameters. The content writing unit also attaches a reflection memory flag to the written content and, when an exception is detected during content writing, restores the task plan and call parameters before writing based on the reflection memory flag.
[0209] The replay execution module is used to verify the parameters, dependencies, and permissions of the repaired tool call chain and isolate the simulation; if the simulation fails, the repaired tool call chain is adjusted and re-verified; if the termination condition is met but the simulation still fails, the real execution is stopped; if the simulation passes, the real execution is performed.
[0210] The replay execution module includes a static verification unit, an isolation environment management unit, an isolation adaptation unit, a verification and judgment unit, a plan adjustment unit, and a real execution unit.
[0211] The static verification unit is used to check the parameters, dependencies, and permissions of the repaired tool call chain according to the tool parameter structure, preceding output, and permission records, and outputs the failed steps when the verification fails.
[0212] The isolated environment management unit is used to create a container isolated environment with a running image that is identical to the real execution environment, and to connect read-only tools to read-only data copies or de-identified snapshots.
[0213] The isolation adaptation unit is used to group the historical traces of actual successful execution according to the tool name and tool version, forming an interface contract that includes parameter structure, environment fields, output field types, boundary values and abnormal states; it matches the parameter structure and environment state of the repaired tool call chain with the interface contract, and constructs simulated output for writing tools, script tools and external interfaces according to the matched interface contract.
[0214] The verification and judgment unit is used to check the required parameters, parameter types, prerequisite dependencies, permissions, output structure and error correction constraints, and to form an output score from the simulated output input discrimination model. Based on the check results and the output score, the current verification failure type is determined.
[0215] The planning adjustment unit is used to perform parameter completion, step rearrangement, context supplementation, or tool replacement according to the current verification failure type, forming a new repaired tool call chain, and resending the new repaired tool call chain to the static verification unit.
[0216] The verification judgment unit is also used to count the number of re-verifications and the number of consecutive occurrences of the same current verification failure type. When the number of re-verifications reaches the preset number of re-verifications, or the number of consecutive occurrences of the same current verification failure type reaches the preset number of repetitions, the termination condition is determined to be met.
[0217] The actual execution unit is used to recheck the tool version, permission records, and key environment status after the replay verification passes, and to perform actual execution according to the verified tool sequence and call parameters; if the termination condition is reached but the verification still fails, the actual execution unit will not execute the actual tool call and will output the verification failure message.
[0218] The credibility update module is used to compare the tools, parameters and output structure of the simulated execution with those of the actual execution after the actual execution, to form an execution consistency. It updates the credibility of the selected reflection memory based on the replay verification results, the actual execution status and the execution consistency. Based on the update results, the selected reflection memory is retained or archived, and the actual execution result or verification failure information is output.
[0219] The credibility update module includes a consistency calculation unit, a credibility promotion unit, a credibility decay unit, an idle processing unit, a memory management unit, and a result output unit.
[0220] The consistency calculation unit compares the tools, tool order, key parameters, and output structure of simulated execution with those of actual execution, and generates an execution consistency score according to preset weights. The consistency calculation unit does not generate an execution consistency score when no actual execution is performed.
[0221] The credibility enhancement unit is used to increase the credibility of the selected reflective memory when the replay verification passes, the actual execution is successful, and the execution consistency reaches a preset consistency threshold.
[0222] The credibility decay unit is used to reduce the credibility of the selected reflective memory when the actual execution fails, the execution consistency does not reach the preset consistency threshold, or the replay verification fails to pass the termination condition and the verification failure is related to the reflective memory.
[0223] The idle processing unit is used to reduce the credibility of a memory if it is not matched within a preset period, according to the idle coefficient.
[0224] The memory management unit is used to add reflective memories to the automatic injection candidate set, retain them, or archive them based on the updated credibility. Archived reflective memories retain associated failure trajectories, verification records, credibility changes, and reasons for failure.
[0225] The result output unit is used to output the actual execution result when the actual execution is completed, to output the failure steps and error information when the actual execution fails, and to output the verification failure information when the replay verification reaches the termination condition but still fails.
[0226] Therefore, the trajectory forming module, the reflective memory construction module, the retrieval injection module, the playback execution module, and the credibility update module in the second embodiment sequentially implement the data processing process corresponding to steps S10 to S60 in the first embodiment.
[0227] The terms “first”, “second”, etc., are used to distinguish similar objects, not to describe or indicate a specific order or sequence.
[0228] The term "comprising" or any other similar term is intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus / device that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent in such process, method, article, or apparatus / device.
[0229] The technical solution of the present invention has been described above with reference to the preferred embodiments shown in the accompanying drawings. However, it will be readily understood by those skilled in the art that the scope of protection of the present invention is obviously not limited to these specific embodiments. Without departing from the principles of the present invention, those skilled in the art can make equivalent changes or substitutions to the relevant technical features, and the technical solutions after these changes or substitutions will all fall within the scope of protection of the present invention.
Claims
1. A method for correcting tool call errors in a large language model intelligent agent, characterized in that, include: Record task plans, call parameters, output, errors, context summaries, and environment states to form an execution trajectory; The failure trajectory is filtered and the failure type is determined. Applicable premises, error correction constraints and parameter templates are generated by the large language model and structured into reflective memory. The reflective memory is injected into the tool call chain reconstructed from the failure trajectory. The replay is performed in an isolated environment and the initial credibility is determined. Before executing a task, extract the task objective, tool sequence, key entities and environmental status, weighted match the failure trajectory, select the reflection memory with applicable premise matching and credibility reaching the preset credibility threshold, and write the error correction constraints and parameter templates into the task plan and call parameters to form the tool call chain after repair. After verification and repair, the parameters, dependencies and permissions of the tool call chain are isolated and simulated. If the verification fails, adjustments are made and the verification is repeated. If the termination condition is met and the verification still fails, the actual execution is stopped. If the verification passes, the actual execution is performed. After actual execution, the tools, parameters, and output structures of simulated execution and actual execution are compared to determine the execution consistency. The credibility of the selected reflective memory is updated based on the replay verification results, the actual execution status, and the execution consistency. The selected reflective memory is retained or archived based on the updated credibility, and the actual execution result or verification failure information is output.
2. The method according to claim 1, characterized in that, The formation of the execution trajectory includes: Create a trajectory record for each tool call, aggregated by task identifier and sorted by step number; Write the plan snapshot, tool name, tool version, and input parameters to the call input area; write the call output and error code to the call result area; and write permissions, dependency versions, network status, and resource level to the environment status area. Extract the task objective, key entities, and references to the results obtained from the dialogue history and intermediate results generated up to the start of the current call to form a context summary; Each region and its context summary is associated with a task identifier, which is used for filtering and matching failure trajectories.
3. The method according to claim 1, characterized in that, The process of filtering out failed trajectories and determining the failure type includes: When the error code, exception stack, parameter verification result, output structure, or task result meets the failure judgment conditions, the corresponding step and its predecessor dependencies are determined as the failure trajectory. The failure trajectory is matched with the preset failure rules. When a match is found, the corresponding failure type is output. When a match is not found, the tool sequence, previous output, context summary and environment state are input into the classification model. When the classification confidence reaches the automatic classification threshold, the failure type of the model output is saved. If it does not reach the threshold, the failure trajectory is sent to the verification interface, and the model output is replaced with the failure type returned by the verification interface.
4. The method according to claim 1, characterized in that, The process of forming reflective memories and determining initial credibility includes: Input the failure trajectory and failure type into the large language model to generate applicable premises, error correction constraints and parameter templates; Convert applicable prerequisites into key-value pairs, error correction constraints into conditional action records, and parameter templates into parameter skeletons with placeholders. Verify the parsability of the conditional action record and the parameter structure of the parameter skeleton; when the verification passes, a reflective memory is formed, and the reflective memory is injected into the tool call chain reconstructed from the failure trajectory to form a pre-verification call chain, which is replayed in an isolated environment, and the initial credibility is determined based on the error elimination state, constraint satisfaction state and output structure conformity state. Reflective memories are linked to failure trajectories and stored together.
5. The method according to claim 1, characterized in that, The weighted matching failure trajectory includes: Build keyword inverted index and semantic vector index for failed trajectories, and recall candidate failed trajectories based on the two types of indexes; Calculate the semantic similarity of the task target, the similarity of the tool sequence, the overlap of entities, and the matching degree of the environment. Sum the computable features according to the normalized weights to form a comprehensive similarity. When the overall similarity reaches a preset similarity threshold, an injection candidate is formed; when it is lower than the preset similarity threshold but reaches the recall threshold, a bypass prompt is formed, and the bypass prompt is sent to the task planner without being written into the task plan. Exclude injection candidates that do not meet the applicable premises or whose credibility does not reach the preset credibility threshold, and determine the reflective memory corresponding to the remaining injection candidates as the selected reflective memory.
6. The method according to claim 4, characterized in that, The step of writing error correction constraints and parameter templates into the task plan and call parameters includes: Parse the conditional action record and write the actions that meet the conditions for the task to be executed as pre-check items, adjustment items, or prohibited items in the task plan; The placeholders in the parameter skeleton are matched with the entities and input values of the task to be executed, and the parameter skeleton that has been filled and passed the parameter structure validation is merged into the calling parameters. Add a reflective memory marker to the written content; When a static verification exception or simulation execution exception is detected due to the written content, the same source written content is deleted according to the reflection memory flag, and the task plan and calling parameters before the write are restored.
7. The method according to claim 1, characterized in that, The verification and isolation simulation includes: Based on the tool parameter structure, preceding outputs, and permission records, verify parameters, dependencies, and permissions. If the verification fails, output the failure steps. If the verification passes, the repaired tool call chain is executed in a container isolation environment with a running image that is identical to the actual execution environment; Read-only tools connect to read-only data copies or desensitized snapshots. The writing tools, script tools, and external interfaces are generated by the isolation adaptation layer based on the tool interface definition and the success trajectory in the historical execution trajectory, and the simulated output is constructed according to the interface contract. The simulation will terminate and output the failed steps if the preset time limit is exceeded. When the simulation is completed, the simulation execution results of each step will be output.
8. The method according to claim 7, characterized in that, The retest after adjustment when failing includes: Check the required parameters, parameter types, prerequisites, permissions, output structure, and error correction constraint satisfaction status of the tool call chain after repair. Calculate the output score from the simulated input-output discrimination model and determine the current verification failure type based on the check results and the output score. Based on the current verification failure type, perform parameter completion, step rearrangement, context supplementation, or tool replacement to form a new repaired tool call chain and re-verify; When the number of re-verifications reaches the preset number of re-verifications, or when the number of consecutive occurrences of the same verification failure type reaches the preset number of repetitions, the termination condition is determined to be met, the actual execution is stopped, and verification failure information is output.
9. The method according to claim 1, characterized in that, The update of the credibility of the selected reflective memory includes: When the replay verification passes and the actual execution is completed, the tools, parameters, and output structures of the simulated execution and the actual execution are compared, and a weighted average is used to form the execution consistency. The credibility is increased when the execution is successful and the execution consistency reaches the consistency threshold; the credibility is decreased when the execution fails or the execution consistency does not reach the consistency threshold. If the replay verification fails even after reaching the termination condition, the credibility is reduced based on the verification failure result. When a selected reflective memory is not matched within a preset period, its credibility is reduced by the idle coefficient. Based on the updated credibility, the selected reflective memories are added to the injection candidate set, retained, or archived.
10. A tool call error correction system for a large language model intelligent agent, characterized in that, It includes a trajectory formation module, a reflective memory construction module, a retrieval and injection module, a replay execution module, and a credibility update module; The trajectory forming module is used to record task plans, call parameters, outputs, errors, context summaries, and environment states to form an execution trajectory; The reflexive memory construction module is used to filter failure trajectories and determine failure types. It generates applicable premises, error correction constraints, and parameter templates from the large language model and structures them into reflexive memories. The reflexive memories are injected into the tool call chain reconstructed from the failure trajectories, and replayed in an isolated environment to determine the initial credibility. The retrieval and injection module is used to extract task objectives, tool sequences, key entities and environmental states before the task to be executed, weighted match failure trajectories, select reflective memories with applicable premise matching and credibility reaching a preset credibility threshold, and write error correction constraints and parameter templates into the task plan and call parameters to form a repaired tool call chain. The replay execution module is used to verify the parameters, dependencies, and permissions of the tool call chain after repair and to isolate the simulation. If it fails, it is adjusted and re-verified. If it still fails after reaching the termination condition, the real execution is stopped. If it passes, the real execution is performed. The credibility update module is used to compare the tools, parameters and output structure of the simulated execution and the actual execution after the actual execution to form an execution consistency. It updates the credibility of the selected reflection memory based on the replay verification results, the actual execution status and the execution consistency. Based on the updated credibility, it retains or archives the selected reflection memory and outputs the actual execution result or verification failure information.