Automated code evaluation system and implementation method for content quality of agent reply

By constructing a four-dimensional weighted evaluation model and dynamic code sandbox execution, the efficiency and accuracy issues in evaluating the quality of agent responses are resolved, achieving efficient and accurate automated evaluation, supporting large-scale agent regression testing, and providing clear optimization guidance.

CN123138084APending Publication Date: 2026-11-20AISINO CORPORATION
View PDF 3 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

Existing technologies are inefficient, costly, and highly subjective in evaluating the quality of responses from intelligent agents. Furthermore, simple automated evaluation methods are limited in scope, lack deep semantic understanding capabilities, and cannot comprehensively measure the semantic accuracy, logical coherence, and security compliance of responses.

Method used

A four-dimensional weighted evaluation model is constructed, including code correctness, semantic relevance, logical integrity, and security compliance. Through dynamic execution in a code sandbox and natural language analysis, combined with a multi-dimensional quality evaluation module and a comprehensive scoring mechanism, the automated evaluation of the agent's response content is achieved.

Benefits of technology

It achieves comprehensive, objective, efficient and automated evaluation of agent responses, improving accuracy by more than 40%. The evaluation process requires no manual intervention, supports large-scale and high-frequency agent regression testing, and provides clear optimization guidance.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123138084A_ABST
    Figure CN123138084A_ABST
Patent Text Reader

Abstract

The application discloses an intelligent agent reply content quality automatic code evaluation system and implementation method and a computer readable storage medium, and the device comprises an interactive interface and a data preprocessing module, a content analysis and code extraction module, a code sandbox dynamic execution module, a multi-dimensional quality evaluation module and a comprehensive score and monitoring alarm module; the content analysis and code extraction module is used for structurally analyzing intelligent agent reply content; the code sandbox dynamic execution module is used for providing an isolated sandbox running environment; the code correctness dimension is scored according to the code execution result returned by the code sandbox dynamic execution module; the logic integrity dimension is used for evaluating reply explanation sufficiency and code structure integrity; the safety compliance dimension is used for detecting high-risk content in the code and the text; and the comprehensive score and monitoring alarm module is used for generating a structured evaluation report according to the scores of the dimensions, the comprehensive quality score and the rating.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of artificial intelligence large model evaluation technology, specifically to an automated code evaluation system and implementation method for evaluating the quality of intelligent agent response content, and a computer-readable storage medium. Background Technology

[0002] With the rapid development of artificial intelligence technology, AI agents based on large language models are increasingly being used in customer service, education, content creation, and other fields. One of the core capabilities of AI agents is generating high-quality text responses based on user input. Currently, the evaluation of the quality of AI agent responses mainly relies on manual assessment or automated testing based on simple rules.

[0003] Human evaluation is currently the gold standard in the industry. Human annotators score the agent's responses based on pre-defined criteria (such as relevance, fluency, accuracy, and harmlessness). However, this method has significant drawbacks. Human evaluation is time-consuming and labor-intensive, failing to meet the demands of frequent evaluations of massive test cases during rapid iterative development of agents. It requires substantial human resources, significantly increasing R&D and operational costs. Furthermore, differing scoring criteria among evaluators can lead to inconsistencies and a lack of objectivity in the evaluation results.

[0004] Automated testing based on simple rules addresses the efficiency issues of manual evaluation. Some existing technologies attempt to use automation methods, such as keyword matching, regular expressions, or simple text similarity algorithms (e.g., BLEU, ROUGE), to evaluate response quality. While these methods improve speed, they suffer from limitations in evaluation dimensions. They can only assess whether a response contains specific keywords or the degree of textual overlap with the reference answer, failing to comprehensively measure deeper qualities such as semantic accuracy, logical coherence, and information richness. They cannot understand complex dialogue contexts, resulting in poor evaluation performance for complex tasks requiring multiple rounds of dialogue. For open-ended questions, agent responses can vary widely, and evaluation methods based on fixed rules or reference answers struggle to cover all reasonable scenarios, easily leading to misjudgments.

[0005] Chinese patent application CN121501658A primarily focuses on quality assessment of code snippets generated by large language models. It involves constructing a structured evaluation dataset, extracting code blocks, running the code in a code execution sandbox, and analyzing the results based on evaluation metrics. However, its evaluation object is limited to code snippets, neglecting a comprehensive assessment of the agent's complete response (natural language + code). Furthermore, its evaluation dimension is singular (focusing on functional correctness), failing to assess the semantic meaning of the natural language interpretation. This invention constructs a four-dimensional weighted evaluation model (code correctness 40% + semantic relevance 30% + logical completeness 20% + security compliance 10%), which not only evaluates the correctness of the code itself but also comprehensively assesses the semantic matching degree between the response content and the user's question, the interpretive completeness of the response content, and security compliance, achieving a comprehensive quality assessment of the agent's response.

[0006] Chinese patent application CN121658099A focuses on enabling interaction between a model and an external system through a code execution sandbox, addressing the question of how a model operates an external system. Its application scenario is the interaction protocol between the model and the system, with the code sandbox serving as an interaction means rather than an evaluation tool. This invention uses a code sandbox as a technical means of quality assessment, employing a stricter isolation strategy. It proactively blocks operations that may harm the host environment through a blacklist of dangerous APIs and uses the code execution results as input for code correctness, participating in the calculation of the overall quality score.

[0007] Chinese patent application CN121502255A employs a technical solution of "vector set center adjustment + multi-dimensional feature evaluation + dynamic weighted fusion," evaluating the performance of the large language model itself (model-level evaluation), rather than the quality of a single response from a non-agent to a specific user question (instance-level evaluation). This invention belongs to instance-level evaluation, introducing dynamic code execution as the core evaluation method. It verifies correctness through actual code execution, avoiding the limitations of static analysis. Building upon existing technologies, this invention achieves a more comprehensive, accurate, and secure automated quality assessment of agent responses by constructing a four-dimensional weighted evaluation model, a joint natural language and code scoring mechanism, a security and compliance detection module, and a scalable multi-language executor architecture.

[0008] In summary, existing technologies face a dilemma in evaluating the quality of intelligent agent responses, where it is difficult to achieve both efficiency and quality. Summary of the Invention

[0009] This invention provides an automated code evaluation system and implementation method for the quality of intelligent agent response content, as well as a computer-readable storage medium, to overcome the shortcomings of existing technologies such as low efficiency, high cost, and strong subjectivity of manual evaluation, as well as the single dimension and lack of deep semantic understanding of simple automated evaluation methods, so as to achieve comprehensive, objective and efficient automated evaluation of intelligent agent response content.

