AI doctor recommendation method and system for multi-campus operation scenario of obstetrics and gynecology hospital
Patent Information
- Application Number
- CN202611221001.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-12
- Publication Date
- 2026-10-20
AI Technical Summary
但妇产科疾病涉及的时节性、急迫性和隐私敏感度十分突出:先兆流产、异位妊娠待排等问题要求就近、尽快获得处置;非侵入性产前筛查有严格的孕周窗口,一旦推荐到当日该检查设备已约满的院区,后续管理流程就会被打乱;加上多院区之间存在动态的排班联动、医生跨院出诊,这些因素在现有推荐逻辑里几乎不被考虑,导致推荐流于形式,无法真正缓解多院区体系下的就医选择困难
[0048]本发明能明显减少挂错科室和反复转诊的情况。对于合并妊娠期糖尿病又存在附件囊肿的复杂描述,系统可以一步找到同时具备高危产科和妇科微创手术条件的院区及医生,避免患者在产科和妇科之间反复奔波。
Smart Images

Figure FT_1 
Figure FT_2 
Figure FT_3
Abstract
Description
Technical Field
[0001] This invention relates to the field of medical software, and in particular to an AI doctor recommendation method and system for multi-site operation scenarios in obstetrics and gynecology hospitals. Background Technology
[0002] To alleviate the pressure on their patient load and develop specialized medical services, obstetrics and gynecology hospitals typically establish multiple campuses in different areas of a city, distributing subspecialties such as obstetrics, gynecological oncology, reproductive endocrinology, and day surgery according to their disciplinary plans. For example, some campuses focus on high-risk obstetrics and prenatal diagnosis, while others concentrate on gynecological endoscopic surgery or comprehensive menopause management. While this layout amplifies the strengths of each campus, it also exposes patients to a large amount of overwhelming information when registering: the number of doctors across different campuses of the same hospital increases exponentially, and the conventional method of displaying doctors by department, name, and title is simply insufficient for patients to discern who is truly the appropriate doctor for their condition.
[0003] Currently, most online appointment platforms prioritize doctors based on positive reviews, patient volume, or simple departmental filtering, rarely addressing the issue of matching patient complaints with actual doctor capabilities. In obstetrics and gynecology, many patients rely solely on labels like "expert" or "chief physician" to secure appointments, only to end up seeing a renowned obstetrician for a gynecological endocrinology issue, or being referred to the most prestigious main hospital while overlooking the fact that nearby branch hospitals also have perfectly qualified subspecialists. This phenomenon not only leads to shortages at popular hospitals and overworked doctors, but also leaves valuable resources in other hospitals underutilized.
[0004] Existing medical recommendation methods largely mimic collaborative filtering or content recommendation algorithms in e-commerce, treating doctors as the subjects of evaluation and generating recommendation lists based on historical appointment behavior. However, obstetric and gynecological diseases are characterized by their timeliness, urgency, and privacy sensitivity: issues such as threatened miscarriage and suspected ectopic pregnancy require prompt and convenient treatment; non-invasive prenatal screening has strict gestational window requirements, and recommending a hospital where the equipment is fully booked for the day disrupts subsequent management processes; furthermore, the dynamic scheduling and cross-hospital visits between multiple hospitals are factors that are almost entirely ignored in existing recommendation logics, rendering the recommendations ineffective and failing to truly alleviate the difficulty of choosing medical care in a multi-hospital system. There is an urgent need for a recommendation method that can understand the semantics of obstetric and gynecological conditions and can real-time allocate multiple factors such as doctor specialties, road networks, and available appointments across multiple hospitals to better reflect the actual operational scenarios of these specialized hospitals. Summary of the Invention
[0005] To address the aforementioned technical problems, this invention provides an AI-powered doctor recommendation method for multi-campus operation scenarios in obstetrics and gynecology hospitals, comprising the following steps:
[0006] S1. Intent Recognition and Subspecialty Triage: Receive patient queries, determine whether a doctor is specified using a large language model. If not specified, filter the candidate subspecialty list from the hospital information system's synchronized table based on the multi-hospital area object identifier (OID) whitelist; call the large language model to select candidate subspecialties from the candidate subspecialty list and output the confidence level; perform dual threshold determination based on the set high confidence threshold and difference threshold, and finally locate one or two target subspecialties.
[0007] S2. Dual-channel doctor recall: Construct an orthogonal deduplication dual-channel recall link; Channel 1 accurately retrieves candidate doctors in the department-doctor mapping table based on the target subspecialty name, hospital whitelist, and director title restriction conditions; Channel 2 calls a large language model to extract obstetrics and gynecology-specific terms from patient queries and dialogue history, and uses the extracted specific terms to perform fuzzy matching retrieval in the specialty and introduction fields of the doctor details table, and obtains candidate doctors after truncation by double-key sorting by the number of hit words and academic impact factor; The results of the two channels are merged, deduplicated by doctor name and multi-turn dialogue exclusion set, and truncated to obtain the recall doctor list;
[0008] S3. Single-inference three-dimensional clinical matching calculation: Perform a three-segment structured rearrangement and simplification of the specialty text of each doctor in the recalled doctor list; input the rearranged specialty texts of multiple doctors into the large language model at once, and output the subspecialty score, disease expertise score and academic influence score of each doctor through single-inference. Add the sum of the above three-dimensional scores to the doctor's pre-stored academic influence factor to obtain the clinical matching degree of each doctor.
[0009] S4. Comprehensive Ranking and Refined Appointment Source Classification: Calculate a comprehensive ranking score based on the doctor's clinical matching degree, administrative position value, and initial granular availability, and truncate in descending order; for the truncated target doctor, query the appointment source interface for the next preset number of days concurrently by employee number and hospital area identifier, analyze the remaining number of appointments, and classify the target doctor into three availability levels based on the number of days since the earliest available appointment date and the number of remaining appointments.
[0010] S5. Construction and Output of Multi-City Redirect Links: Through a pre-defined mapping table of hospital OIDs and external registration platform institution IDs, the OID of the target doctor's hospital is converted, and a silent authorized redirect link with authorization callback is constructed by combining the doctor's employee ID; based on the patient query and the target doctor's department, the matching outpatient entrance is extracted and an outpatient registration link is generated; the list of target doctors, availability level, redirect link, and outpatient entrance are encapsulated as cards for streaming output.
[0011] The dual-threshold determination based on the set high confidence threshold and difference threshold described in S1 specifically includes:
[0012] Set the high confidence threshold to 0.8 and the difference threshold to 0.15;
[0013] When the confidence level of the candidate subspecialty ranked first is ≥ 0.8 and the difference between the first and second confidence levels is ≥ 0.15, one target subspecialty is identified;
[0014] When the first confidence level is ≥ 0.8 and the difference between the first and second confidence levels is < 0.15, two target subspecialties are identified.
[0015] When the first confidence level is less than 0.8, two target subspecialties are identified.
[0016] The specific logic behind the dual-channel doctor recall described in S2 is as follows:
[0017] The precise search criteria for Channel 1 include: excluding records with the department name "Yezi Clinic" and excluding employee IDs with a specified special business prefix;
[0018] The extraction rules for Channel 2 include: extracting 5 to 8 disease names, surgical procedure names, or symptom names as proper nouns, and disabling general verbs and general adjectives; truncating the search to the top 30 people, applying the hospital's whitelist but not excluding Yezi Clinic nodes, and excluding doctors already recalled by Channel 1;
[0019] After merging the two channels, the results from channel 1 will be retained first. After excluding those from the list of recommended doctors in multiple rounds, the results will be truncated to the top 40 in descending order of academic impact factor.
[0020] The three-stage structured rearrangement simplification and clinical matching calculation described in S3 specifically includes:
[0021] Rearrange the doctor's original specialty text into the format of "full text field of diseases specializing + full text field of subspecialty + brief introduction field truncated to 300 characters", and truncate the total number of characters to the maximum of 500 characters after rearsing;
[0022] A validity pre-check was performed on all recalled doctors. When all doctors had no subspecialty and no expertise text, the large language model inference was skipped and all doctors' three-dimensional scores were set to 0.
[0023] The output of the large language model is subjected to two-level character cleaning, including the removal of code block markers and the conversion of Chinese and English symbols. Then, a four-level degradation parsing mechanism is executed in sequence, from JSON serialization loading, array field extraction, object field extraction to regular expression matching extraction.
[0024] The concurrent query interface for scheduling number sources for a preset number of future days, and the number source classification described in S4, have the following specific features:
[0025] Redis is used as a cache for appointment source queries. The cache key contains the doctor's employee number, hospital area identifier, and the start and end dates of the query window. Only results with a successful query status are written to the cache.
[0026] The query scheduling adopts a two-layer concurrency control: the outer layer creates unlimited parallel tasks based on the doctor dimension, and the inner layer limits the number of HTTP requests in transit to the source interface through semaphores.
[0027] If the scheduled date is today and the current system time exceeds the scheduled end time, the available availability of the corresponding appointment slot will be forcibly set to 0.
[0028] The rules for classifying the three levels of availability are as follows: if the earliest available availability is 0-7 days from now and the remaining number is > 3, it is level one; if the earliest available availability is 0-7 days from now and the remaining number is ≤ 3, or if the earliest available availability is 8-14 days from now, it is level two; if the earliest available availability is > 14 days from now, it is level three.
[0029] The specific process for constructing multi-campus redirect links as described in S5 is as follows:
[0030] Before constructing the redirect link, three verification gates are executed sequentially: verifying whether the doctor's employee ID exists, verifying whether the hospital area OID exists, and verifying whether the hospital area OID is located in the preset Yangpu and Huangpu mapping table;
[0031] For records that pass verification, the hospital's OID is converted to the institution ID of the external registration platform according to the mapping table;
[0032] Use the employee ID and the converted institution ID to query doctor information on external platforms. If the query for the main hospital area returns empty, call the institution ID of the Yangpu branch to overwrite the original institution ID and trigger a fallback query.
[0033] The retrieved doctor ID, institution ID, and department ID parameters are URL encoded and embedded as a redirected Uniform Resource Identifier parameter in an OAuth2 authorization link with the snsapi_base scope.
[0034] The specific steps for extracting the matching outpatient portal and generating the outpatient registration link as described in S5 are as follows:
[0035] The outpatient information dictionary is subset-filtered based on the hospital district prefix in the query context;
[0036] The large language model is invoked to use patient queries, dialogue history, and the department name of the target doctor as context, and select no more than two names that completely match the target outpatient entrance from the filtered outpatient subset;
[0037] Extract the corresponding hospital institution ID based on the specific hospital area prefix characters of the selected outpatient name, and generate the corresponding link by querying the outpatient doctor ID on the external registration platform.
[0038] The formula for calculating the overall ranking score as described in S4 is: Overall Ranking Score = Clinical Matching Degree + Physician Administrative Position Value + Physician Availableness Rating Value × 0.01;
[0039] Furthermore, during the dual-channel doctor recall phase of S2, a coarse-grained number source query gate with fault tolerance is executed concurrently. The rule is: if there are remaining numbers in any hospital area, the doctor is retained; if there are no remaining numbers in either hospital area and the query interface of either hospital area returns an error, the doctor is retained.
[0040] During the execution of steps S1 to S5, the progress state frame and the multi-turn dialogue state maintenance mechanism are executed simultaneously:
[0041] During a single inference process in the S3 phase, a large language model request is executed through a background concurrent coroutine, and status text frames describing the calculation dimension of a single score are pushed to the client in a fixed cycle of 3 seconds in the foreground main thread.
[0042] After S5 output is complete, a single call to the large language model generates a consultation guide text with a word count threshold of 150 characters or less for additional push. At the same time, the recommendation intent containing the session ID derivation key and the list of recommended target doctors and departments are extracted, written to the persistent cache and passed to the next round of dialogue context.
[0043] This invention also includes a full-link observability recording step:
[0044] A shared instance timing frame stack is established throughout the process, and method-level decorators and inline code block context managers are used to record the stack-based net time consumption of each sub-step;
[0045] The net time is obtained by calculating the difference between the wall clock time and the accumulated wall clock time of the nested sub-steps when the stack exits, and its own wall clock time is added to the parent time frame stack.
[0046] In the final block of the main process, the step time distribution list generated based on the stack-based net time consumption and the jump link construction result containing the execution status of the three verification gates are bound to the global link tracing ID and uniformly written into the observation report.
[0047] Compared with the prior art, the beneficial effects of the present invention are as follows:
[0048] This invention can significantly reduce the number of patients going to the wrong department and requiring repeated referrals. For complex cases involving gestational diabetes and adnexal cysts, the system can locate hospitals and doctors that are qualified for both high-risk obstetric and gynecological minimally invasive surgeries in one step, avoiding the need for patients to repeatedly travel between obstetrics and gynecology departments.
[0049] This invention takes into account the patient saturation of similar doctors in different hospital districts when making recommendations. This approach effectively helps guide patients to less busy districts in non-emergency situations, improving the experience for pregnant women. As registration and consultation feedback data is continuously collected, this recommendation strategy can be further refined to adjust matching weights, leading to increasingly higher service accuracy and operational efficiency across the multi-district system. Attached Figure Description
[0050] Figure 1 This is a system architecture diagram of the present invention;
[0051] Figure 2 The flowchart for sub-algorithm 3;
[0052] Figure 3 The flowchart for sub-algorithm four. Detailed Implementation
[0053] The terms first, second, third, fourth, etc. (if present) in the specification, claims, and accompanying drawings of this invention are used to distinguish similar objects and are not necessarily used to describe a particular order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms include or have, and any variations thereof, are intended to cover a non-exclusive inclusion; for example, a process, method, system, product, or apparatus that includes a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0054] like Figure 1 This invention comprises eleven sub-algorithms, sequentially forming a recommendation pipeline of intent recognition → subspecialty triage → dual-channel recall → clinical matching → reschedulability grading → jump link generation → outpatient entrance recommendation → patient guide output, supplemented by two mechanisms: progress status frames and end-to-end observability. The end-to-end data flow is described as follows:
[0055] ① Main entry point and intent recognition (check_specified_name_doctor)
[0056] Input: Patient's natural language query, conversation history, and Red House institution ID (used to trigger Red House-specific logic).
[0057] Processing: A single LLM call determines whether the patient specified a doctor's name in the query and outputs the boolean flag has_specified_doctor.
[0058] If true → follow the designated doctor direct search branch: search the mapping table by doctor's name + hospital whitelist, remove duplicates (excluding doctors recommended in multiple rounds), create a card directly, skip sub-algorithms one to four, output the card and enter sub-algorithm nine (medical visit guide).
[0059] If false → Proceed to the general recommendation main link, passing down the query, dialogue history, and organization ID.
[0060] Output: Routing decision + original query, dialogue history → handed over to sub-algorithm 1.
[0061] ② Sub-algorithm 1: Candidate subspecialty acquisition (optional_departments)
[0062] Input: Red House organization ID (to trigger the Red House exclusive branch); no query required.
[0063] Processing: Perform DISTINCT on the HIS synchronized department-doctor mapping table to retrieve the department name, retrieve the subspecialties under the hospital area by the parent department number with a 5% prefix, exclude 13 non-clinical business departments from the blacklist, and filter by the hospital area whitelist (Yangpu, Huangpu).
[0064] Output: List of candidate subspecialties (e.g., [Gynecologic Oncology, Cervical and Uterine Center, Gynecologic Outpatient Clinic, Obstetric Outpatient Clinic, Breast Surgery, ...]) → handed over to sub-algorithm 2 as a candidate set for LLM triage.
[0065] ③ Sub-algorithm 2: LLM subspecialty triage + dual threshold judgment (select_suitable_departments + _validate_department_confidence)
[0066] Input: A list of candidate subspecialties generated by sub-algorithm 1; query, dialogue history.
[0067] Processing: A single LLM call selects up to two subspecialties from the candidate set as is, providing the reason and confidence; then, a double-threshold case with a high confidence threshold of 0.8 and a difference threshold of 0.15 is used to determine whether to finally locate one or two subspecialties.
[0068] Output: 1-2 subspecialties finally located (including reason and confidence tags) → handed over to sub-algorithm 3 as the orgName parameter for channel 1 department recall; their reason also serves as the department recommendation reason in the final output stage.
[0069] ④ Sub-algorithm 3: Dual-channel doctor recall (fetch_doctors + keyword_recall)
[0070] Input: Subspecialty located by sub-algorithm 2 (for channel 1); query, dialogue history (for LLM keyword extraction in channel 2); exclude_doctors list of recommended doctors from multiple rounds (from dialogue status); hospital whitelist.
[0071] deal with:
[0072] Channel 1 (Department Recall): Search the mapping table by subspecialty name + hospital whitelist, with additional exclusion for leaf clinic nodes + employee ID prefix of 60 / 61 / WN + filtering by director title, and merge employees with the same name; check the appointment source in parallel for each recalled doctor (keep gate: if there are appointments in any hospital, keep them; if there are no appointments but the interface is abnormal, retain them for fault tolerance), and create a doctor card.
[0073] Channel 2 (Keyword Recall): First, the LLM extracts 5-8 specialized terms in the field of obstetrics and gynecology (disease names / operative names / symptom names, disabling general verbs and adjectives) from the query and conversation history; then, using these terms, a LIKE search is performed on the doctor's profile and specialties, sorted by hit count + academic impact factor, and truncated to 30 doctors; finally, the mapping table is checked.
[0074] (Using the hospital's whitelist, not excluding Yezi Clinic) + Director filtering + Exclusion channel 1: After recalling doctors, additional doctors will be checked for appointment slots and cards in parallel.
[0075] Merging and deduplication: Results from both channels are deduplicated by doctor's name (channel 1 takes priority), then exclude doctors recommended in multiple rounds by exclude_doctors, and finally select the top 40 doctors in descending order of academic impact factor.
[0076] Output: List of candidate doctors (≤40 people, each doctor includes name, title, subspecialty, skill, academic impact factor, hospital OID, employee number, and initial granularity reducibility tag filled in during the keep gate stage) → handed over to sub-algorithm 4 for clinical matching.
[0077] ⑤ Sub-algorithm 4: Calculation of three-dimensional clinical matching degree in a single inference (_calculate_and_apply_clinical_matching + ClinicalMatcher)
[0078] Input: A list of candidate doctors generated by sub-algorithm 3 (≤40 people); query, dialogue history.
[0079] Processing: The `skill` field for each doctor is structurally rearranged and simplified (full text of expertise in specific diseases + full text of subspecialties + brief introduction truncated to 300 words, with a total limit of 500 words); validity pre-check (if all doctors have neither subspecialties nor specialties, skip the LLM and return 0 points); otherwise, a lightweight, fast model is called in a single operation to output all doctors' subspecialty scores (0-3), expertise in specific diseases scores (0-80), and academic influence scores (0-17); JSON is obtained after two levels of cleaning and four levels of degradation parsing; the doctor's pre-stored academic influence factor is superimposed on the LLM three-dimensional total score, and the results are backfilled into the doctor's database in descending order of the sum.
[0080] The clinical_matching_degree field.
[0081] Output: A list of candidate doctors carrying clinical_matching_degree → handed over to sub-algorithm 8 for comprehensive sorting.
[0082] ⑥ Sub-algorithm 8: Combined sorting and top 5 selection (_sort_doctors_by_score)
[0083] Input: The list of candidate doctors with clinical matching degree output by sub-algorithm 4; the administrative position value of the doctor object itself; the reducibility bookable filled in during the keep gate phase of sub-algorithm 3.
[0084] Processing: Sort by score = clinical matching degree + administrative position value + responsibility × 0.01 in descending order (the responsibility weight is deliberately set small, only for minor adjustments between candidates with the same score), and take the top 5; record these 5 in the recommendation history list (deduplicating and preserving order, with a maximum of 20) for subsequent rounds of anti-duplicate measures.
[0085] Output: The final recommendation is 5 doctors (each with complete fields: name, title, subspecialty, skill, administrative position value, academic impact factor, hospital OID, employee number, clinical matching degree, and initial granular reducibility) → and is simultaneously handed over to sub-algorithm 5 (refined appointment source classification) and sub-algorithm 6 (redirect link construction).
[0086] ⑦ Sub-algorithm 5: Three-tiered classification of appointment source query and resolvability (_query_appointment_source + _resolve_bookable)
[0087] Input: The employee IDs (employee_no) and hospital region OIDs (used to determine regionId) of the 5 doctors output by sub-algorithm 8; Redis cache.
[0088] Processing: First, check the Redis cache (key includes employee ID, hospital district, query window start and end dates, TTL 1 hour; if a match is found, skip the semaphore and HTTP); if no match is found, query the Huangpu and Yangpu hospital districts' appointment slots for the next 28 days in parallel under the semaphore concurrency limit; parse the remaining slots (prioritize available slots, if missing, subtract the number already booked from the total capacity), set slots for the current day's schedule and those past the end time of the current schedule to 0; classify slots into three tiers based on the earliest available date since today + remaining slots (1. Sufficient slots / 2. Available for immediate booking / 3. Available for future booking); only write successful results back to the cache (do not cache if the interface is abnormal so as to retry); retain slots if any hospital district has available slots, and retain slots even if there are no slots but the interface is abnormal, with fault tolerance.
[0089] Note: The keep gate of sub-algorithm 3 has already undergone a coarse-grained source query for filtering during the recall phase. In this phase, a refined three-tier classification and reducibility description are generated for the final 5 people.
[0090] Output: Each doctor's final bookable (1 / 2 / 3) and bookable_desc (if there are enough appointments, the nearest appointment can be made on month M and day D) → fill in the doctor's card → hand it over to the output stage for card display.
[0091] ⑧ Sub-algorithm 6: Automatic construction of Nari appointment registration redirect links (_batch_build_jump_links + _build_jump_link)
[0092] Input: The employee IDs and hospital OIDs of the 5 doctors output by sub-algorithm 8; the mapping table of hospital OID → Nali organId (Yangpu → 1011811, Huangpu → 1011807); Nali doctor query interface; WeChat OAuth2 configuration.
[0093] Processing: For each doctor, pass through three checkpoints in sequence (if the employee ID is missing / the hospital's OID is missing / the hospital's OID is not in the mapping table, record the reason for failure and skip the checkpoint); after passing, map the hospital's OID to the Nali organId, and search for the Nali doctor using the employee ID + organId. If the doctor cannot be found in the main hospital, use the Yangpu organId as a fallback for searching; concatenate the Nali WeChat webpage authorization page URL, and then embed it as the redirect_uri into the WeChat OAuth2 silent authorization URL (scope=snsapi_base); the construction results (success / skipped / failed / abnormal and failure reason) are written into the observation report redirect link construction result table.
[0094] Output: Jump URL for each doctor (Nari appointment registration link) + Build result observation record → Backfill into doctor card → Hand over to output stage; Observation record is handed over to sub-algorithm 10.
[0095] ⑨ Sub-algorithm 7: Outpatient entrance recommendation (_add_outpatient_recommendation_if_needed, exclusive to Red House Hospital)
[0096] Input: Hospital name (including campus information, used for outpatient prefix filtering); query, dialogue history; departments of 5 doctors output by sub-algorithm 8 (used for LLM matching of relevant outpatient clinics); outpatient information dictionary.
[0097] Processing: Filter the outpatient clinic set by hospital district information in the hospital name (Yangpu → (Yang) prefix outpatient clinics, Huangpu → (Huang) prefix outpatient clinics); LLM selects up to 2 best matching outpatient clinic entrances from the filtered outpatient clinic set based on dialogue history, query, and recommended doctor departments (prioritizing those related to or complementary to doctor departments); determine the hospital district organId by the outpatient clinic name prefix, extract the outpatient clinic's did, query the outpatient clinic's doctorId, and generate an outpatient registration link.
[0098] Output: 2 outpatient entry cards (is_outpatient=True, including outpatient name, registration link, etc.) → Passed to the output stage and appended after the doctor card.
[0099] ⑩ Output stage (SSE streaming push)
[0100] Input: Department reason from sub-algorithm 2; list of 5 doctors from sub-algorithm 8; bookable / bookable_desc backfilled from sub-algorithm 5; jump_url backfilled from sub-algorithm 6; outpatient card from sub-algorithm 7; status bar closed frame.
[0101] Processing: The recommendation is processed in the following order: Recommendation reason by department (streaming text) → Doctor list (streaming text) → 5 doctor cards (streaming push) → Outpatient card → Status bar closing frame, and then streamed to the front end via SSE; after the recommendation is completed, the doctor_recommend_completed flag is set, the pending feedback status is set, and the recommendation history is written.
[0102] Output: Streaming messages are pushed to the front end; Sub-algorithm 9 (generating the medical guide) and Sub-algorithm 11 (outputting the observation report) are triggered simultaneously.
[0103] ⑩ Sub-algorithm 9: Generate Medical Guide and Maintain Multi-Turn Dialogue State (_generate_medical_guide)
[0104] Input: query, conversation history, recommended doctor departments; session_id (used for intent persistence).
[0105] Processing: A single LLM call generates a patient guide of ≤150 characters (including pre-visit preparation, process prompts, and a note of precautions).
[0106] The recommendation intent is persisted to Redis (the key is derived from session_id) to ensure that the doctor's recommendation intent is maintained in the second round of dialogue; the recommendation history and the status of pending feedback are recorded; the background asynchronously generates a summary and updates the short-term memory (without blocking the front-end response).
[0107] Output: The consultation guide text (new bubble stream push) is sent to the front end; the persistent intent state + recommendation history is sent to the next round of dialogue (as the basis for exclude_doctors and intent retention).
[0108] ⑫ Sub-algorithm 11: End-to-end observability and time consumption distribution (_dump_perf_to_observe, finally block)
[0109] Input: The stacked net time record throughout the entire process, self._perf_records (generated by each sub-algorithm using the @track_time decorator and the _track_block context manager to share the timing frame stack); the jump link construction result of sub-algorithm six.
[0110] Processing: In the finally block of recommend_doctor, the net time of each step (excluding the timed sub-steps of the outer wall clock, and nested steps are not counted repeatedly) is summarized into a recommended process time distribution table; the jump link construction results are summarized into a jump link construction result table; the process is silent when it fails, without affecting the main process.
[0111] Output: Observation report (bound to session_id by trace_id) → for operations and maintenance to troubleshoot issues such as excessively long waiting times or empty appointment registration links by case.
[0112] The following is a detailed description of each sub-algorithm:
[0113] Sub-algorithm 1: Obtaining the Hospital Whitelist Candidate Departments Based on HIS Synchronized Data
[0114] Based on the HIS synchronization mapping table of the Red House Hospital, a list of candidate subspecialties for LLM triage is obtained to ensure that all candidate subspecialties are located in hospital districts (Yangpu and Huangpu) that have established a registration link with Nali, thus preventing LLMs from selecting departments in hospital districts without doctors or registration links.
[0115] Perform a DISTINCT operation on the department-doctor mapping table to retrieve the department name, and then apply three layers of filtering:
[0116] 1. Parent Department Number Prefix Filtering: Only subspecialty rows under the hospital area are selected, with the granularity being subspecialty (such as gynecologic oncology), rather than leaf outpatient nodes.
[0117] 2. Blacklist Exclusion: Exclude non-clinical departments such as the Medical Insurance Office, Outpatient Office, Medical Affairs Department, Inpatient Operating Room, Preventive Health Care Department, Day Surgery Center, Day Chemotherapy Center, Clinical Research Center, Laboratory Department, Outpatient Operating Room, Intensive Care Unit, and Blood Transfusion Department. These departments do not participate in doctor referral and triage.
[0118] 3. Campus whitelist filtering: The campus OID must be within the Yangpu and Huangpu whitelists to ensure that all candidate subspecialties are within campuses that have established a connection with the Nali registration system.
[0119] When adding a new non-clinical department, the blacklist must be maintained simultaneously; when adding a new hospital area, the hospital whitelist and OID→organId mapping must be updated simultaneously, otherwise the redirect link will return empty because the OID is not in the mapping table.
[0120] Sub-algorithm 2: LLM triage and dual threshold determination for obstetrics and gynecology subspecialties
[0121] From the candidate subspecialties, the LLM selects up to two most suitable subspecialties based on the patient's dialogue history and current query, and then determines whether to finally locate one or two subspecialties based on the confidence distribution.
[0122] LLM Department Selection
[0123] The general inference model is invoked, with the following constraints: Department names must be selected directly from the candidate subspecialty list without modification; a maximum of two departments must be selected based on priority, from highest to lowest; a recommendation reason of no more than 20 words must be provided for each department; and the requirements must be general.
[0124] (If you are looking for a doctor to recommend,) the confidence level should be less than 0.6; do not recommend the emergency department if the patient has not clearly expressed an emergency situation.
[0125] Dual threshold case determination
[0126] The number of subspecialties is determined by a dual threshold: a high confidence threshold of 0.8 and a difference threshold of 0.15 (maximum 2).
[0127] Case 1: Top1 ≥ 0.8 and Top1−Top2 ≥ 0.15 → Identify one subspecialty. Symptoms clearly point to a single subspecialty (e.g., typical uterine fibroids → gynecologic oncology).
[0128] Case 2: Top1 ≥ 0.8 and Top1−Top2 < 0.15 → Locate 2 subspecialties. Multiple subspecialties are highly related (e.g., HPV infection → Cervical and Uterine Center + Gynecologic Oncology).
[0129] Case 3: Top1 < 0.8 → Identify 2 subspecialties and mark them as low confidence. Symptoms are vague (e.g., abdominal pain without other details), requiring multi-subspecialty coverage.
[0130] Sub-algorithm 3: Dual-channel doctor recall (department recall + keyword recall)
[0131] like Figure 2 In response to the fact that obstetric and gynecological diseases often involve multiple subspecialties, a dual-channel recall method is adopted: Channel 1 is precise recall by subspecialty, and Channel 2 is cross-subspecialty recall by extracting obstetric and gynecological domain-specific terms using LLM. The two channels are orthogonal to remove duplicates, avoid duplicate query sources, and improve recommendation coverage.
[0132] Channel 1: Departmental Recall
[0133] Search the mapping table by (employee name, subspecialty name, hospital whitelist), with four additional filters:
[0134] 1. Exclude leaf clinic nodes: Department names are not in leaf clinics such as gynecology clinics and obstetrics clinics, so that department matching is closed by subspecialty and avoids matching to leaf clinics.
[0135] 2. Exclusion of employee IDs with special prefixes: Employee IDs with prefixes 60 / 61 / WN are excluded. These employee IDs are for specific business purposes and are not included in the recommendation process.
[0136] 3. Campus Whitelist: The campus OID must be on the Yangpu or Huangpu whitelist.
[0137] 4. Chief Physician Title Filtering: Only doctors whose titles include "Chief Physician" (including Chief Physician and Associate Chief Physician) are retained, ensuring that senior doctors are recommended.
[0138] After recall, employees with the same name are merged, and the number of available slots (keep gate) are queried in parallel and cards are created.
[0139] Channel 2: Keyword Recall
[0140] Keyword Extraction: Utilize a lightweight and fast model to extract 5-8 domain-specific terms from patient descriptions for doctor retrieval. Only extract disease names (e.g., HPV infection, uterine fibroids), surgical procedure names (e.g., laparoscopic surgery), and symptom names (e.g., menstrual irregularities, lower abdominal pain); general verbs / adjectives (e.g., treatment, surgery, examination, seeing a doctor) are strictly prohibited, as these terms lack distinctiveness. Extract one synonym / near-synonym each to improve the hit rate.
[0141] Keyword recall process: Perform LIKE searches on the doctor's profile and specialties, and OR relationships for multiple keywords; Calculate the number of different keywords hit for each doctor using a Python layer; Sort by (number of hits in descending order, academic impact factor in descending order) using a double-keyword sorting algorithm, truncating to 30 doctors; Batch query the mapping table (using the hospital's whitelist, but not excluding the Yezi Clinic node, as keyword recall is based on doctors' expertise across departments, the department they are registered in should not affect the recall); Filter by chief physician title + merge doctors with the same name; After excluding doctors already recalled through channel 1, create appointment slots for the incremental doctors.
[0142] Two-channel connection and deduplication
[0143] Channel 2 is executed after Channel 1 is completed, and the exclusion set ensures that the two channels are orthogonal. After merging, duplicates are removed by doctor name, with priority given to those from Channel 1; then, they are sorted in descending order by academic impact factor, and the top 40 are selected for clinical matching (expanding from 20 to 40 to avoid premature truncation of doctors retrieved by keyword in the Top 20 stage due to academic factor sorting).
[0144] Doctors have been recommended to rule out (multiple rounds to prevent duplicates).
[0145] After recalling and deduplicating in Channel 1, the list of doctors recommended in multiple rounds of dialogue is excluded by doctor's name. This exclusion set is simultaneously added to the exclusion set in Channel 2, forming a cross-round anti-duplicate recall.
[0146] Sub-algorithm 4: Calculation of 3D Clinical Matching Degree in a Single Inference (Obstetrics and Gynecology Adaptation)
[0147] like Figure 3 In a local single-instance large model deployment scenario, a single LLM inference call is used to simultaneously complete the 3D matching degree scoring of the candidate red house doctor list, eliminating the fixed overhead of the original two serial inferences and GPU concurrency competition, and is combined with the red house structuring.
[0148] Specialty text reflow simplifies and further reduces the input token.
[0149] The three-dimensional scoring definition is shown in Table 1.
[0150] Table 1
[0151]
[0152] Red House Structured Specialty: Text Reflow and Simplification
[0153] The Red House skill structure is "Subspecialty: X. Introduction: Y. Specialized Diseases: Z". The disease matching signal is concentrated at the end Z. Simply truncating by characters will cut off Z and lose the disease signal. The rearrangement is "Specialized Diseases: Z (preserve the full text) + Subspecialty: X (preserve) + Introduction: Y (truncated to 300 characters)", and the entire rearrangement is then truncated to 500 characters. The introduction segment contributes little to disease matching but accounts for a large part of the text, and truncating it can significantly reduce the input tokens. The rearrangement is only used for clinical matching of LLM input and does not modify it.
[0154] The doctor.skill itself will still use the original skill for front-end card display.
[0155] LLM Invocation and Degradation
[0156] The system utilizes a lightweight and fast model and disables the thinking mode to accelerate reasoning. User prompts employ a five-part structure (role / constraint / input data / algorithm logic / output requirements), using XML tags to enclose the boundaries between dialogue history and doctor information. Prompt constraints include: a score must be assigned to each doctor (if information is missing, that dimension is recorded as 0, without omission); only the top 10 doctors are returned, sorted by their total scores across the three dimensions; the output is pure JSON.
[0157] Degradation path: When all doctors have neither valid subspecialties nor valid specialties, return all 0 three-dimensional scores directly, skip the LLM call, and avoid meaningless reasoning; return empty scores in case of any exception or parsing failure, without throwing an exception, to ensure that the upstream link is not interrupted.
[0158] Output parsing employs a two-level cleaning process (removing Markdown code block markers and converting Chinese quotation marks to English) + a four-level degradation parsing process (direct json.loads → array extraction → object extraction → regular expression fallback) to ensure that LLM output format deviations can still be parsed.
[0159] Comprehensive ranking
[0160] Above the LLM ranking results, the doctor's pre-stored academic impact factor is added as a fourth bonus, and then the total is added back to the doctor's clinical matching degree field in descending order.
[0161] Sub-algorithm 5: Real-time query of available slots and three-tiered availability classification
[0162] The system queries appointment availability at both campuses of the Red House Hospital in real time, categorizing availability into three levels (sufficient availability / available for immediate appointment / available for future appointment), allowing recommendations to be directly converted into appointments. Query time is optimized through Redis caching and dual-layer concurrency control.
[0163] Number source query and response analysis
[0164] The appointment slot query calls an internal interface by doctor's employee ID + hospital regionId, and the query window displays the next 28 days starting today. Response parsing: The remaining slot field prioritizes the number of available slots; if missing, it degrades the total capacity by subtracting the number already reserved; it calculates the maximum number of remaining slots per day, the total number of remaining slots, the number of days with available slots, and the earliest date with available slots.
[0165] Same-day scheduling overdue filtering: If the scheduling date is today and the current time has exceeded the scheduling end time, the availability is set to 0 to avoid recommending overdue scheduling.
[0166] Responsibility three-tier classification
[0167] The ranking is based on two dimensions: the number of days since the earliest available appointment date plus the number of remaining appointment slots, as shown in Table 2.
[0168] Table 2
[0169]
[0170] Redis caching mechanism
[0171] The results of the appointment booking query are cached in Redis. The cache key includes the employee ID, hospital district, and the start and end dates of the query window. The TTL is 1 hour. Design considerations:
[0172] Version number: The cache key prefix contains the version number. When the parsing logic / query window changes, upgrading the version will invalidate the old cache.
[0173] Natural expiration across days: The cached key contains start and end dates. When the start and end dates change on a new day, a new key is generated, and no manual clearing is required.
[0174] Only cache successful results: Only cache successful queries (with or without a number), and do not cache abnormal results so that they can be retried next time, avoiding the caching of instantaneous failures for 1 hour.
[0175] Silent degradation: When Redis encounters an anomaly, it silently degrades to a direct query without affecting the main process.
[0176] Hitting the cache skips concurrency and network: hitting the cache returns directly, skipping semaphores and HTTP, and the time spent on repeated queries (across users / multiple rounds) is close to 0.
[0177] Two-layer concurrency control
[0178] The outer layer uses parallel scheduling for multi-doctor appointment queries (one task per doctor, with no upper limit; a single doctor's failure does not interrupt the overall process); the inner layer uses semaphores to limit the number of concurrent HTTP requests to the appointment interface, and cache hits are not counted as concurrent requests.
[0179] Keep gate
[0180] Parallel query of appointment slots at Huangpu and Yangpu campuses; if an appointment is available at either campus, the doctor is retained; if there are no appointment slots available but there is an interface error, the doctor is retained to prevent all doctors from being filtered out due to interface errors.
[0181] Sub-algorithm 6: Automatic Construction of Nari Appointment Registration Redirect Links
[0182] To ultimately recommend doctors, we batch-build Nari appointment registration redirect links (WeChat OAuth2 silent authorization), creating a closed loop between recommendation and appointment. We also record the link building results for each doctor through observation reports to facilitate online screening.
[0183] Three gates
[0184] The redirect link is constructed and validated in sequence through three gates: Gate 1 checks if the employee ID is missing; Gate 2 checks if the hospital area OID is missing; Gate 3 checks if the hospital area OID is in the mapping table (only Yangpu and Huangpu are configured). If any gate fails, the reason for failure is recorded and the process is skipped.
[0185] OID→organId mapping and Yangpu's safety net
[0186] Map the OIDs of the internal branches of the Red House to Nali organIds (Yangpu → 1011811, Huangpu → 1011807), and search for Nali doctors by employee ID + organId. If the doctor cannot be found in the main branch, use the Yangpu organId as a fallback to search, covering cross-branch outpatient scenarios.
[0187] WeChat OAuth2 URL concatenation
[0188] The first-level URL is the Nari WeChat webpage authorization page, with parameters including doctor ID, institution ID, department ID, department name, etc. After URL encoding, it is embedded as the redirect_uri in the WeChat OAuth2 authorization URL, scope=snsapi_base for silent authorization, which does not require manual confirmation from the patient.
[0189] Batch construction and observation
[0190] Iterate through the recommended doctors to build a batch of redirect links, and write the results (success / skipped / failed / abnormal and specific reasons) into the observation report. When encountering an empty appointment registration link online, you can directly check the observation report to determine whether it is due to missing employee ID, institution OID not being in the mapping table, doctor not found in the database, or interface error.
[0191] Sub-algorithm 7: Outpatient Entrance Recommendation (Matching Hospital District Tier with LLM)
[0192] The Red House has a unique logic: adding outpatient entrance cards (such as (Yang) Gynecology Outpatient Clinic and (Huang) Obstetrics Outpatient Clinic) after the doctor's card to provide patients with more granular access to medical care.
[0193] process
[0194] 1. Obtain the outpatient information dictionary.
[0195] 2. Filter outpatient names by hospital district: If the hospital name contains Yangpu, filter outpatients with the prefix "(Yang); if it contains Huangpu, filter outpatients with the prefix "(Huang); otherwise, do not filter.
[0196] 3. LLM Clinic Selection: A lightweight and fast model selects up to two of the most matching clinic entries based on dialogue history, user queries, and recommended doctor departments. It prioritizes clinics that are related to or complementary to the doctor departments and only returns clinic names that match exactly.
[0197] 4. Determining the hospital's organId: The hospital's organId is determined based on the prefix of the outpatient name (for example, if the prefix is "Yang", the organId is taken from Yangpu; if the prefix is "Huang", the organId is taken from Huangpu).
[0198] 5. Outpatient registration link generation: Extract the outpatient nali did, query the outpatient doctorId, generate the outpatient registration link, and append the outpatient registration card to the recommendation list.
[0199] Sub-algorithm 8: Generation of Comprehensive Ranking and Recommendation Results
[0200] The overall sorting is done in descending order using the following formula:
[0201] Ranking Score = Clinical Match + Administrative Position Value + Scheduleability × 0.01
[0202] Clinical match is calculated using a three-dimensional LLM score plus a pre-stored academic impact factor for the physician candidate; administrative position value is derived from the administrative position code in the physician details table; reschedulability is calculated using a three-tiered appointment availability rating (0 or empty indicates unreservable). The reschedulability weight coefficient is intentionally set to 0.01, serving only as a fine-tuning tiebreaker between candidates with the same clinical match, to prevent reschedulability from overriding clinical match.
[0203] Quantity Limits and Historical Records
[0204] After sorting, the top 5 are selected and recorded in the recommendation history list (duplicates are removed while maintaining order, with a maximum of 20) to prevent duplicate recommendations in multi-turn conversations.
[0205] Output mode
[0206] The Red House (a website / company name) defaults to a card-based mode: sequentially pushing the reasons for department recommendations, a list of doctors, and doctor cards (including fields such as name, title, department, subspecialty, hospital name, skill, administrative position value, academic impact factor, responsibility, responsibility description, hospital OID, employee ID, and jump links), in a streaming output. It can be switched to Markdown text mode via configuration (LLM generates structured JSON → local Markdown template rendering).
[0207] Sub-algorithm 9: Patient Guide Generation and Multi-Turn Dialogue State Maintenance
[0208] Medical treatment guide generation
[0209] The system uses a general inference model to generate a patient guide of no more than 150 characters, including pre-visit preparation (documents, medical records, etc.), consultation process tips, and a brief note. After generation, a new pop-up push notification is initiated, and access logs are saved.
[0210] Intending to maintain a state awaiting feedback
[0211] Intent persistence: Write to Redis (key derived from session_id), consistent across coroutines, to ensure that the doctor's recommendation intent is maintained in the second round.
[0212] Exit Keyword Clearing: When exit is detected, keywords such as "stop exiting," "stop changing topics," "no longer needed," or "calculate" are cleared from the recommended intent.
[0213] Pending Feedback Status: Set a "Pending Feedback" flag for recommendations and a list of recently recommended departments, and record recommendation history.
[0214] Completed: Mark as completed for later dialogue consideration.
[0215] Background summary updates asynchronously
[0216] First, save the access log and obtain the message_id (without waiting for digest generation to avoid blocking the frontend response). Then, generate the digest asynchronously and update the short-term memory. The background digest task is executed serially to ensure the correct memory update order.
[0217] Sub-algorithm 10: Progress status frames and the Little Red character
[0218] During the approximately 18-second recommendation wait, the patient is continuously aware of the system's progress through yield backend status notification frames at each stage; the status bar is closed by a status bar closing frame before the streaming recommendation card. The character name in the Red House environment is Xiao Hong.
[0219] Red House Path Status Frame Sequence
[0220] Sequence frame text coverage stage
[0221] Xiao Hong is recommending doctors for you... Check with a specific doctor + Query the path to a specific doctor
[0222] 2. Xiaohong is helping you find a suitable department... Get candidate subspecialties + Department selection
[0223] 3. We have located you to {subspecialty} and are currently searching for doctors in this department... Channel 1 Department Recall + Channel 2 Keyword Recall
[0224] 4. We have initially identified {N} {subspecialty} physicians and are analyzing their clinical fit one by one... ~9s Clinical Matching LLM Call
[0225] 5. We are currently compiling the recommended results to provide you with access to the appointment booking channel... Sorting + Link Building
[0226] 6. Matching you with a suitable outpatient entrance... Outpatient Entrance Recommendation (Red House Exclusive)
[0227] 7. Status bar closed before frame recommendation results.
[0228] Clinical matching phase rotating state frames
[0229] The clinical matching phase is a single blocking LLM call (approximately 9 seconds), executed concurrently in the background via `asyncio.create_task`, with a frame rotating every 3 seconds: the first frame is sent immediately (including the number of doctors and subspecialties), followed by 4 frames describing subspecialty fit analysis, comparison of specialty diseases, academic influence assessment, and overall calculation progress. The mechanism waits for the clinical matching task to complete or time out; if it times out, it switches to the next frame; if the task completes, it stops. Timeouts do not cancel the task, and clinical matching continues in the background. If a task encounters an error, it is re-thrown; if the generator is canceled, the background task is canceled to prevent orphan LLM calls.
[0230] Sub-algorithm 11: End-to-End Observability and Time Consumption Distribution
[0231] Write the time consumption of each node in the recommendation process and the results of the jump link construction into the observation report. If the recommendation wait is too long or the appointment registration link is empty, you can directly check the observation report of the corresponding trace_id to locate the problem.
[0232] Stack-based net elapsed time timing
[0233] Two methods are used: method-level timing decorator and inline code block timing context manager. Both share the instance timing frame stack and record the net timeout (the outer wall clock minus the wall clock of the internal timed sub-steps): a frame is pushed on when entering and popped on exit. The net timeout = wall clock timeout - the accumulated wall clock timeout of the internal sub-steps, and the wall clock timeout of the current frame is added to the parent frame so that the parent frame can deduct the timeout of the current frame.
[0234] Therefore, nested calls are no longer counted repeatedly, and the sum of the net time of all steps is the recommended process's active time. The proportion in the observation report will not be amplified by nested repeated counting. The logs simultaneously print the wall clock and net time for easy troubleshooting.
[0235] Observation report content
[0236] The output of the finally block in the recommended main flow consists of two parts:
[0237] Recommended process time distribution: name of each step, net time, percentage of total active time, and total active time.
[0238] The jump link construction results include: each doctor's employee ID, institution OID, mapped organId, result (success / skipped / failed / abnormal), and reason for failure.
[0239] It remains silent upon failure, without affecting the main process.
[0240] The above embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. 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. Such 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.
Claims
1. An AI doctor recommendation method for multi-site operation scenarios in obstetrics and gynecology hospitals, characterized in that, Includes the following steps: S1. Intent Recognition and Subspecialty Triage: Receive patient queries and determine whether a doctor is specified through a large language model. If not specified, a candidate subspecialty list is obtained by filtering from the hospital information system synchronization table based on the multi-hospital area identifier (OID) whitelist. The large language model is invoked to select candidate subspecialties from the candidate subspecialty list and output the confidence level. Based on the set high confidence threshold and difference threshold, a dual threshold judgment is performed to finally locate one or two target subspecialties. S2. Dual-channel doctor recall: Construct an orthogonal deduplication dual-channel recall link; Channel 1 accurately retrieves candidate doctors in the department-doctor mapping table based on the target subspecialty name, hospital whitelist, and director title restriction conditions; Channel 2 calls a large language model to extract obstetrics and gynecology-specific terms from patient queries and dialogue history, and uses the extracted specific terms to perform fuzzy matching retrieval in the specialty and introduction fields of the doctor details table, and obtains candidate doctors after truncation by double-key sorting by the number of hit words and academic impact factor; The results of the two channels are merged, deduplicated by doctor name and multi-turn dialogue exclusion set, and truncated to obtain the recall doctor list; S3. Single-inference three-dimensional clinical matching calculation: Perform a three-segment structured rearrangement and simplification of the specialty text of each doctor in the recalled doctor list; input the rearranged specialty texts of multiple doctors into the large language model at once, and output the subspecialty score, disease expertise score and academic influence score of each doctor through single-inference. Add the sum of the above three-dimensional scores to the doctor's pre-stored academic influence factor to obtain the clinical matching degree of each doctor. S4. Comprehensive Ranking and Refined Appointment Source Classification: Calculate a comprehensive ranking score based on the doctor's clinical matching degree, administrative position value, and initial granular availability, and truncate in descending order; for the truncated target doctor, query the appointment source interface for the next preset number of days concurrently by employee number and hospital area identifier, analyze the remaining number of appointments, and classify the target doctor into three availability levels based on the number of days since the earliest available appointment date and the number of remaining appointments. S5. Construction and output of multi-hospital area redirect links: Through the preset mapping table of hospital area OID and external registration platform institution ID, the OID of the target doctor's hospital area is converted, and a silent authorized redirect link with authorization callback is concatenated with the doctor's employee number; Based on the patient's query and the department of the target doctor, extract the matching outpatient portal and generate an outpatient registration link; The list of target doctors, availability level, redirect links, and clinic entrances are packaged into cards and streamed.
2. The recommended method according to claim 1, characterized in that, The dual-threshold determination based on the set high confidence threshold and difference threshold described in S1 specifically includes: Set the high confidence threshold to 0.8 and the difference threshold to 0.15; When the confidence level of the candidate subspecialty ranked first is ≥ 0.8 and the difference between the first and second confidence levels is ≥ 0.15, one target subspecialty is identified; When the first confidence level is ≥ 0.8 and the difference between the first and second confidence levels is < 0.15, two target subspecialties are identified. When the first confidence level is less than 0.8, two target subspecialties are identified.
3. The recommended method according to claim 1, characterized in that, The specific logic behind the dual-channel doctor recall described in S2 is as follows: The precise search criteria for Channel 1 include: excluding records with the department name "Yezi Clinic" and excluding employee IDs with a specified special business prefix; The extraction rules for Channel 2 include: extracting 5 to 8 disease names, surgical procedure names, or symptom names as proper nouns, and disabling general verbs and general adjectives; truncating the search to the top 30 people, applying the hospital's whitelist but not excluding Yezi Clinic nodes, and excluding doctors already recalled by Channel 1; After merging the two channels, the results from channel 1 will be retained first. After excluding those from the list of recommended doctors in multiple rounds, the results will be truncated to the top 40 in descending order of academic impact factor.
4. The recommended method according to claim 1, characterized in that, The three-stage structured rearrangement simplification and clinical matching calculation described in S3 specifically includes: Rearrange the doctor's original specialty text into the format of "full text field of diseases specializing + full text field of subspecialty + brief introduction field truncated to 300 characters". After rearrangement, the total number of characters is truncated to the maximum of 500 characters. A validity pre-check was performed on all recalled doctors. When all doctors had no subspecialty and no expertise text, the large language model inference was skipped and all doctors' three-dimensional scores were set to 0. The output of the large language model is subjected to two-level character cleaning, including the removal of code block markers and the conversion of Chinese and English symbols. Then, a four-level degradation parsing mechanism is executed in sequence, from JSON serialization loading, array field extraction, object field extraction to regular expression matching extraction.
5. The recommended method according to claim 1, characterized in that, The concurrent query interface for scheduling number sources for a preset number of future days, and the number source classification described in S4, have the following specific features: Redis is used as a cache for appointment source queries. The cache key contains the doctor's employee number, hospital area identifier, and the start and end dates of the query window. Only results with a successful query status are written to the cache. The query scheduling adopts a two-layer concurrency control: the outer layer creates unlimited parallel tasks based on the doctor dimension, and the inner layer limits the number of HTTP requests in transit to the source interface through semaphores. If the scheduled date is today and the current system time exceeds the scheduled end time, the available availability of the corresponding appointment slot will be forcibly set to 0. The rules for classifying the three levels of availability are as follows: if the earliest available availability is 0-7 days from now and the remaining number is > 3, it is level one; if the earliest available availability is 0-7 days from now and the remaining number is ≤ 3, or if the earliest available availability is 8-14 days from now, it is level two; if the earliest available availability is > 14 days from now, it is level three.
6. The recommendation method according to claim 1, characterized in that, The specific process for constructing multi-campus redirect links as described in S5 is as follows: Before constructing the redirect link, three verification gates are executed sequentially: verifying whether the doctor's employee ID exists, verifying whether the hospital area OID exists, and verifying whether the hospital area OID is located in the preset Yangpu and Huangpu mapping table; For records that pass verification, the hospital's OID is converted into the institution ID of the external registration platform according to the mapping table; Use the employee ID and the converted institution ID to query doctor information on external platforms. If the query for the main hospital area returns empty, call the institution ID of the Yangpu branch to overwrite the original institution ID and trigger a fallback query. The retrieved doctor ID, institution ID, and department ID parameters are URL encoded and embedded as a redirected Uniform Resource Identifier parameter in an OAuth2 authorization link with the snsapi_base scope.
7. The recommended method according to claim 1, characterized in that, The specific steps for extracting the matching outpatient portal and generating the outpatient registration link as described in S5 are as follows: The outpatient information dictionary is subset-filtered based on the hospital district prefix in the query context; The large language model is invoked to use patient queries, dialogue history, and the department name of the target doctor as context, and select no more than two names that completely match the target outpatient entrance from the filtered outpatient subset; Extract the corresponding hospital institution ID based on the specific hospital area prefix characters of the selected outpatient name, and generate the corresponding link by querying the outpatient doctor ID on the external registration platform.
8. The recommended method according to claim 1, characterized in that, The formula for calculating the overall ranking score as described in S4 is: Overall Ranking Score = Clinical Matching Degree + Physician Administrative Position Value + Physician Availableness Rating Value × 0.01; Furthermore, during the dual-channel doctor recall phase of S2, a coarse-grained number source query gate with fault tolerance is executed concurrently. The rule is: if there are remaining numbers in any hospital area, the doctor is retained; if there are no remaining numbers in either hospital area and the query interface of either hospital area returns an error, the doctor is retained.
9. The recommended method according to claim 1, characterized in that, During the execution of steps S1 to S5, the progress state frame and the multi-turn dialogue state maintenance mechanism are executed simultaneously: During a single inference process in the S3 phase, a large language model request is executed through a background concurrent coroutine, and status text frames describing the calculation dimension of a single score are pushed to the client in a fixed cycle of 3 seconds in the foreground main thread. After S5 output is complete, a single call to the large language model generates a consultation guide text with a word count threshold of 150 characters or less for additional push. At the same time, the recommendation intent containing the session ID derivation key and the list of recommended target doctors and departments are extracted, written to the persistent cache and passed to the next round of dialogue context.
10. The recommended method according to any one of claims 1 to 9, characterized in that, It also includes the end-to-end observability recording step: A shared instance timing frame stack is established throughout the process, and method-level decorators and inline code block context managers are used to record the stack-based net time consumption of each sub-step; The net time is obtained by calculating the difference between the wall clock time and the accumulated wall clock time of the nested sub-steps when the stack exits, and its own wall clock time is added to the parent time frame stack. In the final block of the main process, the step time distribution list generated based on the stack-based net time consumption and the jump link construction result containing the execution status of the three verification gates are bound to the global link tracing ID and uniformly written into the observation report.