A large model switching scheduling method and system based on cost quality joint prediction

By using phased task modeling and joint cost-quality scoring, the problem of insufficient model adaptability for enterprise-level intelligent agents in long-path tasks is solved, enabling dynamic model switching and rollback, improving task completion rate and reducing resource waste.

CN123140255APending Publication Date: 2026-11-20LOVE AVATAR TECH (BEIJING) CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611622757.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-10-20
Publication Date
2026-11-20

AI Technical Summary

Technical Problem

Existing technologies cannot dynamically adapt models when enterprise-level intelligent agents execute long-path tasks, resulting in resource waste, difficulty in failure recovery, lack of stage-level model switching and rollback mechanisms, and inability to simultaneously optimize quality, cost, latency and success rate.

Method used

By modeling tasks in stages, constructing complexity and context vectors, jointly predicting model quality, cost, and latency risks, selecting models by stage and classifying and backing down when validation fails, and combining dynamic weights and staged budget control, we can achieve model fit scoring and switching.

Benefits of technology

It improves the completion rate of complex tasks, reduces overall call costs and latency, and enhances the stability of the inference chain.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123140255A_ABST
    Figure CN123140255A_ABST
Patent Text Reader

Abstract

The application discloses a large model switching scheduling method and system based on cost and quality joint prediction. The method comprises the following steps: receiving an agent reasoning task and generating a task image; splitting the reasoning task into multiple stage nodes and generating a complexity vector and a context load vector for each stage node; obtaining a model image of a candidate large language model; for the current stage node, calculating the quality prediction score, cost prediction value, time delay prediction value and failure risk value of each candidate model; generating a comprehensive adaptation score and selecting a target model according to a switching threshold; calling the target model to execute the current stage node and performing stage target verification; when the verification fails or the back-off trigger condition is met, performing retry, backup model switching, context compression or manual takeover according to the failure type; and recording the stage node, candidate model score, switching reason, back-off path and execution result. The application improves the success rate of long-path reasoning tasks and reduces the comprehensive calling cost.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the fields of large model inference scheduling, intelligent agents and multi-model routing technology, and more specifically, to a large model switching scheduling method and system based on joint cost-quality prediction. Background Technology

[0002] As large language models are increasingly used in enterprise office work, code analysis, knowledge-based question answering, data analysis, and process automation, a single model can hardly meet the comprehensive requirements of complex tasks in terms of accuracy, context capacity, response latency, invocation cost, tool invocation capability, and stability. Different models exhibit significant differences in inference ability, structured output capability, code understanding capability, long context processing capability, multilingual capability, tool invocation stability, and invocation cost.

[0003] In intelligent agent systems, complex tasks are typically not completed in a single model call, but rather broken down into multiple inference stages, including intent recognition, information retrieval, solution planning, tool invocation, code generation, result verification, and report generation. These long-path inference tasks present different model capability requirements at different stages. For example, in office automation scenarios, the front end needs to quickly understand user intent, the middle end needs to structurally invoke documents, spreadsheets, and email tools, and the back end needs to generate highly readable summary text. In code analysis scenarios, the front end needs to parse the repository structure, the middle end needs to identify dependency chains and potential defects, and the back end needs to generate and verify remediation suggestions.

[0004] Existing technologies typically employ fixed model calls, pre-set models based on task type, simple cost-priority routing, or manually configured model routing rules. While these solutions can meet basic needs in simple question-answering scenarios, they have significant shortcomings when enterprise-level agents execute long-path tasks: First, they cannot dynamically predict model suitability based on task complexity and context length, easily leading to failures due to low-capability models handling highly complex tasks, or resource waste due to high-cost models handling simple tasks; Second, they lack a stage-level model switching mechanism, making it impossible to select differentiated models for different stages of the inference chain; Third, they lack a joint scoring model that simultaneously considers quality, cost, latency, and historical success rate; Fourth, they lack a tiered rollback mechanism after failure, making it difficult to automatically recover from model call failures, non-compliant outputs, or verification failures; Fifth, they lack execution trajectory auditing for long-path inference, making it difficult to determine whether a failure at a certain stage is caused by inappropriate model selection, excessively long context, abnormal tool calls, or unstable output formats.

[0005] Therefore, designing a large-scale model switching and scheduling scheme that enables agents to score the suitability of different models based on the recognition of task complexity, context length, quality requirements, cost constraints, and latency constraints, select models in stages, and switch and roll back based on the verification results during execution, thereby improving the completion rate of complex tasks, reducing the overall calling cost, and enhancing the stability of the inference chain, is an urgent technical problem to be solved. Summary of the Invention

[0006] The purpose of this application is to provide a large model switching and scheduling method and system based on joint cost-quality prediction. By modeling long-path inference tasks in stages, constructing complexity vectors and context load vectors, performing joint prediction of quality, cost, latency, failure and risk on candidate models, selecting target models in stages and classifying and backing down when verification fails, the method can improve the completion rate of complex tasks, reduce the overall calling cost and improve the stability of the inference chain.

[0007] In a first aspect, embodiments of this application provide a large-scale model switching and scheduling method based on joint cost-quality prediction, comprising the following steps: Receive inference tasks initiated by intelligent agents, analyze the task type, task objective, input context, tool requirements and output constraints of the inference task, and generate a task profile; Based on the task profile, the reasoning task is divided into multiple stage nodes. Each stage node is bound to input references, expected outputs, required capabilities, and success criteria. A complexity vector and a context load vector are generated for each stage node. Obtain model profiles of multiple candidate large language models for pre-access. The candidate large language models are large language models that can be called by the scheduling system to perform inference tasks. The model profiles include context window, capability labels, call cost, average latency, historical success rate, and output stability statistics. For the current stage node, based on the complexity vector, the context load vector, and the model profile, calculate the quality prediction score, cost prediction value, latency prediction value, and failure risk value for each candidate model. Based on the quality prediction score, the cost prediction value, the latency prediction value, and the failure risk value, a comprehensive fit score for each candidate model is generated, and a target model is selected according to a preset switching threshold. The target model is invoked to execute the current stage node, and the stage target is verified on the output of the target model; When the stage target verification fails or the rollback trigger condition is met, model retry, backup model switching, context compression, or manual takeover will be performed according to the failure type. Record the stage nodes, candidate model scores, target model, switching reasons, rollback paths, and execution results.

[0008] Preferably, the complexity vector includes at least one of the following: number of task steps, number of cross-document dependencies, number of entities requiring reasoning, number of tool calls, number of structured output fields, number of code files, number of external system dependencies, error tolerance, and user risk level. The context load vector includes at least one of the following: number of input tokens, number of historical session tokens, number of retrieval fragment tokens, number of tool return result tokens, number of output schema tokens, and retention budget.

