A method and system for generating and self-evolving dynamic prompts tailored to each user in recommendation scenarios.

By generating user profiles and combining them with the Lagrange Bandit algorithm to select the optimal prompt words, the dynamic adaptability problem of LLM recommendation systems in personalized scenarios is solved. This achieves low-cost, highly stable prompt management and cross-vendor compatibility, improving the flexibility and controllability of the recommendation system.

CN122133812APending Publication Date: 2026-06-02HANGZHOU XINSHI UNIVERSE TECH CO LTD
View PDF 6 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
HANGZHOU XINSHI UNIVERSE TECH CO LTD
Filing Date
2026-04-27
Publication Date
2026-06-02

AI Technical Summary

Technical Problem

In existing technologies, recommendation systems based on Large Language Models (LLM) lack systematic and automated Prompt Engineering when facing dynamic scenarios with personalized recommendations for each user. This results in insufficient static and individualized prompts, making it difficult to adapt to dynamic changes in different users, scenarios, and time periods. Furthermore, the lack of measurable closed-loop management and controllable exploration processes leads to high costs, poor stability, and cross-vendor compatibility issues.

Method used

By acquiring user data and generating user profiles, and based on scene templates and slot sets, the system integrates user profiles, context, and supply-side capacity to generate baseline prompt words. The system then selects the optimal prompt words through self-evaluation and self-correction and the Lagrange Bandit algorithm, and combines a large language model to generate recommendation results. This enables the generation and self-evolution of dynamic prompt words, and provides rollback-capable and auditable lifecycle management.

Benefits of technology

It achieves personalized, rollback-enabled, and auditable Prompt lifecycle management, enhances long-tail and cross-layer capabilities, reduces cost and stability issues, provides low-cost and highly stable online evolution capabilities, and supports cross-vendor portable and controllable Prompt exploration.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122133812A_ABST
    Figure CN122133812A_ABST
Patent Text Reader

Abstract

This invention discloses a method and system for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios, belonging to the field of computer technology. The method includes: acquiring user data; parsing the user data to generate a user profile u; generating a baseline prompt word P0; generating a candidate prompt word set C; validating the prompt words in the candidate prompt word set C and updating the candidate prompt word set C; based on the Lagrange Bandit algorithm, under constraint G, selecting the optimal prompt word P* from the updated candidate prompt word set C; generating recommendation results and readable reasons out using the LLM_Infer function; obtaining the core indicator M corresponding to the recommendation result, and performing counterfactual evaluation on unreleased candidate prompt words using the IPW algorithm and DR algorithm to obtain the evaluation result CF. This invention enables personalized, rollback-capable, and auditable Prompt lifecycle management.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer technology, specifically to a method and system for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios. Background Technology

[0002] (1) LLM recommendation based on fixed template: Most systems use the Large Language Model (LLM) as a ranking explanation or dialogue interface. They use a static Prompt template to concatenate user information with candidates and then call the LLM to generate a score / reason.

[0003] (2) Conventional online optimization: mainly A / B or multi-armed betting (MAB), exploring "ranking strategy / exposure ratio", rarely treating the Prompt itself as an optimization object.

[0004] (3) Data-driven offline training: The mainstream still relies on large-scale behavioral data for model retraining; the effects of user cold start, long-tail scenarios, and cross-circle matching are limited.

[0005] (4) Compliance / diversity processing is delayed: Platform objectives (security, privacy, diversity) are mostly corrected after recall or sorting, and do not enter the Prompt decision-making stage.

[0006] The main drawbacks of existing technology: Prompts lack static and personalized features: they are difficult to dynamically change according to user, scenario, and time period; the same set of prompts may be unstable in different contexts.

[0007] Lack of systematic automated prompt engineering (APE): Most only make minor adjustments to words and sentences, without structured search dimensions (instruction wording / thought chain switching / example composition / context budget / candidate splicing order, etc.).

[0008] The exploration process lacks "constraints" and "rollback": A / B or MAB often does not comply with hard constraints such as security, privacy, diversity, and cooldown periods; Prompt changes also lack differential amplitude control and rollback mechanisms.

[0009] Prompt metrics lack a measurable closed loop: it is difficult to causally map metrics such as immersion time, interaction rate, and number of views of different objects to the Prompt version, resulting in unauditable strategy evolution.

[0010] Cost and stability issues: Long Prompts are costly and prone to exceeding the context length; different model vendors have different formats, and there is a lack of unified management by DSL / compiler. Summary of the Invention

[0011] The purpose of this invention is to provide a method and system for generating and self-evolving dynamic prompts tailored to each user in recommendation scenarios.

[0012] To address the aforementioned technical problems, this invention provides a method for generating and self-evolving dynamic prompts tailored to each user in recommendation scenarios, comprising the following steps: Acquire user data; the user data includes scenario s, user natural language demand q, context c, and supply-side capacity k. Parse user data to generate a user profile u; the user profile includes hard constraints u_hard, soft preferences u_soft, and target state g; Based on the scenario template T_s and slot set L, user profile u, context c, and supply-side capacity k are integrated and compiled according to the token budget B to generate the baseline prompt word P0. Starting with the baseline prompt word P0, a candidate prompt word set C is generated through self-evaluation and self-improvement. Validate the prompts in the candidate prompt set C, and update the candidate prompt set C. Based on the Lagrange Bandit algorithm, under constraint G, the optimal prompt word P* is selected from the updated candidate prompt word set C; Input the optimal prompt word P* into the large language model, and generate recommendation results and readable reasons out through the LLM_Infer function; The recommendation results and readable reasons are sent to the user (out), and the core metric (M) is collected.