[0010] To achieve the above objectives, the present invention provides an automated code evaluation system for the quality of intelligent agent response content, which includes: an interaction interface and data preprocessing module, a content parsing and code extraction module, a code sandbox dynamic execution module, a multi-dimensional quality evaluation module, and a comprehensive scoring and monitoring alarm module;

[0011] The interaction interface and data preprocessing module are used to receive a single instance-level data to be evaluated, which includes the original response content of the agent generated by a single interaction and the user question corresponding to the response; the module performs format validation, cleaning and standardization on the input data, and outputs a standardized request object;

[0012] The content parsing and code extraction module is used to perform structured parsing of the agent's response content, identify and extract code blocks in the response content, record the language type and position index information of each code block, and peel the extracted code blocks from the original text to obtain clean natural language text.

[0013] The code sandbox dynamic execution module provides an isolated sandbox runtime environment to dynamically compile and execute extracted code blocks; it captures code execution results, standard output stream, error output stream, and runtime exception information in real time; and it sets timeout control and resource limitation policies to prevent malicious code from damaging the host machine environment.

[0014] The multi-dimensional quality assessment module scores code correctness, semantic relevance, logical completeness, and security compliance using a 0-1 scale. Code correctness is scored based on the execution results returned by the code sandbox dynamic execution module. Semantic relevance is calculated based on user questions and the clean, natural language text after code removal. Logical completeness assesses the sufficiency of the response explanation and the integrity of the code structure. Security compliance detects high-risk content in the code and text. The scores from each dimension are weighted and summed according to preset weights to obtain a comprehensive quality score.

[0015] The comprehensive scoring and monitoring alarm module is used to generate a structured evaluation report based on scores of each dimension, comprehensive quality score, and rating; it collects indicator data of evaluation requests through a non-intrusive data collection method of cross-sectional embedding, and the indicator data includes at least the evaluation request time and evaluation success rate; an alarm is triggered when the anomaly rate or evaluation score reaches the preset alarm threshold.

[0016] In one embodiment of the present invention, preferably, in the multi-dimensional quality assessment module, the weights of each assessment dimension are set according to one of the following methods:

[0017] (1) Perform manual custom configuration to adapt to different business evaluation scenarios;

[0018] (2) The following settings are implemented: code correctness weight is 40%, semantic relevance weight is 30%, logical integrity weight is 20%, and security compliance weight is 10%; the overall quality score is divided into four levels: excellent, good, passable, and failable.

[0019] In one embodiment of the present invention, preferably, in the content parsing and code extraction module, after the code block is extracted from the original text, a placeholder for the corresponding code block is inserted into the original text to obtain pure natural language text, and the context structure of the original text is preserved through the placeholder.

[0020] In one embodiment of the present invention, preferably, the structured evaluation report generated by the comprehensive scoring and monitoring alarm module also includes deduction item location information corresponding to each evaluation dimension; the deduction item location information is used to indicate the specific reasons for the decrease in the score of the corresponding dimension, so as to be used by the intelligent agent for iterative optimization, and the deduction item location information includes at least one of the following: code compilation failure, code logic abnormality, semantic mismatch, missing explanation, and existence of high-risk content.

[0021] In one embodiment of the present invention, preferably, the cross-section embedding is implemented based on AOP cross-section, and the Micrometer monitoring framework is used to complete the embedding, recording and output of indicators.

[0022] This invention also provides an automated code evaluation method for assessing the quality of intelligent agent responses. This method, applied to the aforementioned device, includes the following steps:

[0023] S1: Receives a single instance-level data to be evaluated from upstream. The data to be evaluated includes the original response content of the agent generated by a single interaction and the user question corresponding to the response. Performs format validation, cleaning and standardization on the input data and outputs a standardized request object.

[0024] S2: Perform structured parsing on the agent's response content, identify and extract code blocks from the response content, and record the language type and position index information of each code block; then peel the extracted code blocks from the original text to obtain clean natural language text;

[0025] S3: The extracted code blocks are sent to an isolated and secure sandbox environment for execution, dynamic compilation and execution, and capture of execution results, standard output, error output and runtime exceptions; execution timeout and resource limitation policies are configured.

[0026] S4: Multi-dimensional quality assessment, including the following steps S41-S45:

[0027] S41: Calculate the code correctness score based on the execution results returned by the code sandbox;

[0028] S42: Calculate semantic relevance scores based on user questions and clean natural language text;

[0029] S43: Detect the sufficiency of the response explanation and the completeness of the code structure to obtain a logical completeness score;

[0030] S44: Detect risky content in the code and text to obtain a security compliance score;

[0031] S45: Calculate the overall quality score by weighting the corresponding weights of each dimension, and output the rating of excellent, good, passable, or fail based on the overall quality score;

[0032] S5: Generate a structured evaluation report containing detailed scores for each dimension, a comprehensive quality score, and a rating; collect indicator data for evaluation requests through a non-intrusive data collection method using cross-sectional embedding, with the indicator data including at least the evaluation request time and the evaluation success rate; trigger an alarm when the anomaly rate or evaluation score reaches a preset alarm threshold.

[0033] In one embodiment of the present invention, preferably, in step S2, when the agent replies with code blocks containing multiple different programming languages, each code block is parsed and its metadata is recorded; in step S3, each code block is executed; and in step S41, the execution output results of all code blocks are combined to calculate the code correctness score.

[0034] In one embodiment of the present invention, preferably, in step S3, when an unsupported programming language is identified, the code execution is directly marked as failed, and the code correctness score is 0.

[0035] In one embodiment of the present invention, preferably, in step S3, when the code execution triggers a timeout or resource exhaustion exception, the code execution is directly determined to have failed and is included in the code correctness dimension score.

[0036] In one embodiment of the present invention, preferably, the code correctness scoring rules in step S41 include: 0 points when no code block exists; 1.0 point when compilation and execution are completely successful and the output meets business expectations; 0.6 points when compilation and execution are successful but the output contains some logical errors; and 0 points when compilation fails or throws a fatal runtime exception.

[0037] In one embodiment of the present invention, preferably, step S44 security compliance detection includes matching a blacklist of dangerous APIs and identifying sensitive content; if high-risk malicious code is identified, the execution of code in the sandbox is terminated directly, and the security compliance score is lowered.

[0038] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the above-described method for automated code evaluation of the quality of intelligent agent response content.

[0039] Compared with the prior art, the present invention has the following beneficial technical effects:

[0040] Verifying correctness by actually executing the code avoids misjudgments such as "syntactically correct but logically flawed" or "code that simply cannot run" that occur when relying solely on text similarity (e.g., BLEU) evaluation. This improves evaluation accuracy by over 40% (based on internal test set comparisons). The entire evaluation process requires no manual intervention, being fully automated from receiving responses to generating reports. Evaluation time is reduced from minutes to seconds compared to manual evaluation, supporting large-scale, high-frequency agent regression testing. It not only provides a final score but also clearly indicates which dimension resulted in the deduction (e.g., "code compilation failed" or "missing error handling logic"), providing clear guidance for agent optimization. The code executes in a sandbox environment, completely isolating it from the risk of malicious code in agent responses damaging the evaluation system or host environment. Attached Figure Description

[0041] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0042] Figure 1a This is the upper part of an embodiment of the method for automated code evaluation of the quality of intelligent agent response content according to the present invention;

[0043] Figure 1b This is the lower half of an implementation method for automated code evaluation of the quality of intelligent agent response content according to an embodiment of the present invention;

[0044] Figure 2 This is a flowchart illustrating the multi-dimensional evaluation logic of one embodiment of the present invention. Detailed Implementation

[0045] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0046] This invention constructs an automated code evaluation system for intelligent agent responses, enabling static and dynamic joint evaluation of natural language and code snippets in intelligent agent responses. Developed using Java and the Spring Boot framework, the system combines dynamic code sandbox execution, multi-dimensional weighted scoring, and end-to-end monitoring and alerting to achieve highly accurate and secure automated evaluation.

[0047] The present invention has the following key technical features:

[0048] 1. Dynamic code extraction and sandbox execution mechanism: Innovatively, the code block in the agent's response is separated from the natural language content, and the code is dynamically compiled and executed in an isolated and secure sandbox environment to directly verify the correctness and runnability of the code.

[0049] 2. Multi-dimensional integrated automated evaluation model: A comprehensive evaluation model has been constructed. This model not only includes traditional static analysis dimensions such as semantic relevance, logical integrity, and security compliance, but also innovatively introduces the core dimension of "code correctness" based on dynamic code execution results.

[0050] 3. Joint scoring algorithm for code execution results and natural language analysis: Through a weighted scoring mechanism, dynamic execution results (such as compilation success / failure, output logs) are combined with the semantic understanding results of the natural language part to calculate a more comprehensive and accurate overall quality score.

[0051] This invention provides an automated code evaluation system for the quality of intelligent agent response content, which includes: an interaction interface and data preprocessing module, a content parsing and code extraction module, a code sandbox dynamic execution module, a multi-dimensional quality evaluation module, and a comprehensive scoring and monitoring alarm module;

[0052] The interaction interface and data preprocessing module are used to receive a single instance-level data to be evaluated. The data to be evaluated includes the original response content of the agent generated by a single interaction and the user question corresponding to the response (as a reference benchmark for evaluating semantic relevance); the module performs format validation, cleaning and standardization processing on the input data, and outputs a standardized request object.

[0053] The content parsing and code extraction module is used to perform structured parsing of the agent's response content, identify and extract code blocks in the response content, and record the language type and position index information of each code block; the extracted code blocks are separated from the original text to obtain pure natural language text for subsequent independent analysis in various dimensions;

[0054] The code sandbox dynamic execution module provides an isolated sandbox runtime environment to dynamically compile and execute extracted code blocks; it captures code execution results, standard output stream, error output stream, and runtime exception information in real time; it sets timeout control and resource limitation policies to prevent malicious code from damaging the host environment; the code sandbox dynamic execution module supports multiple programming languages ​​(Java, Python, JavaScript, etc.).

[0055] The multi-dimensional quality assessment module integrates dynamic code execution results, natural language semantic analysis, and preset assessment rules to quantify and score four independent dimensions—code correctness, semantic relevance, logical completeness, and security compliance—using a score range of 0-1. The code correctness dimension is scored based on the code execution results returned by the code sandbox dynamic execution module; the semantic relevance dimension is calculated based on the user's question and the clean natural language text after code removal; the logical completeness dimension assesses the sufficiency of the response explanation and the integrity of the code structure; and the security compliance dimension detects high-risk content in the code and text. The scores from each dimension are weighted and summed according to preset weights to obtain the overall quality score.

[0056] The comprehensive scoring and monitoring alarm module is used to generate a structured evaluation report based on scores of each dimension, comprehensive quality score, and rating; it collects indicator data of evaluation requests through a non-intrusive data collection method of cross-sectional embedding, and the indicator data includes at least the evaluation request time and evaluation success rate; an alarm is triggered when the anomaly rate or evaluation score reaches the preset alarm threshold.

[0057] In this embodiment, the weights of each evaluation dimension in the multi-dimensional quality assessment module are set according to one of the following methods:

[0058] (1) Perform manual custom configuration to adapt to different business evaluation scenarios;

[0059] (2) The following settings are implemented: code correctness weight is 40%, semantic relevance weight is 30%, logical integrity weight is 20%, and security compliance weight is 10%; the overall quality score is divided into four levels: excellent, good, passable, and failable.

[0060] In this embodiment, the multi-dimensional quality assessment module supports two weight configuration modes, one of which can be selected for use. The first mode is a manually customized configuration mode: assessors can manually assign weights to the four dimensions—code correctness, semantic relevance, logical completeness, and security compliance—based on the business scenario, requiring the total weight of all dimensions to equal 100%. For example, for a teaching code Q&A scenario, the code correctness weight can be increased to 60%, while the logical completeness weight can be decreased; for a code-assisted documentation generation scenario, the semantic relevance and logical completeness weights can be increased, flexibly adapting to different business priorities. The second mode is the system's built-in default weight configuration: code correctness weight 40%, semantic relevance weight 30%, logical completeness weight 20%, and security compliance weight 10%, with the weights of each dimension added together to 100%. The overall quality score ranges from 0 to 1, and is used for four levels of rating: an overall score ≥ 0.9 is considered excellent; 0.75 ≤ overall score < 0.9 is considered good; 0.6 ≤ overall score < 0.75 is considered passing; and an overall score < 0.6 is considered failing. The default configuration is designed for general code generation-based intelligent agent evaluation; it's ready to use out of the box and requires no additional parameter adjustments. After configuration, the system reads the scores for each dimension, multiplies them by their corresponding weights, and sums them to obtain the final overall quality score.

[0061] The above technical features can achieve the following beneficial technical effects:

[0062] 1. Dual-mode weight configuration, balancing versatility and business customization capabilities; the default weight meets the general evaluation of most code intelligence agents, while the manual customization mode adapts to differentiated business scenarios such as teaching, document generation, and operation and maintenance scripts.

[0063] 2. A clear four-tier rating standard transforms the continuous quantitative score of 0-1 into a business-readable rating result, facilitating version quality comparison, batch evaluation result statistics, and deployment access determination.