[0009] Preferably, the comprehensive fit score is a weighted sum of quality prediction score, normalized cost, normalized latency, failure risk score, capability matching reward, and rollback cost, wherein the quality prediction score and capability matching reward are given positive weights, and the normalized cost, normalized latency, failure risk score, and rollback cost are given negative weights; the weighting coefficients used for the weighting are dynamically updated based on historical execution data.

[0010] Preferably, the dynamic update of the weighting coefficients includes: After each stage node is completed, the actual quality score, actual call cost, actual response latency, output verification results, rollback count, manual takeover flag, and user feedback results are collected to form a stage execution feedback sample. Based on the stage execution feedback samples, a stage execution reward is constructed, and the weight vector is updated, pruned, and normalized according to the learning rate, the moving average baseline reward, and the weight influence direction.

[0011] Preferably, the preset switching thresholds include a minimum quality threshold, a maximum cost threshold, a maximum latency threshold, a context window security threshold, a failure risk threshold, and a maximum number of retries threshold; When the inference task is divided into multiple stage nodes, the inference task is managed in stages according to the global budget, stage budget and flexible reserved budget. The stage budget is allocated in the global budget according to the stage importance, risk level and complexity. The flexible reserved budget is used for dynamic addition of key stages, failure rollback stages or high-risk verification stages.

[0012] Preferably, the step of performing model retries, switching to backup models, context compression, or manual takeover based on the failure type includes: If a call times out, switch to a low-latency model or split the phase. For output format errors, switch to a backup model with higher structured output capabilities and add output format constraints; for factual inconsistencies, add retrieved evidence and switch to a candidate model with higher quality prediction scores. If the cost exceeds the limit, compress the context and switch to a low-cost model; if the security fails to respond or the permissions are insufficient, proceed to manual review or task downgrade.

[0013] Preferably, the context compression includes: When the context load exceeds the target model context window safety threshold, the input context is divided into three levels: key evidence, plain text, and redundant annotations. Calculate the retention score for each context fragment; Context-based hierarchical trimming is performed in the following order: first, redundant annotations are removed; then, plain text is compressed; and finally, key evidence is compressed.

[0014] Preferably, after invoking the target model to execute the current stage node, the method further includes: Write the actual quality, actual cost, actual latency, output format pass rate, fact consistency pass rate, tool call success rate, number of rollbacks, manual takeover results, and user feedback of this phase into the model phase execution log; The success rate, cost, and latency profiles of each model at each stage type are updated using exponential moving averages. The model profiles are maintained hierarchically by global profile, task type profile, and stage profile. When scoring, the profile that matches the current task type and stage type is read first. If the number of samples is insufficient, the global profile is used as a fallback.

[0015] Preferably, the step of selecting a target model according to a preset switching threshold and the step of performing model retries, switching to a backup model, context compression, or manual takeover based on the failure type include: Model switching is performed at the stage boundary, matching different capability models to different stage nodes; Rollback during the execution phase when an exception is triggered; For each stage call, a routing record is generated, which includes the candidate model score, the final selected model, the switching reason, the fallback path, and the output verification result.

[0016] Secondly, embodiments of this application provide a large model switching and scheduling system based on joint cost-quality prediction, used to implement the method described in any one of the first aspects, comprising: The task identification module is used to receive reasoning tasks initiated by the intelligent agent, parse the task type, task objective, input context, tool requirements and output constraints, and generate a task profile. The complexity evaluation module is used to generate task complexity vectors; The context load assessment module is used to generate context load vectors; The model profile management module is used to maintain the model profiles of candidate models and dynamically update the model profiles based on the stage execution data. The cost-quality joint scoring module is used to calculate the quality prediction score, cost prediction value, time delay prediction value and failure risk value of each candidate model, and generate a comprehensive fitness score. The dynamic weight adaptive optimization module is used to dynamically update the scoring weight coefficients based on historical stage execution data; The stage routing module is used to select the target model according to a preset switching threshold and record the reason for the stage-level model selection. The execution verification module is used to perform format verification, fact consistency verification, and stage target verification on the model output; The switching and rollback module is used to perform model retries, switch to standby models, context compression, or manual takeover based on the failure type. The phased budget control module is used to implement budget control according to the overall budget, phased budget, and flexible reserved budget. The context-based hierarchical cropping module is used to perform hierarchical cropping of key evidence, plain text, and redundant annotations when the context exceeds the limit. The audit log module is used to record stage nodes, candidate model scores, target models, switching reasons, rollback paths, and execution results.

[0017] Compared with the solutions of the prior art, the present invention has at least the following beneficial technical effects: (1) By splitting complex tasks into multiple stage nodes and constructing complexity vectors and context load vectors containing multi-dimensional information such as the number of task steps, the number of cross-document dependencies, the number of entities, the number of tool calls, and the number of structured output fields, the scheduling system can distinguish the differences in the model capability requirements of different stages, and avoid wasting high-cost models in simple stages or using low-capability models in high-complexity stages. (2) By setting up a comprehensive suitability scoring model that includes quality prediction score, cost prediction value, time delay prediction value and failure risk value and superimposed capability matching reward and rollback cost, and dynamically adjusting the weight coefficients of each scoring dimension under different task scenarios, the upgrade from single-dimensional routing to multi-dimensional comprehensive optimization is realized, so that the model selection takes into account both task success rate and call cost. (3) By performing model switching at stage boundaries during long-path inference, performing stage rollback when an exception is triggered, and selecting differentiated rollback paths corresponding to timeout, format error, fact inconsistency, cost overrun, etc. according to the failure type, the inference task can be automatically recovered when a certain stage fails without restarting the entire inference process. (4) By dividing the input context into three levels—key evidence, ordinary text, and redundant annotations—and performing hierarchical pruning based on retention scores, information strongly bound to the current stage goal and output constraints is prioritized for retention when the context window exceeds the limit, thus reducing the loss of key information in long context tasks. (5) Through phased budget control of global budget, phase budget and flexible reserved budget, as well as the exponential moving average self-iterative update of model profile, the system can continuously correct the model success rate, cost, latency and risk indicators based on real execution data, forming a complete technical closed loop from historical execution feedback collection, weight self-optimization, phase budget allocation to model profile self-iteration. In summary, this application organically combines key technologies such as task-stage modeling, joint cost-quality scoring and dynamic weighting, stage-level switching and classification rollback, context-level pruning, staged budget control, and model profiling self-iteration to form a complete heterogeneous large model switching and long-path inference scheduling scheme. It can run stably in various enterprise intelligent agent scenarios such as office automation, code analysis, knowledge question answering, and data analysis, improving the completion rate of complex tasks while reducing the overall calling cost and latency. Attached Figure Description