[0013] Preferably, based on the scene template T_s and the slot set L, the user profile u, context c, and supply-side capacity k are integrated and compiled according to the token budget B to generate the baseline prompt word P0, which specifically includes the following steps: Input the user profile u, context c, and supply-side capacity k into the slot set L, and output the result; Calculate the similarity sim(d,u) based on the user profile: φ(·) represents the similarity between the semantic vector of candidate item d and the semantic vector of user needs / profile u, where φ(·) represents text embedding, d represents candidate context item / candidate data unit, and λ represents semantic similarity weight coefficient / linear fusion weight. d satisfies u_hard, and φ(·) is the text embedding; MMR selects K search segments: d*=argmax_{d∈D\S}{α·sim(d,u)-(1-α)·max_{d'∈S}cos(φ(d),φ(d'))}, iterates until |S|=K; Select positive examples based on hard constraints and historical interface interaction rates; Negative examples are selected based on the boundaries; The search fragments, positive examples, and negative examples selected by MMR are embedded into the slot set L and input into the scene template T_s to generate baseline prompt words.

[0014] Preferably, starting with the baseline prompt word P0, a candidate prompt word set C is generated through self-evaluation and self-correction, specifically including the following steps: The baseline cue word P0 is self-assessed using LLM to obtain a three-dimensional self-assessment result; the three-dimensional self-assessment result includes relevance, stability and security. Based on the three-dimensional self-assessment results and preset thresholds, the baseline prompt word P0 is screened to obtain several candidate prompt words.

[0015] Preferably, based on the Lagrange Bandit algorithm, under constraint G, the optimal prompt word P* is selected from the updated candidate prompt word set C, specifically including the following steps: Calculate the similarity difference between candidate suggestions and the stable version: Calculate the degree of difference: Δ(P,P^stable)=α·d_tok+β·d_emb+γ·d_len d_tok = 1 - Jaccard (token sequence), d_emb = 1 - cos (sentence vector), d_len = |length difference| / B, passing the condition: Determine if the difference is greater than the preset maximum radius; if it is, it is considered normal and no further processing is required; if it is not, proceed to the exception handling process. Calculate the stability score S_stab: S_stab=η·S_stab_prev+(1-η)·(w1·ST ~ +w2·IR ~ +w3·DIV ~ ) Where: S_stab_prev is the historical stability score, ST ~ IR ~ DIV ~ These are the standardized structural consistency, information retention rate, and output diversity indicators, respectively, with η and w1 / w2 / w3 being weighting coefficients. If S_stab ≥ stability threshold τ_stab, then only candidate prompt words need to be pruned, and step 5 should be executed; If S_stab < τ_stab and Δ > warning radius r_warn: trigger the rollback mechanism and restore to the stable version P^stable; If the preset guardrail rule is triggered: directly reject the candidate prompt word P; Candidate suggestion word pruning: Tokens are pruned in descending order of priority from the example area, search fragment, and instruction area. Δ is recalculated after each round of pruning until Δ≤r_max. If the requirement is still not met after pruning, the CoT function is turned off, and the tokens are pruned again and checked. If the requirement is still not met, the tokens are rolled back to P^stable.

[0016] Preferably, the optimal prompt word P* is input into the large language model, and the recommendation result and readability reason out are generated through the LLM_Infer function, specifically including the following steps: Calculate the profit: R_i=λ1·ST ~ _i+λ2·IR ~ _i+λ3·DIV ~ _i Substitute single-user immersion time ST ~ Interface Interaction Rate (IR) ~ Different object view count DIV ~ And the corresponding weights λ1, λ2, and λ3, to obtain the reward Ri for each candidate prompt word Pi; Hard constraint verification: Check whether each Pi violates any hard constraints of security, privacy, cooldown period, or capacity. If it violates any of these constraints, set its target value to -∞ and exclude it from the selection in this round. Arm selection: For Pi that meets the hard constraints, according to the formula Calculate and select the optimal candidate i*; i*=argmax_i{ _i-μ^Tg_i+UCB_i} _i represents the estimated revenue, μ represents the constraint multiplier, g_i represents the constraint term, and UCB_i represents the upper confidence bound. Multiplier update: Adjust the constraint multiplier according to the formula μ←[μ+ημ·gi*]+; η_μ is the update step size, and [·]_+ indicates non-negative truncation; Traffic allocation: Traffic allocation is completed by calculating the traffic share of each compliant Pi.

[0017] Preferably, the method further includes the following steps: Counterfactual evaluation of unavailable candidate suggestions is performed using the IPW and DR algorithms to obtain the evaluation result CF.

[0018] Preferably, the method further includes the following steps: The optimal prompt word P*, candidate set C, metric M, and counterfactual evaluation result CF are fed back to the prompt word state machine and version control system to update the parameters of the Prompt orchestrator, automated PromptEngineering, and constrained online optimization.

[0019] This invention also provides a dynamic prompt word generation and self-evolution system for personalized recommendation scenarios, comprising: The scenario and context acquisition module is used to acquire user data; the user data includes scenario s, user natural language demand q, context c, and supply-side capacity k; The user profile modeling module is used to parse user data and generate a user profile u; the user profile includes hard constraints u_hard, soft preferences u_soft, and target state g; The Prompt orchestrator module is used to compile based on the scene template T_s and slot set L, integrate user profile u, context c, supply-side capacity k, and Token budget B to generate the baseline prompt word P0. The automated PromptEngineering module is used to generate a set of candidate prompt words C by self-evaluation and self-correction, starting from the baseline prompt word P0. The guardrail and Δ-Prompt radius verification module is used to verify the prompt words in the candidate prompt word set C and update the candidate prompt word set C. The constrained online optimization module is used to select the optimal prompt word P* from the updated candidate prompt word set C under the constraint condition G, based on the Lagrange Bandit algorithm. The LLM inference and output module is used to input the optimal prompt word P* into the large language model and generate recommendation results and readable reasons out through the LLM_Infer function. The indicator collection and counterfactual evaluation module is used to send the recommendation results and readable reasons to the user, and to collect the core indicator M. Compared with the prior art, the beneficial effects of the present invention are as follows: 1. Upgrade Prompt from "template" to "policy object": achieve personalized, rollback-enabled, and auditable Prompt lifecycle management.