[0064] 3. Weight configuration is switchable. The same evaluation system does not need to modify the evaluation logic. Only the weight parameters need to be adjusted to adapt to multiple types of business, thus improving system reusability.

[0065] In this embodiment, in the content parsing and code extraction module, after the code block is extracted from the original text, a placeholder for the corresponding code block is inserted into the original text to obtain pure natural language text. The context structure of the original text is preserved through the placeholder.

[0066] In this embodiment, the content parsing and code extraction module identifies Markdown format code blocks, extracts the code blocks, and records the language and start / end index information. After stripping the original code block text, the corresponding position of the code block is not directly deleted. Instead, a unique placeholder is inserted at the original position of the code block, such as [CODE_BLOCK_1] and [CODE_BLOCK_2]. The placeholder number corresponds one-to-one with the extracted code block ID. After replacement processing, clean natural language text is output. The overall paragraph order, line breaks, sentence structure, and agent response are consistent with the original response. The placeholder marks retain the position information of the code block in the whole text. When performing semantic relevance and logical integrity analysis, the analysis object is the clean natural language text with placeholder marks. This can identify the position and role of the code in the original text, avoid the context breakage and paragraph misalignment caused by directly deleting the code block, and prevent the distortion of text semantic parsing. When the report is output, a reverse mapping can also be performed based on the placeholder marks to associate back with the original code block.

[0067] The above technical features can achieve the following beneficial technical effects:

[0068] 1. Use placeholders to preserve the full text context structure, avoid text word order and paragraph logic disorder caused by directly deleting code blocks, and improve the accuracy of semantic calculation in natural language processing.

[0069] 2. Placeholder identifiers are mapped one-to-one with code block IDs, supporting backtracking and locating natural language fragments and corresponding code blocks in the evaluation report, making it convenient for developers to see which piece of text corresponds to which piece of code.

[0070] 3. No need to modify the main logic of the parsing algorithm, only add a placeholder replacement step to achieve text-code association and realize full-chain traceability of parsing, evaluation and reporting.

[0071] In this embodiment, the structured evaluation report generated by the comprehensive scoring and monitoring alarm module also includes the deduction item location information corresponding to each evaluation dimension; the deduction item location information is used to indicate the specific reasons for the decrease in the score of the corresponding dimension, so as to be used by the intelligent agent for iterative optimization. The deduction item location information includes at least one of the following: code compilation failure, code logic abnormality, semantic mismatch, missing explanation, and existence of high-risk content.

[0072] In this embodiment, when generating a structured evaluation report, the comprehensive scoring and monitoring alarm module outputs not only scores for each dimension, the overall score, and the rating, but also the location information of deduction items. During the multi-dimensional quality assessment module's scoring process, the system simultaneously records the root cause of deductions for each dimension: for code correctness, it records whether the deduction was due to code compilation failure or abnormal code logic; for semantic relevance, it marks semantic mismatch; for logical integrity, it marks missing explanation; and for security compliance, it marks high-risk content. The location information of each deduction item is bound to each evaluation instance and written into the evaluation report. For example, if the report marks a deduction item as "code compilation failure," it means the code correctness dimension score loss stems from a compilation error; if it marks "missing explanation," it means the logical integrity dimension score loss stems from the agent lacking necessary business explanation. The location information of deduction items not only provides scores but also outputs the root cause of the failure. Developers can directly locate agent defects based on the report for use in prompt word optimization, knowledge base iteration, and model fine-tuning.

[0073] The above technical features can achieve the following beneficial technical effects:

[0074] 1. Achieve "score + root cause" output, solving the pain point of traditional assessments that only output scores and cannot know the reasons for lost points, and directly guiding the intelligent agent to iterative optimization.

[0075] 2. Standardize and categorize fault types to facilitate statistical analysis after batch testing. For example, calculate the percentage of "compilation failures" in a batch of test cases to optimize the agent's code generation capabilities.

[0076] 3. Structured deduction information facilitates integration with downstream defect management systems, enabling automated flow of evaluation results.

[0077] In this embodiment, the cross-section embedding is implemented based on AOP cross-sections, and the Micrometer monitoring framework is used to complete the embedding, recording and output of indicators.

[0078] In this embodiment, the comprehensive scoring and monitoring alarm module uses AOP (Aspect-Oriented Programming) technology for non-intrusive data tracking, combined with the Micrometer monitoring framework to collect full-link metrics for the evaluation process. Interception is performed at the front and back edges of the evaluation execution interface, allowing data collection without modifying the core business evaluation code. Collected metrics include the total time spent on a single evaluation request, the time spent executing code in the sandbox, the success rate of evaluation requests, and the number of abnormal requests. Metrics are output to a monitoring time-series database, supporting visual dashboard viewing. When sandbox execution anomalies, parsing anomalies, or evaluation logic anomalies occur during the evaluation, the aspect automatically records the anomaly tag. The system calculates the anomaly rate based on the collected metrics. When the anomaly rate is lower than the business threshold, or when the comprehensive score of a single evaluation is lower than the alarm threshold, an alarm notification is triggered. AOP aspects decouple the data tracking logic from the business evaluation logic; the business code only concerns itself with the evaluation business, while the monitoring logic is uniformly handled by the aspects.

[0079] The above technical features can achieve the following beneficial technical effects:

[0080] 1. AOP aspects are non-intrusive and use data entry points, decoupling business evaluation code and monitoring code. Business logic is not affected by monitoring and data collection logic, which facilitates subsequent iteration and maintenance.

[0081] 2. Based on the Micrometer framework, the metrics are standardized and compatible with mainstream monitoring components such as Prometheus, enabling rapid integration into the operations and maintenance monitoring dashboard.

[0082] 3. It can continuously monitor the operating status of the evaluation system itself, promptly detect platform faults such as sandbox timeouts and parsing errors, and not only evaluate intelligent agents, but also ensure the observability of the evaluation system itself.

[0083] The following is a portion of the code for this embodiment:

[0084] The main code corresponding to the interaction interface and data preprocessing module is as follows:

[0085] @RestController

[0086] public class EvaluationController {

[0087] @Autowired

[0088] private QualityEvaluator qualityEvaluator;

[0089] @PostMapping(" / evaluate")

[0090] public EvaluationReport evaluate(@RequestBody EvaluationRequestrequest) {

[0091] / / 1. Parameter validation and data cleaning

[0092] String cleanedResponse = request.getAgentResponse().trim()

[0093] .replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");

[0094] / / 2. Construct a standardized request object

[0095] StandardRequest standardRequest = new StandardRequest(cleanedResponse, request.getUserQuery());

[0096] / / 3. Call the core evaluation engine

[0097] return qualityEvaluator.evaluate(standardRequest);

[0098] }

[0099] }