[0018] Exemplary embodiments of the present invention can be more fully understood by referring to the accompanying drawings. The drawings are provided to further illustrate the embodiments of this application and form part of the specification. They are used together with the embodiments of this application to explain the present invention and do not constitute a limitation thereof. In the drawings, the same reference numerals generally represent the same components or steps.

[0019] Figure 1 A flowchart illustrating a large model switching and scheduling method based on joint cost-quality prediction provided in this application embodiment; Figure 2 A schematic diagram of the scoring model provided in the embodiments of this application; Figure 3 A schematic diagram of the structure of a large model switching and scheduling system based on joint cost-quality prediction provided in this application embodiment; Figure 4 A schematic diagram of an electronic device provided for an exemplary embodiment of this application; Figure 5 This is a schematic diagram of a computer-readable medium provided for an exemplary embodiment of this application. Detailed Implementation

[0020] Exemplary embodiments of the present disclosure will now be described in more detail with reference to the accompanying drawings. While exemplary embodiments of the present disclosure are shown in the drawings, it should be understood that the present disclosure may be implemented in various forms and should not be limited to the embodiments set forth herein. Rather, these embodiments are provided so that this disclosure will be thorough and complete, and will fully convey the scope of the disclosure to those skilled in the art.

[0021] In the description of this invention, it should be noted that the terms "center," "upper," "lower," "left," "right," "vertical," "horizontal," "inner," and "outer," etc., indicate the orientation or positional relationship based on the orientation or positional relationship shown in the accompanying drawings. They are used only for the convenience of describing the invention and for simplifying the description, and do not indicate or imply that the device or element referred to must have a specific orientation, or be constructed and operated in a specific orientation. Therefore, they should not be construed as limitations on the invention. Furthermore, the terms "first," "second," and "third" are used for descriptive purposes only and should not be construed as indicating or implying relative importance.

[0022] For ease of explanation, the task profile in this application describes the type, objective, tool requirements, output format, and risk level of the task to be processed; the stage node describes a single stage in long-path inference and its inputs, outputs, and completion conditions; the complexity vector describes the task complexity and inference path length; the context load vector describes the context length and available context budget; and the model profile describes the candidate model's capabilities, cost, latency, and historical performance. The parameters involved in the remaining formulas are explained after each formula.

[0023] Furthermore, the technical features involved in the different embodiments of the present invention described below can be combined with each other as long as they do not conflict with each other.

[0024] This embodiment uses an enterprise-level AgentOS as the runtime environment to provide a detailed explanation of each step of the above method. See also... Figure 1 , Figure 1 A flowchart illustrating a large-model switching and scheduling method based on joint cost-quality prediction is provided in this application embodiment. Specifically, the method provided in this application embodiment includes the following steps: S101, Receive the reasoning task initiated by the intelligent agent, parse the task type, task objective, input context, tool requirements and output constraints of the reasoning task, and generate a task profile; Specifically, the task identification module receives user requests, system tasks, or intelligent agent subtasks, parses the task type, task objective, input context, tool requirements, and output constraints, and generates a task profile containing a task identifier, task type, task objective, required tools, output format, and risk level. The task profile can be represented using a task description data structure called TaskProfile, whose fields include task identifier (task_id), task type (task_type), task objective (goal), required tools (required_tools), output format (output_schema), and risk level (risk_level). Task types include office automation, code analysis, knowledge-based Q&A, data analysis, or process automation, while output formats include JSON, tables, emails, or code. The risk level is determined based on whether the task involves external transmission, deletion, modification, payment, permission changes, or access to high-value data.

[0025] Furthermore, the task identification module extracts quality requirement vectors, cost constraint vectors, and latency constraint vectors from the task description and user configuration: the quality requirement vector describes the factual consistency requirements, structuring requirements, and risk tolerance; the cost constraint vector describes the total task budget, single-stage cost cap, and retry cost cap; and the latency constraint vector describes the first token latency requirement, total completion time requirement, and critical stage deadlines. These task profiles, constraint vectors, and input context serve as input for subsequent stage decomposition, model scoring, budget allocation, and rollback determination.

[0026] S102, based on the task profile, the reasoning task is divided into multiple stage nodes. Each stage node is bound to input reference, expected output, required capabilities and success judgment conditions, and a complexity vector and context load vector are generated for each stage node. Specifically, the system breaks down the task into one or more stage nodes, which may include the intent understanding stage, retrieval planning stage, tool invocation stage, inference analysis stage, result generation stage, and result verification stage. Each stage node is bound to input references, expected outputs, required capabilities, and success criteria, and can be represented using a stage description data structure StageNode. Its fields include stage identifier stage_id, stage type stage_type, input references input_refs, expected outputs expected_output, and success criteria success_criteria. Input references are used to bind the output of the previous stage, retrieval fragments, or tool return results. Success criteria are used to verify the goals of subsequent stages, such as the completeness rate of structured output fields, the consistency rate of facts and evidence, the success rate of tool invocation, or the pass rate of static analysis. The task complexity vector can be composed of the following features: number of task steps, number of cross-document dependencies, number of entities requiring inference, number of tool invocations, number of structured output fields, number of code files, number of external system dependencies, error tolerance, and user risk level. The context load vector can be composed of the number of input tokens, the number of historical session tokens, the number of retrieval fragment tokens, the number of tool return result tokens, the number of output schema tokens, and the reserved budget. The system determines whether a task is a short-path, medium-path, or long-path task based on the complexity vector and the context load vector: As an example, and not a limitation, tasks with no more than 2 steps, short input context, and no or only one tool call are classified as short-path tasks, prioritizing low-latency, low-cost models; tasks with 3 to 5 steps, involving retrieval or tool calls, and requiring structured output are classified as medium-path tasks, selecting a quality-cost balanced model and enabling output format verification; tasks with more than 5 steps, involving multiple rounds of retrieval, multiple tool calls, multiple stages of verification, or long context are classified as long-path tasks, enabling stage-level model routing, context compression, execution verification, and failure rollback.