[0020] 2. Significantly enhanced long-tail and cross-sector capabilities: Through the injection of diversity and awareness of supply capacity, it can proactively guide "new connections" at the Prompt decision-making level, in addition to matching logic.

[0021] 3. Low-cost and highly stable online evolution: Δ-Prompt radius + stability score + guardrail ensures controllable exploration and one-click rollback in case of anomalies.

[0022] 4. No need for large-scale retraining: The optimization mainly focuses on the structure / content of the Prompt, which significantly reduces the burden of offline training and feature engineering.

[0023] 5. Measurable metrics and causal assessment: Targets include immersion time, interaction rate, and number of views for different objects, combined with IPW / DR to reduce online trial and error costs.

[0024] 6. Cross-vendor portability and cost control: DSL / compiler and context budget, balancing performance and inference cost. Attached Figure Description

[0025] The specific embodiments of the present invention will be further described in detail below with reference to the accompanying drawings.

[0026] Figure 1 This is a schematic diagram of the overall system architecture: showing the closed-loop data flow from “Scene and Context Acquisition (20) → Profile Modeling (30) → Prompt Orchestrator (40) → APE (50) → Guardrail and Δ-Prompt (60) → Constrained Online Optimization (70) → LLM Inference (80) → Indicator and Counterfactual Evaluation (90) → Prompt State Machine (100)”.

[0027] Figure 2 This is a schematic diagram of the internal structure of the Prompt orchestrator: including a template layer (41), a personalization fusion layer (42), a context packer (43), a Prompt compiler (44), and interactions with APE (50) / guardrail (60) / online optimization (70) / evaluation (90).

[0028] Figure 3 This is a flowchart illustrating the process flow: the sequential flow and loop relationships of S1 to S8, marking the Δ-Prompt radius, rollback trigger point, context budget location, and counterfactual evaluation entry point. Detailed Implementation

[0029] Numerous specific details are set forth in the following description to provide a full understanding of the invention. However, the invention can be practiced in many other ways different from those described herein, and those skilled in the art can make similar extensions without departing from the spirit of the invention. Therefore, the invention is not limited to the specific embodiments disclosed below.

[0030] The terminology used in one or more embodiments of this specification is for the purpose of describing particular embodiments only and is not intended to be limiting of the one or more embodiments of this specification. The singular forms “a,” “described,” and “the” as used in one or more embodiments of this specification and the appended claims are also intended to include the plural forms unless the context clearly indicates otherwise. It should also be understood that the term “and / or” as used in one or more embodiments of this specification refers to and includes any or all possible combinations of one or more associated listed items.

[0031] It should be understood that although the terms first, second, etc., may be used to describe various information in one or more embodiments of this specification, such information should not be limited to these terms. These terms are only used to distinguish information of the same type from one another. For example, first may also be referred to as second without departing from the scope of one or more embodiments of this specification, and similarly, second may also be referred to as first. Depending on the context, the word "if" as used herein may be interpreted as "when," "when," or "in response to a determination."

[0032] The present invention will now be described in further detail with reference to the accompanying drawings: To better illustrate the technical effects of the present invention, the present invention provides the following specific embodiments to illustrate the above technical process: Terminology and Symbol Conventions Scenario: s (such as running buddies for certification exams, running partners, roommates, etc.).

[0033] User input in natural language: q.

[0034] Context: c = (t, geo, device).

[0035] Supply-side capacity vector: k (e.g., teacher's evening schedule, number of running friends in the same community online).

[0036] User profile: u = (u_hard, u_soft, g), representing hard constraints, soft preferences, and target state, respectively.

[0037] Scene template: T_s; Slot set: L = {L_inst, L_ctx, L_ex, L_fmt}.

[0038] Baseline prompt word: P0; Candidate prompt word set: P = {P_i}.

[0039] Metrics: M = {ST, IR, DIV} (single user immersion time, interface interaction rate, number of different objects a user is willing to browse).

[0040] Stability score: S_stab; Δ-Prompt radius: Δ.

[0041] Token maximum budget: B; Category budget: b_inst, b_ex, b_ret, b_fmt (instruction / example / retrieval / format).

[0042] Restraining multi-armed gambling: CMAB; Counterfactual assessment: IPW (Inverse Propensity Weighted) and DR (Double Robustness).

[0043] LLM: Large Language Model; CoT: Mind Chain; DSL: Domain-Specific Language.

[0044] Example 1: A dynamic prompt word generation and self-evolution system for personalized recommendation scenarios, such as... Figures 1-3 As shown, the system architecture (modules and relationships) is as follows: 1) Scene and Context Acquisition Module (20): Collects s, c, k and platform targets (diversity threshold, cooling strategy).

[0045] 2) Image modeling module (30): parse q into u_hard, u_soft, and g.

[0046] 3) Prompt orchestrator (40): template layer (41), personalization fusion (42), context packer (43), Prompt compiler (44).

[0047] 4) Automation Prompt Engineering (APE, 50): Structured search and model self-evaluation / self-correction.

[0048] 5) Guardrail and Δ-Prompt radius verification (60): Sensitive / Privacy / Variety / Cooldown period rule verification and anomaly rollback.

[0049] 6) Constrained Online Optimization (CMAB, 70): Allocate traffic and select candidate suggestion word versions under constraints.