[0100] The main code corresponding to the content parsing and code extraction module is as follows:

[0101] / / Content parsing and code extraction module

[0102] @Service

[0103] public class ContentParsingService {

[0104] public ParsedContent parse(String agentResponse) {

[0105] while (matcher.find()) {

[0106] / / Extract the natural language part before the code block

[0107] naturalLanguageBuffer.append(agentResponse, lastIndex,matcher.start());

[0108] / / Record code block information

[0109] CodeBlock block = new CodeBlock();

[0110] block.setId(blockId++);

[0111] block.setLanguage(matcher.group(1));

[0112] block.setCode(matcher.group(2));

[0113] block.setStartIndex(matcher.start());

[0114] block.setEndIndex(matcher.end());

[0115] codeBlocks.add(block);

[0116] / / Insert placeholders in natural language to preserve text structure

[0117] naturalLanguageBuffer.append("[CODE_BLOCK_").append(block.getId()).append("]");

[0118] lastIndex = matcher.end();

[0119] }

[0120] / / Add the final natural language section

[0121] naturalLanguageBuffer.append(agentResponse, lastIndex,agentResponse.length());

[0122] parsedContent.setCodeBlocks(codeBlocks);

[0123] parsedContent.setNaturalLanguageText(naturalLanguageBuffer.toString());

[0124] parsedContent.setHasCodeBlocks(!codeBlocks.isEmpty());

[0125] return parsedContent;

[0126] }

[0127] }

[0128] The main code corresponding to the code sandbox dynamic execution module is as follows:

[0129] / / Code Sandbox Dynamic Execution Module

[0130] @Service

[0131] public class CodeSandboxExecutor {

[0132] private static final long EXECUTION_TIMEOUT_SECONDS = 30;

[0133] private static final String TEMP_DIR = " / tmp / code_sandbox / ";

[0134] @Autowired

[0135] private Map<String, LanguageExecutor> executorRegistry;

[0136] public CodeExecutionResult execute(CodeBlock codeBlock) {

[0137] CodeExecutionResult result = new CodeExecutionResult();

[0138] result.setOriginalCode(codeBlock.getCode());

[0139] result.setLanguage(codeBlock.getLanguage());

[0140] / / Get the executor for the corresponding language

[0141] LanguageExecutor executor = executorRegistry.get(codeBlock.getLanguage().toLowerCase());

[0142] if (executor == null) {

[0143] result.setSuccess(false);

[0144] result.setErrorMessage("Unsupported language type: " +codeBlock.getLanguage());

[0145] return result;

[0146] }

[0147] / / Execute code in a controlled environment and set a timeout limit

[0148] Future <codeexecutionresult>future = Executors.newSingleThreadExecutor()

[0149] .submit(() -> executor.execute(codeBlock.getCode()));

[0150] result = future.get(EXECUTION_TIMEOUT_SECONDS,TimeUnit.SECONDS);

[0151] return result;

[0152] }

[0153] }

[0154] / / Java Language Executor Implementation

[0155] @Service("java")

[0156] public class JavaLanguageExecutor implements LanguageExecutor {

[0157] @Override

[0158] public CodeExecutionResult execute(String code) {

[0159] / / 1. Wrap user code into an executable class

[0160] String className = "DynamicEvalCode";

[0161] String wrappedCode = wrapCode(className, code);

[0162] / / 2. Dynamic compilation using memory-based JavaFileObject

[0163] JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

[0164] DiagnosticCollector <javafileobject>diagnostics = newDiagnosticCollector<>();

[0165] JavaFileManager fileManager = new StandardJavaFileManager(null, null, null) {

[0166] / / Simplified implementation, using in-memory storage in practice

[0167] };

[0168] JavaFileObject fileObject = new InMemoryJavaFileObject(className, wrappedCode);

[0169] JavaCompiler.CompilationTask task = compiler.getTask(null,null, diagnostics,

[0170] Arrays.asList("-Xlint:none"), null, Arrays.asList(fileObject));

[0171] boolean compileSuccess = task.call();

[0172] if (!compileSuccess) {

[0173] result.setSuccess(false);

[0174] result.setErrorMessage("Compilation failed: " +diagnostics.getDiagnostics());

[0175] result.setOutput(outputStream.toString());

[0176] result.setErrorOutput(errorStream.toString());

[0177] return result;

[0178] }

[0179] }

[0180] }

[0181] The main code for the multi-dimensional quality assessment module is as follows:

[0182] / / Multi-dimensional quality assessment module

[0183] @Service