[0027] S103, obtain model profiles of multiple candidate large language models to be pre-accessed. The candidate large language models are large language models that can be called by the scheduling system to perform inference tasks. The model profiles include context window, capability labels, call cost, average latency, historical success rate and output stability statistics. Specifically, the model profiling management module maintains model profiles for pre-accessible candidate large language models. These profiles include context windows, capability tags, unit cost, average latency, tool invocation capabilities, structured output capabilities, and historical success rates. They can be represented using the ModelProfile data structure, whose fields include model ID (model_id), context window (context_window), capability tags (capability_tags), cost per 1k tokens (cost_per_1k_tokens), average latency (avg_latency), and historical success statistics (success_stats). Historical success statistics include success rates for each task type and stage type, structured output pass rate, tool invocation success rate, average cost, and average latency. Model profiles are maintained at a hierarchical granularity: the global profile reflects the overall model performance; task type profiles reflect the model's performance in tasks such as office work, coding, retrieval, and data analysis; and stage profiles reflect the model's performance in stages such as intent recognition, evidence integration, structured generation, tool invocation, and result verification. During routing scoring, profiles matching the current task type and stage type are read first; when the sample size is insufficient, the global profile is used as a fallback. The model profile can be generated during system initialization from the model's nominal parameters, benchmark test results, and manual configuration, and then continuously updated during operation based on the stage execution logs.

[0028] In addition, the model profile management module also maintains a switch policy data structure SwitchPolicy, whose fields include minimum score gap (min_score_gap), maximum number of retries (max_retry), fallback model list (fallback_models), cost ceiling (cost_ceiling), and latency ceiling (latency_ceiling), which are used for stage routing and failure fallback determination.

[0029] S104, For the current stage node, based on the complexity vector, the context load vector and the model profile, calculate the quality prediction score, cost prediction value, latency prediction value and failure risk value of each candidate model respectively; Specifically, the quality prediction score is calculated based on the model's capability label matching degree with stage requirements, historical success rate, structured output stability (i.e., structured output pass rate), tool call success rate, and long context processing capability, and is used to predict the likelihood of the model completing the current stage's goal; the cost prediction score is calculated based on the input token, output token prediction value, model unit price, estimated retry cost, and context compression cost, and is used to predict the cost of completing the current stage; the latency prediction score is calculated based on historical average latency (including historical first token latency and historical total generation latency), current queue load, and context length estimation; the failure risk score is calculated based on historical failure rate, task complexity exceeding limits, context approaching the window limit (i.e., context window overflow probability), tool call failure statistics, structured output failure rate, historical rollback rate, and output schema complexity, and is used to predict whether a more stable model needs to be selected in advance or a backup model needs to be set up.

[0030] In one specific implementation, the aforementioned quality prediction score, cost prediction value, time delay prediction value, and failure risk value can be calculated using the following formulas: Quality prediction score of candidate model m in stage s Calculate according to formula (1): (1); in, The matching degree between the capability labels of model m and the requirements of stage s, with a value range of 0 to 1, is calculated based on the proportion of the intersection between the capability labels required by the stage and the capability labels of the model. The historical success rate of model m in the same stage is taken from the stage profile in the model profile. The structured output pass rate for model m; For model m, the success rate of tool calls; The long context processing capability of model m is scored based on a comprehensive evaluation of the context window size and the success rate of historical long context tasks. to For quality prediction weighting coefficients, satisfying The initial values ​​can be set to 0.25, 0.30, 0.20, 0.15, and 0.10 respectively, and can be adjusted differently for each task type based on historical execution data.

[0031] Cost prediction of candidate model m at stage s Calculate according to formula (2): (2); in, The number of input tokens for stage s, taken from the context load vector; The expected number of output tokens for model m in stage s is estimated based on the average length of historical outputs for similar stages. The unit price for calling per thousand tokens for model m is taken from the model profile; To estimate the cost of retrying, it is estimated as the product of the failure probability and the cost per call, with the failure probability taken from the failure risk value; The estimated cost for context compression is set to 0 when the context load does not exceed the model window safety threshold; otherwise, the number of tokens and the estimated cost per unit of compression processing are pruned as needed.

[0032] The predicted time delay of candidate model m in stage s is calculated according to formula (3): (3); in, The historical average latency of model m in the same stage includes the latency of the first token and the total generation latency, taken from the model profile; This is the current queue load coefficient, with a value ranging from 0 to 1, calculated based on the ratio of the current number of requests to be processed to the model's concurrency limit. The context length factor is calculated as the ratio of the current number of input tokens to the model context window. When the ratio exceeds 0.7, it increases non-linearly by an exponential function to reflect the impact of long context on generation speed.

[0033] Failure risk value of candidate model m in stage s Calculate according to formula (4): (4); in, Let m be the historical failure rate of model m in the same stage; The degree of task complexity exceeding the limit is calculated after normalization based on the matching deviation between each dimension of the current stage complexity vector and the model's capability boundary, with a value range of 0 to 1. The probability of context window overflow is estimated based on the ratio of the current context load to the model window capacity; the closer the ratio is to 1, the higher the probability. The failure rate of tool calls for model m; The structured output failure rate for model m; The historical regression rate of model m; to The failure risk weighting coefficient satisfies... The initial values ​​can be set to 0.25, 0.15, 0.20, 0.15, 0.15, and 0.10 respectively.

[0034] In a preferred embodiment, the scoring model further includes a capability matching reward and a fallback cost: the capability matching reward is calculated based on the degree of matching between the candidate model and the capabilities required for the current stage in dimensions such as code capability, mathematical reasoning, long context processing, function calls, Chinese writing, and document generation; the fallback cost is calculated based on the expected costs and latency incurred after the model fails, including switching to a backup model, re-executing the stage, and compressing the context. Each cost and latency prediction value is normalized before weighting. Normalization can be performed using range normalization or normalization according to task budget and latency constraints, so that scoring dimensions of different dimensions can be weighted and summed. The normalized values ​​all range from 0 to 1.

[0035] S105, Based on the quality prediction score, the cost prediction value, the delay prediction value and the failure risk value, generate a comprehensive fit score for each candidate model, and select a target model according to a preset switching threshold; Specifically, see Figure 2 , Figure 2 A schematic diagram of the scoring model provided in this application embodiment. The comprehensive fitness score of candidate model m in stage s is calculated according to formula (5): (5); in, Indicates the scheduling period or task batch. , , , , , The weighting coefficients are dynamically updated: quality prediction score and capability matching reward are given positive weights, while normalized cost, normalized latency, failure risk score, and rollback cost are given negative weights. The initial weights can be manually configured and generated based on enterprise strategy, task scenario, and model profile, and then adaptively adjusted based on historical execution data during operation.