[0050] 7) LLM Reasoning and Output (80): Generate recommendation results and reasons.

[0051] 8) Indicator collection and counterfactual assessment (90): Record M; estimate IPW / DR for candidates that have not yet gone online.

[0052] 9) Prompt word state machine and version library (100): Record the current version, candidate pool, stability and rollback pointer for each user × scenario; backflow to 40 / 50 / 70.

[0053] The method includes the following steps: S1 Requirements Acquisition and Analysis: Input (s, q, c, k) → Output u=(u_hard, u_soft, g).

[0054] S2 benchmark prompt generation: Based on T_s and L, u, c, and k are merged to compile and generate P0.

[0055] S3 Candidate Generation (APE): Starting from P0, a candidate set P={P_i} is generated through structured search and self-evaluation.

[0056] S4 Guardrail and Radius Validation: Perform security / privacy / diversity / cooling validation and Δ radius limit for each P_i; if it fails, trim or roll back.

[0057] S5 Constrained Online Optimization (CMAB): Allocate traffic to P under constraint G and select the online version P* to invoke LLM.

[0058] S6 Reasoning and Results / Reasons: Produce a list of candidates and readable reasons.

[0059] S7 Indicators and Counterfactual Assessment: Collect core indicator M; perform IPW / DR estimation for candidates not yet online.

[0060] S8 state machine update: Update (P*, P, S_stab, rollback), and feed back to S2 / S3 / S5.

[0061] The interaction result M comes from the user's actual interaction and is calculated from the event logs after the S6 display.

[0062] This corresponds to single-user immersion time (dwell / stay time), interface interaction rate (number of interactions such as clicks / replies / favorites / initiating communication, etc., or whether they occur), and the number of different objects that the user is willing to browse (deduplicated count).

[0063] These metrics are all based on the actual behavior generated by the recommended object list and readable reasons presented to the user by S6, and are tracked through data collection and statistics. Calculated within (e.g., 30 minutes / 2 hours / 24 hours).

[0064] Unreleased Prompt: Refers to the Prompt versions in Season 5 that were not selected for release. This is not the "recommended list" of S6. S7's IPW / DR performs counterfactual evaluations on these unreleased Prompt versions.

[0065] "Not yet online candidate" = "Candidate Prompt version" that was not selected and actually displayed by S5. (or the round was not allocated traffic) ).

[0066] Who to evaluate: The Prompt versions that were not launched or only partially launched in this round. The counterfactual benefits of "what would happen if it went live".

[0067] If a certain If a small amount of flow is obtained through exploration in S5, then there is a direct observation M (small sample) + counterfactual estimation to make a trade-off between variance and bias.

[0068] No data usage at all Only counterfactual estimates exist.

[0069] For each exposure log (context) Actual online action Observed rewards With tendency ), for any subject to be evaluated Do ; The resulting model trained using historical data (regressing / classifying the combined returns of ST / IR / DIV).

[0070] S5 bandit logging tendency (documented).

[0071] If this round If not online, the indicator function is 0, and only the model item is used. ;like With a small amount of real traffic, the second option will reduce deviation and improve consistency.

[0072] In this way, without disturbing users, a reliable estimate of what would happen if the Prompt version that has not yet been launched can be obtained, which can be used for the next round of screening and scheduling.

[0073] The technical problem solved by the present invention, a method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios, is as follows: 1. Real-time generation of personalized Prompts: Make Prompts a first-class citizen, achieving dynamic arrangement at the **"user × scenario × time period"** level.

[0074] 2. Automated Prompt Engineering (APE): Establish an engineering pipeline for multi-dimensional structure search and self-evaluation rewriting, surpassing the crude parameter tuning that relies solely on interactive data.

[0075] 3. Constrained online exploration and rollback: Select Prompt under constraints such as security, privacy, diversity, supply capacity, and cooldown period, and provide Δ-Prompt radius and stability score to ensure controllable evolution and one-click rollback.

[0076] 4. Measurable closed loop: Establish causal estimation and counterfactual evaluation (IPW / DR) with metrics such as single-user immersion time, interface interaction rate, and the number of different objects that users are willing to browse, and the Prompt version to support low-cost and robust deployment.

[0077] 5. Cross-model vendor portability and cost optimization: Context budget planning and cross-vendor format unification are achieved through Prompt DSL and compiler, reducing computational and maintenance costs.

[0078] In the aforementioned method for generating and self-evolving dynamic prompts tailored to individual users in recommendation scenarios: 1) Prompt Arranger: Templates and Slots Slot definitions: Instruction slot L_inst (role / target / evaluation / CoT / security), Context slot L_ctx (u / c / k / platform target), Example slot L_ex (positive / negative example), Output slot L_fmt (JSON / score / reason).

[0079] Scenario A: Accompanying someone to an exam (gentle evening) Command slot: Role = "Gentle Study Coach"; Goal = "Improve review efficiency without putting pressure on students"; Evaluation weight: Time 0.4 / Personality 0.3 / Experience 0.3; CoT = On.

[0080] Context slot: time window [20:00, 22:00]; u_soft includes "mild"; k = evening slot; DIV ≥ 0.3.

[0081] Example slot: Positive example = available time in the evening + gentle language; Negative example = available time during the day + high-pressure tone.

[0082] Output slot: {score:[0,1], reasons:[...], schedule:["20:00-22:00"]}.

[0083] score: Recommendation matching score, used to quantify the degree of fit between the user and the recommended object; reasons: Matching reasons; schedule: Time arrangement; Scenario Example B: Running Partner (Beginner 5km, afraid of being pushed to the limit) Command slot: Role = "Pace Matcher"; Evaluation criteria = Geographic proximity + pace difference ≤ 30 seconds / km.