[0184] public class QualityEvaluationService {

[0185] @Autowired

[0186] private SemanticAnalyzer semanticAnalyzer;

[0187] public EvaluationResult evaluate(StandardRequest request,

[0188] ParsedContent

[0189] List <codeexecutionresult>execResults) {

[0190] EvaluationResult result = new EvaluationResult();

[0191] / / Dimension 1: Code Correctness (Weight 40%)

[0192] double correctnessScore = evaluateCorrectness(parsedContent,execResults);

[0193] result.setCorrectnessScore(correctnessScore);

[0194] / / Dimension 2: Semantic Relevance (Weight 30%)

[0195] double relevanceScore = evaluateRelevance(parsedContent,request.getUserQuery());

[0196] result.setRelevanceScore(relevanceScore);

[0197] / / Dimension 3: Logical Completeness (Weight 20%)

[0198] double completenessScore = evaluateCompleteness(parsedContent, execResults);

[0199] result.setCompletenessScore(completenessScore);

[0200] / / Dimension 4: Security Compliance (Weight 10%)

[0201] double safetyScore = evaluateSafety(parsedContent,execResults);

[0202] result.setSafetyScore(safetyScore);

[0203] / / Overall score = weighted sum

[0204] double finalScore = correctnessScore * 0.40

[0205] + relevanceScore * 0.30

[0206] + completenessScore * 0.20

[0207] + safetyScore * 0.10;

[0208] result.setFinalScore(finalScore);

[0209] / / Generate rating

[0210] If (finalScore >= 0.9) result.setGrade("Excellent");

[0211] else if (finalScore >= 0.75) result.setGrade("Good");

[0212] else if (finalScore >= 0.6) result.setGrade("pass");

[0213] else result.setGrade("failed");

[0214] return result;

[0215] The main code corresponding to the comprehensive scoring and monitoring alarm module is as follows:

[0216] / / Comprehensive scoring and monitoring alarm module

[0217] public class ReportGenerationService {

[0218] @Autowired

[0219] private MeterRegistry meterRegistry;

[0220] public EvaluationReport generateReport(EvaluationRequestoriginalRequest,

[0221] ParsedContentparsedContent,

[0222] List <codeexecutionresult>execResults,

[0223] EvaluationResultevalResult) {

[0224] EvaluationReport report = new EvaluationReport();

[0225] report.setReportId(UUID.randomUUID().toString());

[0226] report.setTimestamp(LocalDateTime.now());

[0227] report.setFinalScore(evalResult.getFinalScore());

[0228] report.setGrade(evalResult.getGrade());

[0229] / / Construct Dimension Scoring Details

[0230] Map<String, Double> dimensionDetails = new LinkedHashMap<>();

[0231] dimensionDetails.put("Code Correctness", evalResult.getCorrectnessScore() * 100);

[0232] dimensionDetails.put("Semantic relevance", evalResult.getRelevanceScore() * 100);

[0233] dimensionDetails.put("Logical Integrity", evalResult.getCompletenessScore() * 100);

[0234] dimensionDetails.put("Safety Compliance", evalResult.getSafetyScore() * 100);

[0235] report.setDimensionScores(dimensionDetails);

[0236] analysis.append("\n

Scoring in each dimension

[0237] dimensionDetails.forEach((dim, score) ->

[0238] analysis.append("- ").append(dim).append(":").append(String.format("%.1f", score)).append("point\n"));

[0239] analysis.append("\n

Comprehensive Score

[0240] analysis.append("[Rating]").append(evalResult.getGrade());

[0241] report.setDetailedAnalysis(analysis.toString());

[0242] / / Record monitoring metrics

[0243] recordMetrics(report);

[0244] Return report;

[0245] }

[0246] When an agent responds to a request and enters the evaluation system of this invention, the interaction interface and data preprocessing module first perform parameter verification and data cleaning, converting the original response into a standardized internal request. Next, the content parsing and code extraction module identifies and extracts Markdown-formatted code blocks from the response using regular expression matching, while simultaneously separating the clean natural language text. Then, the code sandbox dynamic execution module compiles and runs each code block in an isolated, secure environment, capturing execution results, output streams, and exception information in real time. Subsequently, the multi-dimensional quality assessment module comprehensively considers code execution results, natural language semantics, and preset rules, independently scoring from four dimensions: code correctness, semantic relevance, logical completeness, and security compliance, and calculating a comprehensive quality score through weighted summation. Finally, the comprehensive scoring and monitoring alarm module generates an evaluation report containing scores for each dimension, detailed analysis, and a final rating, while simultaneously recording monitoring indicators through Micrometer. When the score falls below a threshold, a log alarm is triggered to ensure the observability and stability of the evaluation system.

[0247] like Figure 1a , Figure 1b (To ensure the readability of the illustrations, Figure 1a The bottom and Figure 1b As shown in the figure (with some overlap at the top), the present invention also provides an automated code evaluation method for the quality of intelligent agent response content. This method, applied to the aforementioned device, includes the following steps:

[0248] S1: Receives a single instance-level data to be evaluated from upstream. The data to be evaluated includes the original response content of the agent generated by a single interaction and the user question corresponding to the response. Performs format validation, cleaning and standardization on the input data and outputs a standardized request object.

[0249] S2: Perform structured parsing on the agent's response content, identify and extract code blocks from the response content, and record the language type and position index information of each code block; then peel the extracted code blocks from the original text to obtain clean natural language text;

[0250] S3: The extracted code blocks are sent to an isolated and secure sandbox environment for execution, dynamic compilation and execution, and capture of execution results, standard output, error output and runtime exceptions; execution timeout and resource limitation policies are configured.

[0251] S4: Multi-dimensional quality assessment, including the following steps S41-S45:

[0252] S41: Calculate the code correctness score based on the execution results returned by the code sandbox;

[0253] S42: Calculate semantic relevance scores based on user questions and clean natural language text;

[0254] S43: Detect the sufficiency of the response explanation and the completeness of the code structure to obtain a logical completeness score;

[0255] S44: Detect risky content in the code and text to obtain a security compliance score;

[0256] S45: Calculate the overall quality score based on the weights corresponding to each dimension, and output a rating of Excellent, Good, Pass, or Fail based on the overall quality score; for example... Figure 2 The diagram shown is a flowchart of the multi-dimensional evaluation logic of one embodiment of the present invention.

[0257] S5: Generate a structured evaluation report containing detailed scores for each dimension, a comprehensive quality score, and a rating; collect indicator data for evaluation requests through a non-intrusive data collection method using cross-sectional embedding, with the indicator data including at least the evaluation request time and the evaluation success rate; trigger an alarm when the anomaly rate or evaluation score reaches a preset alarm threshold.

[0258] In this embodiment, in step S2, when the agent replies with code blocks containing multiple different programming languages, each code block is parsed and its metadata is recorded; in step S3, each code block is executed; and in step S41, the execution output results of all code blocks are combined to calculate the code correctness score.

[0259] In step S2, the parsing phase, if the agent contains multiple code blocks within the same response, and these blocks use different programming languages ​​(e.g., one Python code block and one SQL code block), the parsing module identifies each Markdown code block individually, recording the code ID, programming language, text content, and start and end index metadata of each block in the original response. Then, in step S3, the sandbox execution phase, all code blocks are traversed, and each block is independently sent to the sandbox executor for execution. Each code block independently captures compilation, output, and exception information, generating its own independent code execution result object. In step S41, when calculating the code correctness score, the result of a single code block is not taken; instead, the execution results of all code blocks are combined for a fusion score. Example rule: In multi-code-block scenarios, the success / failure status of each code block is prioritized; if multiple code blocks are core business code, and any one of these core code blocks experiences a fatal compilation or runtime exception, the overall code correctness score will significantly decrease; a lower deduction weight can be set for failed auxiliary example code blocks to distinguish between core business code and demonstration example code. The final output is a combined code with a correctness score of 0-1.

[0260] The above technical features correspond to the following beneficial technical effects:

[0261] 1. Supports single reply with multiple segments and multiple programming language code scenarios, closely matching the output of real intelligent agents. Intelligent agents often output multiple language codes and explanatory texts simultaneously, avoiding processing only the first code block while ignoring the rest.

[0262] 2. Each code block is executed in isolation and does not interfere with each other. A crash in one code block will not affect the evaluation of other code blocks.

[0263] 3. The scoring system integrates results from multiple code blocks, distinguishing between core code and example code. The scoring logic is more aligned with real business needs, and the entire response will not be negated simply because a small example code has an error.

[0264] In this embodiment, in step S3, when an unsupported programming language is identified, the code execution is directly marked as failed, and the code correctness score is 0.

[0265] Step S3: Before sending the code to the sandbox for execution, read the language type recorded in the code block, query the sandbox's internal language executor registry, and determine whether the current environment has an executor corresponding to that programming language. If an unregistered or unsupported programming language is identified, such as some niche scripting languages, it is not necessary to send it to the sandbox for compilation and execution; the code block is directly marked as failing, and its corresponding score is recorded as 0. When multiple code blocks containing both supported and unsupported languages ​​exist in the same response, only the code blocks containing the unsupported languages ​​are marked as failing, while the code blocks containing the supported languages ​​execute normally. Subsequently, in Step S41, the overall code correctness score is calculated by combining the results of all code blocks. At the same time, "Unsupported programming language XXX" is marked in the deduction item location information in the evaluation report to help users understand the reason for the loss.

[0266] The above technical features correspond to the following beneficial technical effects:

[0267] 1. Preemptively intercept unsupported languages ​​to avoid ineffective sandbox scheduling and compilation attempts, save computing resources, and shorten evaluation time.

[0268] 2. Clearly define the rules for determining a score of 0, ensure that the scoring logic is reproducible, and prevent uncontrollable exceptions from being thrown by the sandbox due to unknown languages, thereby improving system stability.

[0269] 3. Mark unsupported languages ​​in the report to alert the testers and facilitate the subsequent expansion of the sandbox language executor.

[0270] In this embodiment, in step S3, when the code execution triggers a timeout or resource exhaustion exception, the code execution is directly determined to have failed and is included in the code correctness dimension score.

[0271] In the sandbox execution phase, maximum execution time, CPU, and memory resource limits are pre-configured. If the code under test contains malicious or low-quality logic such as infinite loops, infinite recursion, or excessive memory allocation, a timeout termination or resource exhaustion protection strategy will be triggered. Once a timeout or resource exhaustion exception is triggered, the sandbox immediately and forcibly terminates the code process, without waiting for the code to complete execution, directly determining that the code block has failed. This failure result is sent to S41 for code correctness scoring. Simultaneously, the exception type (timeout / memory limit exceeded) is recorded and written into the evaluation report as deduction information. This protection strategy prevents malicious code from occupying sandbox resources for extended periods, preventing resource exhaustion avalanche in batch evaluation tasks.

[0272] The above technical features correspond to the following beneficial technical effects:

[0273] 1. Timeout and resource exhaustion directly determine execution failure. Errors such as infinite loops and resource leaks are included in the code correctness assessment, which is consistent with real business scenarios. In a real environment, code that times out is considered unusable code.

[0274] 2. The sandbox's resource protection strategy and evaluation scoring rules are linked, which not only protects the host environment's security but also completes the quality assessment, achieving integrated security protection and evaluation.

[0275] 3. Record timeouts and resource exhaustion anomalies as deduction items to help identify code generated by the agent that has performance defects.

[0276] In this embodiment, the scoring rules for code correctness in step S41 include: 0 points when no code block exists; 1.0 point when compilation and execution are completely successful and the output meets business expectations; 0.6 points when compilation and execution are successful but the output contains some logical errors; and 0 points when compilation fails or throws a fatal runtime exception.

[0277] Step S41: If the code correctness score is in the range of 0-1, execute the explicit grading scoring rules.

[0278] The response contains no code blocks, so the code correctness score is directly assigned to 0. This is suitable for evaluation examples where the agent only outputs natural language text and does not output code.

[0279] The code compiles and runs successfully, and the sandbox output meets business expectations, earning a perfect score of 1.0 for code correctness;

[0280] The code compiles successfully without any compilation errors and runs normally, but the output contains some logical errors and the business results are not entirely correct. This scenario scores 0.6 points. This level is specifically designed to distinguish between "can run but has incorrect results" and "cannot run at all", avoiding directly scoring 0 points for code that can run but has logical errors.

[0281] If compilation fails, or the code throws a fatal runtime exception or crashes, the code correctness score is 0. When the response contains multiple code blocks, the final code correctness score is obtained by weighted summation based on the execution results of each code block. This scoring rule is configurable, and the score levels can be fine-tuned according to business needs.

[0282] The above technical features correspond to the following beneficial technical effects:

[0283] 1. The tiered scoring system distinguishes four typical scenarios, especially differentiating between "compilation successful but with logical errors" and "compilation fails directly". This granularity is more refined than simple binary classification (success / failure), and the evaluation results are more in line with actual business needs.

[0284] 2. For scenarios without code blocks, explicitly assign a score of 0 to avoid null pointer exceptions and missing logical branches, ensuring a robust evaluation process.

[0285] 3. The scoring rules are clear and can be programmed, and the scoring of different batches of evaluations can be reproduced.

[0286] In this embodiment, step S44 security compliance detection includes matching dangerous API blacklists and identifying sensitive content; if high-risk malicious code is identified, the execution of code in the sandbox is terminated directly, and the security compliance score is lowered.

[0287] The S44 security compliance assessment includes detection of both extracted code text and the natural language text after code removal. The detection comprises two parts: first, matching against a blacklist of dangerous APIs, scanning the code text for high-risk system call APIs such as file deletion, system command execution, and internal network probing; second, sensitive content identification, identifying sensitive text in natural language and code comments that indicates violations, leaks, or malicious inducements. When a high-risk malicious code fragment is identified, without waiting for the code to finish running, an instruction is immediately issued to terminate the code process within the sandbox, blocking the execution of malicious logic; simultaneously, a low score is given in the security compliance dimension, and the location information for the deduction item is marked "Contains high-risk content." Even if the code has not actually completed execution, points are still deducted as long as the detected text contains high-risk characteristics. The blacklist is maintainable and updatable, supporting the addition of new risky APIs.

[0288] The above technical features correspond to the following beneficial technical effects:

[0289] 1. Static text scanning identifies malicious code in advance and terminates the sandbox process before the code runs, further strengthening the sandbox security defenses and providing double-layer protection.

[0290] 2. Simultaneously detect the code body and natural language comment text, covering the security risks brought by code comments and explanatory text.

[0291] 3. Directly map security risks to security compliance scores, making security risks quantifiable rather than just alerts, and directly reflecting security defects in the comprehensive evaluation results.

[0292] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the above-described method for automated code evaluation of the quality of intelligent agent response content.

[0293] Those skilled in the art will understand that the accompanying drawings are merely schematic diagrams of one embodiment, and the modules or processes shown in the drawings are not necessarily essential for implementing the present invention.

[0294] Those skilled in the art will understand that the modules in the apparatus of the embodiments can be distributed in the apparatus of the embodiments as described in the embodiments, or they can be located in one or more devices different from this embodiment with corresponding changes. The modules of the above embodiments can be combined into one module, or they can be further divided into multiple sub-modules.

[0295] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention 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 of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.< / codeexecutionresult> < / codeexecutionresult> < / javafileobject> < / codeexecutionresult>

Claims

1. An automated code evaluation system for assessing the quality of intelligent agent response content, characterized in that, include: The module includes an interactive interface and data preprocessing module, a content parsing and code extraction module, a code sandbox dynamic execution module, a multi-dimensional quality assessment module, and a comprehensive scoring and monitoring alarm module. The interaction interface and data preprocessing module are used to receive a single instance-level data to be evaluated, which includes the original response content of the agent generated by a single interaction and the user question corresponding to the response; the module performs format validation, cleaning and standardization on the input data, and outputs a standardized request object; The content parsing and code extraction module is used to perform structured parsing of the agent's response content, identify and extract code blocks in the response content, record the language type and position index information of each code block, and peel the extracted code blocks from the original text to obtain clean natural language text. The code sandbox dynamic execution module provides an isolated sandbox runtime environment for dynamically compiling and executing extracted code blocks. Capture code execution results, standard output stream, error output stream, and runtime exception information in real time; set timeout control and resource limitation policies to prevent malicious code from damaging the host environment; The multi-dimensional quality assessment module scores code correctness, semantic relevance, logical completeness, and security compliance using a 0-1 scale. Code correctness is scored based on the execution results returned by the code sandbox dynamic execution module. Semantic relevance is calculated based on user questions and the clean, natural language text after code removal. Logical completeness assesses the sufficiency of the response explanation and the integrity of the code structure. Security compliance detects high-risk content in the code and text. The scores from each dimension are weighted and summed according to preset weights to obtain a comprehensive quality score. The comprehensive scoring and monitoring alarm module is used to generate a structured evaluation report based on scores of each dimension, comprehensive quality score, and rating; it collects indicator data of evaluation requests through a non-intrusive data collection method of cross-sectional embedding, and the indicator data includes at least the evaluation request time and evaluation success rate; an alarm is triggered when the anomaly rate or evaluation score reaches the preset alarm threshold.

2. The apparatus according to claim 1, characterized in that, In the multi-dimensional quality assessment module, the weights of each assessment dimension are set according to one of the following methods: (1) Perform manual custom configuration to adapt to different business evaluation scenarios; (2) The following settings are implemented: code correctness weight is 40%, semantic relevance weight is 30%, logical integrity weight is 20%, and security compliance weight is 10%; the overall quality score is divided into four levels: excellent, good, passable, and failable.

3. The apparatus according to claim 1, characterized in that, In the content parsing and code extraction module, after the code blocks are extracted from the original text, placeholders for the corresponding code blocks are inserted into the original text to obtain clean natural language text. The contextual structure of the original text is preserved through the placeholders.

4. The apparatus according to claim 1, characterized in that, The structured evaluation report generated by the comprehensive scoring and monitoring alarm module also includes the location information of deduction items for each evaluation dimension. The location information of deduction items is used to indicate the specific reasons for the decrease in the score of the corresponding dimension, so as to be used by the agent for iterative optimization. The location information of deduction items includes at least one of the following: code compilation failure, code logic exception, semantic mismatch, missing explanation, and high-risk content.

5. The apparatus according to claim 1, characterized in that, The aspect tracking is implemented based on AOP aspects, and the Micrometer monitoring framework is used to complete the tracking, recording and output of metrics.

6. A method for automated code evaluation of the quality of intelligent agent response content, characterized in that, The method, when applied to the apparatus according to any one of claims 1-5, comprises the following steps: S1: Receives a single instance-level data to be evaluated from upstream. The data to be evaluated includes the original response content of the agent generated by a single interaction and the user question corresponding to the response. Performs format validation, cleaning and standardization on the input data and outputs a standardized request object. S2: Perform structured parsing on the agent's response content, identify and extract code blocks from the response content, and record the language type and position index information of each code block; then peel the extracted code blocks from the original text to obtain clean natural language text; S3: The extracted code blocks are sent to an isolated and secure sandbox environment for execution, dynamic compilation and execution, and capture of execution results, standard output, error output and runtime exceptions; execution timeout and resource limitation policies are configured. S4: Multi-dimensional quality assessment, including the following steps S41-S45: S41: Calculate the code correctness score based on the execution results returned by the code sandbox; S42: Calculate semantic relevance scores based on user questions and clean natural language text; S43: Detect the sufficiency of the response explanation and the completeness of the code structure to obtain a logical completeness score; S44: Detect risky content in the code and text to obtain a security compliance score; S45: Calculate the overall quality score by weighting the corresponding weights of each dimension, and output the rating of excellent, good, passable, or fail based on the overall quality score; S5: Generate a structured evaluation report containing detailed scores for each dimension, a comprehensive quality score, and a rating; collect indicator data for evaluation requests through a non-intrusive data collection method using cross-sectional embedding, with the indicator data including at least the evaluation request time and the evaluation success rate; trigger an alarm when the anomaly rate or evaluation score reaches a preset alarm threshold.

7. The implementation method according to claim 6, characterized in that, In step S2, when the agent responds with code blocks containing multiple different programming languages, each code block is parsed and its metadata is recorded; in step S3, each code block is executed; in step S41, the execution output of all code blocks is combined to calculate the code correctness score.

8. The implementation method according to claim 6, characterized in that, In step S3, when an unsupported programming language is identified, the code execution is directly marked as failed, and the code correctness score is 0.

9. The implementation method according to claim 6, characterized in that, In step S3, if the code execution triggers a timeout or resource exhaustion exception, the code execution is directly determined to have failed and is included in the code correctness score.

10. The implementation method according to claim 6, characterized in that, The scoring rules for code correctness in step S41 include: 0 points if no code block exists; 1.0 point if compilation and execution are completely successful and the output meets business expectations; 0.6 points if compilation and execution are successful but the output contains some logical errors; and 0 points if compilation fails or a fatal runtime exception is thrown.

11. The implementation method according to claim 6, characterized in that, Step S44 security compliance testing includes matching dangerous API blacklists and identifying sensitive content; if high-risk malicious code is identified, code execution within the sandbox will be terminated directly, and the security compliance score will be lowered.

12. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the automated code evaluation method for assessing the quality of the agent's response content as described in any one of claims 6-11.

Citation Information

Patent Citations

  • Large language model test and code generation quality evaluation method, device and equipment

    CN121501658A

  • Large model comprehensive evaluation system based on artificial intelligence

    CN121502255A

  • Model context protocol interaction method and device based on code execution

    CN121658099A