[0036] Before each stage begins, the system calculates the fitness scores of all candidate models and selects the target model based on these scores. When the score difference between the highest-scoring model and the second-highest-scoring model is less than a preset threshold, a lower-cost model can be selected by considering both cost and latency constraints. When the stage risk level is high, a model with a higher quality prediction score can be selected even if the cost is high. The model switching thresholds include at least a minimum quality threshold, a maximum cost threshold, a maximum latency threshold, a failure risk threshold, a context window safety threshold, and a retry count threshold. As examples, not limitations: When a candidate model's prediction context occupies more than 85% of its window capacity, it is marked as a high-risk model; when a candidate model's quality prediction score is below the minimum quality threshold (e.g., 0.72), the model is not selected or is moved to the high-capacity model candidate pool; when the single-stage prediction cost exceeds 35% of the task budget, a low-cost alternative model is prioritized or the context is compressed and re-evaluated; when the prediction latency exceeds the maximum latency threshold (e.g., 8 seconds), a low-latency model is switched to or the current stage is split; when the failure risk value exceeds the failure risk threshold (e.g., 0.40), conservative routing is enabled and a backup model is pre-configured; when the actual output fails structured validation and the number of retries reaches the maximum number of retries (e.g., 2 times), a backup model is switched to; when the cumulative cost exceeds 80% of the task budget and the current stage is a low-risk stage, a low-cost model is switched to. The above thresholds are for illustrative purposes only and are not limitations; specific values ​​can be configured based on enterprise strategies and task types.

[0037] Furthermore, this embodiment also sets up a dynamic weight adaptive optimization mechanism: after the execution of each stage node, the system collects the actual quality score, actual call cost, actual response latency, output verification results, rollback count, manual takeover flag, and user feedback results to form a stage execution feedback sample. Based on the feedback sample, the system periodically updates the weight coefficients in the joint scoring model, ensuring that the model selection strategy under different task types, stages, and tenant strategies can continuously converge. The weight vector is represented as... The stage performance reward is expressed according to formula (6): (6); in, In order to perform quality scoring, To normalize costs, For normalized delay, Penalty for failure or rollback To verify the reward, For manual takeover punishment, to The reward coefficient is determined according to the following rules: This is the quality reward coefficient, ranging from 0.3 to 0.7, with the upper limit applied to high-risk or high-quality tasks. This is the cost penalty coefficient, ranging from 0.1 to 0.3, with the upper limit applied to cost-sensitive tasks. This is the latency penalty coefficient, ranging from 0.1 to 0.3, with the upper limit used for latency-sensitive tasks; This is the failure penalty coefficient, ranging from 0.2 to 0.5, with the upper limit applied during critical stages; To verify the pass rate, the reward coefficient ranges from 0.1 to 0.3, with the upper limit used for more stringent verification tasks. The penalty coefficient for manual intervention ranges from 0.5 to 1.0, with a higher value used in all scenarios to avoid frequent manual intervention. The initial value of the above coefficient can be configured by the enterprise strategy, and can be dynamically adjusted within the above range based on the stage execution feedback data during operation. The system can update the weights using multi-armed slot machine, strategy gradient, or constrained sliding window optimization methods. To facilitate engineering implementation, the system can update the weights using multi-armed slot machine, strategy gradient, or constrained sliding window optimization methods. To facilitate engineering implementation, the update rule shown in formula (7) can be used: (7); in, This is the sliding average reward for similar tasks. The direction vector is influenced by the gradient or weights of the stage features. Used to limit the magnitude of a single adjustment. Used to keep the total weight stable Let be the lower bound for clipping each component of the weight vector. This represents the upper bound for clipping each component of the weight vector. The learning rate is used for various purposes. For example, in an office automation agent, if quality verification fails repeatedly during the document summarization phase but the cost is low, the system will increase the weight of quality and failure risk while decreasing the weight of cost. In a code analysis agent, if timeouts occur multiple times during the complex code call chain analysis phase, the system will increase the weight of latency and failure risk. In low-risk chat or format conversion tasks, the system can increase the weight of cost to prioritize low-cost models.

[0038] Furthermore, this embodiment also sets up a phased budget control mechanism: the task budget is divided into a global budget, a phase budget, and a flexible reserved budget. The global budget is used to limit the maximum token cost, call cost, and maximum completion time of the entire long-path task; the phase budget is used to limit the cost limit, latency limit, number of retries, and context usage of each phase node; the flexible reserved budget is used to dynamically add resources in critical phases, failure rollback phases, or high-risk verification phases. When generating phase nodes, the system generates phase budgets based on task type, phase importance, risk level, and historical resource consumption, and calculates them according to formula (8): (8); And reserve a flexible budget, calculated according to formula (9): (9); in, Let s be the stage budget. Reserve budget for flexibility. For the overall budget, Importance coefficient of stage s The risk level coefficient for stage s. Let be the complexity coefficient of stage s, and the denominator is the sum of the products of the importance coefficients, risk level coefficients and complexity coefficients of all stages; The proportion of the budget reserved for flexibility within the overall budget can be configured between 5% and 25% based on the task's risk level. When the actual consumption of a stage exceeds the stage budget but not the sum of the stage budget and the flexibility budget, and that stage is marked as a critical stage, additional flexibility budget is allowed. When a non-critical stage exceeds its budget, context pruning, low-cost model switching, or abort and retry will be prioritized. As an example, and not a limitation, office automation tasks can allocate the budget as follows: 10% for intent identification, 15% for retrieval planning, 30% for evidence integration, 25% for result generation, and 20% for result verification. Code analysis tasks can allocate the budget as follows: 15% for repository parsing, 20% for critical file location, 35% for call chain reasoning, 20% for fix suggestion generation, and 10% for static verification. The specific allocation ratio of the stage budget can be configured in conjunction with enterprise strategy and task type.

[0039] S106, Invoke the target model to execute the current stage node, and verify the stage target output of the target model; Specifically, the stage routing module sends the current stage context and prompt words to the target model for execution; the execution verification module performs stage target verification on the model output, which includes at least four categories: format verification, factual consistency verification, tool call result verification, and stage target completion verification. Format verification checks whether the output conforms to the agreed format such as JSON, schema, table, or code, and whether the required fields are complete. Factual consistency verification compares the output content with the retrieved evidence, tool execution results, or database query results to identify factual conflicts, fictitious references, and expired information. Tool call result verification checks whether the tool call parameters are compliant, whether the interface return is successful, and whether the returned fields meet the stage requirements. Stage target completion verification determines whether the output has achieved the current stage target based on the success criteria.

[0040] When all the above verifications pass, the system writes the stage output to the stage results and proceeds to the next stage node, simultaneously triggering updates to the model profile and dynamic weights. When any verification fails or the rollback trigger condition is met, the system proceeds to step S107, performing a classification rollback based on the failure type. Format validation results, factual consistency validation results, tool call results, and stage goal completion results generated during the verification process are all written to the model stage execution log, serving as the basis for subsequent score prediction, model profile updates, and dynamic weight updates.

[0041] Specifically, the current stage context and prompt words are sent to the target model for execution; the execution verification module performs format verification, factual consistency verification, tool call result verification, and stage target completion verification on the model output.