[0084] Context slot: Same community; Tuesday to Thursday 7:00; k = number of online users in the same community.

[0085] Example slot: Positive example = "pace 6'30 + stretch reminder"; Negative example = "pace 5'10 high strength".

[0086] Output slot: {"score":0.82,"reasons":["pace difference <=30s","same community, close distance","remind stretch"],"trial":"2km"}.

[0087] Scenario C: Roommate (early to bed, non-smoking, quiet) Instruction slot: Emphasizes "consistency of life rules".

[0088] Contextual slot: No smoking = true; Guest agreement = lenient.

[0089] Example slot: Positive example = "Regular cleaning / no smoking / Scheduled guests"; Negative example = "Night owl / Smoking".

[0090] Output slot: {"match":0.77,"reasons":["fixed cleaning","smokeless","consistent with visitor agreement"]}.

[0091] 2) The selection process and function of the context packer

[0092] Similarity: φ(·) represents the similarity between the semantic vector of candidate item d and the semantic vector of user needs / profile u, where φ(·) represents text embedding, d represents candidate context item / candidate data unit, and λ represents semantic similarity weight coefficient / linear fusion weight.

[0093] MMR selects K lines: d* = argmax_{d∈D\S} { α·sim(d,u) - (1-α)·max_{d'∈S}cos(φ(d),φ(d'))}, iterating until |S|=K.

[0094] The best candidate context entry selected in this iteration.

[0095] (D): Candidate library / candidate set, containing all context entries that can be selected into the Prompt, such as: candidate object summary cards, positive / negative examples, rule / knowledge cards, etc.

[0096] The selected set represents the set of context entries that have been selected so far; it is initially an empty set and then gradually increases in size.

[0097] Correlation – Diversity Tradeoff Coefficient .

[0098] The larger the size, the more emphasis is placed on its relevance to user needs. ; The smaller the value, the more emphasis is placed on the difference from the selected set (avoiding repetition), i.e., the diversity factor.

[0099] Selected set Any entry in the list is used to calculate the "maximum similarity between candidate entry d and selected entry" (i.e., "which one is most similar").

[0100] : The similarity between candidate entry d and the most similar entry in the selected set, used to penalize "duplicate / redundant".

[0101] Each round selects one candidate from the "candidate pool that has not yet been selected". It should be most relevant to user needs, and should avoid duplication with already selected items as much as possible.

[0102] Iteration to Afterwards, the assembly It contains K selected context entries (in each round). All join The purpose of these K entries is to construct the context of the Prompt. Positive example: Satisfies hard constraints and has a high historical IR.

[0103] Negative examples: include "undesirable" features to clarify boundaries.

[0104] Reason fragment: Extract standardized phrases such as "first 30 minutes for diagnosis / first 2 kilometers trial run" from high-performance output.

[0105] The search fragments selected by MMR and the positive / negative examples are written to slots L_ctx and L_ex, respectively. Their coverage directly affects the stability and upper limit of LLMScore.

[0106] The context packer outputs a set of context entries to populate the prompt word template; then the prompt word arranger / compiler of S2 writes the set into the corresponding slot and completes the compilation under the Token budget constraint, thereby generating the base prompt word P0.

[0107] 3) Automated Prompt Engineering (APE): Structured search and model self-evaluation / self-correction Search space: instruction wording variations, evaluation scale, CoT switch and steps, number of examples K and composition ρ, splicing order, Prompt compression, budget vector b.

[0108] Candidate generation pseudocode: P0 = compile(T_s, L(u,c,k), B) C = { mutate(P0, d) | d ∈ S} S_ref = LLM.self_review(P0) # Self-assessment of correlation / stability / security C += { apply_refine(P0, r) | r ∈ S_ref} return C Self-evaluation output: q̂=(q_rel,q_stab,q_safe)∈[0,1]^3; rewrite patch δ overwrite instruction / example / sequence / scale / budget.

[0109] Default thresholds: q_safe ≥ 0.7, q_stab ≥ 0.5; when either is below the threshold, only shrinkage rewriting is retained (reducing examples, disabling CoT).

[0110] 4) The Prompt compiler allocates a budget and outputs a set of candidate prompt words. (or Each candidate suggestion is compiled under the constraints of token budget B and DSL verification, and has a callable format and security boundaries; Objective: Maximize the value Max Σ V_c(b_c) st within the token budget B, where Σ b_c ≤ B, b_c ≥ 0, and c∈{inst, ex, ret, fmt}.

[0111] V_inst: Instruction information gain; V_ex(K): Diminishing marginal returns for the number / length of examples; V_ret(r): Fragment retrieval gain; V_fmt: Output format parsing gain.

[0112] Solution: Use a greedy or Lagrange algorithm to iterate once based on "marginal value / marginal length"; output K, the maximum length of each example, and the number of retrieved fragments r.

[0113] DSL type validation: Placeholders such as TimeWindow, GeoRadius, SafetyTag, and PrivacyField undergo static validation and privilege escalation restrictions at compile time.

[0114] When ∂V_ex / ∂b_ex < ∂V_ret / ∂b_ret, move 100 tokens from the sample budget to the retrieval budget to increase the total value.

[0115] 5) Δ-Prompt radius verification and anomaly detection Δ(P, P^stable) = α·d_tok + β·d_emb + γ·d_len; where d_tok = 1 - Jaccard (token sequence), d_emb = 1 - cos (sentence vector), and d_len = |length difference| / B. The condition is: Δ ≤ r_max.

[0116] The token sequence is obtained from the word text through the target model tokenizer; the sentence vector is obtained by encoding the prompt word text using the embedding model. The threshold parameter for radius verification can be preset by the system.