[0042] S107, when the stage target verification fails or the rollback trigger condition is met, perform model retry, standby model switching, context compression or manual takeover according to the failure type. Specifically, the failure rollback mechanism not only replaces the model, but also selects different rollback paths based on the type of failure: for call timeout, it prioritizes switching to a low-latency model or splitting the context; for format failure, it prioritizes switching to a stable model with structured output and strengthening the output schema constraints; for fact consistency failure, it prioritizes adding retrieval evidence and selecting a model with stronger reasoning capabilities; for cost exceeding limits, it prioritizes compressing the context and switching to a low-cost model; and for security refusal or insufficient permissions, it enters the path of manual review or task degradation.

[0043] For scenarios where the context window exceeds the limit, this embodiment does not adopt a uniform compression method, but instead divides the input context into three levels: key evidence, ordinary text, and redundant annotations. Key evidence includes the original text fragments retrieved by the search, database query results, key fields returned by the tool, user-specified constraints, and verified conclusions from the previous stage. Ordinary text includes background information, general historical dialogues, auxiliary explanations, and non-core paragraphs. Redundant annotations include duplicate content, formatting instructions, low-similarity fragments, expired contexts, and intermediate outputs unrelated to the current stage's objective. The system generates a retention score for each context fragment, calculated according to formula (10): (10); in, This indicates the semantic relevance of a fragment to the current stage's objective. Indicates whether the fragment is bound to output constraints or compliance rules. Indicates timeliness, Indicates the credibility of the source. Indicates the degree of repetition with other segments. Indicates the cost per segment length. , , , , , These are non-negative weighting coefficients, corresponding to the importance of the six scoring dimensions mentioned above. Their values ​​can be configured based on enterprise strategy and task type. When limits are exceeded, the system processes data in the following order: first, redundant comments are removed; then, ordinary text is compressed; and finally, key evidence is compressed only if the evidence coverage requirement is met. Different task types can be configured with different pruning priorities: risk control tasks prioritize retaining key evidence and compliance constraints; code analysis tasks prioritize retaining error logs, call chains, and related code snippets; and office automation tasks prioritize retaining user instructions, the latest meeting conclusions, and key pending items. After tiered pruning, the system recalculates the context load. If it still exceeds the target model window safety threshold, a long context model switch or stage split is triggered.

[0044] Furthermore, to avoid inaccurate routing results due to long-term static model profiles, this embodiment sets up a self-iterative mechanism for model profiles: after each stage execution, the system writes the actual quality, actual cost, actual latency, output format pass rate, fact consistency pass rate, tool call success rate, rollback count, manual takeover results, and user feedback into the model stage execution log, and periodically updates the model profile according to task type and stage type. The success rate of model m in stage type k is updated according to the exponential moving average, expressed by formula (11): (11); in, The success rate of the updated model m on stage type k. The success rate of model m on stage type k before the update. For smoothing coefficients, This is the actual success indicator for this phase of execution. It is determined based on a combination of structured validation, factual consistency validation, manual review, and user feedback, and can take a value between 0 and 1.

[0045] Cost profiles and latency profiles are updated in the same way. For abnormal failures, service degradation, or supplier rate limiting events, the system can introduce penalty events to temporarily adjust the model's risk profile upwards.

[0046] S108 records the stage node, candidate model score, target model, switching reason, rollback path, and execution result.

[0047] Specifically, the audit log module records task segments, model scores, selection results, switching reasons, rollback paths, and final execution results, enabling operations and maintenance personnel to analyze model performance, optimize routing strategies, and track abnormal tasks.

[0048] In summary, this embodiment achieves stage-level cost-quality joint prediction routing for long-path inference tasks by organically combining task-stage modeling, joint cost-quality scoring and dynamic weighting, stage-level switching and classification rollback, context-level pruning, stage-based budget control, and model profiling self-iteration. This improves the completion rate of complex tasks while reducing overall call costs and latency.

[0049] To further illustrate the above method, this application embodiment will further elaborate on the solution by combining two scenarios: office automation agent and code analysis agent.

[0050] In an office automation agent scenario, a user requests, "Based on the sales meeting minutes, CRM customer status, and project delivery weekly reports from the past three months, please generate a follow-up plan for key customers this week and simultaneously generate an email draft." The system identifies this as a long-path office task and breaks it down into six stages: meeting minute retrieval, CRM status reading, project weekly report summary, customer priority ranking, follow-up plan generation, and email draft generation. In the meeting minute retrieval stage, the system selects a low-cost retrieval planning model; in the project weekly report summary stage, the system selects a long-context model based on context length; in the customer priority ranking stage, the system selects a model with strong structured capabilities based on structured output requirements; and in the email draft generation stage, the system selects a model with strong writing capabilities and a moderate cost. If the email draft output does not meet the format requirements, the system switches to a stable structured output model and regenerates the email.

[0051] In the code analysis agent scenario, the user requests to "analyze the reasons for the order synchronization failure in this warehouse and provide repair suggestions." The system breaks down the task into warehouse structure parsing, key file location, call chain analysis, anomaly log matching, defect reasoning, and repair suggestion generation. Because code call chain analysis requires a high level of code comprehension from the model, the system increases the weight of code comprehension at this stage. In the repair suggestion generation stage, the system adds factual consistency verification, requiring the output to reference specific file paths and function names. If the repair suggestions output by the model fail static checks or are inconsistent with log evidence, the system will trigger a failure rollback mechanism, switching to a model with a higher historical code analysis success rate, while retaining the file structure and log evidence parsed in the previous stage to reduce the cost of repeated calls.

[0052] Furthermore, in multi-model inference gateway scenarios, enterprises can uniformly access multiple commercial models, private models, and open-source models. After receiving inference requests from different agents, the gateway no longer forwards requests solely based on model name or fixed rules. Instead, it predicts model suitability based on task complexity, context length, success rate, cost, and latency. The gateway generates routing records for each stage call, including candidate model scores, the final selected model, the reason for switching, the fallback path, and the output verification results.

[0053] In summary, the system provided in this embodiment is based on the same inventive concept as the above method embodiment. The twelve modules in the system correspond one-to-one with the eight steps in the above method embodiment. It can be deployed in an intelligent agent operation platform, a multi-model inference gateway, or an enterprise-level AgentOS, and has good engineering feasibility.

[0054] Please refer to Figure 3 , Figure 3 This is a schematic diagram of the structure of a large model switching and scheduling system 20 based on joint cost-quality prediction provided in this application embodiment. This embodiment further illustrates the aforementioned method embodiment by combining the detailed working process of each module of the system. The system 20 includes a task identification module 201, a complexity assessment module 202, a context load assessment module 203, a model profile management module 204, a joint cost-quality scoring module 205, a dynamic weight adaptive optimization module 206, a staged routing module 207, an execution verification module 208, a switching and rollback module 209, a staged budget control module 210, a context hierarchical pruning module 211, and an audit log module 212. Each module in the system corresponds one-to-one with each step in the above method embodiment: The task identification module 201, corresponding to step S101, is used to receive the reasoning task initiated by the intelligent agent and generate a task profile. The complexity evaluation module 202 and the context load evaluation module 203 correspond to step S102 and are used to generate the task complexity vector and the context load vector, respectively. The model profile management module 204 corresponds to steps S103 and S108 and is used to maintain the model profile of the candidate model and dynamically update the model profile based on the stage execution data. The cost-quality joint scoring module 205, corresponding to steps S104 and S105, is used to calculate the quality prediction score, cost prediction value, time delay prediction value and failure risk value of each candidate model, and generate a comprehensive fit score. The dynamic weight adaptive optimization module 206 and the stage routing module 207 correspond to step S105 and are respectively used to dynamically update the scoring weight coefficient based on historical stage execution data and to perform budget control according to the global pre-calculated stage budget and the flexible reserved budget. The execution verification module 208, corresponding to step S107, is used to perform format verification, fact consistency verification, and stage target verification on the model output. The switching and rollback module 209, corresponding to step S105, is used to perform model retry, standby model switching, context compression, or manual takeover based on the failure type. Phased budget control module 210, corresponding to step S106, is used to perform budget control according to global budget, phased budget and flexible reserved budget; The context-based hierarchical cropping module 211, corresponding to step S107, is used to perform hierarchical cropping of key evidence, ordinary text, and redundant annotations when the context exceeds the limit. The audit log module 212, corresponding to step S108, is used to record stage nodes, candidate model scores, target models, switching reasons, rollback paths, and execution results.

[0055] It should be noted that the division of labor and naming of the modules and their sub-modules described in this embodiment are merely illustrative examples. Those skilled in the art can merge multiple modules into one module or split one module into multiple sub-modules with finer functions according to the actual system architecture. These adjustments do not affect the substance of the technical solution of this invention and should be considered as falling within the protection scope of this invention.

[0056] In summary, the system provided in this embodiment is based on the same inventive concept as the above method embodiment. The twelve modules in the system correspond one-to-one with the eight steps in the above method embodiment. It can be deployed in an intelligent agent operation platform, a multi-model inference gateway, or an enterprise-level AgentOS, and has good engineering feasibility.

[0057] Please refer to Figure 4 This illustrates a schematic diagram of an electronic device provided by some embodiments of this application. For example... Figure 4 As shown, the electronic device 30 includes: a processor 300, a memory 301, a bus 302, and a communication interface 303. The processor 300, the communication interface 303, and the memory 301 are connected via the bus 302. The memory 301 stores a computer program that can run on the processor 300. When the processor 300 runs the computer program, it executes the method described above in this application.

[0058] The memory 301 may include high-speed random access memory (RAM) or non-volatile memory, such as at least one disk storage device. Communication between this system network element and at least one other network element is achieved through at least one communication interface 303 (which can be wired or wireless), such as the Internet, wide area network, local area network, or metropolitan area network.

[0059] Bus 302 can be an ISA bus, PCI bus, or EISA bus, etc. The bus can be divided into an address bus, a data bus, a control bus, etc. The memory 301 is used to store programs. After receiving an execution instruction, the processor 300 executes the program. The methods disclosed in any of the foregoing embodiments of this application can be applied to the processor 300, or implemented by the processor 300.

[0060] The processor 300 may be an integrated circuit chip with signal processing capabilities. In implementation, each step of the above method can be completed by the integrated logic circuitry in the hardware of the processor 300 or by instructions in software form. The processor 300 may be a general-purpose processor, including a central processing unit (CPU), a network processor (NP), etc.; it may also be a digital signal processor (DSP), an application-specific integrated circuit (ASIC), an off-the-shelf programmable gate array (FPGA), or other programmable logic devices, discrete gate or transistor logic devices, or discrete hardware components. It can implement or execute the methods, steps, and logic block diagrams disclosed in the embodiments of this application. The general-purpose processor may be a microprocessor or any conventional processor. The steps of the methods disclosed in the embodiments of this application can be directly embodied in the execution of a hardware decoding processor, or executed by a combination of hardware and software modules in the decoding processor. The software modules may reside in random access memory, flash memory, read-only memory, programmable read-only memory, electrically erasable programmable memory, registers, or other mature storage media in the art. The storage medium is located in memory 301. The processor 300 reads the information in memory 301 and, in conjunction with its hardware, completes the steps of the above method.

[0061] The electronic device and the method provided in this application are based on the same inventive concept and have the same beneficial effects as the methods they employ, operate, or implement. The electronic device can be a terminal device with inference scheduling capabilities, such as a smartphone, tablet, laptop, desktop computer, workstation, or edge computing device.

[0062] This application also provides a computer-readable medium corresponding to the method provided in the foregoing embodiments. Please refer to... Figure 5 The computer-readable storage medium shown is an optical disc 40, on which a computer program (i.e., a program product) is stored, which, when run by a processor, performs the aforementioned method.

[0063] The computer-readable storage medium may include, but is not limited to, various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks. In a specific application scenario, the computer-readable storage medium may be built into the AgentOS execution control host as part of the firmware; or it may be a standalone software product.

[0064] The computer-readable storage medium provided in the above embodiments of this application and the method provided in the embodiments of this application are based on the same inventive concept and have the same beneficial effects as the methods adopted, run or implemented by the applications stored therein.

[0065] This embodiment also provides a computer program product, which includes a computer program. When executed by a processor, the computer program implements the methods described in any of the above embodiments.

[0066] The computer program product may include any combination of one or more program modules.

[0067] It should be noted that the flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code, which contains one or more executable instructions for implementing the specified logical function. It should also be noted that in some alternative implementations, the functions marked in the blocks may occur in a different order than those marked in the drawings. For example, two consecutive blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or action, or using a combination of dedicated hardware and computer instructions.

[0068] Those skilled in the art will understand that, for the sake of convenience and brevity, the specific working processes of the systems, devices, and units described above can be referred to the corresponding processes in the foregoing method embodiments, and will not be repeated here.

[0069] In the several embodiments provided in this application, it should be understood that the disclosed apparatus and methods can be implemented in other ways. The apparatus embodiments described above are merely illustrative. For example, the division of units is only a logical functional division, and there may be other division methods in actual implementation. Furthermore, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Additionally, the coupling or direct coupling or communication connection shown or discussed may be through some communication interface; the indirect coupling or communication connection between apparatuses or units may be electrical, mechanical, or other forms.