[0117] Stability score: S_stab = η·S_stab_prev + (1-η)·(w1·ST) ~ + w2·IR ~ + w3·DIV ~ If S_stab < τ_stab and Δ > r_warn → rollback; if the guardrail is triggered, it is directly rejected. η, w1 / w2 / w3 are weighting coefficients.

[0118] Immersion time (duration of stay):

[0119] in A collection of exposed / visible events.

[0120] Interaction rate:

[0121] Alternatively, use 0 / 1 (whether any key interaction occurred).

[0122] Diversity:

[0123] Count by the deduplicated object ID.

[0124] Standardization (example): ; Similarly, quantiles / sliding window mean variance normalization can also be used.

[0125] in conclusion: All data were calculated from real user interaction logs after S6 using S7.

[0126] Standardized single-user immersion time metric (standardized dwell time).

[0127] Standardized interface interaction rate metric (standardized interaction rate / interaction intensity).

[0128] Standardized diversity metrics (number of different objects viewed in standardized browsing / coverage diversity).

[0129] ST, IR, and DIV are defined as immersion time, interaction rate, and diversity of visitors. The original metrics ST, IR, and DIV are calculated based on the interaction result M.

[0130] Immersion time (duration of stay): in A collection of exposed / visible events.

[0131] Interaction rate: Alternatively, use 0 / 1 (whether any key interaction occurred).

[0132] Diversity: Count by the deduplicated object ID.

[0133] Standardization (example): Similarly, quantiles / sliding window mean variance normalization can also be used.

[0134] All data were calculated from real user interaction logs after S6 using S7.

[0135] Constrained Online Optimization (CMAB) Profit: R_i = λ1·ST ~ _i + λ2·IR ~ _i + λ3·DIV ~ _i; constraints g_i: diversity threshold, cooling limit, capacity limit, security and privacy. λ1, λ2, and λ3 are weights.

[0136] : indicates when the first Version of candidate prompts When presenting the data, the corresponding standardized indicator value (or its estimated value) should be used.

[0137] Log statistics (true) or counterfactual estimates (IPW / DR) from S7 are used to calculate revenue in S5. .

[0138] Arm selection: i* = argmax_i { Ŕ_i - μ^T g_i + UCB_i}; Multiplier update: μ ← [ μ +η_μ·g_{i*} ]_+; Flow allocation: softmax(Ŕ_i - μ^T g_i).

[0139] Estimated by S7 (observations or IPW / DR); Calculated from S4 (hard constraints) and S7 (indicators / capacity); This was obtained from the statistics of the number of calls and rounds in S8; These are S5 internal optimization parameters; These are the constraint values ​​for the version selected in this round.

[0140] If candidate P_i violates any hard constraint (security / privacy / cooldown / capacity), set its target value to -∞ in the current round and reselect it to ensure that hard constraints take precedence.

[0141] 6) Scoring Fusion (LLM and Structured Features) Score = θ0·LLMScore(P, pair) + Σ θ_j·f_j(pair); where f_j represents features such as time overlap, geographical distance, pace difference, and consistency of work and rest, and θ is determined by historical feedback or L1 dynamic weights.

[0142] A pair is a matching pair between a requesting user and a candidate object, which comes from the S6 recommended object candidate set (the list of objects after recall and merging) or the TopN candidate objects in your system; The weighting factor of the LLM score in the final score; : The j-th structured feature The weighting coefficients (such as time overlap, geographical distance, pace difference, and consistency of work and rest) come from the default configuration or L1 personalized weights and can be updated by S8 feedback; the scoring fusion is to fuse the semantic score output by LLM with the structured feature score calculated by the system to obtain the final ranking score.

[0143] Exceptions and Rollback Strategies Instant rollback: If the guardrail is triggered (privacy / sensitivity / unauthorized access / cooldown violation), immediately roll back to the stable version.

[0144] Grayscale rollback: S_stab If two consecutive windows are below the threshold, subgroup rollback will occur.

[0145] Full rollback: A full rollback is triggered by a scenario-level exception.

[0146] Audit: Record the differences, Δ, indicator changes, and reasons for guardrail triggering.

[0147] 7) End-to-end instance Example 1 (Exam Preparation): q = "Exam in four weeks, available at 8 PM, don't be too aggressive." S1 Analyzes time window and mild preferences; S3 Generates 12 candidates; S4 Eliminates candidates exceeding the radius and those violating privacy rules; S5 CMAB allocation is 60 / 25 / 15%; S6 Produces "mild teacher + evening schedule; schedule 30 minutes for initial diagnosis"; S7 Indicators increase; S8 Records the best version and improves stability.

[0148] Example 2 (Running Partner): Emphasize pace difference ≤ 30 seconds / km; select 2 positive and 1 negative examples in the packer; the compiler allocates 1.2k / 1.6k / 0.9k / 0.3k; if the capacity is insufficient, the Prompt is automatically rewritten as "Try running 2km first / Stretching guidance / Available by appointment".

[0149] 8) Default parameters and recommended values λ (weighted similarity) = 0.7; α (MMR) = 0.7; K (number of examples) = 3 ± 1; positive / negative ratio ρ ≈ 2:1.

[0150] B (token) is typically 4k; initial budget values: b_inst=1.2k, b_ex=1.6k, b_ret=0.9k, b_fmt=0.3k.

[0151] Δ Radius: Instruction area r_max=0.15; Example area 0.25; Output area 0.3; r_warn is 0.05 higher than r_max.

[0152] Stability: η=0.6; w1=w2=w3=1 / 3; τ_stab=0.45.

[0153] CMAB: λ1=0.5, λ2=0.3, λ3=0.2; Exploration intensity limit = User level ≤ 10%.

[0154] pseudocode Algorithm DynamicPromptEvo Input: scene s, query q, context c, capacity k 1: u ← Parse(q, s, c) / / S1 2: P0 ← Compile(T_s, L(u,c,k), B) / / S2 3: C ← APE_Generate(P0, S) / / S3 (Structure search + self-evaluation and self-correction) 4: C ← GuardAndRadiusFilter(C, P_stable, r_max) / / S4 5: P* ← CMAB_Select(C, Constraints G) / / S5 (Lagrange Bandit) 6: out ← LLM_Infer(P*) / / S6 7: M ← Measure(out); CF ← CF_Eval(C, logs) / / S7 (IPW / DR) 8: UpdateState(P*, C, M, CF) / / S8 return out The present invention has the following advantages: 1. PMoE gating strategy replacement: Change the gating from hard selection to weighted fusion or temperature regulation, supporting multi-objective dynamic balance.

[0155] 2. Δ-Prompt radius adaptive: The radius is automatically widened / tightened based on the "stability score / recent 7-day anomaly rate / guardrail trigger rate" and layered constraints are applied (instruction area > example area > output area).

[0156] 3. Layered APE scheduling: High-impact slots (instructions / evaluation criteria) are searched at low frequency, while low-impact slots (examples / assembly order) are searched at high frequency to reduce jitter.

[0157] 4. Supply capacity and script adaptation: When supply is tight, the Prompt automatically inserts the script of "appointment / waiting / alternative solution"; when supply is abundant, it highlights "experience now".

[0158] 5. Privacy / Sensitive Isolation: DSL stipulates that sensitive placeholders can only appear in the local search summary and must not enter the LLM context, or local desensitization / hash mapping should be used.

[0159] 6. Edge-Cloud Collaboration: Lightweight retrieval and context trimming are completed on the edge, while LLM inference and APE search are completed in the cloud, reducing latency and cost.

[0160] 7. Counterfactual assessment enhancement: Combining paired scoring / nearest-neighbor replay improves estimation stability.

[0161] 8. Prompt Distillation: Automatically summarizes well-performing long prompts into short macro-prompts and performs token budget reclamation at the compiler level.

[0162] 9. Multi-level rollback strategies for abnormal situations: immediate rollback (minute-level), gray rollback (user subgroup level), and full rollback (scenario-level), and record rollback reason tags.

[0163] 10. Explainable output: Record "Hit Prompt fragment / quota / constraint reason" for each recommendation for operational audit and compliance review.

[0164] In the several embodiments provided by this invention, it should be understood that the disclosed apparatus and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative. For instance, the division of modules, units, or units is merely a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units, modules, or components may be combined or integrated into another device, or some features may be ignored or not executed.

[0165] The units may or may not be physically separate. The components shown as units can be one or more physical units, meaning they can be located in one place or distributed in multiple different locations. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0166] Furthermore, the functional units in the various embodiments of the present invention 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. The integrated unit can be implemented in hardware or as a software functional unit.

[0167] In particular, according to embodiments disclosed in this invention, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments of this disclosure include a computer program product comprising a computer program carried on a computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication component, and / or installed from a removable medium. When the computer program is executed by a central processing unit (CPU), it performs the functions defined in the methods of this invention. It should be noted that the computer-readable medium described above in this invention can be a computer-readable signal medium or a computer-readable storage medium, or any combination of the two. The computer-readable storage medium can be, for example, but not limited to, an electrical, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, or device, or any combination thereof.

[0168] 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 the present invention. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code containing one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those indicated in the drawings. For example, two consecutively indicated 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 operation, or using a combination of dedicated hardware and computer instructions.

[0169] The above description is merely a specific embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any variations or substitutions within the technical scope disclosed in the present invention should be covered within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be determined by the scope of the claims.

Claims

1. A method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios, characterized in that: include: Acquire user data; the user data includes scenario s, user natural language demand q, context c, and supply-side capacity k. Parse user data to generate a user profile u; the user profile includes hard constraints u_hard, soft preferences u_soft, and target state g; Based on the scenario template T_s and slot set L, user profile u, context c, and supply-side capacity k are integrated and compiled according to the token budget B to generate the baseline prompt word P0. Starting with the baseline prompt word P0, a candidate prompt word set C is generated through self-evaluation and self-improvement. Validate the prompts in the candidate prompt set C, and update the candidate prompt set C. Based on the Lagrange Bandit algorithm, under constraint G, the optimal prompt word P* is selected from the updated candidate prompt word set C; Input the optimal prompt word P* into the large language model, and generate recommendation results and readable reasons out through the LLM_Infer function; The recommendation results and readable reasons are sent to the user (out), and the core metric (M) is collected.

2. The method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios according to claim 1, characterized in that, Based on the scenario template T_s and the slot set L, and integrating the user profile u, context c, and supply-side capacity k, the benchmark prompt word P0 is generated by compiling according to the token budget B. The specific steps include: Input the user profile u, context c, and supply-side capacity k into the slot set L, and output the result; Calculate the similarity sim(d,u) based on the user profile: φ(·) represents the similarity between the semantic vector of candidate item d and the semantic vector of user needs / profile u, where φ(·) represents text embedding, d represents candidate context item / candidate data unit, and λ represents semantic similarity weight coefficient / linear fusion weight. d satisfies u_hard, and φ(·) is the text embedding; MMR selects K search segments: d*=argmax_{d∈D\S}{α·sim(d,u)-(1-α)·max_{d'∈S}cos(φ(d),φ(d'))}, iterates until |S|=K; Select positive examples based on hard constraints and historical interface interaction rates; Negative examples are selected based on the boundaries; The search fragments, positive examples, and negative examples selected by MMR are embedded into the slot set L and input into the scene template T_s to generate baseline prompt words.