[0070] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0071] In addition, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.

[0072] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit them. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of this application, and they should all be covered within the scope of the claims and specification of this application.

Claims

1. A large-scale model switching and scheduling method based on joint cost-quality prediction, characterized in that, Includes the following steps: Receive inference tasks initiated by intelligent agents, analyze the task type, task objective, input context, tool requirements and output constraints of the inference task, and generate a task profile; Based on the task profile, the reasoning task is divided into multiple stage nodes. Each stage node is bound to input references, expected outputs, required capabilities, and success criteria. A complexity vector and a context load vector are generated for each stage node. Obtain model profiles of multiple candidate large language models for pre-access. The candidate large language models are large language models that can be called by the scheduling system to perform inference tasks. The model profiles include context window, capability labels, call cost, average latency, historical success rate, and output stability statistics. For the current stage node, based on the complexity vector, the context load vector, and the model profile, calculate the quality prediction score, cost prediction value, latency prediction value, and failure risk value for each candidate model. Based on the quality prediction score, the cost prediction value, the latency prediction value, and the failure risk value, a comprehensive fit score for each candidate model is generated, and a target model is selected according to a preset switching threshold. The target model is invoked to execute the current stage node, and the stage target is verified on the output of the target model; When the stage target verification fails or the rollback trigger condition is met, model retry, backup model switching, context compression, or manual takeover will be performed according to the failure type. Record the stage nodes, candidate model scores, target model, switching reasons, rollback paths, and execution results.

2. The method according to claim 1, characterized in that, The complexity vector includes at least one of the following: number of task steps, number of cross-document dependencies, number of entities requiring reasoning, number of tool calls, number of structured output fields, number of code files, number of external system dependencies, error tolerance, and user risk level. The context load vector includes at least one of the following: number of input tokens, number of historical session tokens, number of retrieval fragment tokens, number of tool return result tokens, number of output schema tokens, and retention budget.

3. The method according to claim 1, characterized in that, The overall fit score is a weighted sum of quality prediction score, normalized cost, normalized latency, failure risk score, capability matching reward, and rollback cost. The quality prediction score and capability matching reward are given positive weights, while the normalized cost, normalized latency, failure risk score, and rollback cost are given negative weights. The weighting coefficients used for the weighting are dynamically updated based on historical execution data.

4. The method according to claim 3, characterized in that, The dynamic updating of the weighting coefficients includes: After each stage node is completed, the actual quality score, actual call cost, actual response latency, output verification results, rollback count, manual takeover flag, and user feedback results are collected to form a stage execution feedback sample. Based on the stage execution feedback samples, a stage execution reward is constructed, and the weight vector is updated, pruned, and normalized according to the learning rate, the moving average baseline reward, and the weight influence direction.

5. The method according to claim 1, characterized in that, The preset switching thresholds include a minimum quality threshold, a maximum cost threshold, a maximum latency threshold, a context window security threshold, a failure risk threshold, and a maximum number of retries threshold. When the inference task is divided into multiple stage nodes, the inference task is managed in stages according to the global budget, stage budget and flexible reserved budget. The stage budget is allocated in the global budget according to the stage importance, risk level and complexity. The flexible reserved budget is used for dynamic addition of key stages, failure rollback stages or high-risk verification stages.

6. The method according to claim 1, characterized in that, The steps of retrying the model based on the failure type, switching to a backup model, context compression, or manual takeover include: If a call times out, switch to a low-latency model or split the phase. For output format errors, switch to a backup model with higher structured output capabilities and add output format constraints; for factual inconsistencies, add retrieved evidence and switch to a candidate model with higher quality prediction scores. If the cost exceeds the limit, compress the context and switch to a low-cost model; if the security fails to respond or the permissions are insufficient, proceed to manual review or task downgrade.

7. The method according to claim 1, characterized in that, The context compression includes: When the context load exceeds the target model context window safety threshold, the input context is divided into three levels: key evidence, plain text, and redundant annotations. Calculate the retention score for each context fragment; Context-based hierarchical trimming is performed in the following order: first, redundant annotations are removed; then, plain text is compressed; and finally, key evidence is compressed.

8. The method according to claim 1, characterized in that, After invoking the target model to execute the current stage node, the process also includes: Write the actual quality, actual cost, actual latency, output format pass rate, fact consistency pass rate, tool call success rate, number of rollbacks, manual takeover results, and user feedback of this phase into the model phase execution log; The success rate, cost, and latency profiles of each model at each stage type are updated using exponential moving averages. The model profiles are maintained hierarchically by global profile, task type profile, and stage profile. When scoring, the profile that matches the current task type and stage type is read first. If the number of samples is insufficient, the global profile is used as a fallback.

9. The method according to claim 1, characterized in that, The steps of selecting a target model according to a preset switching threshold and performing model retries, switching to a backup model, context compression, or manual takeover based on the failure type include: Model switching is performed at the stage boundary, matching different capability models to different stage nodes; Rollback during the execution phase when an exception is triggered; For each stage call, a routing record is generated, which includes the candidate model score, the final selected model, the switching reason, the fallback path, and the output verification result.

10. A large-scale model switching and scheduling system based on joint cost-quality prediction, characterized in that, For implementing the method of any one of claims 1 to 9, comprising: The task identification module is used to receive reasoning tasks initiated by the intelligent agent, parse the task type, task objective, input context, tool requirements and output constraints, and generate a task profile. The complexity evaluation module is used to generate task complexity vectors; The context load assessment module is used to generate context load vectors; The model profile management module is used to maintain the model profiles of candidate models and dynamically update the model profiles based on the stage execution data. The cost-quality joint scoring module is used to calculate the quality prediction score, cost prediction value, time delay prediction value and failure risk value of each candidate model, and generate a comprehensive fitness score. The dynamic weight adaptive optimization module is used to dynamically update the scoring weight coefficients based on historical stage execution data; The stage routing module is used to select the target model according to a preset switching threshold and record the reason for the stage-level model selection. The execution verification module is used to perform format verification, fact consistency verification, and stage target verification on the model output; The switching and rollback module is used to perform model retries, switch to standby models, context compression, or manual takeover based on the failure type. The phased budget control module is used to implement budget control according to the overall budget, phased budget, and flexible reserved budget. The context-based hierarchical cropping module is used to perform hierarchical cropping of key evidence, plain text, and redundant annotations when the context exceeds the limit. The audit log module is used to record stage nodes, candidate model scores, target models, switching reasons, rollback paths, and execution results.