3. The method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios according to claim 2, characterized in that, Starting with the baseline prompt word P0, a candidate prompt word set C is generated through self-assessment and self-improvement, specifically including the following steps: The baseline cue word P0 is self-assessed using LLM to obtain a three-dimensional self-assessment result; the three-dimensional self-assessment result includes relevance, stability and security. Based on the three-dimensional self-assessment results and preset thresholds, the baseline prompt word P0 is screened to obtain several candidate prompt words.

4. The method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios according to claim 3, characterized in that, Based on the Lagrange Bandit algorithm, under constraint G, the optimal prompt word P* is selected from the updated candidate prompt word set C, specifically including the following steps: Calculate the similarity difference between candidate suggestions and the stable version: Calculate the degree of difference: Δ(P,P^stable)=α·d_tok+β·d_emb+γ·d_len d_tok = 1 - Jaccard (token sequence), d_emb = 1 - cos (sentence vector), d_len = |length difference| / B, passing the condition: Determine if the difference is greater than the preset maximum radius; if it is, it is considered normal and no further processing is required; if it is not, proceed to the exception handling process. Calculate the stability score S_stab: S_stab=η·S_stab_prev+(1-η)·(w1·ST ~ +w2·IR ~ +w3·DIV ~ ) Where: S_stab_prev is the historical stability score, ST ~ IR ~ DIV ~ These are the standardized structural consistency, information retention rate, and output diversity indicators, respectively, with η and w1 / w2 / w3 being weighting coefficients. If S_stab ≥ stability threshold τ_stab, then only candidate prompt words need to be pruned, and step 5 should be executed; If S_stab < τ_stab and Δ > warning radius r_warn: trigger the rollback mechanism and restore to the stable version P^stable; If the preset guardrail rule is triggered: directly reject the candidate prompt word P; Candidate suggestion word pruning: Tokens are pruned in descending order of priority from the example area, search fragment, and instruction area. Δ is recalculated after each round of pruning until Δ≤r_max. If the requirement is still not met after pruning, the CoT function is turned off, and the tokens are pruned again and checked. If the requirement is still not met, the tokens are rolled back to P^stable.

5. The method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios according to claim 4, characterized in that, The optimal suggestion word P* is input into the large language model, and the recommendation result and readability reason out are generated through the LLM_Infer function. The specific steps include: Calculate the profit: R_i=λ1·ST ~ _i+λ2·IR ~ _i+λ3·DIV ~ _i Substitute single-user immersion time ST ~ Interface Interaction Rate (IR) ~ Different object view count DIV ~ And the corresponding weights λ1, λ2, and λ3, to obtain the reward Ri for each candidate prompt word Pi; Hard constraint verification: Check whether each Pi violates any hard constraints of security, privacy, cooldown period, or capacity. If it violates any of these constraints, set its target value to -∞ and exclude it from the selection in this round. Arm selection: For Pi that meets the hard constraints, according to the formula Calculate and select the optimal candidate i*; i*=argmax_i{ _i-μ^Tg_i+UCB_i} _i represents the estimated revenue, μ represents the constraint multiplier, g_i represents the constraint term, and UCB_i represents the upper confidence bound. Multiplier update: Adjust the constraint multiplier according to the formula μ←[μ+ημ⋅gi∗]+; η_μ is the update step size, and [·]_+ indicates non-negative truncation; Traffic allocation: via Calculate the traffic share of each compliant Pi and complete the traffic allocation.

6. The method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios according to claim 5, characterized in that, It also includes the following steps: Counterfactual evaluation of unavailable candidate suggestions is performed using the IPW and DR algorithms to obtain the evaluation result CF.

7. The method for generating and self-evolving dynamic prompts for personalized recommendations in recommendation scenarios according to claim 6, characterized in that, It also includes the following steps: The optimal prompt word P*, candidate set C, metric M, and counterfactual evaluation result CF are fed back to the prompt word state machine and version control system to update the parameters of the Prompt orchestrator, automated PromptEngineering, and constrained online optimization.

8. A personalized dynamic prompt generation and self-evolution system for recommendation scenarios, used to implement the personalized dynamic prompt generation and self-evolution method for recommendation scenarios as described in any one of claims 1-7, characterized in that it includes: The scenario and context acquisition module is used to acquire user data; the user data includes scenario s, user natural language demand q, context c, and supply-side capacity k; The user profile modeling module is used to parse user data and generate a user profile u; the user profile includes hard constraints u_hard, soft preferences u_soft, and target state g; The Prompt orchestrator module is used to compile based on the scene template T_s and slot set L, integrate user profile u, context c, supply-side capacity k, and Token budget B to generate the baseline prompt word P0. The automated PromptEngineering module is used to generate a set of candidate prompt words C by self-evaluation and self-correction, starting from the baseline prompt word P0. The guardrail and Δ-Prompt radius verification module is used to verify the prompt words in the candidate prompt word set C and update the candidate prompt word set C. The constrained online optimization module is used to select the optimal prompt word P* from the updated candidate prompt word set C under the constraint condition G, based on the Lagrange Bandit algorithm. The LLM inference and output module is used to input the optimal prompt word P* into the large language model and generate recommendation results and readable reasons out through the LLM_Infer function. The indicator collection and counterfactual evaluation module is used to send the recommendation results and readable reasons (out) to the user and collect the core indicator (M).

Citation Information

Patent Citations

  • Automatic prompt construction method based on man-machine conversation history and semantic retrieval

    CN119441443A

  • Writing illustration generation system and method based on AI

    CN120655758A

  • Multi-knowledge-base scheduling routing method based on intention recognition and feedback optimization

    CN120973866A

  • Deep learning framework fuzzy testing method based on large model cue word optimization

    CN121455829A

  • Error correction type RAG method for self-adaptive re-retrieval and evidence purification

    CN121743445A