Datasets:
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/incomplete/task_001/role_agents/facility_utilities.json +15 -0
- data/incomplete/task_001/role_agents/hydrology_lead.json +15 -0
- data/incomplete/task_001/role_agents/public_health.json +15 -0
- data/incomplete/task_001/role_agents/shelter_operations.json +15 -0
- data/incomplete/task_001/role_agents/structural_safety.json +15 -0
- data/incomplete/task_001/role_agents/volunteer_corps.json +15 -0
- data/incomplete/task_001/tasks/run_one.py +1396 -0
- data/incomplete/task_002/role_agents/air_traffic_authority.json +15 -0
- data/incomplete/task_002/role_agents/flight_operations_safety.json +15 -0
- data/incomplete/task_002/role_agents/logistics_support_liaison.json +15 -0
- data/incomplete/task_002/role_agents/marine_meteorological_service.json +15 -0
- data/incomplete/task_002/role_agents/medical_receiving_facility.json +15 -0
- data/incomplete/task_002/tasks/run_one.py +1396 -0
- data/incomplete/task_003/role_agents/acoustic_consultant.json +15 -0
- data/incomplete/task_003/role_agents/commercial_manager.json +15 -0
- data/incomplete/task_003/role_agents/community_liaison.json +15 -0
- data/incomplete/task_003/role_agents/facility_engineer.json +15 -0
- data/incomplete/task_003/role_agents/logistics_director.json +15 -0
- data/incomplete/task_003/role_agents/safety_commissioner.json +15 -0
- data/incomplete/task_003/tasks/run_one.py +1396 -0
- data/incomplete/task_004/role_agents/dockside_stevedoring.json +15 -0
- data/incomplete/task_004/role_agents/environmental_compliance.json +15 -0
- data/incomplete/task_004/role_agents/expedition_logistics.json +15 -0
- data/incomplete/task_004/role_agents/harbour_master.json +15 -0
- data/incomplete/task_004/role_agents/marine_safety.json +15 -0
- data/incomplete/task_004/role_agents/polar_quartermaster.json +15 -0
- data/incomplete/task_004/role_agents/technical_operations.json +15 -0
- data/incomplete/task_004/tasks/run_one.py +1396 -0
- data/incomplete/task_005/role_agents/climate_systems_engineer.json +15 -0
- data/incomplete/task_005/role_agents/heritage_liaison.json +15 -0
- data/incomplete/task_005/role_agents/logistics_estimator.json +15 -0
- data/incomplete/task_005/role_agents/preservation_conservator.json +15 -0
- data/incomplete/task_005/role_agents/security_director.json +15 -0
- data/incomplete/task_005/role_agents/statutory_compliance_officer.json +15 -0
- data/incomplete/task_005/role_agents/structural_engineer.json +15 -0
- data/incomplete/task_005/tasks/run_one.py +1396 -0
- data/incomplete/task_006/role_agents/analytical_chemistry.json +15 -0
- data/incomplete/task_006/role_agents/community_relations.json +15 -0
- data/incomplete/task_006/role_agents/environmental_safety.json +15 -0
- data/incomplete/task_006/role_agents/field_operations.json +15 -0
- data/incomplete/task_006/role_agents/forensics_qa.json +15 -0
- data/incomplete/task_006/role_agents/instrumentation.json +15 -0
- data/incomplete/task_006/role_agents/regulatory_liaison.json +15 -0
- data/incomplete/task_006/tasks/run_one.py +1396 -0
- data/incomplete/task_007/role_agents/clinical_evaluator.json +15 -0
- data/incomplete/task_007/role_agents/compliance_officer.json +15 -0
- data/incomplete/task_007/role_agents/credentialing_officer.json +15 -0
- data/incomplete/task_007/role_agents/governance_lead.json +15 -0
- data/incomplete/task_007/role_agents/leadership_assessor.json +15 -0
- data/incomplete/task_007/role_agents/talent_analytics.json +15 -0
data/incomplete/task_001/role_agents/facility_utilities.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Power and utilities coordinator (PWR)",
|
| 3 |
+
"abstract": "Maintains backup generation equipment and auxiliary fuel reserves",
|
| 4 |
+
"system_message": "You are the Power and utilities coordinator (PWR), responsible for maintaining backup generation equipment and auxiliary fuel reserves across municipal facilities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains backup generation equipment and auxiliary fuel reserves(GEN)",
|
| 8 |
+
"content": "PWR-GEN-TOH:At Pinewood Regional Sports Complex, the backup generator operational status is confirmed true according to primary auxiliary plant testing, with dedicated on-site reserves yielding a continuous fuel runtime capacity of 24 h at full electrical load.\nPWR-GEN-RCM:Harborview Exhibition Pavilion maintains an operational backup generator status confirmed true by auxiliary power plant start testing, and its on-site fuel reservoir supports a continuous fuel runtime capacity of 72 h under full load.\nPWR-GEN-M5M:For Crestview Civic Auditorium, the backup generator operational status is confirmed true based on installation and live start-test certification of the primary auxiliary power plant, and dedicated on-site fuel reserves provide a continuous fuel runtime capacity of 72 h at full load."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Solar array backup(SOLAR)",
|
| 12 |
+
"content": "PWR-SOLAR-7D6:Harborview Exhibition Pavilion achieves a rooftop photovoltaic peak output of 85 kW sustained electrical power output to the building busbars during peak solar hours.\nPWR-SOLAR-16Q:At Crestview Civic Auditorium, the installed rooftop photovoltaic peak output reaches 60 kW delivered to the building busbars during midday peak periods.\nPWR-SOLAR-3QW:Pinewood Regional Sports Complex provides a rooftop photovoltaic peak output of 40 kW delivered to the busbars during midday peak conditions."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_001/role_agents/hydrology_lead.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Flood protection specialist (HYD)",
|
| 3 |
+
"abstract": "Validates stormwater drainage and perimeter flood barrier protections",
|
| 4 |
+
"system_message": "You are the Flood protection specialist (HYD), responsible for validating stormwater drainage and perimeter flood barrier protections across municipal shelter facilities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Ningbo·Validates stormwater drainage and perimeter flood barrier protections(BARR)",
|
| 8 |
+
"content": "HYD-BARR-0LO:For Harborview Exhibition Pavilion in the Ningbo municipal jurisdiction, verification records indicate that perimeter flood barrier certified status is false across its surrounding deployable flood walls and drainage gates.\nHYD-BARR-8TT:For Crestview Civic Auditorium within the Ningbo municipal jurisdiction, verification of surrounding deployable flood walls and drainage gates confirms that the perimeter flood barrier certified status is true based on hydrostatic pressure sealing tests.\nHYD-BARR-SKY:For Pinewood Regional Sports Complex located in the municipal jurisdiction of Ningbo, hydrostatic pressure sealing tests verify that the perimeter flood barrier certified status is true for its deployable flood walls and drainage gates."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Xiamen·Validates stormwater drainage and perimeter flood barrier protections(PUMP)",
|
| 12 |
+
"content": "HYD-PUMP-Z67:For Pinewood Regional Sports Complex situated in the municipal jurisdiction of Xiamen, hydrostatic pressure sealing test results establish that perimeter flood barrier certified status is true.\nHYD-PUMP-Z3Q:For Harborview Exhibition Pavilion within the Xiamen municipal jurisdiction, hydrostatic sealing records confirm that perimeter flood barrier certified status is false for the perimeter deployable walls and drainage gates.\nHYD-PUMP-PW4:For Crestview Civic Auditorium within the Xiamen municipal jurisdiction, hydrostatic sealing evaluations confirm that perimeter flood barrier certified status is false."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_001/role_agents/public_health.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Public health inspector (HLT)",
|
| 3 |
+
"abstract": "Inspects medical triage rooms and healthcare sanitation standards",
|
| 4 |
+
"system_message": "You are Public health inspector (HLT). The public health inspector (HLT) evaluates municipal shelter facilities for healthcare sanitation standards, including the clearance of dedicated medical triage rooms and medical logistics allocations such as staff bunks, alongside on-site potable water reserves.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Potable water reserve(WATER)",
|
| 8 |
+
"content": "HLT-WATER-LVU:Harborview Exhibition Pavilion possesses 6000 gal of potable drinking water storage across its on-site sanitary holding tanks.\nHLT-WATER-HCR:Pinewood Regional Sports Complex holds 2500 gal of potable drinking water storage in its on-site sanitary holding tanks.\nHLT-WATER-CMD:Crestview Civic Auditorium maintains 4000 gal of potable drinking water storage in on-site sanitary holding tanks."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Inspects medical triage rooms and healthcare sanitation standards(MED)",
|
| 12 |
+
"content": "HLT-MED-9IY:For the Crestview Civic Auditorium, the dedicated medical triage room is cleared under regional healthcare infection control and bio-waste containment protocols, and the medical logistics plan reserves 80 bunks exclusively for dedicated emergency staff.\nHLT-MED-HR7:For the Harborview Exhibition Pavilion, the dedicated medical triage room is cleared under regional healthcare infection control protocols, and 100 bunks are designated as dedicated emergency staff reserve bunks.\nHLT-MED-N90:For the Pinewood Regional Sports Complex, the dedicated medical triage room is not cleared under regional healthcare infection control and bio-waste containment protocols, while 40 bunks are allocated as dedicated emergency staff reserve bunks."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_001/role_agents/shelter_operations.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Emergency housing director (OPS)",
|
| 3 |
+
"abstract": "Oversees floor capacity, cot layouts, and staff allocations",
|
| 4 |
+
"system_message": "You are Emergency housing director (OPS). The Emergency housing director (OPS) oversees floor capacity, cot layouts, and staff allocations across emergency shelter facilities, as well as household pet sheltering capabilities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Oversees floor capacity, cot layouts, and staff allocations(BUNK)",
|
| 8 |
+
"content": "OPS-BUNK-24U:For Pinewood Regional Sports Complex, the indoor climate-controlled congregate housing areas provide a total rated bunk capacity of 800 bunks, measured as the total physical bunks and emergency cots assembled and spaced per fire code.\nOPS-BUNK-PYE:For Crestview Civic Auditorium, the indoor climate-controlled congregate housing areas provide a total rated bunk capacity of 350 bunks, measured as the total physical bunks and emergency cots assembled and spaced per fire code.\nOPS-BUNK-APN:For Harborview Exhibition Pavilion, the indoor climate-controlled congregate housing areas provide a total rated bunk capacity of 800 bunks, measured as the total physical bunks and emergency cots assembled and spaced per fire code."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Household pet sheltering(PETS)",
|
| 12 |
+
"content": "OPS-PETS-91F:At Crestview Civic Auditorium, the companion animal kennel capacity in the isolated indoor pet holding area is 50 kennels meeting animal control isolation spacing.\nOPS-PETS-X3X:At Harborview Exhibition Pavilion, the companion animal kennel capacity in the isolated indoor pet holding area is 80 kennels meeting animal control isolation spacing.\nOPS-PETS-CQ3:At Pinewood Regional Sports Complex, the companion animal kennel capacity in the isolated indoor pet holding area is 30 kennels meeting animal control isolation spacing."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_001/role_agents/structural_safety.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Structural safety engineer (STR)",
|
| 3 |
+
"abstract": "Evaluates seismic integrity and facility physical clearance",
|
| 4 |
+
"system_message": "You are the Structural safety engineer (STR), responsible for evaluating seismic integrity, facility physical clearance, and related structural engineering assessments across municipal shelter facilities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Evaluates seismic integrity and facility physical clearance(SEIS)",
|
| 8 |
+
"content": "STR-SEIS-Z2T:For Crestview Civic Auditorium, seismic clearance verified is true according to the structural safety sign-off for the main building.\nSTR-SEIS-IGH:For Pinewood Regional Sports Complex, seismic clearance verified is true based on the structural safety sign-off for the main building.\nSTR-SEIS-0XH:For Harborview Exhibition Pavilion, seismic clearance verified is false based on the structural safety evaluation of the main building."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Roof load assessment(ROOF)",
|
| 12 |
+
"content": "STR-ROOF-Z8H:For Crestview Civic Auditorium, the roof snow and ash live load tolerance of the primary roof truss assembly is 65 psf.\nSTR-ROOF-XOQ:For Harborview Exhibition Pavilion, the primary roof truss assembly has a roof snow and ash live load tolerance of 35 psf.\nSTR-ROOF-WID:For Pinewood Regional Sports Complex, the primary roof truss assembly demonstrates a roof snow and ash live load tolerance of 50 psf."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_001/role_agents/volunteer_corps.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Community liaison officer (VOL)",
|
| 3 |
+
"abstract": "Maintains community volunteer registrations and civic group pledges",
|
| 4 |
+
"system_message": "You are a Community liaison officer (VOL) responsible for maintaining community volunteer registrations, civic group pledges, and multilingual interpreter rosters.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Multilingual interpreter roster(TRAN)",
|
| 8 |
+
"content": "VOL-TRAN-AQM:At Pinewood Regional Sports Complex, the roster shows 12 persons registered as certified emergency translators for round-the-clock on-call emergency intake shifts.\nVOL-TRAN-XIC:The volunteer dispatch registry lists 4 persons as certified emergency translators committed to on-call emergency intake shifts for Crestview Civic Auditorium.\nVOL-TRAN-RUD:For Harborview Exhibition Pavilion, the volunteer dispatch registry records 8 persons serving as certified emergency translators committed to round-the-clock emergency intake shifts."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains community volunteer registrations and civic group pledges(CMTY)",
|
| 12 |
+
"content": "VOL-CMTY-LLT:For Harborview Exhibition Pavilion, the pledged community volunteer headcount is 50 volunteers registered for kitchen and logistics support shifts across the initial 48-hour response window.\nVOL-CMTY-FPG:For Crestview Civic Auditorium, the community response mobilization database records a pledged community volunteer headcount of 50 volunteers confirmed for kitchen and logistics support shifts during the first 48 hours.\nVOL-CMTY-JJF:According to the community response mobilization database, Pinewood Regional Sports Complex has a pledged community volunteer headcount of 90 volunteers committed to kitchen and logistics support shifts for the first 48 hours."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_001/tasks/run_one.py
ADDED
|
@@ -0,0 +1,1396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from typing import Any
|
| 5 |
+
COMMUNICATION_ROLE_NAMES = []
|
| 6 |
+
GOLD = {'conclusion': 'Select', 'numeric_result': 270}
|
| 7 |
+
POSITIVE_CONCLUSION = 'Select'
|
| 8 |
+
NEGATIVE_CONCLUSION = 'Do not select'
|
| 9 |
+
NUMERIC_PRECISION = 0
|
| 10 |
+
PUBLIC_ROLES = [{'role_name': 'Structural safety engineer (STR)', 'responsibility': 'Evaluates seismic integrity and facility physical clearance', 'role_abbreviation': 'STR'}, {'role_name': 'Power and utilities coordinator (PWR)', 'responsibility': 'Maintains backup generation equipment and auxiliary fuel reserves', 'role_abbreviation': 'PWR'}, {'role_name': 'Public health inspector (HLT)', 'responsibility': 'Inspects medical triage rooms and healthcare sanitation standards', 'role_abbreviation': 'HLT'}, {'role_name': 'Flood protection specialist (HYD)', 'responsibility': 'Validates stormwater drainage and perimeter flood barrier protections', 'role_abbreviation': 'HYD'}, {'role_name': 'Emergency housing director (OPS)', 'responsibility': 'Oversees floor capacity, cot layouts, and staff allocations', 'role_abbreviation': 'OPS'}, {'role_name': 'Community liaison officer (VOL)', 'responsibility': 'Maintains community volunteer registrations and civic group pledges', 'role_abbreviation': 'VOL'}]
|
| 11 |
+
ROLE_KEY_PREFIXES = {'Structural safety engineer (STR)': 'STR-', 'Power and utilities coordinator (PWR)': 'PWR-', 'Public health inspector (HLT)': 'HLT-', 'Flood protection specialist (HYD)': 'HYD-', 'Emergency housing director (OPS)': 'OPS-', 'Community liaison officer (VOL)': 'VOL-'}
|
| 12 |
+
ROLE_VALID_KEYS = {'Structural safety engineer (STR)': ['STR-SEIS-Z2T', 'STR-SEIS-IGH', 'STR-SEIS-0XH', 'STR-ROOF-Z8H', 'STR-ROOF-XOQ', 'STR-ROOF-WID'], 'Power and utilities coordinator (PWR)': ['PWR-GEN-TOH', 'PWR-GEN-RCM', 'PWR-GEN-M5M', 'PWR-SOLAR-7D6', 'PWR-SOLAR-16Q', 'PWR-SOLAR-3QW'], 'Public health inspector (HLT)': ['HLT-WATER-LVU', 'HLT-WATER-HCR', 'HLT-WATER-CMD', 'HLT-MED-9IY', 'HLT-MED-HR7', 'HLT-MED-N90'], 'Flood protection specialist (HYD)': ['HYD-BARR-0LO', 'HYD-BARR-8TT', 'HYD-BARR-SKY', 'HYD-PUMP-Z67', 'HYD-PUMP-Z3Q', 'HYD-PUMP-PW4'], 'Emergency housing director (OPS)': ['OPS-BUNK-24U', 'OPS-BUNK-PYE', 'OPS-BUNK-APN', 'OPS-PETS-91F', 'OPS-PETS-X3X', 'OPS-PETS-CQ3'], 'Community liaison officer (VOL)': ['VOL-TRAN-AQM', 'VOL-TRAN-XIC', 'VOL-TRAN-RUD', 'VOL-CMTY-LLT', 'VOL-CMTY-FPG', 'VOL-CMTY-JJF']}
|
| 13 |
+
RECORD_REPLY_KEYS = {'STR-SEIS-Z2T': ['STR-SEIS-Z2T'], 'STR-SEIS-IGH': ['STR-SEIS-IGH'], 'STR-SEIS-0XH': ['STR-SEIS-0XH'], 'PWR-GEN-M5M': ['PWR-GEN-M5M'], 'PWR-GEN-TOH': ['PWR-GEN-TOH'], 'PWR-GEN-RCM': ['PWR-GEN-RCM'], 'HLT-MED-9IY': ['HLT-MED-9IY'], 'HLT-MED-N90': ['HLT-MED-N90'], 'HLT-MED-HR7': ['HLT-MED-HR7'], 'HYD-BARR-8TT': ['HYD-BARR-8TT'], 'HYD-BARR-SKY': ['HYD-BARR-SKY'], 'HYD-BARR-0LO': ['HYD-BARR-0LO'], 'OPS-BUNK-PYE': ['OPS-BUNK-PYE'], 'OPS-BUNK-24U': ['OPS-BUNK-24U'], 'OPS-BUNK-APN': ['OPS-BUNK-APN'], 'VOL-CMTY-FPG': ['VOL-CMTY-FPG'], 'VOL-CMTY-JJF': ['VOL-CMTY-JJF'], 'VOL-CMTY-LLT': ['VOL-CMTY-LLT'], 'STR-ROOF-Z8H': ['STR-ROOF-Z8H'], 'STR-ROOF-WID': ['STR-ROOF-WID'], 'STR-ROOF-XOQ': ['STR-ROOF-XOQ'], 'PWR-SOLAR-16Q': ['PWR-SOLAR-16Q'], 'PWR-SOLAR-3QW': ['PWR-SOLAR-3QW'], 'PWR-SOLAR-7D6': ['PWR-SOLAR-7D6'], 'HLT-WATER-CMD': ['HLT-WATER-CMD'], 'HLT-WATER-HCR': ['HLT-WATER-HCR'], 'HLT-WATER-LVU': ['HLT-WATER-LVU'], 'OPS-PETS-91F': ['OPS-PETS-91F'], 'OPS-PETS-CQ3': ['OPS-PETS-CQ3'], 'OPS-PETS-X3X': ['OPS-PETS-X3X'], 'VOL-TRAN-XIC': ['VOL-TRAN-XIC'], 'VOL-TRAN-AQM': ['VOL-TRAN-AQM'], 'VOL-TRAN-RUD': ['VOL-TRAN-RUD'], 'HYD-PUMP-PW4': ['HYD-PUMP-PW4'], 'HYD-PUMP-Z67': ['HYD-PUMP-Z67'], 'HYD-PUMP-Z3Q': ['HYD-PUMP-Z3Q']}
|
| 14 |
+
REQUIRED_KEYS = ['HLT-MED-9IY', 'HYD-BARR-8TT', 'OPS-BUNK-PYE', 'PWR-GEN-M5M', 'PWR-GEN-TOH', 'STR-SEIS-0XH', 'STR-SEIS-Z2T']
|
| 15 |
+
DISTRACTOR_KEYS = ['VOL-CMTY-FPG', 'VOL-CMTY-JJF', 'VOL-CMTY-LLT', 'VOL-TRAN-AQM', 'VOL-TRAN-RUD', 'VOL-TRAN-XIC']
|
| 16 |
+
SETTING = 'incomplete'
|
| 17 |
+
|
| 18 |
+
def runtime_defaults() -> dict[str, Any]:
|
| 19 |
+
return {
|
| 20 |
+
"setting": SETTING,
|
| 21 |
+
"communication_role_names": list(COMMUNICATION_ROLE_NAMES),
|
| 22 |
+
"finalize_ideal_round": 3,
|
| 23 |
+
"max_turns": 6,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
FINALIZE_IDEAL_ROUND = runtime_defaults()["finalize_ideal_round"]
|
| 27 |
+
DEFAULT_MAX_TURNS = runtime_defaults()["max_turns"]
|
| 28 |
+
ERROR_INJECTION = {'enabled': False, 'role_name': 'Flood protection specialist (HYD)', 'target_key': 'HYD-BARR-8TT', 'alternate_key': 'HYD-PUMP-PW4', 'target_context': 'Ningbo', 'alternate_context': 'Xiamen'}
|
| 29 |
+
INCOMPLETE_INJECTION = {'record_id': 'rec_facility_utilities_A', 'role_id': 'facility_utilities', 'candidate_id': 'A', 'key': 'PWR-GEN-M5M', 'boolean_predicate_id': 'A_backup_generator_installed', 'boolean_label': 'Backup generator operational status', 'hidden_predicate_id': 'A_continuous_fuel_runtime', 'threshold_label': 'Continuous fuel runtime capacity', 'threshold_aliases': ['Fuel runtime hours', 'Backup generator autonomous runtime'], 'threshold_value': 72, 'threshold_unit': 'h', 'partial_record_text': 'PWR-GEN-M5M: Crestview Civic Auditorium.Crestview Civic Auditorium: Backup generator operational status = true .Source: Emergency power inspection manifest; Scope: Facility primary auxiliary power plant; Measurement: Physical installation and live start-test certification of stationary diesel generator.', 'alternative_outputs': [{'conclusion': 'Do not select', 'numeric_result': None, 'qualified_candidate_id': None}], 'disclosure_mode': 'upper_bound', 'disclosure_version': 'truthful_bounds_v3_domain_bounds', 'disclosure_bounds': {'lower': None, 'upper': 90}, 'coarse_statement': 'Continuous fuel runtime capacity is at most 90 h.', 'role_name': 'Power and utilities coordinator (PWR)', 'candidate_name': 'Crestview Civic Auditorium', 'other_candidate_names': ['Pinewood Regional Sports Complex', 'Harborview Exhibition Pavilion'], 'context_value': None, 'other_context_values': [], 'language': 'en'}
|
| 30 |
+
INCOMPLETE_FOLLOWUP_RECORDS = [{'key': 'STR-SEIS-Z2T', 'role': 'Structural safety engineer (STR)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'seismic_clearance', 'label': 'Seismic clearance verified', 'aliases': ['Seismic clearance', 'Earthquake structural clearance']}]}, {'key': 'STR-SEIS-IGH', 'role': 'Structural safety engineer (STR)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'seismic_clearance', 'label': 'Seismic clearance verified', 'aliases': ['Seismic clearance', 'Earthquake structural clearance']}]}, {'key': 'STR-SEIS-0XH', 'role': 'Structural safety engineer (STR)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'seismic_clearance', 'label': 'Seismic clearance verified', 'aliases': ['Seismic clearance', 'Earthquake structural clearance']}]}, {'key': 'PWR-GEN-M5M', 'role': 'Power and utilities coordinator (PWR)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'backup_generator_installed', 'label': 'Backup generator operational status', 'aliases': ['Backup generator installed', 'Emergency generator presence']}, {'id': 'continuous_fuel_runtime', 'label': 'Continuous fuel runtime capacity', 'aliases': ['Fuel runtime hours', 'Backup generator autonomous runtime']}]}, {'key': 'PWR-GEN-TOH', 'role': 'Power and utilities coordinator (PWR)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'backup_generator_installed', 'label': 'Backup generator operational status', 'aliases': ['Backup generator installed', 'Emergency generator presence']}, {'id': 'continuous_fuel_runtime', 'label': 'Continuous fuel runtime capacity', 'aliases': ['Fuel runtime hours', 'Backup generator autonomous runtime']}]}, {'key': 'PWR-GEN-RCM', 'role': 'Power and utilities coordinator (PWR)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'backup_generator_installed', 'label': 'Backup generator operational status', 'aliases': ['Backup generator installed', 'Emergency generator presence']}, {'id': 'continuous_fuel_runtime', 'label': 'Continuous fuel runtime capacity', 'aliases': ['Fuel runtime hours', 'Backup generator autonomous runtime']}]}, {'key': 'HLT-MED-9IY', 'role': 'Public health inspector (HLT)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'triage_room_cleared', 'label': 'Dedicated medical triage room cleared', 'aliases': ['Medical triage clearance', 'Triage area sanitation approval']}, {'id': 'staff_reserve_bunks', 'label': 'Dedicated emergency staff reserve bunks', 'aliases': ['Staff bunk reservation', 'First responder cot allocation']}]}, {'key': 'HLT-MED-N90', 'role': 'Public health inspector (HLT)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'triage_room_cleared', 'label': 'Dedicated medical triage room cleared', 'aliases': ['Medical triage clearance', 'Triage area sanitation approval']}, {'id': 'staff_reserve_bunks', 'label': 'Dedicated emergency staff reserve bunks', 'aliases': ['Staff bunk reservation', 'First responder cot allocation']}]}, {'key': 'HLT-MED-HR7', 'role': 'Public health inspector (HLT)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'triage_room_cleared', 'label': 'Dedicated medical triage room cleared', 'aliases': ['Medical triage clearance', 'Triage area sanitation approval']}, {'id': 'staff_reserve_bunks', 'label': 'Dedicated emergency staff reserve bunks', 'aliases': ['Staff bunk reservation', 'First responder cot allocation']}]}, {'key': 'HYD-BARR-8TT', 'role': 'Flood protection specialist (HYD)', 'candidate': 'Crestview Civic Auditorium', 'context': 'Ningbo', 'fields': [{'id': 'flood_barrier_certified', 'label': 'Perimeter flood barrier certified', 'aliases': ['Flood barrier certification', 'Perimeter water intrusion barrier']}]}, {'key': 'HYD-BARR-SKY', 'role': 'Flood protection specialist (HYD)', 'candidate': 'Pinewood Regional Sports Complex', 'context': 'Ningbo', 'fields': [{'id': 'flood_barrier_certified', 'label': 'Perimeter flood barrier certified', 'aliases': ['Flood barrier certification', 'Perimeter water intrusion barrier']}]}, {'key': 'HYD-BARR-0LO', 'role': 'Flood protection specialist (HYD)', 'candidate': 'Harborview Exhibition Pavilion', 'context': 'Ningbo', 'fields': [{'id': 'flood_barrier_certified', 'label': 'Perimeter flood barrier certified', 'aliases': ['Flood barrier certification', 'Perimeter water intrusion barrier']}]}, {'key': 'OPS-BUNK-PYE', 'role': 'Emergency housing director (OPS)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'total_bunk_capacity', 'label': 'Total rated bunk capacity', 'aliases': ['Gross cot capacity', 'Nominal shelter bed count']}]}, {'key': 'OPS-BUNK-24U', 'role': 'Emergency housing director (OPS)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'total_bunk_capacity', 'label': 'Total rated bunk capacity', 'aliases': ['Gross cot capacity', 'Nominal shelter bed count']}]}, {'key': 'OPS-BUNK-APN', 'role': 'Emergency housing director (OPS)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'total_bunk_capacity', 'label': 'Total rated bunk capacity', 'aliases': ['Gross cot capacity', 'Nominal shelter bed count']}]}, {'key': 'VOL-CMTY-FPG', 'role': 'Community liaison officer (VOL)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'community_volunteer_count', 'label': 'Pledged community volunteer headcount', 'aliases': ['Volunteer pledge count', 'Civic volunteer corps size']}]}, {'key': 'VOL-CMTY-JJF', 'role': 'Community liaison officer (VOL)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'community_volunteer_count', 'label': 'Pledged community volunteer headcount', 'aliases': ['Volunteer pledge count', 'Civic volunteer corps size']}]}, {'key': 'VOL-CMTY-LLT', 'role': 'Community liaison officer (VOL)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'community_volunteer_count', 'label': 'Pledged community volunteer headcount', 'aliases': ['Volunteer pledge count', 'Civic volunteer corps size']}]}, {'key': 'STR-ROOF-Z8H', 'role': 'Structural safety engineer (STR)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'supplemental_structural_safety', 'label': 'Roof snow and ash live load tolerance', 'aliases': []}]}, {'key': 'STR-ROOF-WID', 'role': 'Structural safety engineer (STR)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'supplemental_structural_safety', 'label': 'Roof snow and ash live load tolerance', 'aliases': []}]}, {'key': 'STR-ROOF-XOQ', 'role': 'Structural safety engineer (STR)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'supplemental_structural_safety', 'label': 'Roof snow and ash live load tolerance', 'aliases': []}]}, {'key': 'PWR-SOLAR-16Q', 'role': 'Power and utilities coordinator (PWR)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'supplemental_facility_utilities', 'label': 'Rooftop photovoltaic peak output', 'aliases': []}]}, {'key': 'PWR-SOLAR-3QW', 'role': 'Power and utilities coordinator (PWR)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'supplemental_facility_utilities', 'label': 'Rooftop photovoltaic peak output', 'aliases': []}]}, {'key': 'PWR-SOLAR-7D6', 'role': 'Power and utilities coordinator (PWR)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'supplemental_facility_utilities', 'label': 'Rooftop photovoltaic peak output', 'aliases': []}]}, {'key': 'HLT-WATER-CMD', 'role': 'Public health inspector (HLT)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'supplemental_public_health', 'label': 'Potable drinking water storage', 'aliases': []}]}, {'key': 'HLT-WATER-HCR', 'role': 'Public health inspector (HLT)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'supplemental_public_health', 'label': 'Potable drinking water storage', 'aliases': []}]}, {'key': 'HLT-WATER-LVU', 'role': 'Public health inspector (HLT)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'supplemental_public_health', 'label': 'Potable drinking water storage', 'aliases': []}]}, {'key': 'OPS-PETS-91F', 'role': 'Emergency housing director (OPS)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'supplemental_shelter_operations', 'label': 'Companion animal kennel capacity', 'aliases': []}]}, {'key': 'OPS-PETS-CQ3', 'role': 'Emergency housing director (OPS)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'supplemental_shelter_operations', 'label': 'Companion animal kennel capacity', 'aliases': []}]}, {'key': 'OPS-PETS-X3X', 'role': 'Emergency housing director (OPS)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'supplemental_shelter_operations', 'label': 'Companion animal kennel capacity', 'aliases': []}]}, {'key': 'VOL-TRAN-XIC', 'role': 'Community liaison officer (VOL)', 'candidate': 'Crestview Civic Auditorium', 'context': '', 'fields': [{'id': 'supplemental_volunteer_corps', 'label': 'Certified emergency translators', 'aliases': []}]}, {'key': 'VOL-TRAN-AQM', 'role': 'Community liaison officer (VOL)', 'candidate': 'Pinewood Regional Sports Complex', 'context': '', 'fields': [{'id': 'supplemental_volunteer_corps', 'label': 'Certified emergency translators', 'aliases': []}]}, {'key': 'VOL-TRAN-RUD', 'role': 'Community liaison officer (VOL)', 'candidate': 'Harborview Exhibition Pavilion', 'context': '', 'fields': [{'id': 'supplemental_volunteer_corps', 'label': 'Certified emergency translators', 'aliases': []}]}, {'key': 'HYD-PUMP-PW4', 'role': 'Flood protection specialist (HYD)', 'candidate': 'Crestview Civic Auditorium', 'context': 'Xiamen', 'fields': [{'id': 'flood_barrier_certified', 'label': 'Perimeter flood barrier certified', 'aliases': ['Flood barrier certification', 'Perimeter water intrusion barrier']}]}, {'key': 'HYD-PUMP-Z67', 'role': 'Flood protection specialist (HYD)', 'candidate': 'Pinewood Regional Sports Complex', 'context': 'Xiamen', 'fields': [{'id': 'flood_barrier_certified', 'label': 'Perimeter flood barrier certified', 'aliases': ['Flood barrier certification', 'Perimeter water intrusion barrier']}]}, {'key': 'HYD-PUMP-Z3Q', 'role': 'Flood protection specialist (HYD)', 'candidate': 'Harborview Exhibition Pavilion', 'context': 'Xiamen', 'fields': [{'id': 'flood_barrier_certified', 'label': 'Perimeter flood barrier certified', 'aliases': ['Flood barrier certification', 'Perimeter water intrusion barrier']}]}]
|
| 31 |
+
KEY_PATTERN = re.compile(r"^[A-Z]+-[A-Z]+-[A-Z0-9]{3}$")
|
| 32 |
+
REPLY_KEY_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z]+-[A-Z]+-[A-Z0-9]{3}(?![A-Z0-9])", re.IGNORECASE)
|
| 33 |
+
ROLE_REPLY_MAX_ATTEMPTS = 3
|
| 34 |
+
TASK_QUERY = 'Determine whether to Select or Do not select a municipal shelter facility. A facility can be approved only if exactly one candidate meets all of the following criteria:\n- Seismic clearance verified is true;\n- Backup generator operational status is true and continuous fuel runtime capacity is at least 48 h;\n- Dedicated medical triage room cleared is true;\n- Perimeter flood barrier certified is true under the Ningbo municipal jurisdiction.\n\nIf exactly one municipal shelter facility meets these conditions, output Select and determine its net available bunk capacity, evaluating total rated bunk capacity and dedicated emergency staff reserve bunks in bunks. If no facility or more than one facility qualifies, output Do not select.\n\nNumeric calculation rule: Compute only for the unique eligible candidate: [Total rated bunk capacity] - [Dedicated emergency staff reserve bunks]. Result unit: bunks. Round only the final result to 0 decimal places (ties to even). If no candidate qualifies, numeric_result is null.\n\nCandidates and records to verify:\n- Crestview Civic Auditorium:STR-SEIS-Z2T、PWR-GEN-M5M、HLT-MED-9IY、HYD-BARR-8TT、OPS-BUNK-PYE、VOL-CMTY-FPG\n- Pinewood Regional Sports Complex:STR-SEIS-IGH、PWR-GEN-TOH、HLT-MED-N90、HYD-BARR-SKY、OPS-BUNK-24U、VOL-CMTY-JJF\n- Harborview Exhibition Pavilion:STR-SEIS-0XH、PWR-GEN-RCM、HLT-MED-HR7、HYD-BARR-0LO、OPS-BUNK-APN、VOL-CMTY-LLT'
|
| 35 |
+
TASK_CONTEXT = 'During coastal emergency management operations, public safety leadership coordinates the opening of municipal shelter facilities to ensure safe, resilient congregate housing for evacuees. Eligible facilities must undergo rigorous verification across structural earthquake safety, continuous emergency backup power generation, dedicated medical triage readiness, and perimeter flood defenses before receiving shelter activation approval.'
|
| 36 |
+
|
| 37 |
+
"""Parse one model message without treating trailing generation noise as an action."""
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from typing import Any
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_json_message(content: Any, *, trace: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 44 |
+
if trace is not None:
|
| 45 |
+
trace.clear()
|
| 46 |
+
trace.update(policy="first_complete_object", raw_response=content, recovered=False)
|
| 47 |
+
if not isinstance(content, str):
|
| 48 |
+
raise ValueError("model response must be text")
|
| 49 |
+
text = content.strip().lstrip("\ufeff").strip()
|
| 50 |
+
# Parse the first complete object; never recover a nested fragment.
|
| 51 |
+
try:
|
| 52 |
+
value, end = json.JSONDecoder().raw_decode(text)
|
| 53 |
+
start = 0
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
if text.startswith(("{", "[", '"')):
|
| 56 |
+
raise
|
| 57 |
+
opening = re.search(r"[\{\[]", text)
|
| 58 |
+
if opening is None:
|
| 59 |
+
raise
|
| 60 |
+
start = opening.start()
|
| 61 |
+
value, consumed = json.JSONDecoder().raw_decode(text[start:])
|
| 62 |
+
end = start + consumed
|
| 63 |
+
if not isinstance(value, dict):
|
| 64 |
+
raise ValueError("model response must be a JSON object")
|
| 65 |
+
prefix, suffix = text[:start], text[end:]
|
| 66 |
+
if trace is not None:
|
| 67 |
+
trace.update(recovered=bool(prefix.strip() or suffix.strip()),
|
| 68 |
+
ignored_prefix=prefix, ignored_suffix=suffix)
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def expand_question_keys(questions):
|
| 73 |
+
expanded = []
|
| 74 |
+
for question in questions:
|
| 75 |
+
if not isinstance(question, dict):
|
| 76 |
+
expanded.append(question)
|
| 77 |
+
continue
|
| 78 |
+
text = question.get("question")
|
| 79 |
+
keys = list(dict.fromkeys(REPLY_KEY_PATTERN.findall(text))) if isinstance(text, str) else []
|
| 80 |
+
for key in keys or [None]:
|
| 81 |
+
expanded.append(dict(question, key=key))
|
| 82 |
+
return expanded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def validate_question(question, *, role_name, semantic_enabled=False):
|
| 86 |
+
if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
|
| 87 |
+
raise ValueError("question must contain natural-language text")
|
| 88 |
+
if role_name not in ROLE_KEY_PREFIXES:
|
| 89 |
+
raise ValueError("unknown Role")
|
| 90 |
+
key = question.get("key")
|
| 91 |
+
authorized = semantic_enabled if key is None else (
|
| 92 |
+
isinstance(key, str) and key in ROLE_VALID_KEYS[role_name] and key in question["question"])
|
| 93 |
+
return {"authorized": bool(authorized)}
|
| 94 |
+
|
| 95 |
+
def recovery_key_match(answer: str) -> str | None:
|
| 96 |
+
target = ERROR_INJECTION.get("target_key")
|
| 97 |
+
if not target:
|
| 98 |
+
return None
|
| 99 |
+
def contains(key: str) -> bool:
|
| 100 |
+
return bool(re.search(r"(?<![A-Z0-9-])" + re.escape(key) + r"(?![A-Z0-9-])", answer, re.IGNORECASE))
|
| 101 |
+
if contains(target):
|
| 102 |
+
return "full_key"
|
| 103 |
+
parts = target.split("-")
|
| 104 |
+
alias = parts[0] + "-" + parts[-1]
|
| 105 |
+
matches = [key for key in ROLE_VALID_KEYS.get(ERROR_INJECTION.get("role_name"), [])
|
| 106 |
+
if key.split("-")[0] + "-" + key.split("-")[-1] == alias]
|
| 107 |
+
if matches == [target] and contains(alias):
|
| 108 |
+
return "abbreviated_key"
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
def communication_metrics(transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 112 |
+
key_query_rounds: dict[str, int] = {}
|
| 113 |
+
key_query_counts: dict[str, int] = {}
|
| 114 |
+
queried_roles: set[str] = set()
|
| 115 |
+
mismatch_round: int | None = None
|
| 116 |
+
recovery_query_sent = False
|
| 117 |
+
recovery_query_turn: int | None = None
|
| 118 |
+
target_key_returned = False
|
| 119 |
+
recovery_turn: int | None = None
|
| 120 |
+
recovery_method: str | None = None
|
| 121 |
+
recovery_reference: str | None = None
|
| 122 |
+
target_key_query_turn: int | None = None
|
| 123 |
+
finalized_before_recovery = False
|
| 124 |
+
for event in transcript:
|
| 125 |
+
turn = int(event.get("turn", len(transcript)))
|
| 126 |
+
action = event.get("main_agent_action", {})
|
| 127 |
+
if (
|
| 128 |
+
ERROR_INJECTION.get("enabled")
|
| 129 |
+
and action.get("action") == "finalize"
|
| 130 |
+
and not target_key_returned
|
| 131 |
+
):
|
| 132 |
+
finalized_before_recovery = True
|
| 133 |
+
if action.get("action") != "ask_role_agents": continue
|
| 134 |
+
for answer in event.get("role_answers", []):
|
| 135 |
+
role_name = answer.get("role_agent")
|
| 136 |
+
if role_name: queried_roles.add(role_name)
|
| 137 |
+
if (
|
| 138 |
+
ERROR_INJECTION.get("enabled") and mismatch_round is not None and turn > mismatch_round
|
| 139 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 140 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("target_key")
|
| 141 |
+
and "role_trace" in answer
|
| 142 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 143 |
+
):
|
| 144 |
+
target_key_query_turn = target_key_query_turn or turn
|
| 145 |
+
if (
|
| 146 |
+
ERROR_INJECTION.get("enabled")
|
| 147 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 148 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("alternate_key")
|
| 149 |
+
and "role_trace" in answer
|
| 150 |
+
):
|
| 151 |
+
mismatch_round = mismatch_round or turn
|
| 152 |
+
for message in action.get("messages", []):
|
| 153 |
+
for question in message.get("questions", []):
|
| 154 |
+
key = question.get("key")
|
| 155 |
+
if (
|
| 156 |
+
ERROR_INJECTION.get("enabled")
|
| 157 |
+
and resolve_role_name(message.get("role_agent")) == ERROR_INJECTION.get("role_name")
|
| 158 |
+
and (key is None or key == ERROR_INJECTION.get("target_key"))
|
| 159 |
+
and mismatch_round is not None
|
| 160 |
+
and turn > mismatch_round
|
| 161 |
+
):
|
| 162 |
+
recovery_query_sent = True
|
| 163 |
+
recovery_query_turn = recovery_query_turn or turn
|
| 164 |
+
if not isinstance(key, str) or not KEY_PATTERN.fullmatch(key): continue
|
| 165 |
+
key_query_rounds.setdefault(key, turn)
|
| 166 |
+
key_query_counts[key] = key_query_counts.get(key, 0) + 1
|
| 167 |
+
if recovery_query_sent and not target_key_returned and mismatch_round is not None and turn > mismatch_round:
|
| 168 |
+
for answer in event.get("role_answers", []):
|
| 169 |
+
question = answer.get("question", {})
|
| 170 |
+
if (
|
| 171 |
+
answer.get("role_agent") == ERROR_INJECTION.get("role_name")
|
| 172 |
+
and (question.get("key") is None or question.get("key") == ERROR_INJECTION.get("target_key"))
|
| 173 |
+
and "role_trace" in answer
|
| 174 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 175 |
+
):
|
| 176 |
+
target_key_returned = True
|
| 177 |
+
recovery_reference = recovery_key_match(str(answer.get("answer", "")))
|
| 178 |
+
recovery_turn = turn
|
| 179 |
+
recovery_method = "keyless_query" if question.get("key") is None else "target_key_query"
|
| 180 |
+
break
|
| 181 |
+
queried = set(key_query_counts)
|
| 182 |
+
required = set(REQUIRED_KEYS)
|
| 183 |
+
relevant = queried & required
|
| 184 |
+
return {
|
| 185 |
+
"required_key_recall":len(relevant)/len(required) if required else 1.0,
|
| 186 |
+
"required_key_precision":len(relevant)/len(queried) if queried else 0.0,
|
| 187 |
+
"key_query_rounds":key_query_rounds,
|
| 188 |
+
"key_query_counts":key_query_counts,
|
| 189 |
+
"duplicate_key_queries":sum(max(0, count-1) for count in key_query_counts.values()),
|
| 190 |
+
"distractor_key_queries":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS),
|
| 191 |
+
"distractor_key_query_rate":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS)/sum(key_query_counts.values()) if key_query_counts else 0.0,
|
| 192 |
+
"turns_to_finalize":len(transcript),
|
| 193 |
+
"mismatch_key_queried":mismatch_round is not None,
|
| 194 |
+
"mismatch_key_turn":mismatch_round,
|
| 195 |
+
"recovery_query_sent":recovery_query_sent,
|
| 196 |
+
"recovery_query_turn":recovery_query_turn,
|
| 197 |
+
"target_key_returned":target_key_returned,
|
| 198 |
+
"recovery_turn":recovery_turn,
|
| 199 |
+
"recovery_method":recovery_method,
|
| 200 |
+
"target_key_query_turn":target_key_query_turn,
|
| 201 |
+
"recovery_key_match":recovery_reference,
|
| 202 |
+
"recovery_metrics_version":"keyed_and_keyless_v3",
|
| 203 |
+
"recovery_latency":recovery_turn - mismatch_round if recovery_turn is not None and mismatch_round is not None else None,
|
| 204 |
+
"finalized_before_recovery":finalized_before_recovery,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
def main_system_prompt() -> str:
|
| 208 |
+
role_text = "\n".join(f"- {item['role_name']}: {item['responsibility']}" for item in PUBLIC_ROLES)
|
| 209 |
+
ask_example = json.dumps({"action":"ask_role_agents","messages":[{"role_agent":"Role name","questions":[{"id":"Q1","question":"Please provide the record for ABC-DATA-A1B using the supplied key."}]}]}, ensure_ascii=False)
|
| 210 |
+
final_example = json.dumps({"action":"finalize","conclusion":"Exactly: " + POSITIVE_CONCLUSION + " or " + NEGATIVE_CONCLUSION,"numeric_result":None}, ensure_ascii=False).replace('"numeric_result": null', '"numeric_result": null/number')
|
| 211 |
+
communication_protocol = ('You may output {"action":"wait"} to advance one logical turn. An empty observation {"observations":[]} means no new visible messages; it does not imply receipt, processing or any future reply.' if SETTING in {'missed', 'mixed'} else '')
|
| 212 |
+
followup = ('For keyless follow-ups, name the candidate in full and the metric explicitly, or request that candidate\'s complete records. A unique previously queried record can be checked directly; otherwise supply a full key and metric when asked to clarify. Explicit directory requests return the complete directory.' if SETTING == 'incomplete' else
|
| 213 |
+
'Authorized keyless follow-ups may name the candidate and metric or request complete records. A role may retrieve facts, request clarification or return a directory. If given a directory, select a valid key to obtain facts.' if SETTING == 'mixed' else
|
| 214 |
+
'Authorized keyless questions return that role\'s complete directory. Choose a key from the directory to obtain concrete facts.')
|
| 215 |
+
return "\n\n".join([
|
| 216 |
+
'You are the Main Agent. Integrate information from independent role agents and make the final decision. Communicate in English.',
|
| 217 |
+
'You cannot see private role information directly. Obtain it only by explicitly messaging the role agents.',
|
| 218 |
+
'Key protocol:\n1. Candidate names and record keys are supplied in the task. Initial access requires a valid key; authorized later follow-ups are the exception.\n'
|
| 219 |
+
'2. Keys use ROLE-BUSINESS-XXX: role abbreviation, business abbreviation and three random alphanumeric characters. Use complete supplied keys; do not invent them.\n'
|
| 220 |
+
'3. Send each key to its owning business role. Use valid keys supplied by roles for subsequent checks.\n'
|
| 221 |
+
'4. Do not output a separate key field. Put the complete key in question text; the system extracts it and checks ownership. Separate different keys into individual questions, preferably one record per question.\n'
|
| 222 |
+
'5. After a successful keyed query to a role, keyless natural-language follow-ups to that role are authorized starting from the next turn.\n6. ' + followup,
|
| 223 |
+
'Available independent role agents:\n\n' + role_text,
|
| 224 |
+
'To ask questions, output only JSON in this form:\n\n' + ask_example,
|
| 225 |
+
*([communication_protocol] if communication_protocol else []),
|
| 226 |
+
'Final answer format (output only valid JSON):\n\n' + final_example,
|
| 227 |
+
'Use exactly one of these conclusion labels: ' + POSITIVE_CONCLUSION + ' or ' + NEGATIVE_CONCLUSION + '. '
|
| 228 |
+
'Do not append a candidate name, explanation or other text. null/number means choose one, not literal syntax. '
|
| 229 |
+
'For a positive conclusion provide the computed number; for a negative conclusion use null. Do not include units or explanations in numeric_result.',
|
| 230 |
+
])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
"""Conservative English evidence rules shared by standalone generated runtimes.
|
| 234 |
+
|
| 235 |
+
This is attribution of explicit statements, not arbitrary semantic entailment.
|
| 236 |
+
Unsupported or conflicting statements remain unknown; no model calls are made.
|
| 237 |
+
"""
|
| 238 |
+
import re
|
| 239 |
+
from decimal import Decimal
|
| 240 |
+
|
| 241 |
+
_RECOVERY_NUMBER = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?'
|
| 242 |
+
_RECOVERY_UNCERTAIN = r"\b(?:unknown|uncertain|unclear|may|might|could|should|would|must|expected|possibly|whether|cannot|unable|unconfirmed|approximately|about|around|roughly|estimated|not confirmed|not known|not established)\b"
|
| 243 |
+
_RECOVERY_NEGATIVE = r'\b(?:not|no|never|false|invalid|blocked|failed|denied|unavailable|unapproved|revoked|inactive|disabled|noncompliant)\b'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def evidence_text(text):
|
| 247 |
+
text = text.replace('’', "'").replace('−', '-').replace('‑', '-')
|
| 248 |
+
text = re.sub(r"\bcan't\b", 'cannot', text, flags=re.I)
|
| 249 |
+
text = re.sub(r"n't\b", ' not', text, flags=re.I)
|
| 250 |
+
text = re.sub(r'(?<![\w.,])[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,]|\.\d)',
|
| 251 |
+
lambda m: m[0].replace(',', ''), text)
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def evidence_phrase(text, phrase):
|
| 256 |
+
if not phrase:
|
| 257 |
+
return False
|
| 258 |
+
return bool(re.search(r'(?<!\w)' + re.escape(phrase).replace(r'\ ', r'\s+') + r'(?!\w)', text, re.I))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def evidence_nonasserted(text):
|
| 262 |
+
"""Questions, hypotheses and unconfirmed claims are not returned facts."""
|
| 263 |
+
return bool('?' in text or re.search(_RECOVERY_UNCERTAIN, text, re.I)
|
| 264 |
+
or re.search(r'\b(?:if|unless|assuming|suppose|supposing|hypothetically)\b', text, re.I)
|
| 265 |
+
or re.search(r'\b(?:do|does|did|has|have|had)\s+not\s+(?:confirm|verify|establish)(?:ed)?\b', text, re.I))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def evidence_clauses(text):
|
| 269 |
+
# Preserve questions and uncertainty when splitting assertions.
|
| 270 |
+
sentences = re.split(r'[。\n]|\.(?!\d)|(?<=[!?])\s+', text)
|
| 271 |
+
clauses = []
|
| 272 |
+
for sentence in sentences:
|
| 273 |
+
if evidence_nonasserted(sentence):
|
| 274 |
+
clauses.append(sentence)
|
| 275 |
+
else:
|
| 276 |
+
clauses.extend(re.split(r'[;;]|,?\s+\b(?:but|and)\b\s+(?![+-]?\d)', sentence, flags=re.I))
|
| 277 |
+
return clauses
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def evidence_scope(answer, question, profile):
|
| 281 |
+
for target in [profile.get('candidate', ''), profile.get('target_context', '')]:
|
| 282 |
+
if target and re.search(r'\b(?:not|outside|excluding|except)(?:\s+(?:for|the))?\s+' + re.escape(target) + r'(?!\w)', answer, re.I):
|
| 283 |
+
return 'not_returned'
|
| 284 |
+
candidates = profile.get('other_candidates', [])
|
| 285 |
+
contexts = profile.get('other_contexts', [profile.get('alternate_context', '')])
|
| 286 |
+
if any(evidence_phrase(answer, c) for c in [*candidates, *contexts] if c):
|
| 287 |
+
target_also_present = evidence_phrase(answer, profile.get('candidate', '')) and (
|
| 288 |
+
not profile.get('target_context') or evidence_phrase(answer, profile['target_context']))
|
| 289 |
+
return 'unknown' if target_also_present else 'not_returned'
|
| 290 |
+
combined = question.get('question', '') + '\n' + answer
|
| 291 |
+
target_key = profile.get('target_key', '')
|
| 292 |
+
if target_key and (question.get('key') == target_key or evidence_phrase(combined, target_key)):
|
| 293 |
+
return 'eligible'
|
| 294 |
+
if evidence_phrase(combined, profile.get('candidate', '')) and (
|
| 295 |
+
not profile.get('target_context') or evidence_phrase(combined, profile['target_context'])):
|
| 296 |
+
return 'eligible'
|
| 297 |
+
return 'unknown'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def evidence_unit_pattern(unit):
|
| 301 |
+
# Unit names may inflect; canonical symbols remain case-sensitive.
|
| 302 |
+
groups = [('h', 'hour', 'hours'), ('min', 'minute', 'minutes'), ('s', 'second', 'seconds'),
|
| 303 |
+
('kg', 'kilogram', 'kilograms'), ('m', 'meter', 'meters', 'metre', 'metres'),
|
| 304 |
+
('%', 'percent', 'per cent'), ('instances', 'instance'), ('items', 'item'),
|
| 305 |
+
('people', 'person', 'persons'), ('days', 'day')]
|
| 306 |
+
for group in groups:
|
| 307 |
+
if unit in group:
|
| 308 |
+
canonical, *words = group
|
| 309 |
+
if canonical in {'instances', 'items', 'people', 'days'}:
|
| 310 |
+
words.append(canonical)
|
| 311 |
+
canonical = None
|
| 312 |
+
parts = ([re.escape(canonical)] if canonical else []) + ['(?i:' + re.escape(w) + ')' for w in words]
|
| 313 |
+
if unit == '%': parts.append('%')
|
| 314 |
+
return '(?:' + '|'.join(sorted(parts, key=len, reverse=True)) + ')'
|
| 315 |
+
return re.escape(unit)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evidence_measurements(text, unit):
|
| 319 |
+
text = evidence_text(text)
|
| 320 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 321 |
+
suffix = (r'(?:\s+(?:1|(?i:dimensionless)))?' if unit == '1'
|
| 322 |
+
else r'\s*' + evidence_unit_pattern(unit))
|
| 323 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')' + suffix + r'(?![A-Za-z0-9_/%]|\.\d|,\d)'
|
| 324 |
+
return text, list(re.finditer(pattern, text))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def evidence_exact_measurement(text, match):
|
| 328 |
+
before, after = text[max(0, match.start()-60):match.start()], text[match.end():match.end()+45]
|
| 329 |
+
if evidence_nonasserted(text):
|
| 330 |
+
return False
|
| 331 |
+
if re.search(r'(?:\b(?:under|over|below|above|less than|more than|at most|at least|up to|between|to|and|not|no more than|no less than)|不超过|���低于|小于等于|大于等于|小于|大于|至少|至多|最多|最少|低于|高于|介于|至|到|[<>≤≥~~–—])\s*$', before, re.I):
|
| 332 |
+
return False
|
| 333 |
+
if re.search(r'\d\s*[-–—]\s*$', before):
|
| 334 |
+
return False
|
| 335 |
+
if re.match(r'\s*(?:\b(?:maximum|minimum|max|min)\b|\bor (?:less|more|lower|higher)\b|\b(?:to|through)\s+[+-]?\d|[-–—~~]\s*\d)', after, re.I):
|
| 336 |
+
return False
|
| 337 |
+
return True
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def english_exact_value(answer, value, unit):
|
| 341 |
+
for clause in evidence_clauses(evidence_text(answer)):
|
| 342 |
+
text, matches = evidence_measurements(clause, unit)
|
| 343 |
+
if any(Decimal(m[1]) == Decimal(str(value)) and evidence_exact_measurement(text, m) for m in matches):
|
| 344 |
+
return True
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def numeric_evidence(answer, question, profile, fact):
|
| 349 |
+
answer = evidence_text(answer)
|
| 350 |
+
scope = evidence_scope(answer, question, profile)
|
| 351 |
+
if scope != 'eligible':
|
| 352 |
+
return scope
|
| 353 |
+
labels = [fact.get('label', ''), *fact.get('aliases', [])]
|
| 354 |
+
states = set()
|
| 355 |
+
for clause in evidence_clauses(answer):
|
| 356 |
+
# Bind each value to its asserted metric; nearby numbers are not evidence.
|
| 357 |
+
if not any(evidence_phrase(clause, label) for label in labels if label):
|
| 358 |
+
continue
|
| 359 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 360 |
+
continue
|
| 361 |
+
# Leave ambiguous multi-metric clauses unscored.
|
| 362 |
+
others = profile.get('facts', profile.get('numeric', []) + profile.get('boolean', []))
|
| 363 |
+
if any(other.get('topic') != fact.get('topic') and any(evidence_phrase(clause, label) for label in
|
| 364 |
+
[other.get('label', ''), *other.get('aliases', [])] if label) for other in others):
|
| 365 |
+
continue
|
| 366 |
+
text, matches = evidence_measurements(clause, fact.get('unit', ''))
|
| 367 |
+
for m in matches:
|
| 368 |
+
if evidence_exact_measurement(text, m) and not re.search(_RECOVERY_NEGATIVE, text[:m.start()], re.I):
|
| 369 |
+
states.add(Decimal(m[1]) == Decimal(str(fact['value'])))
|
| 370 |
+
if len(states) != 1:
|
| 371 |
+
return 'unknown'
|
| 372 |
+
return 'returned' if states.pop() else 'not_returned'
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _evidence_predicate(text):
|
| 376 |
+
text = re.sub(r'\b(?:is|are|was|were|has|have|had|been|the|a|an|already)\b', ' ', text.casefold())
|
| 377 |
+
return re.sub(r'\s+', ' ', text).strip(' .:')
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def boolean_evidence(answer, question, profile):
|
| 381 |
+
answer = evidence_text(answer)
|
| 382 |
+
scope = evidence_scope(answer, question, profile)
|
| 383 |
+
if scope != 'eligible':
|
| 384 |
+
return scope
|
| 385 |
+
labels = [profile['label'], *profile.get('aliases', [])]
|
| 386 |
+
states = set()
|
| 387 |
+
for clause in evidence_clauses(answer):
|
| 388 |
+
plain = _evidence_predicate(clause)
|
| 389 |
+
no_negative = _evidence_predicate(re.sub(_RECOVERY_NEGATIVE, ' ', clause, flags=re.I))
|
| 390 |
+
if not any(evidence_phrase(plain, _evidence_predicate(label)) or evidence_phrase(no_negative, _evidence_predicate(label)) for label in labels if label):
|
| 391 |
+
continue
|
| 392 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 393 |
+
continue
|
| 394 |
+
remainder = clause
|
| 395 |
+
for label in sorted(labels, key=len, reverse=True):
|
| 396 |
+
remainder = re.sub(re.escape(label), '', remainder, flags=re.I)
|
| 397 |
+
negative = bool(re.search(_RECOVERY_NEGATIVE, remainder, re.I))
|
| 398 |
+
explicit = bool(re.search(r'\b(?:true|yes|false|no)\b', remainder, re.I))
|
| 399 |
+
predicate = r'\b(?:enabled|issued|approved|valid|clear|ready|open|active|completed|available|installed|registered|signed|granted|confirmed|operational|compliant|meets|passed|released|equipped|connected|running|accepted)\b'
|
| 400 |
+
affirmative = evidence_phrase(no_negative, _evidence_predicate(profile['label'])) and bool(re.search(predicate, profile['label'], re.I))
|
| 401 |
+
label_match = evidence_phrase(no_negative, _evidence_predicate(profile['label']))
|
| 402 |
+
# Do not transfer negation between unrelated metrics.
|
| 403 |
+
opposites = {'disabled':'enabled', 'unavailable':'available', 'invalid':'valid',
|
| 404 |
+
'closed':'open', 'inactive':'active', 'blocked':'clear', 'revoked':'granted'}
|
| 405 |
+
opposite = False
|
| 406 |
+
for denied, affirmed in opposites.items():
|
| 407 |
+
if re.search(r'\b' + denied + r'\b', clause, re.I):
|
| 408 |
+
rewritten = re.sub(r'\b' + denied + r'\b', affirmed, clause, flags=re.I)
|
| 409 |
+
opposite |= evidence_phrase(_evidence_predicate(rewritten), _evidence_predicate(profile['label']))
|
| 410 |
+
bare_boolean = bool(explicit and re.fullmatch(r'(?:status\s*[:=]?\s*)?(?:true|yes|false|no)',
|
| 411 |
+
_evidence_predicate(remainder), re.I))
|
| 412 |
+
if affirmative or label_match and (negative or explicit) or opposite or bare_boolean:
|
| 413 |
+
states.add(not (negative or opposite))
|
| 414 |
+
if len(states) != 1:
|
| 415 |
+
return 'unknown'
|
| 416 |
+
return 'returned' if states.pop() == profile['value'] else 'not_returned'
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def recovery_number_present(answer, value):
|
| 420 |
+
"""Literal numeric occurrence, independent of unit, metric, scope or wording."""
|
| 421 |
+
text = re.sub(r'(?<![A-Z0-9])[A-Z]{2,10}-[A-Z]{2,10}-[A-Z0-9]{3}(?![A-Z0-9])', '', answer, flags=re.I)
|
| 422 |
+
text = evidence_text(text)
|
| 423 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 424 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')(?![0-9_]|\.\d|,\d)'
|
| 425 |
+
return any(Decimal(m[1]) == Decimal(str(value)) for m in re.finditer(pattern, text))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
import os
|
| 431 |
+
import random
|
| 432 |
+
from datetime import datetime
|
| 433 |
+
from pathlib import Path
|
| 434 |
+
from typing import Dict, List
|
| 435 |
+
|
| 436 |
+
from openai import OpenAI
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_project_env() -> None:
|
| 440 |
+
for parent in Path(__file__).resolve().parents:
|
| 441 |
+
env_path = parent / ".env"
|
| 442 |
+
if not env_path.is_file():
|
| 443 |
+
continue
|
| 444 |
+
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
| 445 |
+
line = raw_line.strip()
|
| 446 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 447 |
+
continue
|
| 448 |
+
key, value = line.split("=", 1)
|
| 449 |
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
load_project_env()
|
| 454 |
+
MAIN_AGENT_API_KEY = os.getenv("MAIN_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 455 |
+
MAIN_AGENT_MODEL_NAME = os.getenv("MAIN_AGENT_MODEL_NAME", "openai/gpt-5.5")
|
| 456 |
+
MAIN_AGENT_BASE_URL = os.getenv("MAIN_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 457 |
+
ROLE_AGENT_API_KEY = os.getenv("ROLE_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 458 |
+
ROLE_AGENT_MODEL_NAME = "deepseek/deepseek-v4-flash-0731"
|
| 459 |
+
ROLE_AGENT_BASE_URL = os.getenv("ROLE_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 460 |
+
LLM_REASONING_EFFORT = os.getenv("LLM_REASONING_EFFORT", "medium")
|
| 461 |
+
ROLE_REASONING_EFFORT = "low"
|
| 462 |
+
ROLE_MAX_TOKENS = 8192
|
| 463 |
+
LLM_REASONING_EXCLUDE = os.getenv("LLM_REASONING_EXCLUDE", "1") != "0"
|
| 464 |
+
MAIN_AGENT_ROLE_ORDER_SEED = os.getenv("MAIN_AGENT_ROLE_ORDER_SEED")
|
| 465 |
+
AGENT_DIR = str(Path(__file__).resolve().parent.parent / "role_agents")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def print_key_trace(title: str, content: Any = "") -> None:
|
| 469 |
+
print(f"\n========== {title} ==========\n", flush=True)
|
| 470 |
+
if content != "":
|
| 471 |
+
print(str(content), flush=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def format_metric_value(value: Any) -> str:
|
| 475 |
+
if isinstance(value, float):
|
| 476 |
+
return f"{value:.4f}"
|
| 477 |
+
if value is None:
|
| 478 |
+
return "None"
|
| 479 |
+
return str(value)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def format_llm_config() -> str:
|
| 483 |
+
return "\n".join([
|
| 484 |
+
f"main_agent_llm: {MAIN_AGENT_MODEL_NAME}",
|
| 485 |
+
f"role_agent_llm: {ROLE_AGENT_MODEL_NAME}",
|
| 486 |
+
f"reasoning_effort: {LLM_REASONING_EFFORT}",
|
| 487 |
+
f"role_reasoning_effort: {ROLE_REASONING_EFFORT}",
|
| 488 |
+
])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def format_available_roles(role_agents: Dict[str, Any]) -> str:
|
| 492 |
+
lines = []
|
| 493 |
+
for role_name, role in role_agents.items():
|
| 494 |
+
key_prefix = ROLE_KEY_PREFIXES.get(role_name, "")
|
| 495 |
+
lines.append(f"- {role_name}(Key 格式:{key_prefix}业务缩写-XXX):{role.config['abstract']}")
|
| 496 |
+
return "\n".join(lines)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def format_evaluation_summary(evaluation: Dict[str, Any]) -> str:
|
| 500 |
+
conclusion = evaluation.get("conclusion_evaluation", {})
|
| 501 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 502 |
+
fields = [
|
| 503 |
+
("ground_truth_conclusion", conclusion.get("ground_truth_conclusion")),
|
| 504 |
+
("ground_truth_numeric_result", conclusion.get("ground_truth_numeric_result")),
|
| 505 |
+
("final_conclusion", conclusion.get("final_conclusion")),
|
| 506 |
+
("parsed_numeric_result", conclusion.get("parsed_numeric_result")),
|
| 507 |
+
("conclusion_correct", conclusion.get("conclusion_correct")),
|
| 508 |
+
("numeric_result_correct", conclusion.get("numeric_result_correct")),
|
| 509 |
+
("turns_to_finalize", communication.get("turns_to_finalize")),
|
| 510 |
+
("total_role_agent_queries", communication.get("total_role_agent_queries")),
|
| 511 |
+
("total_questions", communication.get("total_questions")),
|
| 512 |
+
("duplicate_key_queries", communication.get("duplicate_key_queries")),
|
| 513 |
+
]
|
| 514 |
+
return "\n".join(f"{name}: {format_metric_value(value)}" for name, value in fields)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def format_key_metrics(evaluation: Dict[str, Any]) -> str:
|
| 518 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 519 |
+
correctness = int(bool(evaluation.get("joint_correctness")))
|
| 520 |
+
turns = communication.get("turns_to_finalize")
|
| 521 |
+
lines = [
|
| 522 |
+
f"正确率: {correctness}",
|
| 523 |
+
f"完成轮数: {format_metric_value(turns)} / {communication.get('max_turns', DEFAULT_MAX_TURNS)}(理想:{communication.get('finalize_ideal_round', FINALIZE_IDEAL_ROUND)})",
|
| 524 |
+
]
|
| 525 |
+
if SETTING in {"incomplete", "mixed"}:
|
| 526 |
+
lines.append(f"阈值补齐: {communication.get('incomplete_threshold_returned', False)};补齐轮次: {communication.get('incomplete_recovery_turn')};补救成功: {communication.get('incomplete_recovery_success')}")
|
| 527 |
+
if SETTING in {"missed", "mixed"}:
|
| 528 |
+
lines.append(f"忽略: {communication.get('neglect_ignored_count', 0)};交付: {communication.get('neglect_delivered_count', 0)};待答: {communication.get('neglect_pending_count', 0)}")
|
| 529 |
+
if SETTING not in {"misaligned", "mixed"}:
|
| 530 |
+
return "\n".join(lines)
|
| 531 |
+
|
| 532 |
+
if communication.get("error_recovery_status") == "unknown":
|
| 533 |
+
lines.append("Recovery result: UNKNOWN (evidence cannot be classified; excluded from recovery rates)")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
+
|
| 536 |
+
mismatch_queried = bool(communication.get("mismatch_key_queried"))
|
| 537 |
+
mismatch_turn = communication.get("mismatch_key_turn")
|
| 538 |
+
recovery_query_sent = bool(communication.get("recovery_query_sent"))
|
| 539 |
+
recovery_query_turn = communication.get("recovery_query_turn")
|
| 540 |
+
target_key_returned = bool(communication.get("error_fact_returned", communication.get("target_key_returned")))
|
| 541 |
+
recovery_turn = communication.get("recovery_turn")
|
| 542 |
+
finalized_early = bool(communication.get("finalized_before_recovery"))
|
| 543 |
+
|
| 544 |
+
def turn_suffix(turn: Any) -> str:
|
| 545 |
+
return f"(第{turn}轮)" if isinstance(turn, int) else ""
|
| 546 |
+
|
| 547 |
+
lines.extend(["", "恢复链路:"])
|
| 548 |
+
if not mismatch_queried:
|
| 549 |
+
lines.extend([
|
| 550 |
+
f"✗ 未访问错配 key:{ERROR_INJECTION.get('alternate_key')}",
|
| 551 |
+
"— 未触发补救询问",
|
| 552 |
+
"— Role 未返回目标 key",
|
| 553 |
+
"— 未进入恢复流程",
|
| 554 |
+
"",
|
| 555 |
+
"恢复延迟:N/A",
|
| 556 |
+
"恢复结果:NOT_TRIGGERED(Main 未访问错配 key)",
|
| 557 |
+
])
|
| 558 |
+
return "\n".join(lines)
|
| 559 |
+
|
| 560 |
+
lines.append(
|
| 561 |
+
f"✓ 已访问错配 key:{ERROR_INJECTION.get('alternate_key')}{turn_suffix(mismatch_turn)}"
|
| 562 |
+
)
|
| 563 |
+
lines.append(
|
| 564 |
+
("✓ 已发起补救询问" if recovery_query_sent else "✗ 未发起补救询问")
|
| 565 |
+
+ turn_suffix(recovery_query_turn)
|
| 566 |
+
)
|
| 567 |
+
lines.append(
|
| 568 |
+
(
|
| 569 |
+
f"✓ Role 已返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 570 |
+
if target_key_returned
|
| 571 |
+
else f"✗ Role 未返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 572 |
+
)
|
| 573 |
+
+ turn_suffix(recovery_turn)
|
| 574 |
+
)
|
| 575 |
+
lines.append("✗ 已在恢复前提前 finalize" if finalized_early else "✓ 未在恢复前提前 finalize")
|
| 576 |
+
if target_key_returned:
|
| 577 |
+
lines.append("✓ 恢复后最终答案正确" if correctness else "✗ 恢复后最终答案错误")
|
| 578 |
+
else:
|
| 579 |
+
lines.append("— 尚未完成恢复,无法判断恢复后答案")
|
| 580 |
+
|
| 581 |
+
recovery_latency = communication.get("recovery_latency")
|
| 582 |
+
recovery_method = communication.get("recovery_method")
|
| 583 |
+
if recovery_method:
|
| 584 |
+
target_query_turn = communication.get("target_key_query_turn")
|
| 585 |
+
if recovery_method == "keyless_query" and isinstance(target_query_turn, int) and isinstance(recovery_turn, int) and target_query_turn > recovery_turn:
|
| 586 |
+
method_label = "无 key 获取目录 → 正确 key 查询"
|
| 587 |
+
lines.append(f"取得目标 key:第{recovery_turn}轮")
|
| 588 |
+
lines.append(f"正确 key 查询取得答复:第{target_query_turn}轮")
|
| 589 |
+
recovery_latency = target_query_turn - mismatch_turn if isinstance(mismatch_turn, int) else recovery_latency
|
| 590 |
+
else:
|
| 591 |
+
method_label = {"keyless_query": "无 key 补充询问", "target_key_query": "目标 key 纠正查询"}.get(recovery_method, recovery_method)
|
| 592 |
+
lines.append(f"补救方式:{method_label}")
|
| 593 |
+
if communication.get("recovery_success"):
|
| 594 |
+
status = "SUCCESS"
|
| 595 |
+
elif finalized_early:
|
| 596 |
+
status = "FINALIZED_EARLY"
|
| 597 |
+
elif not recovery_query_sent:
|
| 598 |
+
status = "RECOVERY_NOT_REQUESTED"
|
| 599 |
+
elif not target_key_returned:
|
| 600 |
+
status = "TARGET_NOT_RETURNED"
|
| 601 |
+
else:
|
| 602 |
+
status = "RECOVERED_BUT_WRONG"
|
| 603 |
+
lines.extend([
|
| 604 |
+
"",
|
| 605 |
+
f"恢复延迟:{recovery_latency}轮" if isinstance(recovery_latency, int) else "恢复延迟:N/A",
|
| 606 |
+
f"恢复结果:{status}",
|
| 607 |
+
])
|
| 608 |
+
return "\n".join(lines)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def format_role_messages(action: Dict[str, Any], role_answers: List[Dict[str, Any]]) -> str:
|
| 612 |
+
requested = {
|
| 613 |
+
(message.get("role_agent"), question.get("id"), question.get("key")): question.get("question")
|
| 614 |
+
for message in action.get("messages", [])
|
| 615 |
+
for question in message.get("questions", [])
|
| 616 |
+
}
|
| 617 |
+
blocks = []
|
| 618 |
+
for item in role_answers:
|
| 619 |
+
question = item.get("question", {})
|
| 620 |
+
identity = (item.get("role_agent"), question.get("id"), question.get("key"))
|
| 621 |
+
blocks.append("\n".join([
|
| 622 |
+
f"role_agent: {item.get('role_agent')}",
|
| 623 |
+
f"question_id: {question.get('id')}",
|
| 624 |
+
f"key: {question.get('key')}",
|
| 625 |
+
f"question: {requested.get(identity, question.get('question'))}",
|
| 626 |
+
f"answer: {item.get('answer')}",
|
| 627 |
+
]))
|
| 628 |
+
return "\n\n".join(blocks)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def parse_numeric_result(value: Any) -> int | float | None:
|
| 632 |
+
if value is None or isinstance(value, bool):
|
| 633 |
+
return None
|
| 634 |
+
if isinstance(value, (int, float)):
|
| 635 |
+
number = float(value)
|
| 636 |
+
elif isinstance(value, str):
|
| 637 |
+
match = re.search(r"[-+]?\d+(?:\.\d+)?", value.strip())
|
| 638 |
+
if not match:
|
| 639 |
+
return None
|
| 640 |
+
number = float(match.group(0))
|
| 641 |
+
else:
|
| 642 |
+
return None
|
| 643 |
+
rounded = round(number, NUMERIC_PRECISION)
|
| 644 |
+
return int(rounded) if NUMERIC_PRECISION == 0 else rounded
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def compute_conclusion_correctness(final_result: Dict[str, Any]) -> Dict[str, Any]:
|
| 648 |
+
parsed = parse_numeric_result(final_result.get("numeric_result"))
|
| 649 |
+
expected = parse_numeric_result(GOLD["numeric_result"])
|
| 650 |
+
conclusion_correct = int(final_result.get("conclusion") == GOLD["conclusion"])
|
| 651 |
+
numeric_correct = int(parsed == expected)
|
| 652 |
+
return {
|
| 653 |
+
"ground_truth_conclusion": GOLD["conclusion"],
|
| 654 |
+
"ground_truth_numeric_result": GOLD["numeric_result"],
|
| 655 |
+
"final_conclusion": final_result.get("conclusion"),
|
| 656 |
+
"numeric_result_raw": final_result.get("numeric_result"),
|
| 657 |
+
"parsed_numeric_result": parsed,
|
| 658 |
+
"conclusion_correct": conclusion_correct,
|
| 659 |
+
"numeric_result_correct": numeric_correct,
|
| 660 |
+
"conclusion_correctness": int(conclusion_correct and numeric_correct),
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def format_role_user_message(question: Dict[str, Any]) -> str:
|
| 665 |
+
question_id = str(question.get("id") or "Q")
|
| 666 |
+
text = str(question["question"]).strip()
|
| 667 |
+
return f"{question_id}: {text}"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
"""Deterministic follow-up routing; metadata contains no hidden values or target flags."""
|
| 671 |
+
import re
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def build_followup_records(task):
|
| 675 |
+
roles = {r['role_id']: r['name'] for r in task['roles']}
|
| 676 |
+
candidates = {c['candidate_id']: c['name'] for c in task['candidates']}
|
| 677 |
+
topics = {t['topic_id']: t for group in ('topics', 'distractor_topics', 'supplemental_topics')
|
| 678 |
+
for t in task.get(group, [])}
|
| 679 |
+
observations = {o['observation_id']: o for o in task['observations']}
|
| 680 |
+
records = []
|
| 681 |
+
for record in task['records']:
|
| 682 |
+
fields = []
|
| 683 |
+
for oid in record['observation_ids']:
|
| 684 |
+
tid = observations[oid]['topic_id']
|
| 685 |
+
topic = topics.get(tid, {})
|
| 686 |
+
if topic.get('label'):
|
| 687 |
+
fields.append({'id': tid, 'label': topic['label'], 'aliases': topic.get('aliases', [])})
|
| 688 |
+
records.append(dict(key=task['routing']['record_keys'][record['record_id']],
|
| 689 |
+
role=roles[record['owner_role_id']], candidate=candidates[record['candidate_id']],
|
| 690 |
+
context=(record.get('context') or {}).get('value', ''), fields=fields))
|
| 691 |
+
return records
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class IncompleteFollowupResolver:
|
| 695 |
+
VERSION = 'rule_followup_v2_english'
|
| 696 |
+
CLARIFY = 'The record and metric cannot be uniquely identified. Put the complete record key and the metric to verify in your question.'
|
| 697 |
+
|
| 698 |
+
def __init__(self, records):
|
| 699 |
+
self.records = records
|
| 700 |
+
self.reset()
|
| 701 |
+
|
| 702 |
+
def reset(self):
|
| 703 |
+
self.seen = {}
|
| 704 |
+
self.events = []
|
| 705 |
+
|
| 706 |
+
def observe(self, role, key, turn):
|
| 707 |
+
if key is not None:
|
| 708 |
+
self.seen.setdefault((role, key), turn)
|
| 709 |
+
|
| 710 |
+
@staticmethod
|
| 711 |
+
def normalize(text):
|
| 712 |
+
return re.sub(r'\s+', ' ', text).strip().casefold().replace('’', "'").replace('‑', '-').replace('–', '-')
|
| 713 |
+
|
| 714 |
+
@classmethod
|
| 715 |
+
def mentions(cls, text, phrase):
|
| 716 |
+
phrase = cls.normalize(phrase)
|
| 717 |
+
if re.search(r'[\u3400-\u9fff]', phrase):
|
| 718 |
+
return phrase.replace(' ', '') in text.replace(' ', '')
|
| 719 |
+
return bool(re.search(r'(?<![\w])' + re.escape(phrase) + r'(?![\w])', text))
|
| 720 |
+
|
| 721 |
+
def resolve(self, role, text, turn):
|
| 722 |
+
text = self.normalize(text)
|
| 723 |
+
available = [r for r in self.records if r['role'] == role]
|
| 724 |
+
if re.search(r'目录|索引列表|key列表|\b(?:catalog(?:ue)?s?|director(?:y|ies)|(?:key|index)\s+lists?)\b', text):
|
| 725 |
+
result = dict(status='catalog', key=None, fields=[])
|
| 726 |
+
else:
|
| 727 |
+
# Match the full role catalog before restricting to previously queried records.
|
| 728 |
+
names = {r['candidate'] for r in available if self.mentions(text, r['candidate'])}
|
| 729 |
+
contexts = {r['context'] for r in available if r['context'] and self.mentions(text, r['context'])}
|
| 730 |
+
fields = {f['id'] for r in available for f in r['fields']
|
| 731 |
+
if any(self.mentions(text, a) for a in [f['label'], *f['aliases']] if a)}
|
| 732 |
+
full = bool(re.search(r'完整(?:资料|信息|内容|记录)|全部(?:资料|信息|内容)|详细资料|\b(?:complete|full|all|detailed)\s+(?:(?:the|your|available)\s+)*(?:records?|information|details|data)\b', text))
|
| 733 |
+
matches = [r for r in available
|
| 734 |
+
if self.seen.get((role, r['key']), turn) < turn
|
| 735 |
+
and r['candidate'] in names
|
| 736 |
+
and (not contexts or r['context'] in contexts)
|
| 737 |
+
and (fields <= {f['id'] for f in r['fields']} if fields else full)]
|
| 738 |
+
# Ambiguous references require a key; do not infer pronouns or fuzzy matches.
|
| 739 |
+
unique = len(names) == 1 and len(contexts) <= 1 and len(matches) == 1 and (fields or full)
|
| 740 |
+
result = dict(status='resolved' if unique else 'clarify',
|
| 741 |
+
key=matches[0]['key'] if unique else None, fields=sorted(fields), full=full)
|
| 742 |
+
self.events.append(dict(turn=turn, role_agent=role, question=text, **result))
|
| 743 |
+
return result
|
| 744 |
+
|
| 745 |
+
def catalog(self, role):
|
| 746 |
+
return 'Complete record directory (supply a key to obtain facts):\n' + '\n'.join(
|
| 747 |
+
r['key'] + ':' + r['candidate'] + (';' + r['context'] if r['context'] else '')
|
| 748 |
+
+ '; Metrics: ' + '、'.join(f['label'] for f in r['fields'])
|
| 749 |
+
for r in self.records if r['role'] == role)
|
| 750 |
+
|
| 751 |
+
def metrics(self):
|
| 752 |
+
return dict(incomplete_followup_protocol=self.VERSION,
|
| 753 |
+
incomplete_keyless_followup_count=len(self.events),
|
| 754 |
+
incomplete_rule_resolved_count=sum(e['status'] == 'resolved' for e in self.events),
|
| 755 |
+
incomplete_clarification_count=sum(e['status'] == 'clarify' for e in self.events),
|
| 756 |
+
incomplete_followup_routing=list(self.events))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
"""Self-contained Incomplete policy embedded only in generated Incomplete run_one.py files."""
|
| 760 |
+
import re
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class IncompletePolicy:
|
| 764 |
+
def __init__(self, profile):
|
| 765 |
+
self.profile = profile
|
| 766 |
+
self.reset()
|
| 767 |
+
|
| 768 |
+
def reset(self):
|
| 769 |
+
self.omitted_at_turn = None
|
| 770 |
+
self.followup_at_turn = None
|
| 771 |
+
self.recovered_at_turn = None
|
| 772 |
+
|
| 773 |
+
def mode(self, role_name, question, turn):
|
| 774 |
+
if role_name != self.profile['role_name'] or question.get('key') != self.profile['key']:
|
| 775 |
+
return None
|
| 776 |
+
if self.recovered_at_turn is not None:
|
| 777 |
+
return None
|
| 778 |
+
# Any valid later query of the same record can recover the omitted value.
|
| 779 |
+
if self.omitted_at_turn is not None and turn > self.omitted_at_turn:
|
| 780 |
+
if self.followup_at_turn is None:
|
| 781 |
+
self.followup_at_turn = turn
|
| 782 |
+
return 'incomplete_recovery'
|
| 783 |
+
return 'incomplete_partial'
|
| 784 |
+
|
| 785 |
+
def request_options(self, mode, full_system_message):
|
| 786 |
+
profile = self.profile
|
| 787 |
+
coarse = profile.get('disclosure_mode', 'omission') != 'omission'
|
| 788 |
+
if mode == 'incomplete_partial':
|
| 789 |
+
system = (
|
| 790 |
+
f"You are {profile['role_name']}. For this request use only the business record below. "
|
| 791 |
+
"Respond in English in one or two connected sentences, retaining the key, candidate, material scope and facts. "
|
| 792 |
+
"Do not add metrics, infer facts or assert that the overall plan qualifies. "
|
| 793 |
+
"Do not say information is incomplete, unavailable or requires follow-up, and do not recommend another question. "
|
| 794 |
+
)
|
| 795 |
+
if coarse:
|
| 796 |
+
system += (
|
| 797 |
+
"Include the supplied coarse metric statement, retaining its numbers, units and bound wording. "
|
| 798 |
+
"Bounds are not exact values. Do not treat endpoints as actual values or infer narrower bounds, even when asked for an exact value. "
|
| 799 |
+
)
|
| 800 |
+
system += "\n\n" + profile['partial_record_text']
|
| 801 |
+
if coarse:
|
| 802 |
+
system += "\n" + profile['coarse_statement']
|
| 803 |
+
system += '\n\nOutput only valid JSON: {"answer":"Answer text"}.'
|
| 804 |
+
else:
|
| 805 |
+
system = (full_system_message + "\n\nFor this request, give the complete specified record, explicitly stating "
|
| 806 |
+
+ profile['threshold_label'] + " as its original numeric value and unit. Use Arabic numerals, not just a compliance judgment.")
|
| 807 |
+
if coarse:
|
| 808 |
+
system += (" Introduce the exact finding naturally with 'After careful verification'. "
|
| 809 |
+
"The exact number must come from the true private record, not a previous bound or interval endpoint. "
|
| 810 |
+
"Do not merely repeat the earlier coarse range.")
|
| 811 |
+
return {'system_override': system, 'response_validator': None}
|
| 812 |
+
|
| 813 |
+
def validate_answer(self, mode, answer):
|
| 814 |
+
if mode == 'incomplete_partial':
|
| 815 |
+
return None
|
| 816 |
+
return (None if recovery_number_present(answer, self.profile['threshold_value'])
|
| 817 |
+
else 'incomplete_threshold_not_returned')
|
| 818 |
+
|
| 819 |
+
def observe(self, mode, turn, answer=None):
|
| 820 |
+
if mode == 'incomplete_partial' and self.omitted_at_turn is None:
|
| 821 |
+
self.omitted_at_turn = turn
|
| 822 |
+
elif mode == 'incomplete_recovery' and answer is not None:
|
| 823 |
+
if self.validate_answer(mode, answer) is None:
|
| 824 |
+
self.recovered_at_turn = turn
|
| 825 |
+
|
| 826 |
+
def observe_keyless(self, role_name, question, turn, answer=None):
|
| 827 |
+
"""Measure accepted search replies without changing their runtime protocol."""
|
| 828 |
+
if (role_name != self.profile['role_name'] or question.get('key') is not None
|
| 829 |
+
or self.omitted_at_turn is None or turn <= self.omitted_at_turn
|
| 830 |
+
or self.recovered_at_turn is not None):
|
| 831 |
+
return
|
| 832 |
+
# Recovery uses numeric occurrence only, without wording, scope or unit checks.
|
| 833 |
+
# Observe only accepted replies; identifiers are excluded by validate_answer.
|
| 834 |
+
if answer is not None and self.validate_answer("incomplete_recovery", answer) is None:
|
| 835 |
+
if self.followup_at_turn is None:
|
| 836 |
+
self.followup_at_turn = turn
|
| 837 |
+
self.recovered_at_turn = turn
|
| 838 |
+
|
| 839 |
+
def metrics(self, *, correct, finalized):
|
| 840 |
+
triggered = self.omitted_at_turn is not None
|
| 841 |
+
recovered = self.recovered_at_turn is not None
|
| 842 |
+
return {
|
| 843 |
+
'incomplete_omission_triggered': triggered,
|
| 844 |
+
'incomplete_omission_turn': self.omitted_at_turn,
|
| 845 |
+
'incomplete_followup_sent': self.followup_at_turn is not None,
|
| 846 |
+
'incomplete_followup_turn': self.followup_at_turn,
|
| 847 |
+
'incomplete_threshold_returned': recovered,
|
| 848 |
+
'incomplete_recovery_turn': self.recovered_at_turn,
|
| 849 |
+
'incomplete_recovery_latency': self.recovered_at_turn - self.omitted_at_turn if recovered else None,
|
| 850 |
+
'finalized_before_incomplete_recovery': bool(finalized and triggered and not recovered),
|
| 851 |
+
'incomplete_recovery_success': bool(recovered) if triggered else None,
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def exact_value_present(answer, profile):
|
| 856 |
+
"""Compatibility name: count the target numeric value, including within bounds."""
|
| 857 |
+
return recovery_number_present(answer, profile['threshold_value'])
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def incomplete_numeric_metrics(profile, transcript, communication, *, correct, finalized):
|
| 861 |
+
"""Measure later accepted replies only; never alter interaction policy state.
|
| 862 |
+
|
| 863 |
+
User-defined numeric-occurrence rule: no unit, polarity, metric or scope gate.
|
| 864 |
+
Only later accepted replies from the affected role are eligible.
|
| 865 |
+
"""
|
| 866 |
+
omitted = communication.get('incomplete_omission_turn')
|
| 867 |
+
followup = communication.get('incomplete_followup_turn')
|
| 868 |
+
recovered = None
|
| 869 |
+
for event in transcript:
|
| 870 |
+
turn = event['turn']
|
| 871 |
+
if omitted is None or turn <= omitted:
|
| 872 |
+
continue
|
| 873 |
+
for reply in event.get('role_answers', []) + event.get('delivered_role_answers', []):
|
| 874 |
+
if (reply.get('role_agent') != profile['role_name']
|
| 875 |
+
or 'role_trace' not in reply
|
| 876 |
+
or reply.get('protocol_error') or 'role_validation_trace' in reply):
|
| 877 |
+
continue
|
| 878 |
+
if exact_value_present(reply.get('answer', ''), profile):
|
| 879 |
+
recovered = turn if recovered is None else min(recovered, turn)
|
| 880 |
+
if recovered is not None:
|
| 881 |
+
followup = recovered if followup is None else min(followup, recovered)
|
| 882 |
+
status = 'returned' if recovered is not None else 'not_returned'
|
| 883 |
+
return {
|
| 884 |
+
'incomplete_recovery_status': status,
|
| 885 |
+
'incomplete_omission_triggered': omitted is not None,
|
| 886 |
+
'incomplete_omission_turn': omitted,
|
| 887 |
+
'incomplete_followup_sent': followup is not None,
|
| 888 |
+
'incomplete_followup_turn': followup,
|
| 889 |
+
'incomplete_threshold_returned': recovered is not None,
|
| 890 |
+
'incomplete_recovery_turn': recovered,
|
| 891 |
+
'incomplete_recovery_latency': recovered - omitted if recovered is not None else None,
|
| 892 |
+
'finalized_before_incomplete_recovery': bool(finalized and omitted is not None and recovered is None),
|
| 893 |
+
'incomplete_recovery_success': bool(recovered is not None) if omitted is not None else None,
|
| 894 |
+
'incomplete_statistics_version': 'numeric_occurrence_v4',
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class RoleAgent:
|
| 899 |
+
def __init__(self, config: Dict[str, Any], client: OpenAI, model: str = ROLE_AGENT_MODEL_NAME):
|
| 900 |
+
self.config = config
|
| 901 |
+
self.client = client
|
| 902 |
+
self.model = model
|
| 903 |
+
self.system_message = self._build_system_message()
|
| 904 |
+
self.reset_history()
|
| 905 |
+
|
| 906 |
+
def reset_history(self) -> None:
|
| 907 |
+
self.messages = [{"role": "system", "content": self.system_message}]
|
| 908 |
+
|
| 909 |
+
def _build_system_message(self) -> str:
|
| 910 |
+
private_blocks = []
|
| 911 |
+
for index, point in enumerate(self.config["information_points"]):
|
| 912 |
+
content = "\n\n".join(
|
| 913 |
+
line for line in str(point["content"]).splitlines() if line.strip()
|
| 914 |
+
)
|
| 915 |
+
private_blocks.append(f"{index + 1}. {point['title']}:\n\n{content}")
|
| 916 |
+
private = "\n\n".join(private_blocks)
|
| 917 |
+
return (
|
| 918 |
+
f"{self.config['system_message']}\n\n"
|
| 919 |
+
f"Your private information:\n\n{private}\n\n"
|
| 920 |
+
"Output only a valid JSON object: {\"answer\":\"Answer text\"}。"
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def answer_with_trace(
|
| 924 |
+
self, question: str, *, allowed_keys: set[str], response_mode: str,
|
| 925 |
+
system_override: str | None = None, response_validator: Any = None,
|
| 926 |
+
) -> Dict[str, Any]:
|
| 927 |
+
user_message = {"role": "user", "content": question}
|
| 928 |
+
attempts = []
|
| 929 |
+
for _ in range(ROLE_REPLY_MAX_ATTEMPTS):
|
| 930 |
+
# Keep rejected replies in the audit trace, outside model conversation history.
|
| 931 |
+
messages = [*self.messages, user_message]
|
| 932 |
+
if system_override is not None:
|
| 933 |
+
messages[0] = {"role": "system", "content": system_override}
|
| 934 |
+
response = self.client.chat.completions.create(
|
| 935 |
+
model=self.model, messages=messages, temperature=0.1,
|
| 936 |
+
max_tokens=ROLE_MAX_TOKENS,
|
| 937 |
+
response_format={"type": "json_object"},
|
| 938 |
+
extra_body={"reasoning": {"effort": ROLE_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 939 |
+
)
|
| 940 |
+
finish_reason = getattr(response.choices[0], "finish_reason", None)
|
| 941 |
+
response_message = {"role": "assistant", "content": response.choices[0].message.content}
|
| 942 |
+
answer = ""
|
| 943 |
+
unexpected_keys = []
|
| 944 |
+
validation_error = None
|
| 945 |
+
json_parse_trace = {}
|
| 946 |
+
try:
|
| 947 |
+
if finish_reason == "length":
|
| 948 |
+
raise ValueError("truncated role response")
|
| 949 |
+
parsed = parse_json_message(response_message["content"], trace=json_parse_trace)
|
| 950 |
+
if set(parsed) != {"answer"} or not isinstance(parsed.get("answer"), str) or not parsed["answer"].strip():
|
| 951 |
+
raise ValueError("response must contain only a non-empty answer string")
|
| 952 |
+
answer = parsed["answer"].strip()
|
| 953 |
+
if response_validator is not None:
|
| 954 |
+
validation_error = response_validator(answer)
|
| 955 |
+
except ValueError:
|
| 956 |
+
validation_error = "output_truncated" if finish_reason == "length" else "invalid_answer_json"
|
| 957 |
+
attempt = {
|
| 958 |
+
"request_messages": messages, "response_message": response_message,
|
| 959 |
+
"answer": answer, "unexpected_keys": unexpected_keys,
|
| 960 |
+
"validation_error": validation_error, "finish_reason": finish_reason,
|
| 961 |
+
}
|
| 962 |
+
if json_parse_trace.get("recovered"):
|
| 963 |
+
attempt["json_parse"] = json_parse_trace
|
| 964 |
+
attempts.append(attempt)
|
| 965 |
+
if validation_error is None:
|
| 966 |
+
history_response = ({"role": "assistant", "content": json.dumps(parsed, ensure_ascii=False)}
|
| 967 |
+
if json_parse_trace.get("recovered") else response_message)
|
| 968 |
+
self.messages.extend([user_message, history_response])
|
| 969 |
+
return {**attempt, "accepted": True, "response_mode": response_mode, "attempts": attempts}
|
| 970 |
+
return {
|
| 971 |
+
"accepted": False, "response_mode": response_mode, "attempts": attempts,
|
| 972 |
+
"answer": "The role reply failed output validation. Please query again.",
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
def load_role_agent_configs(agent_dir: str = AGENT_DIR) -> Dict[str, Dict[str, Any]]:
|
| 976 |
+
root = Path(agent_dir)
|
| 977 |
+
if not root.is_dir():
|
| 978 |
+
raise FileNotFoundError(f"Missing role_agents directory: {root}")
|
| 979 |
+
configs: Dict[str, Dict[str, Any]] = {}
|
| 980 |
+
for path in sorted(root.glob("*.json")):
|
| 981 |
+
config = json.loads(path.read_text(encoding="utf-8"))
|
| 982 |
+
configs[config["role_agent_name"]] = config
|
| 983 |
+
return configs
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_role_agents(
|
| 987 |
+
client: OpenAI, agent_dir: str = AGENT_DIR,
|
| 988 |
+
model: str = ROLE_AGENT_MODEL_NAME,
|
| 989 |
+
) -> Dict[str, RoleAgent]:
|
| 990 |
+
configs = load_role_agent_configs(agent_dir)
|
| 991 |
+
if not configs:
|
| 992 |
+
raise ValueError(f"Empty role_agents directory: {agent_dir}")
|
| 993 |
+
return {name: RoleAgent(config, client, model) for name, config in configs.items()}
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def resolve_role_name(role_name, role_names=None):
|
| 997 |
+
"""Resolve unique full names, Chinese names, or abbreviations without guessing."""
|
| 998 |
+
if not isinstance(role_name, str):
|
| 999 |
+
return None
|
| 1000 |
+
names = list(role_names) if role_names is not None else [item["role_name"] for item in PUBLIC_ROLES]
|
| 1001 |
+
if role_name in names:
|
| 1002 |
+
return role_name
|
| 1003 |
+
text = role_name.strip().replace("(", "(").replace(")", ")")
|
| 1004 |
+
matches = set()
|
| 1005 |
+
for name in names:
|
| 1006 |
+
normalized = name.strip().replace("(", "(").replace(")", ")")
|
| 1007 |
+
aliases = {normalized}
|
| 1008 |
+
parts = re.fullmatch(r"(.+?)(([^()]+))", normalized)
|
| 1009 |
+
if parts:
|
| 1010 |
+
aliases.update(part.strip() for part in parts.groups())
|
| 1011 |
+
if text in aliases:
|
| 1012 |
+
matches.add(name)
|
| 1013 |
+
return next(iter(matches)) if len(matches) == 1 else role_name
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
"""Ignore each selected role's first contact; a later contact responds normally."""
|
| 1017 |
+
import copy
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class NeglectPolicy:
|
| 1021 |
+
def __init__(self, role_names):
|
| 1022 |
+
self.roles = {name: {"state": "uncontacted", "pending": {}}
|
| 1023 |
+
for name in role_names}
|
| 1024 |
+
self.events = []
|
| 1025 |
+
|
| 1026 |
+
def contact(self, role, questions, turn):
|
| 1027 |
+
"""Called once per role/turn with only authorized questions.
|
| 1028 |
+
|
| 1029 |
+
Pending questions are tracked for metrics only, never auto-delivered.
|
| 1030 |
+
On retry, the caller answers the current questions normally.
|
| 1031 |
+
"""
|
| 1032 |
+
state = self.roles.get(role)
|
| 1033 |
+
if state is None or state["state"] == "active" or not questions:
|
| 1034 |
+
return None
|
| 1035 |
+
if state["state"] == "uncontacted":
|
| 1036 |
+
for q in questions:
|
| 1037 |
+
state["pending"].setdefault(q.get("key") or q["question"], copy.deepcopy(q))
|
| 1038 |
+
state.update(state="ignored", first_turn=turn)
|
| 1039 |
+
self.events.append({"kind": "neglect_ignored", "turn": turn, "role_agent": role})
|
| 1040 |
+
return ""
|
| 1041 |
+
if turn <= state["first_turn"]:
|
| 1042 |
+
return ""
|
| 1043 |
+
state.update(state="active", pending={})
|
| 1044 |
+
self.events.append({"kind": "neglect_delivered", "turn": turn, "role_agent": role})
|
| 1045 |
+
return None
|
| 1046 |
+
|
| 1047 |
+
def metrics(self):
|
| 1048 |
+
# Keep legacy counters at zero for compatible result readers.
|
| 1049 |
+
return {**{kind + "_count": sum(e["kind"] == kind for e in self.events)
|
| 1050 |
+
for kind in ("neglect_ignored", "neglect_busy", "neglect_refused", "neglect_delivered")},
|
| 1051 |
+
"neglect_pending_count": sum(len(s["pending"]) for s in self.roles.values())}
|
| 1052 |
+
|
| 1053 |
+
"""Direct-access main loop, embedded in standalone runtimes."""
|
| 1054 |
+
|
| 1055 |
+
def run_direct(self, task):
|
| 1056 |
+
self._semantic_enabled_roles = set()
|
| 1057 |
+
self.empty_observation_count = 0
|
| 1058 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config['communication_role_names'])
|
| 1059 |
+
self.communication_events = self.neglect_policy.events
|
| 1060 |
+
self.delivered_messages = []
|
| 1061 |
+
if self.incomplete_policy:
|
| 1062 |
+
self.incomplete_policy.reset()
|
| 1063 |
+
self.followup_resolver.reset()
|
| 1064 |
+
for role in self.role_agents.values():
|
| 1065 |
+
role.reset_history()
|
| 1066 |
+
self.messages = [{'role': 'system', 'content': self.system_message}, {'role': 'user', 'content': task}]
|
| 1067 |
+
transcript = []
|
| 1068 |
+
consecutive_errors = 0
|
| 1069 |
+
|
| 1070 |
+
def answer(role, question):
|
| 1071 |
+
result, _ = self._answer_question(role, question)
|
| 1072 |
+
return dict(result, role_agent=role, question=dict(question))
|
| 1073 |
+
|
| 1074 |
+
def publish(replies):
|
| 1075 |
+
for reply in replies:
|
| 1076 |
+
if reply.pop('authorized_exact', False):
|
| 1077 |
+
self._semantic_enabled_roles.add(reply['role_agent'])
|
| 1078 |
+
if replies:
|
| 1079 |
+
self.messages.append({'role': 'user', 'content': '\n'.join(
|
| 1080 |
+
r['role_agent'] + ':' + r['answer'] for r in replies)})
|
| 1081 |
+
|
| 1082 |
+
for turn in range(1, self.max_turns + 1):
|
| 1083 |
+
self.current_turn = turn
|
| 1084 |
+
event = {'turn': turn, 'role_answers': []}
|
| 1085 |
+
try:
|
| 1086 |
+
action = self._call_main()
|
| 1087 |
+
if not isinstance(action, dict):
|
| 1088 |
+
raise ValueError('action must be a JSON object')
|
| 1089 |
+
public_action = copy.deepcopy(action)
|
| 1090 |
+
kind = action.get('action')
|
| 1091 |
+
if kind == 'finalize':
|
| 1092 |
+
if action.get('conclusion') not in {POSITIVE_CONCLUSION, NEGATIVE_CONCLUSION}:
|
| 1093 |
+
raise ValueError('conclusion must use one of the two allowed labels')
|
| 1094 |
+
elif kind == 'wait':
|
| 1095 |
+
if SETTING not in {'missed', 'mixed'}:
|
| 1096 |
+
raise ValueError('wait is only supported by neglect and mixed')
|
| 1097 |
+
elif kind == 'ask_role_agents':
|
| 1098 |
+
if not isinstance(action.get('messages'), list) or not action['messages']:
|
| 1099 |
+
raise ValueError('messages must be a nonempty list')
|
| 1100 |
+
for request in action['messages']:
|
| 1101 |
+
if not isinstance(request, dict) or not isinstance(request.get('role_agent'), str):
|
| 1102 |
+
raise ValueError('message must specify role_agent')
|
| 1103 |
+
if not isinstance(request.get('questions'), list) or not request['questions']:
|
| 1104 |
+
raise ValueError('questions must be a nonempty list')
|
| 1105 |
+
request['role_agent'] = resolve_role_name(request['role_agent'], self.role_agents)
|
| 1106 |
+
request['questions'] = expand_question_keys(request['questions'])
|
| 1107 |
+
if any(not isinstance(q, dict) or not isinstance(q.get('question'), str) or not q['question'].strip()
|
| 1108 |
+
for q in request['questions']):
|
| 1109 |
+
raise ValueError('question must contain natural-language text')
|
| 1110 |
+
else:
|
| 1111 |
+
raise ValueError('unsupported action')
|
| 1112 |
+
except (ValueError, TypeError) as exc:
|
| 1113 |
+
event.update(main_agent_action={}, protocol_error=str(exc))
|
| 1114 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1115 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1116 |
+
transcript.append(event)
|
| 1117 |
+
self.messages.append({'role': 'user', 'content': 'Invalid output format: ' + str(exc)})
|
| 1118 |
+
consecutive_errors += 1
|
| 1119 |
+
if consecutive_errors >= 3:
|
| 1120 |
+
break
|
| 1121 |
+
continue
|
| 1122 |
+
consecutive_errors = 0
|
| 1123 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1124 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1125 |
+
event['main_agent_action'] = action
|
| 1126 |
+
transcript.append(event)
|
| 1127 |
+
if kind == 'ask_role_agents':
|
| 1128 |
+
for request in public_action['messages']:
|
| 1129 |
+
for question in request['questions']:
|
| 1130 |
+
question.pop('key', None)
|
| 1131 |
+
self.messages.append({'role': 'assistant', 'content': json.dumps(public_action, ensure_ascii=False)})
|
| 1132 |
+
if kind == 'finalize':
|
| 1133 |
+
return self._result({'conclusion': action['conclusion'], 'numeric_result': action.get('numeric_result')}, transcript, turn)
|
| 1134 |
+
if kind == 'wait':
|
| 1135 |
+
event['waited'] = True
|
| 1136 |
+
continue
|
| 1137 |
+
grouped = {}
|
| 1138 |
+
for request in action['messages']:
|
| 1139 |
+
grouped.setdefault(request['role_agent'], []).extend(request['questions'])
|
| 1140 |
+
replies = event['role_answers']
|
| 1141 |
+
for role, questions in grouped.items():
|
| 1142 |
+
authorized = []
|
| 1143 |
+
invalid = []
|
| 1144 |
+
for q in questions:
|
| 1145 |
+
try:
|
| 1146 |
+
valid = validate_question(q, role_name=role, semantic_enabled=role in self._semantic_enabled_roles)['authorized']
|
| 1147 |
+
except ValueError:
|
| 1148 |
+
valid = False
|
| 1149 |
+
(authorized if valid else invalid).append(q)
|
| 1150 |
+
replies.extend(answer(role, q) for q in invalid)
|
| 1151 |
+
response = self.neglect_policy.contact(role, authorized, turn)
|
| 1152 |
+
if response is None:
|
| 1153 |
+
replies.extend(answer(role, q) for q in authorized)
|
| 1154 |
+
else:
|
| 1155 |
+
event.setdefault('deferred_role_requests', []).extend(
|
| 1156 |
+
{'role_agent': role, 'question': dict(q)} for q in authorized)
|
| 1157 |
+
if response:
|
| 1158 |
+
replies.append({'role_agent': role, 'question': dict(authorized[0]),
|
| 1159 |
+
'answer': response, 'communication_event': 'neglect'})
|
| 1160 |
+
publish(replies)
|
| 1161 |
+
return self._result({'conclusion': None, 'numeric_result': None}, transcript, None)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class MainAgent:
|
| 1165 |
+
def __init__(
|
| 1166 |
+
self, client: OpenAI, role_agents: Dict[str, RoleAgent],
|
| 1167 |
+
model: str = MAIN_AGENT_MODEL_NAME, max_turns: int | None = None,
|
| 1168 |
+
):
|
| 1169 |
+
self.client = client
|
| 1170 |
+
self.role_agents = role_agents
|
| 1171 |
+
self.model = model
|
| 1172 |
+
self.runtime_config = runtime_defaults()
|
| 1173 |
+
self.max_turns = max_turns if max_turns is not None else int(os.getenv("MAX_TURNS", str(self.runtime_config["max_turns"])))
|
| 1174 |
+
self.runtime_config["max_turns"] = self.max_turns
|
| 1175 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config["communication_role_names"])
|
| 1176 |
+
self.delivered_messages = []
|
| 1177 |
+
self.incomplete_policy = IncompletePolicy(INCOMPLETE_INJECTION) if SETTING in {"incomplete", "mixed"} else None
|
| 1178 |
+
self.followup_resolver = IncompleteFollowupResolver(INCOMPLETE_FOLLOWUP_RECORDS) if SETTING in {"incomplete", "mixed"} else None
|
| 1179 |
+
self.current_turn = 0
|
| 1180 |
+
self.communication_events = []
|
| 1181 |
+
self.empty_observation_count = 0
|
| 1182 |
+
self.messages: List[Dict[str, str]] = []
|
| 1183 |
+
self.system_message = self._build_system_message()
|
| 1184 |
+
self._semantic_enabled_roles: set[str] = set()
|
| 1185 |
+
|
| 1186 |
+
def _build_system_message(self) -> str:
|
| 1187 |
+
if MAIN_AGENT_ROLE_ORDER_SEED is None:
|
| 1188 |
+
return main_system_prompt()
|
| 1189 |
+
roles = list(PUBLIC_ROLES)
|
| 1190 |
+
random.Random(MAIN_AGENT_ROLE_ORDER_SEED).shuffle(roles)
|
| 1191 |
+
role_text = "\n".join(
|
| 1192 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1193 |
+
for item in roles
|
| 1194 |
+
)
|
| 1195 |
+
return main_system_prompt().replace(
|
| 1196 |
+
"\n".join(
|
| 1197 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1198 |
+
for item in PUBLIC_ROLES
|
| 1199 |
+
),
|
| 1200 |
+
role_text,
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _call_main(self) -> Dict[str, Any]:
|
| 1204 |
+
if SETTING in {"missed", "mixed"} and self.messages[-1]["role"] == "assistant":
|
| 1205 |
+
self.messages.append({"role": "user", "content": '{"observations":[]}'})
|
| 1206 |
+
self.empty_observation_count += 1
|
| 1207 |
+
response = self.client.chat.completions.create(
|
| 1208 |
+
model=self.model,
|
| 1209 |
+
messages=self.messages,
|
| 1210 |
+
temperature=0.1,
|
| 1211 |
+
response_format={"type": "json_object"},
|
| 1212 |
+
extra_body={"reasoning": {"effort": LLM_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 1213 |
+
)
|
| 1214 |
+
self._last_main_parse_trace = {}
|
| 1215 |
+
return parse_json_message(response.choices[0].message.content, trace=self._last_main_parse_trace)
|
| 1216 |
+
|
| 1217 |
+
def _answer_question(
|
| 1218 |
+
self, role_name: str, question: Dict[str, Any],
|
| 1219 |
+
) -> tuple[Dict[str, Any], bool]:
|
| 1220 |
+
role_name = resolve_role_name(role_name, self.role_agents)
|
| 1221 |
+
role = self.role_agents.get(role_name)
|
| 1222 |
+
if role is None:
|
| 1223 |
+
return {"answer": f"Error: unknown role {role_name}。"}, False
|
| 1224 |
+
try:
|
| 1225 |
+
normalized = validate_question(
|
| 1226 |
+
question, role_name=role_name,
|
| 1227 |
+
semantic_enabled=role_name in self._semantic_enabled_roles,
|
| 1228 |
+
)
|
| 1229 |
+
except ValueError as error:
|
| 1230 |
+
return {"answer": f"Invalid query: {error}"}, False
|
| 1231 |
+
if not normalized["authorized"]:
|
| 1232 |
+
return {"answer": "The key is invalid, belongs to another role, or keyless follow-up is not yet authorized. Include a complete key for this role in question text, without a separate key field."}, False
|
| 1233 |
+
key = question.get("key")
|
| 1234 |
+
role_question = dict(question)
|
| 1235 |
+
binding = None
|
| 1236 |
+
if (self.followup_resolver and key is None
|
| 1237 |
+
and (SETTING != "mixed" or role_name == INCOMPLETE_INJECTION["role_name"])):
|
| 1238 |
+
binding = self.followup_resolver.resolve(role_name, question['question'], self.current_turn)
|
| 1239 |
+
if binding['status'] != 'resolved':
|
| 1240 |
+
answer = (self.followup_resolver.catalog(role_name) if binding['status'] == 'catalog'
|
| 1241 |
+
else self.followup_resolver.CLARIFY)
|
| 1242 |
+
return {"answer": answer, "followup_binding": binding}, False
|
| 1243 |
+
key = binding['key']
|
| 1244 |
+
# Resolve keys only for role requests; preserve the main question in transcripts.
|
| 1245 |
+
role_question = dict(question, key=key, question=question['question'] + ' (System-linked record: ' + key + ')')
|
| 1246 |
+
allowed_keys = set(RECORD_REPLY_KEYS[key] if key is not None else ROLE_VALID_KEYS[role_name])
|
| 1247 |
+
unrelated_field = False
|
| 1248 |
+
if binding and key == INCOMPLETE_INJECTION['key']:
|
| 1249 |
+
hidden_topic = INCOMPLETE_INJECTION['hidden_predicate_id'].removeprefix(INCOMPLETE_INJECTION['candidate_id'] + '_')
|
| 1250 |
+
unrelated_field = not binding['full'] and hidden_topic not in binding['fields'] and self.incomplete_policy.recovered_at_turn is None
|
| 1251 |
+
disclosure_mode = ('incomplete_partial' if unrelated_field else self.incomplete_policy.mode(role_name, role_question, self.current_turn)) if self.incomplete_policy else None
|
| 1252 |
+
if binding:
|
| 1253 |
+
binding['recovery_requested'] = disclosure_mode == 'incomplete_recovery'
|
| 1254 |
+
options = self.incomplete_policy.request_options(disclosure_mode, role.system_message) if disclosure_mode else {}
|
| 1255 |
+
trace = role.answer_with_trace(
|
| 1256 |
+
format_role_user_message(role_question), allowed_keys=allowed_keys,
|
| 1257 |
+
response_mode=disclosure_mode or ("exact" if key is not None else "search"),
|
| 1258 |
+
**options,
|
| 1259 |
+
)
|
| 1260 |
+
if not trace["accepted"]:
|
| 1261 |
+
return {
|
| 1262 |
+
"answer": trace["answer"], "role_validation_trace": trace,
|
| 1263 |
+
"protocol_error": "role_reply_scope_violation",
|
| 1264 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1265 |
+
}, False
|
| 1266 |
+
if disclosure_mode:
|
| 1267 |
+
self.incomplete_policy.observe(disclosure_mode, self.current_turn, trace["answer"])
|
| 1268 |
+
if self.followup_resolver:
|
| 1269 |
+
self.followup_resolver.observe(role_name, key, self.current_turn)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": trace["answer"], "role_trace": trace,
|
| 1272 |
+
"authorized_exact": question.get("key") is not None,
|
| 1273 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1274 |
+
}, False
|
| 1275 |
+
|
| 1276 |
+
def _communication_evaluation(
|
| 1277 |
+
self, transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1278 |
+
) -> Dict[str, Any]:
|
| 1279 |
+
metrics = communication_metrics(transcript)
|
| 1280 |
+
total_questions = sum(
|
| 1281 |
+
len(message.get("questions", []))
|
| 1282 |
+
for event in transcript
|
| 1283 |
+
for message in event.get("main_agent_action", {}).get("messages", [])
|
| 1284 |
+
)
|
| 1285 |
+
ideal = max(1, self.runtime_config["finalize_ideal_round"])
|
| 1286 |
+
turns = final_turn if final_turn is not None else len(transcript)
|
| 1287 |
+
return {
|
| 1288 |
+
**metrics,
|
| 1289 |
+
"total_role_agent_queries": total_questions,
|
| 1290 |
+
"total_questions": total_questions,
|
| 1291 |
+
"finalize_ideal_round": self.runtime_config["finalize_ideal_round"],
|
| 1292 |
+
"max_turns": self.max_turns,
|
| 1293 |
+
"wait_turns": sum(bool(event.get("waited")) for event in transcript),
|
| 1294 |
+
"empty_observation_count": self.empty_observation_count,
|
| 1295 |
+
**self.neglect_policy.metrics(),
|
| 1296 |
+
"delivered_reply_count": len(self.delivered_messages),
|
| 1297 |
+
"pending_reply_count": self.neglect_policy.metrics()["neglect_pending_count"],
|
| 1298 |
+
"efficiency": min(1.0, ideal / turns) if final_turn else 0.0,
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
def _result(
|
| 1302 |
+
self, final: Dict[str, Any], transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1303 |
+
) -> Dict[str, Any]:
|
| 1304 |
+
conclusion = compute_conclusion_correctness(final)
|
| 1305 |
+
communication = self._communication_evaluation(transcript, final_turn)
|
| 1306 |
+
communication["recovery_success"] = (
|
| 1307 |
+
recovery_success(communication, conclusion["conclusion_correctness"] == 1)
|
| 1308 |
+
if ERROR_INJECTION.get("enabled") else None
|
| 1309 |
+
)
|
| 1310 |
+
if self.incomplete_policy:
|
| 1311 |
+
communication.update(self.followup_resolver.metrics())
|
| 1312 |
+
communication.update(self.incomplete_policy.metrics(
|
| 1313 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1314 |
+
))
|
| 1315 |
+
communication.update(incomplete_numeric_metrics(
|
| 1316 |
+
INCOMPLETE_INJECTION, transcript, communication,
|
| 1317 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1318 |
+
))
|
| 1319 |
+
return {
|
| 1320 |
+
"final_result": final,
|
| 1321 |
+
"evaluation": {
|
| 1322 |
+
"conclusion_correct": conclusion["conclusion_correct"],
|
| 1323 |
+
"numeric_result_correct": conclusion["numeric_result_correct"],
|
| 1324 |
+
"joint_correctness": conclusion["conclusion_correctness"],
|
| 1325 |
+
"conclusion_evaluation": conclusion,
|
| 1326 |
+
"communication_evaluation": communication,
|
| 1327 |
+
},
|
| 1328 |
+
"transcript": transcript,
|
| 1329 |
+
"runtime_config": dict(self.runtime_config),
|
| 1330 |
+
"collaboration_state": {
|
| 1331 |
+
"neglect_roles": self.neglect_policy.roles,
|
| 1332 |
+
"delivered_messages": list(self.delivered_messages),
|
| 1333 |
+
"communication_events": list(self.communication_events),
|
| 1334 |
+
},
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
run = run_direct
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def build_task() -> str:
|
| 1341 |
+
return TASK_CONTEXT.strip() + "\n\n" + TASK_QUERY.strip()
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def create_timestamped_run_dir(
|
| 1345 |
+
root: str | Path, prefix: str, started: datetime | None = None,
|
| 1346 |
+
) -> Path:
|
| 1347 |
+
root_path = Path(root)
|
| 1348 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 1349 |
+
timestamp = (started or datetime.now()).strftime("%m%d_%H%M")
|
| 1350 |
+
base_name = f"{prefix}_{timestamp}"
|
| 1351 |
+
suffix = 1
|
| 1352 |
+
while True:
|
| 1353 |
+
name = base_name if suffix == 1 else f"{base_name}_{suffix:02d}"
|
| 1354 |
+
candidate = root_path / name
|
| 1355 |
+
try:
|
| 1356 |
+
candidate.mkdir(exist_ok=False)
|
| 1357 |
+
return candidate
|
| 1358 |
+
except FileExistsError:
|
| 1359 |
+
suffix += 1
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
def save_single_run_result(
|
| 1363 |
+
result: Dict[str, Any], output_root: str | Path | None = None,
|
| 1364 |
+
) -> Path:
|
| 1365 |
+
logs_root = (
|
| 1366 |
+
Path(output_root)
|
| 1367 |
+
if output_root is not None
|
| 1368 |
+
else Path(__file__).resolve().parent.parent / "logs"
|
| 1369 |
+
)
|
| 1370 |
+
run_dir = create_timestamped_run_dir(logs_root, "single_run")
|
| 1371 |
+
result_path = run_dir / "result.json"
|
| 1372 |
+
result_path.write_text(
|
| 1373 |
+
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
|
| 1374 |
+
encoding="utf-8",
|
| 1375 |
+
)
|
| 1376 |
+
return result_path
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def main() -> None:
|
| 1380 |
+
main_client = OpenAI(base_url=MAIN_AGENT_BASE_URL, api_key=MAIN_AGENT_API_KEY)
|
| 1381 |
+
role_client = OpenAI(base_url=ROLE_AGENT_BASE_URL, api_key=ROLE_AGENT_API_KEY)
|
| 1382 |
+
role_agents = build_role_agents(role_client)
|
| 1383 |
+
agent = MainAgent(main_client, role_agents)
|
| 1384 |
+
task = build_task()
|
| 1385 |
+
print_key_trace("LLM CONFIG", format_llm_config())
|
| 1386 |
+
print_key_trace("AVAILABLE ROLES", format_available_roles(role_agents))
|
| 1387 |
+
print_key_trace("TASK QUERY", task)
|
| 1388 |
+
result = agent.run(task)
|
| 1389 |
+
result_path = save_single_run_result(result)
|
| 1390 |
+
summary_title = "MISALIGNED RECOVERY SUMMARY" if SETTING in {"misaligned", "mixed"} else "TASK SUMMARY"
|
| 1391 |
+
print_key_trace(summary_title, format_key_metrics(result["evaluation"]))
|
| 1392 |
+
print_key_trace("RESULT SAVED", result_path)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
if __name__ == "__main__":
|
| 1396 |
+
main()
|
data/incomplete/task_002/role_agents/air_traffic_authority.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Airspace coordinator (ATC)",
|
| 3 |
+
"abstract": "Manages emergency flight corridor clearances and transit segment distances",
|
| 4 |
+
"system_message": "You are Airspace coordinator (ATC). The Airspace coordinator (ATC) manages emergency flight corridor clearances and transit segment distances across offshore emergency evacuation sectors.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Manages emergency flight corridor clearances and transit segment distances(CORR)",
|
| 8 |
+
"content": "ATC-CORR-PUU:For the North Shoal Direct Route, airspace corridor authorization is granted, and the total transit distance along the corridor centerline is 150 km.\nATC-CORR-F3E:For the Outer Archipelago Bypass, airspace corridor authorization is granted, and the corridor's transit distance measures 120 km.\nATC-CORR-1DL:For the Southern Channel Transit, airspace corridor authorization is not granted, and the recorded transit distance is 180 km."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Airspace hazard notices(NOTAM)",
|
| 12 |
+
"content": "ATC-NOTAM-M2F:The Outer Archipelago Bypass currently has 5 active hazard notices published for its adjacent maritime transit sectors.\nATC-NOTAM-OEY:Along adjacent maritime transit sectors for the North Shoal Direct Route, there is currently 1 active hazard notice published.\nATC-NOTAM-J9C:For the Southern Channel Transit, there are currently 3 active hazard notices published affecting adjacent maritime transit sectors."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_002/role_agents/flight_operations_safety.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Flight operations officer (FLT)",
|
| 3 |
+
"abstract": "Audits de-icing readiness, baseline cruise burn rates, and night transit duration",
|
| 4 |
+
"system_message": "You are the Flight operations officer (FLT), responsible for auditing de-icing readiness, baseline cruise burn rates, night transit durations, and flight crew rest compliance across candidate offshore emergency aeromedical evacuation routes.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Audits de-icing readiness, baseline cruise burn rates, and night transit duration(SAFE)",
|
| 8 |
+
"content": "FLT-SAFE-3PZ:For the Outer Archipelago Bypass, the departure staging pad helideck de-icing installation is verified operational, the maximum night-flight transit time under nighttime instrument flight conditions is 100 min, and the specific fuel burn rate is 4.0 kg/km.\nFLT-SAFE-7G0:For the Southern Channel Transit, operational helideck de-icing installation is verified at the staging pad, the maximum night-flight transit time from liftoff to hospital landing is 55 min, and the specific fuel burn rate is 3.2 kg/km.\nFLT-SAFE-WA5:For the North Shoal Direct Route, the helideck de-icing installation is confirmed active and operational at the departure offshore staging pad, with a maximum night-flight transit time of 70 min and a specific fuel burn rate of 3.8 kg/km under standard rescue payload configurations."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Flight crew rest auditing(CREW)",
|
| 12 |
+
"content": "FLT-CREW-I9R:Duty roster audits for the Outer Archipelago Bypass record a standby crew rest margin of 8 h for assigned rescue flight crews before starting an alert shift.\nFLT-CREW-GRP:Duty roster audits for the North Shoal Direct Route confirm that assigned rescue flight crews maintain a standby crew rest margin of 12 h prior to shift commencement.\nFLT-CREW-V5Y:Duty roster audits for the Southern Channel Transit record a standby crew rest margin of 16 h of continuous rest for assigned rescue flight crews prior to their alert shift."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_002/role_agents/logistics_support_liaison.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Harbor logistics liaison (LOG)",
|
| 3 |
+
"abstract": "Tracks auxiliary sea vessel intercept positions and harbor support",
|
| 4 |
+
"system_message": "You are the Harbor logistics liaison (LOG), responsible for monitoring auxiliary sea vessel intercept positions, marine surface rescue escort coverage, and harbor support standby operations.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Berth availability(DOCK)",
|
| 8 |
+
"content": "LOG-DOCK-R8F:According to the harbor safety fleet records for the Outer Archipelago Bypass, tugboat escort availability is confirmed as true, with dedicated escort tugs available on standby.\nLOG-DOCK-0WF:According to the harbor safety fleet records for the North Shoal Direct Route, tugboat escort availability is confirmed as false, indicating no dedicated escort tugs are on standby.\nLOG-DOCK-6LB:According to the harbor safety fleet records for the Southern Channel Transit, tugboat escort availability is confirmed as false, showing dedicated escort tugs are not on standby."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Tracks auxiliary sea vessel intercept positions and harbor support(VESL)",
|
| 12 |
+
"content": "LOG-VESL-E7O:For the North Shoal Direct Route across corridor maritime surface sectors, auxiliary sea rescue escort availability stands at 45%, representing the portion of the corridor covered within 15 minutes by fast rescue patrol cutters.\nLOG-VESL-WK4:For the Southern Channel Transit across corridor maritime surface sectors, auxiliary sea rescue escort availability reaches 92%, reflecting rapid fast rescue cutter coverage within 15 minutes.\nLOG-VESL-R2H:For the Outer Archipelago Bypass across corridor maritime surface sectors, auxiliary sea rescue escort availability is documented at 45% coverage by fast rescue patrol cutters within 15 minutes."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_002/role_agents/marine_meteorological_service.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Coastal meteorologist (MET)",
|
| 3 |
+
"abstract": "Monitors coastal fog radar lock clearance and maritime wind profiles",
|
| 4 |
+
"system_message": "You are the Coastal meteorologist (MET). Your operational responsibilities include monitoring coastal fog radar lock clearance across low-visibility maritime approach corridors and tracking maritime wind profiles and sea surface conditions.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Monitors coastal fog radar lock clearance and maritime wind profiles(RADR)",
|
| 8 |
+
"content": "MET-RADR-N5L:For the Outer Archipelago Bypass, coastal fog radar lock clearance is not verified, as continuous radar tracking lock through coastal fog is absent along the low-visibility maritime approach corridor.\nMET-RADR-K34:For the Southern Channel Transit, coastal fog radar lock clearance is confirmed, with primary coastal tracking radar maintaining continuous lock through coastal fog in the low-visibility maritime approach corridor.\nMET-RADR-T9R:For the North Shoal Direct Route, coastal fog radar lock clearance is verified, confirming that the primary coastal radar maintains continuous lock through coastal fog along the low-visibility maritime approach corridor."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Sea surface condition tracking(WAVE)",
|
| 12 |
+
"content": "MET-WAVE-0V6:Telemetry for the Southern Channel Transit indicates a significant wave height of 2.5 m across the maritime corridor approach zone.\nMET-WAVE-EMC:Telemetry for the North Shoal Direct Route indicates a significant wave height of 5.5 m across the maritime corridor approach zone.\nMET-WAVE-ISS:Telemetry for the Outer Archipelago Bypass indicates a significant wave height of 4.0 m across the maritime corridor approach zone."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_002/role_agents/medical_receiving_facility.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Trauma intake director (MED)",
|
| 3 |
+
"abstract": "Verifies onshore receiving trauma bay status and emergency surgical team availability",
|
| 4 |
+
"system_message": "You are the Trauma intake director (MED). Your business responsibility is to verify onshore receiving trauma bay status, emergency surgical team availability, and related blood product readiness across prospective offshore aeromedical corridors.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Blood product inventory(BLOOD)",
|
| 8 |
+
"content": "MED-BLOOD-R4Y:For the Outer Archipelago Bypass, the designated receiving hospital transfusion service maintains an inventory of 60 units of universal donor blood units.\nMED-BLOOD-7BV:At the designated receiving hospital transfusion service, the available inventory of universal donor blood units for the North Shoal Direct Route is 40 units of immediately ready uncrossmatched O-negative whole blood.\nMED-BLOOD-KQC:The inventory of universal donor blood units allocated for Southern Channel Transit at the designated receiving hospital transfusion service stands at 20 units."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Verifies onshore receiving trauma bay status and emergency surgical team availability(TRMA)",
|
| 12 |
+
"content": "MED-TRMA-NK2:Evaluated under the live production environment, medical trauma bay reception clearance is false for the Southern Channel Transit.\nMED-TRMA-YAK:Under the readiness simulation environment, medical trauma bay reception clearance is recorded as false for the North Shoal Direct Route.\nMED-TRMA-ESO:For the Outer Archipelago Bypass within the live production environment, medical trauma bay reception clearance is confirmed as true.\nMED-TRMA-89F:Monitored under the live production environment, medical trauma bay reception clearance is confirmed as true for the North Shoal Direct Route, ensuring immediate unreserved trauma resuscitation bay capacity."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_002/tasks/run_one.py
ADDED
|
@@ -0,0 +1,1396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 5 |
+
COMMUNICATION_ROLE_NAMES = []
|
| 6 |
+
GOLD = {'conclusion': 'Select', 'numeric_result': 570.0}
|
| 7 |
+
POSITIVE_CONCLUSION = 'Select'
|
| 8 |
+
NEGATIVE_CONCLUSION = 'Do not select'
|
| 9 |
+
NUMERIC_PRECISION = 1
|
| 10 |
+
PUBLIC_ROLES = [{'role_name': 'Airspace coordinator (ATC)', 'responsibility': 'Manages emergency flight corridor clearances and transit segment distances', 'role_abbreviation': 'ATC'}, {'role_name': 'Flight operations officer (FLT)', 'responsibility': 'Audits de-icing readiness, baseline cruise burn rates, and night transit duration', 'role_abbreviation': 'FLT'}, {'role_name': 'Trauma intake director (MED)', 'responsibility': 'Verifies onshore receiving trauma bay status and emergency surgical team availability', 'role_abbreviation': 'MED'}, {'role_name': 'Coastal meteorologist (MET)', 'responsibility': 'Monitors coastal fog radar lock clearance and maritime wind profiles', 'role_abbreviation': 'MET'}, {'role_name': 'Harbor logistics liaison (LOG)', 'responsibility': 'Tracks auxiliary sea vessel intercept positions and harbor support', 'role_abbreviation': 'LOG'}]
|
| 11 |
+
ROLE_KEY_PREFIXES = {'Airspace coordinator (ATC)': 'ATC-', 'Flight operations officer (FLT)': 'FLT-', 'Trauma intake director (MED)': 'MED-', 'Coastal meteorologist (MET)': 'MET-', 'Harbor logistics liaison (LOG)': 'LOG-'}
|
| 12 |
+
ROLE_VALID_KEYS = {'Airspace coordinator (ATC)': ['ATC-CORR-PUU', 'ATC-CORR-F3E', 'ATC-CORR-1DL', 'ATC-NOTAM-M2F', 'ATC-NOTAM-OEY', 'ATC-NOTAM-J9C'], 'Flight operations officer (FLT)': ['FLT-SAFE-3PZ', 'FLT-SAFE-7G0', 'FLT-SAFE-WA5', 'FLT-CREW-I9R', 'FLT-CREW-GRP', 'FLT-CREW-V5Y'], 'Trauma intake director (MED)': ['MED-BLOOD-R4Y', 'MED-BLOOD-7BV', 'MED-BLOOD-KQC', 'MED-TRMA-NK2', 'MED-TRMA-YAK', 'MED-TRMA-ESO', 'MED-TRMA-89F'], 'Coastal meteorologist (MET)': ['MET-RADR-N5L', 'MET-RADR-K34', 'MET-RADR-T9R', 'MET-WAVE-0V6', 'MET-WAVE-EMC', 'MET-WAVE-ISS'], 'Harbor logistics liaison (LOG)': ['LOG-DOCK-R8F', 'LOG-DOCK-0WF', 'LOG-DOCK-6LB', 'LOG-VESL-E7O', 'LOG-VESL-WK4', 'LOG-VESL-R2H']}
|
| 13 |
+
RECORD_REPLY_KEYS = {'ATC-CORR-PUU': ['ATC-CORR-PUU'], 'ATC-CORR-F3E': ['ATC-CORR-F3E'], 'ATC-CORR-1DL': ['ATC-CORR-1DL'], 'FLT-SAFE-WA5': ['FLT-SAFE-WA5'], 'FLT-SAFE-3PZ': ['FLT-SAFE-3PZ'], 'FLT-SAFE-7G0': ['FLT-SAFE-7G0'], 'MED-TRMA-89F': ['MED-TRMA-89F'], 'MED-TRMA-ESO': ['MED-TRMA-ESO'], 'MED-TRMA-NK2': ['MED-TRMA-NK2'], 'MET-RADR-T9R': ['MET-RADR-T9R'], 'MET-RADR-N5L': ['MET-RADR-N5L'], 'MET-RADR-K34': ['MET-RADR-K34'], 'LOG-VESL-E7O': ['LOG-VESL-E7O'], 'LOG-VESL-R2H': ['LOG-VESL-R2H'], 'LOG-VESL-WK4': ['LOG-VESL-WK4'], 'ATC-NOTAM-OEY': ['ATC-NOTAM-OEY'], 'ATC-NOTAM-M2F': ['ATC-NOTAM-M2F'], 'ATC-NOTAM-J9C': ['ATC-NOTAM-J9C'], 'FLT-CREW-GRP': ['FLT-CREW-GRP'], 'FLT-CREW-I9R': ['FLT-CREW-I9R'], 'FLT-CREW-V5Y': ['FLT-CREW-V5Y'], 'MED-BLOOD-7BV': ['MED-BLOOD-7BV'], 'MED-BLOOD-R4Y': ['MED-BLOOD-R4Y'], 'MED-BLOOD-KQC': ['MED-BLOOD-KQC'], 'MET-WAVE-EMC': ['MET-WAVE-EMC'], 'MET-WAVE-ISS': ['MET-WAVE-ISS'], 'MET-WAVE-0V6': ['MET-WAVE-0V6'], 'LOG-DOCK-0WF': ['LOG-DOCK-0WF'], 'LOG-DOCK-R8F': ['LOG-DOCK-R8F'], 'LOG-DOCK-6LB': ['LOG-DOCK-6LB'], 'MED-TRMA-YAK': ['MED-TRMA-YAK']}
|
| 14 |
+
REQUIRED_KEYS = ['ATC-CORR-1DL', 'ATC-CORR-PUU', 'FLT-SAFE-3PZ', 'FLT-SAFE-WA5', 'MED-TRMA-89F', 'MET-RADR-T9R']
|
| 15 |
+
DISTRACTOR_KEYS = ['LOG-DOCK-0WF', 'LOG-DOCK-6LB', 'LOG-DOCK-R8F', 'LOG-VESL-E7O', 'LOG-VESL-R2H', 'LOG-VESL-WK4']
|
| 16 |
+
SETTING = 'incomplete'
|
| 17 |
+
|
| 18 |
+
def runtime_defaults() -> dict[str, Any]:
|
| 19 |
+
return {
|
| 20 |
+
"setting": SETTING,
|
| 21 |
+
"communication_role_names": list(COMMUNICATION_ROLE_NAMES),
|
| 22 |
+
"finalize_ideal_round": 3,
|
| 23 |
+
"max_turns": 6,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
FINALIZE_IDEAL_ROUND = runtime_defaults()["finalize_ideal_round"]
|
| 27 |
+
DEFAULT_MAX_TURNS = runtime_defaults()["max_turns"]
|
| 28 |
+
ERROR_INJECTION = {'enabled': False, 'role_name': 'Trauma intake director (MED)', 'target_key': 'MED-TRMA-89F', 'alternate_key': 'MED-TRMA-YAK', 'target_context': 'live production environment', 'alternate_context': 'readiness simulation environment'}
|
| 29 |
+
INCOMPLETE_INJECTION = {'record_id': 'rec_flight_operations_safety_A', 'role_id': 'flight_operations_safety', 'candidate_id': 'A', 'key': 'FLT-SAFE-WA5', 'boolean_predicate_id': 'A_deicing_installed', 'boolean_label': 'Helideck de-icing installation', 'hidden_predicate_id': 'A_night_transit_time', 'threshold_label': 'Maximum night-flight transit time', 'threshold_aliases': ['Night transit duration', 'Evacuation flight transit time'], 'threshold_value': 70, 'threshold_unit': 'min', 'partial_record_text': 'FLT-SAFE-WA5: North Shoal Direct Route.North Shoal Direct Route: Helideck de-icing installation = true .Source: Helideck technical inspection log; Scope: Staging pad at the departure offshore platform; Measurement: Confirmation that active automated surface de-icing equipment is operational.North Shoal Direct Route: Specific fuel burn rate = 3.8 kg/km.Source: Aeronautical performance chart; Scope: Standard rescue helicopter under medical payload configuration at corridor altitude; Measurement: Mass of jet fuel consumed per kilometer flown along the corridor.', 'alternative_outputs': [{'conclusion': 'Do not select', 'numeric_result': None, 'qualified_candidate_id': None}], 'disclosure_mode': 'interval', 'disclosure_version': 'truthful_bounds_v3_domain_bounds', 'disclosure_bounds': {'lower': 50, 'upper': 200}, 'coarse_statement': 'Maximum night-flight transit time is between 50 min and 200 min, inclusive.', 'role_name': 'Flight operations officer (FLT)', 'candidate_name': 'North Shoal Direct Route', 'other_candidate_names': ['Outer Archipelago Bypass', 'Southern Channel Transit'], 'context_value': None, 'other_context_values': [], 'language': 'en'}
|
| 30 |
+
INCOMPLETE_FOLLOWUP_RECORDS = [{'key': 'ATC-CORR-PUU', 'role': 'Airspace coordinator (ATC)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'airspace_authorized', 'label': 'Airspace corridor authorization', 'aliases': ['Airspace clearance', 'Corridor flight approval']}, {'id': 'corridor_distance', 'label': 'Transit distance', 'aliases': ['Corridor flight distance', 'Sector flight distance']}]}, {'key': 'ATC-CORR-F3E', 'role': 'Airspace coordinator (ATC)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'airspace_authorized', 'label': 'Airspace corridor authorization', 'aliases': ['Airspace clearance', 'Corridor flight approval']}, {'id': 'corridor_distance', 'label': 'Transit distance', 'aliases': ['Corridor flight distance', 'Sector flight distance']}]}, {'key': 'ATC-CORR-1DL', 'role': 'Airspace coordinator (ATC)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'airspace_authorized', 'label': 'Airspace corridor authorization', 'aliases': ['Airspace clearance', 'Corridor flight approval']}, {'id': 'corridor_distance', 'label': 'Transit distance', 'aliases': ['Corridor flight distance', 'Sector flight distance']}]}, {'key': 'FLT-SAFE-WA5', 'role': 'Flight operations officer (FLT)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'deicing_installed', 'label': 'Helideck de-icing installation', 'aliases': ['De-icing capability', 'Deck surface heating enabled']}, {'id': 'night_transit_time', 'label': 'Maximum night-flight transit time', 'aliases': ['Night transit duration', 'Evacuation flight transit time']}, {'id': 'specific_fuel_burn', 'label': 'Specific fuel burn rate', 'aliases': ['Cruise burn rate', 'Helicopter specific fuel consumption rate']}]}, {'key': 'FLT-SAFE-3PZ', 'role': 'Flight operations officer (FLT)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'deicing_installed', 'label': 'Helideck de-icing installation', 'aliases': ['De-icing capability', 'Deck surface heating enabled']}, {'id': 'night_transit_time', 'label': 'Maximum night-flight transit time', 'aliases': ['Night transit duration', 'Evacuation flight transit time']}, {'id': 'specific_fuel_burn', 'label': 'Specific fuel burn rate', 'aliases': ['Cruise burn rate', 'Helicopter specific fuel consumption rate']}]}, {'key': 'FLT-SAFE-7G0', 'role': 'Flight operations officer (FLT)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'deicing_installed', 'label': 'Helideck de-icing installation', 'aliases': ['De-icing capability', 'Deck surface heating enabled']}, {'id': 'night_transit_time', 'label': 'Maximum night-flight transit time', 'aliases': ['Night transit duration', 'Evacuation flight transit time']}, {'id': 'specific_fuel_burn', 'label': 'Specific fuel burn rate', 'aliases': ['Cruise burn rate', 'Helicopter specific fuel consumption rate']}]}, {'key': 'MED-TRMA-89F', 'role': 'Trauma intake director (MED)', 'candidate': 'North Shoal Direct Route', 'context': 'live production environment', 'fields': [{'id': 'trauma_bay_ready', 'label': 'Medical trauma bay reception clearance', 'aliases': ['Trauma reception readiness', 'Emergency surgical bed status']}]}, {'key': 'MED-TRMA-ESO', 'role': 'Trauma intake director (MED)', 'candidate': 'Outer Archipelago Bypass', 'context': 'live production environment', 'fields': [{'id': 'trauma_bay_ready', 'label': 'Medical trauma bay reception clearance', 'aliases': ['Trauma reception readiness', 'Emergency surgical bed status']}]}, {'key': 'MED-TRMA-NK2', 'role': 'Trauma intake director (MED)', 'candidate': 'Southern Channel Transit', 'context': 'live production environment', 'fields': [{'id': 'trauma_bay_ready', 'label': 'Medical trauma bay reception clearance', 'aliases': ['Trauma reception readiness', 'Emergency surgical bed status']}]}, {'key': 'MET-RADR-T9R', 'role': 'Coastal meteorologist (MET)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'radar_lock_cleared', 'label': 'Coastal fog radar lock clearance', 'aliases': ['Fog radar tracking clearance', 'Approach radar verification']}]}, {'key': 'MET-RADR-N5L', 'role': 'Coastal meteorologist (MET)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'radar_lock_cleared', 'label': 'Coastal fog radar lock clearance', 'aliases': ['Fog radar tracking clearance', 'Approach radar verification']}]}, {'key': 'MET-RADR-K34', 'role': 'Coastal meteorologist (MET)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'radar_lock_cleared', 'label': 'Coastal fog radar lock clearance', 'aliases': ['Fog radar tracking clearance', 'Approach radar verification']}]}, {'key': 'LOG-VESL-E7O', 'role': 'Harbor logistics liaison (LOG)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'cutter_standby_score', 'label': 'Auxiliary sea rescue escort availability', 'aliases': ['Marine cutter escort score', 'Offshore surface escort index']}]}, {'key': 'LOG-VESL-R2H', 'role': 'Harbor logistics liaison (LOG)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'cutter_standby_score', 'label': 'Auxiliary sea rescue escort availability', 'aliases': ['Marine cutter escort score', 'Offshore surface escort index']}]}, {'key': 'LOG-VESL-WK4', 'role': 'Harbor logistics liaison (LOG)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'cutter_standby_score', 'label': 'Auxiliary sea rescue escort availability', 'aliases': ['Marine cutter escort score', 'Offshore surface escort index']}]}, {'key': 'ATC-NOTAM-OEY', 'role': 'Airspace coordinator (ATC)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'supplemental_air_traffic_authority', 'label': 'Active hazard notices', 'aliases': []}]}, {'key': 'ATC-NOTAM-M2F', 'role': 'Airspace coordinator (ATC)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'supplemental_air_traffic_authority', 'label': 'Active hazard notices', 'aliases': []}]}, {'key': 'ATC-NOTAM-J9C', 'role': 'Airspace coordinator (ATC)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'supplemental_air_traffic_authority', 'label': 'Active hazard notices', 'aliases': []}]}, {'key': 'FLT-CREW-GRP', 'role': 'Flight operations officer (FLT)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'supplemental_flight_operations_safety', 'label': 'Standby crew rest margin', 'aliases': []}]}, {'key': 'FLT-CREW-I9R', 'role': 'Flight operations officer (FLT)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'supplemental_flight_operations_safety', 'label': 'Standby crew rest margin', 'aliases': []}]}, {'key': 'FLT-CREW-V5Y', 'role': 'Flight operations officer (FLT)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'supplemental_flight_operations_safety', 'label': 'Standby crew rest margin', 'aliases': []}]}, {'key': 'MED-BLOOD-7BV', 'role': 'Trauma intake director (MED)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'supplemental_medical_receiving_facility', 'label': 'Universal donor blood units', 'aliases': []}]}, {'key': 'MED-BLOOD-R4Y', 'role': 'Trauma intake director (MED)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'supplemental_medical_receiving_facility', 'label': 'Universal donor blood units', 'aliases': []}]}, {'key': 'MED-BLOOD-KQC', 'role': 'Trauma intake director (MED)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'supplemental_medical_receiving_facility', 'label': 'Universal donor blood units', 'aliases': []}]}, {'key': 'MET-WAVE-EMC', 'role': 'Coastal meteorologist (MET)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'supplemental_marine_meteorological_service', 'label': 'Significant wave height', 'aliases': []}]}, {'key': 'MET-WAVE-ISS', 'role': 'Coastal meteorologist (MET)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'supplemental_marine_meteorological_service', 'label': 'Significant wave height', 'aliases': []}]}, {'key': 'MET-WAVE-0V6', 'role': 'Coastal meteorologist (MET)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'supplemental_marine_meteorological_service', 'label': 'Significant wave height', 'aliases': []}]}, {'key': 'LOG-DOCK-0WF', 'role': 'Harbor logistics liaison (LOG)', 'candidate': 'North Shoal Direct Route', 'context': '', 'fields': [{'id': 'supplemental_logistics_support_liaison', 'label': 'Tugboat escort availability', 'aliases': []}]}, {'key': 'LOG-DOCK-R8F', 'role': 'Harbor logistics liaison (LOG)', 'candidate': 'Outer Archipelago Bypass', 'context': '', 'fields': [{'id': 'supplemental_logistics_support_liaison', 'label': 'Tugboat escort availability', 'aliases': []}]}, {'key': 'LOG-DOCK-6LB', 'role': 'Harbor logistics liaison (LOG)', 'candidate': 'Southern Channel Transit', 'context': '', 'fields': [{'id': 'supplemental_logistics_support_liaison', 'label': 'Tugboat escort availability', 'aliases': []}]}, {'key': 'MED-TRMA-YAK', 'role': 'Trauma intake director (MED)', 'candidate': 'North Shoal Direct Route', 'context': 'readiness simulation environment', 'fields': [{'id': 'trauma_bay_ready', 'label': 'Medical trauma bay reception clearance', 'aliases': ['Trauma reception readiness', 'Emergency surgical bed status']}]}]
|
| 31 |
+
KEY_PATTERN = re.compile(r"^[A-Z]+-[A-Z]+-[A-Z0-9]{3}$")
|
| 32 |
+
REPLY_KEY_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z]+-[A-Z]+-[A-Z0-9]{3}(?![A-Z0-9])", re.IGNORECASE)
|
| 33 |
+
ROLE_REPLY_MAX_ATTEMPTS = 3
|
| 34 |
+
TASK_QUERY = 'Determine whether to Select or Do not select an offshore emergency evacuation corridor by confirming whether exactly one corridor meets all operational criteria: Airspace corridor authorization is true, Helideck de-icing installation is true while Maximum night-flight transit time is at most 75 min, Medical trauma bay reception clearance under the live production environment is true, and Coastal fog radar lock clearance is true. If exactly one evacuation corridor satisfies these conditions, calculate the evacuation flight fuel requirement defined as the product of Transit distance and Specific fuel burn rate in kg; otherwise, conclude Do not select with a null numeric result.\n\nNumeric calculation rule: Compute only for the unique eligible candidate: [Transit distance] * [Specific fuel burn rate]. Result unit: kg. Round only the final result to 1 decimal places (ties to even). If no candidate qualifies, numeric_result is null.\n\nCandidates and records to verify:\n- North Shoal Direct Route:ATC-CORR-PUU、FLT-SAFE-WA5、MED-TRMA-89F、MET-RADR-T9R、LOG-VESL-E7O\n- Southern Channel Transit:ATC-CORR-1DL、FLT-SAFE-7G0、MED-TRMA-NK2、MET-RADR-K34、LOG-VESL-WK4\n- Outer Archipelago Bypass:ATC-CORR-F3E、FLT-SAFE-3PZ、MED-TRMA-ESO、MET-RADR-N5L、LOG-VESL-R2H'
|
| 35 |
+
TASK_CONTEXT = 'In offshore transport and emergency aeromedical rescue operations, route planning teams evaluate candidate offshore emergency evacuation corridors to ensure critical patient transit feasibility and safety under demanding conditions. Flight dispatch coordinators assess regulatory approvals, platform capabilities, flight duration thresholds, trauma receiving capacity, and navigation radar lock before activating a corridor and calculating standard fuel mission requirements.'
|
| 36 |
+
|
| 37 |
+
"""Parse one model message without treating trailing generation noise as an action."""
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from typing import Any
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_json_message(content: Any, *, trace: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 44 |
+
if trace is not None:
|
| 45 |
+
trace.clear()
|
| 46 |
+
trace.update(policy="first_complete_object", raw_response=content, recovered=False)
|
| 47 |
+
if not isinstance(content, str):
|
| 48 |
+
raise ValueError("model response must be text")
|
| 49 |
+
text = content.strip().lstrip("\ufeff").strip()
|
| 50 |
+
# Parse the first complete object; never recover a nested fragment.
|
| 51 |
+
try:
|
| 52 |
+
value, end = json.JSONDecoder().raw_decode(text)
|
| 53 |
+
start = 0
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
if text.startswith(("{", "[", '"')):
|
| 56 |
+
raise
|
| 57 |
+
opening = re.search(r"[\{\[]", text)
|
| 58 |
+
if opening is None:
|
| 59 |
+
raise
|
| 60 |
+
start = opening.start()
|
| 61 |
+
value, consumed = json.JSONDecoder().raw_decode(text[start:])
|
| 62 |
+
end = start + consumed
|
| 63 |
+
if not isinstance(value, dict):
|
| 64 |
+
raise ValueError("model response must be a JSON object")
|
| 65 |
+
prefix, suffix = text[:start], text[end:]
|
| 66 |
+
if trace is not None:
|
| 67 |
+
trace.update(recovered=bool(prefix.strip() or suffix.strip()),
|
| 68 |
+
ignored_prefix=prefix, ignored_suffix=suffix)
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def expand_question_keys(questions):
|
| 73 |
+
expanded = []
|
| 74 |
+
for question in questions:
|
| 75 |
+
if not isinstance(question, dict):
|
| 76 |
+
expanded.append(question)
|
| 77 |
+
continue
|
| 78 |
+
text = question.get("question")
|
| 79 |
+
keys = list(dict.fromkeys(REPLY_KEY_PATTERN.findall(text))) if isinstance(text, str) else []
|
| 80 |
+
for key in keys or [None]:
|
| 81 |
+
expanded.append(dict(question, key=key))
|
| 82 |
+
return expanded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def validate_question(question, *, role_name, semantic_enabled=False):
|
| 86 |
+
if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
|
| 87 |
+
raise ValueError("question must contain natural-language text")
|
| 88 |
+
if role_name not in ROLE_KEY_PREFIXES:
|
| 89 |
+
raise ValueError("unknown Role")
|
| 90 |
+
key = question.get("key")
|
| 91 |
+
authorized = semantic_enabled if key is None else (
|
| 92 |
+
isinstance(key, str) and key in ROLE_VALID_KEYS[role_name] and key in question["question"])
|
| 93 |
+
return {"authorized": bool(authorized)}
|
| 94 |
+
|
| 95 |
+
def recovery_key_match(answer: str) -> str | None:
|
| 96 |
+
target = ERROR_INJECTION.get("target_key")
|
| 97 |
+
if not target:
|
| 98 |
+
return None
|
| 99 |
+
def contains(key: str) -> bool:
|
| 100 |
+
return bool(re.search(r"(?<![A-Z0-9-])" + re.escape(key) + r"(?![A-Z0-9-])", answer, re.IGNORECASE))
|
| 101 |
+
if contains(target):
|
| 102 |
+
return "full_key"
|
| 103 |
+
parts = target.split("-")
|
| 104 |
+
alias = parts[0] + "-" + parts[-1]
|
| 105 |
+
matches = [key for key in ROLE_VALID_KEYS.get(ERROR_INJECTION.get("role_name"), [])
|
| 106 |
+
if key.split("-")[0] + "-" + key.split("-")[-1] == alias]
|
| 107 |
+
if matches == [target] and contains(alias):
|
| 108 |
+
return "abbreviated_key"
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
def communication_metrics(transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 112 |
+
key_query_rounds: dict[str, int] = {}
|
| 113 |
+
key_query_counts: dict[str, int] = {}
|
| 114 |
+
queried_roles: set[str] = set()
|
| 115 |
+
mismatch_round: int | None = None
|
| 116 |
+
recovery_query_sent = False
|
| 117 |
+
recovery_query_turn: int | None = None
|
| 118 |
+
target_key_returned = False
|
| 119 |
+
recovery_turn: int | None = None
|
| 120 |
+
recovery_method: str | None = None
|
| 121 |
+
recovery_reference: str | None = None
|
| 122 |
+
target_key_query_turn: int | None = None
|
| 123 |
+
finalized_before_recovery = False
|
| 124 |
+
for event in transcript:
|
| 125 |
+
turn = int(event.get("turn", len(transcript)))
|
| 126 |
+
action = event.get("main_agent_action", {})
|
| 127 |
+
if (
|
| 128 |
+
ERROR_INJECTION.get("enabled")
|
| 129 |
+
and action.get("action") == "finalize"
|
| 130 |
+
and not target_key_returned
|
| 131 |
+
):
|
| 132 |
+
finalized_before_recovery = True
|
| 133 |
+
if action.get("action") != "ask_role_agents": continue
|
| 134 |
+
for answer in event.get("role_answers", []):
|
| 135 |
+
role_name = answer.get("role_agent")
|
| 136 |
+
if role_name: queried_roles.add(role_name)
|
| 137 |
+
if (
|
| 138 |
+
ERROR_INJECTION.get("enabled") and mismatch_round is not None and turn > mismatch_round
|
| 139 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 140 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("target_key")
|
| 141 |
+
and "role_trace" in answer
|
| 142 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 143 |
+
):
|
| 144 |
+
target_key_query_turn = target_key_query_turn or turn
|
| 145 |
+
if (
|
| 146 |
+
ERROR_INJECTION.get("enabled")
|
| 147 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 148 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("alternate_key")
|
| 149 |
+
and "role_trace" in answer
|
| 150 |
+
):
|
| 151 |
+
mismatch_round = mismatch_round or turn
|
| 152 |
+
for message in action.get("messages", []):
|
| 153 |
+
for question in message.get("questions", []):
|
| 154 |
+
key = question.get("key")
|
| 155 |
+
if (
|
| 156 |
+
ERROR_INJECTION.get("enabled")
|
| 157 |
+
and resolve_role_name(message.get("role_agent")) == ERROR_INJECTION.get("role_name")
|
| 158 |
+
and (key is None or key == ERROR_INJECTION.get("target_key"))
|
| 159 |
+
and mismatch_round is not None
|
| 160 |
+
and turn > mismatch_round
|
| 161 |
+
):
|
| 162 |
+
recovery_query_sent = True
|
| 163 |
+
recovery_query_turn = recovery_query_turn or turn
|
| 164 |
+
if not isinstance(key, str) or not KEY_PATTERN.fullmatch(key): continue
|
| 165 |
+
key_query_rounds.setdefault(key, turn)
|
| 166 |
+
key_query_counts[key] = key_query_counts.get(key, 0) + 1
|
| 167 |
+
if recovery_query_sent and not target_key_returned and mismatch_round is not None and turn > mismatch_round:
|
| 168 |
+
for answer in event.get("role_answers", []):
|
| 169 |
+
question = answer.get("question", {})
|
| 170 |
+
if (
|
| 171 |
+
answer.get("role_agent") == ERROR_INJECTION.get("role_name")
|
| 172 |
+
and (question.get("key") is None or question.get("key") == ERROR_INJECTION.get("target_key"))
|
| 173 |
+
and "role_trace" in answer
|
| 174 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 175 |
+
):
|
| 176 |
+
target_key_returned = True
|
| 177 |
+
recovery_reference = recovery_key_match(str(answer.get("answer", "")))
|
| 178 |
+
recovery_turn = turn
|
| 179 |
+
recovery_method = "keyless_query" if question.get("key") is None else "target_key_query"
|
| 180 |
+
break
|
| 181 |
+
queried = set(key_query_counts)
|
| 182 |
+
required = set(REQUIRED_KEYS)
|
| 183 |
+
relevant = queried & required
|
| 184 |
+
return {
|
| 185 |
+
"required_key_recall":len(relevant)/len(required) if required else 1.0,
|
| 186 |
+
"required_key_precision":len(relevant)/len(queried) if queried else 0.0,
|
| 187 |
+
"key_query_rounds":key_query_rounds,
|
| 188 |
+
"key_query_counts":key_query_counts,
|
| 189 |
+
"duplicate_key_queries":sum(max(0, count-1) for count in key_query_counts.values()),
|
| 190 |
+
"distractor_key_queries":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS),
|
| 191 |
+
"distractor_key_query_rate":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS)/sum(key_query_counts.values()) if key_query_counts else 0.0,
|
| 192 |
+
"turns_to_finalize":len(transcript),
|
| 193 |
+
"mismatch_key_queried":mismatch_round is not None,
|
| 194 |
+
"mismatch_key_turn":mismatch_round,
|
| 195 |
+
"recovery_query_sent":recovery_query_sent,
|
| 196 |
+
"recovery_query_turn":recovery_query_turn,
|
| 197 |
+
"target_key_returned":target_key_returned,
|
| 198 |
+
"recovery_turn":recovery_turn,
|
| 199 |
+
"recovery_method":recovery_method,
|
| 200 |
+
"target_key_query_turn":target_key_query_turn,
|
| 201 |
+
"recovery_key_match":recovery_reference,
|
| 202 |
+
"recovery_metrics_version":"keyed_and_keyless_v3",
|
| 203 |
+
"recovery_latency":recovery_turn - mismatch_round if recovery_turn is not None and mismatch_round is not None else None,
|
| 204 |
+
"finalized_before_recovery":finalized_before_recovery,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
def main_system_prompt() -> str:
|
| 208 |
+
role_text = "\n".join(f"- {item['role_name']}: {item['responsibility']}" for item in PUBLIC_ROLES)
|
| 209 |
+
ask_example = json.dumps({"action":"ask_role_agents","messages":[{"role_agent":"Role name","questions":[{"id":"Q1","question":"Please provide the record for ABC-DATA-A1B using the supplied key."}]}]}, ensure_ascii=False)
|
| 210 |
+
final_example = json.dumps({"action":"finalize","conclusion":"Exactly: " + POSITIVE_CONCLUSION + " or " + NEGATIVE_CONCLUSION,"numeric_result":None}, ensure_ascii=False).replace('"numeric_result": null', '"numeric_result": null/number')
|
| 211 |
+
communication_protocol = ('You may output {"action":"wait"} to advance one logical turn. An empty observation {"observations":[]} means no new visible messages; it does not imply receipt, processing or any future reply.' if SETTING in {'missed', 'mixed'} else '')
|
| 212 |
+
followup = ('For keyless follow-ups, name the candidate in full and the metric explicitly, or request that candidate\'s complete records. A unique previously queried record can be checked directly; otherwise supply a full key and metric when asked to clarify. Explicit directory requests return the complete directory.' if SETTING == 'incomplete' else
|
| 213 |
+
'Authorized keyless follow-ups may name the candidate and metric or request complete records. A role may retrieve facts, request clarification or return a directory. If given a directory, select a valid key to obtain facts.' if SETTING == 'mixed' else
|
| 214 |
+
'Authorized keyless questions return that role\'s complete directory. Choose a key from the directory to obtain concrete facts.')
|
| 215 |
+
return "\n\n".join([
|
| 216 |
+
'You are the Main Agent. Integrate information from independent role agents and make the final decision. Communicate in English.',
|
| 217 |
+
'You cannot see private role information directly. Obtain it only by explicitly messaging the role agents.',
|
| 218 |
+
'Key protocol:\n1. Candidate names and record keys are supplied in the task. Initial access requires a valid key; authorized later follow-ups are the exception.\n'
|
| 219 |
+
'2. Keys use ROLE-BUSINESS-XXX: role abbreviation, business abbreviation and three random alphanumeric characters. Use complete supplied keys; do not invent them.\n'
|
| 220 |
+
'3. Send each key to its owning business role. Use valid keys supplied by roles for subsequent checks.\n'
|
| 221 |
+
'4. Do not output a separate key field. Put the complete key in question text; the system extracts it and checks ownership. Separate different keys into individual questions, preferably one record per question.\n'
|
| 222 |
+
'5. After a successful keyed query to a role, keyless natural-language follow-ups to that role are authorized starting from the next turn.\n6. ' + followup,
|
| 223 |
+
'Available independent role agents:\n\n' + role_text,
|
| 224 |
+
'To ask questions, output only JSON in this form:\n\n' + ask_example,
|
| 225 |
+
*([communication_protocol] if communication_protocol else []),
|
| 226 |
+
'Final answer format (output only valid JSON):\n\n' + final_example,
|
| 227 |
+
'Use exactly one of these conclusion labels: ' + POSITIVE_CONCLUSION + ' or ' + NEGATIVE_CONCLUSION + '. '
|
| 228 |
+
'Do not append a candidate name, explanation or other text. null/number means choose one, not literal syntax. '
|
| 229 |
+
'For a positive conclusion provide the computed number; for a negative conclusion use null. Do not include units or explanations in numeric_result.',
|
| 230 |
+
])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
"""Conservative English evidence rules shared by standalone generated runtimes.
|
| 234 |
+
|
| 235 |
+
This is attribution of explicit statements, not arbitrary semantic entailment.
|
| 236 |
+
Unsupported or conflicting statements remain unknown; no model calls are made.
|
| 237 |
+
"""
|
| 238 |
+
import re
|
| 239 |
+
from decimal import Decimal
|
| 240 |
+
|
| 241 |
+
_RECOVERY_NUMBER = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?'
|
| 242 |
+
_RECOVERY_UNCERTAIN = r"\b(?:unknown|uncertain|unclear|may|might|could|should|would|must|expected|possibly|whether|cannot|unable|unconfirmed|approximately|about|around|roughly|estimated|not confirmed|not known|not established)\b"
|
| 243 |
+
_RECOVERY_NEGATIVE = r'\b(?:not|no|never|false|invalid|blocked|failed|denied|unavailable|unapproved|revoked|inactive|disabled|noncompliant)\b'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def evidence_text(text):
|
| 247 |
+
text = text.replace('’', "'").replace('−', '-').replace('‑', '-')
|
| 248 |
+
text = re.sub(r"\bcan't\b", 'cannot', text, flags=re.I)
|
| 249 |
+
text = re.sub(r"n't\b", ' not', text, flags=re.I)
|
| 250 |
+
text = re.sub(r'(?<![\w.,])[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,]|\.\d)',
|
| 251 |
+
lambda m: m[0].replace(',', ''), text)
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def evidence_phrase(text, phrase):
|
| 256 |
+
if not phrase:
|
| 257 |
+
return False
|
| 258 |
+
return bool(re.search(r'(?<!\w)' + re.escape(phrase).replace(r'\ ', r'\s+') + r'(?!\w)', text, re.I))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def evidence_nonasserted(text):
|
| 262 |
+
"""Questions, hypotheses and unconfirmed claims are not returned facts."""
|
| 263 |
+
return bool('?' in text or re.search(_RECOVERY_UNCERTAIN, text, re.I)
|
| 264 |
+
or re.search(r'\b(?:if|unless|assuming|suppose|supposing|hypothetically)\b', text, re.I)
|
| 265 |
+
or re.search(r'\b(?:do|does|did|has|have|had)\s+not\s+(?:confirm|verify|establish)(?:ed)?\b', text, re.I))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def evidence_clauses(text):
|
| 269 |
+
# Preserve questions and uncertainty when splitting assertions.
|
| 270 |
+
sentences = re.split(r'[。\n]|\.(?!\d)|(?<=[!?])\s+', text)
|
| 271 |
+
clauses = []
|
| 272 |
+
for sentence in sentences:
|
| 273 |
+
if evidence_nonasserted(sentence):
|
| 274 |
+
clauses.append(sentence)
|
| 275 |
+
else:
|
| 276 |
+
clauses.extend(re.split(r'[;;]|,?\s+\b(?:but|and)\b\s+(?![+-]?\d)', sentence, flags=re.I))
|
| 277 |
+
return clauses
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def evidence_scope(answer, question, profile):
|
| 281 |
+
for target in [profile.get('candidate', ''), profile.get('target_context', '')]:
|
| 282 |
+
if target and re.search(r'\b(?:not|outside|excluding|except)(?:\s+(?:for|the))?\s+' + re.escape(target) + r'(?!\w)', answer, re.I):
|
| 283 |
+
return 'not_returned'
|
| 284 |
+
candidates = profile.get('other_candidates', [])
|
| 285 |
+
contexts = profile.get('other_contexts', [profile.get('alternate_context', '')])
|
| 286 |
+
if any(evidence_phrase(answer, c) for c in [*candidates, *contexts] if c):
|
| 287 |
+
target_also_present = evidence_phrase(answer, profile.get('candidate', '')) and (
|
| 288 |
+
not profile.get('target_context') or evidence_phrase(answer, profile['target_context']))
|
| 289 |
+
return 'unknown' if target_also_present else 'not_returned'
|
| 290 |
+
combined = question.get('question', '') + '\n' + answer
|
| 291 |
+
target_key = profile.get('target_key', '')
|
| 292 |
+
if target_key and (question.get('key') == target_key or evidence_phrase(combined, target_key)):
|
| 293 |
+
return 'eligible'
|
| 294 |
+
if evidence_phrase(combined, profile.get('candidate', '')) and (
|
| 295 |
+
not profile.get('target_context') or evidence_phrase(combined, profile['target_context'])):
|
| 296 |
+
return 'eligible'
|
| 297 |
+
return 'unknown'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def evidence_unit_pattern(unit):
|
| 301 |
+
# Unit names may inflect; canonical symbols remain case-sensitive.
|
| 302 |
+
groups = [('h', 'hour', 'hours'), ('min', 'minute', 'minutes'), ('s', 'second', 'seconds'),
|
| 303 |
+
('kg', 'kilogram', 'kilograms'), ('m', 'meter', 'meters', 'metre', 'metres'),
|
| 304 |
+
('%', 'percent', 'per cent'), ('instances', 'instance'), ('items', 'item'),
|
| 305 |
+
('people', 'person', 'persons'), ('days', 'day')]
|
| 306 |
+
for group in groups:
|
| 307 |
+
if unit in group:
|
| 308 |
+
canonical, *words = group
|
| 309 |
+
if canonical in {'instances', 'items', 'people', 'days'}:
|
| 310 |
+
words.append(canonical)
|
| 311 |
+
canonical = None
|
| 312 |
+
parts = ([re.escape(canonical)] if canonical else []) + ['(?i:' + re.escape(w) + ')' for w in words]
|
| 313 |
+
if unit == '%': parts.append('%')
|
| 314 |
+
return '(?:' + '|'.join(sorted(parts, key=len, reverse=True)) + ')'
|
| 315 |
+
return re.escape(unit)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evidence_measurements(text, unit):
|
| 319 |
+
text = evidence_text(text)
|
| 320 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 321 |
+
suffix = (r'(?:\s+(?:1|(?i:dimensionless)))?' if unit == '1'
|
| 322 |
+
else r'\s*' + evidence_unit_pattern(unit))
|
| 323 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')' + suffix + r'(?![A-Za-z0-9_/%]|\.\d|,\d)'
|
| 324 |
+
return text, list(re.finditer(pattern, text))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def evidence_exact_measurement(text, match):
|
| 328 |
+
before, after = text[max(0, match.start()-60):match.start()], text[match.end():match.end()+45]
|
| 329 |
+
if evidence_nonasserted(text):
|
| 330 |
+
return False
|
| 331 |
+
if re.search(r'(?:\b(?:under|over|below|above|less than|more than|at most|at least|up to|between|to|and|not|no more than|no less than)|不超过|不低于|小于等于|大于等于|小于|大于|至少|至多|最多|最少|低于|高于|介于|至|到|[<>≤≥~~–—])\s*$', before, re.I):
|
| 332 |
+
return False
|
| 333 |
+
if re.search(r'\d\s*[-–—]\s*$', before):
|
| 334 |
+
return False
|
| 335 |
+
if re.match(r'\s*(?:\b(?:maximum|minimum|max|min)\b|\bor (?:less|more|lower|higher)\b|\b(?:to|through)\s+[+-]?\d|[-–—~~]\s*\d)', after, re.I):
|
| 336 |
+
return False
|
| 337 |
+
return True
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def english_exact_value(answer, value, unit):
|
| 341 |
+
for clause in evidence_clauses(evidence_text(answer)):
|
| 342 |
+
text, matches = evidence_measurements(clause, unit)
|
| 343 |
+
if any(Decimal(m[1]) == Decimal(str(value)) and evidence_exact_measurement(text, m) for m in matches):
|
| 344 |
+
return True
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def numeric_evidence(answer, question, profile, fact):
|
| 349 |
+
answer = evidence_text(answer)
|
| 350 |
+
scope = evidence_scope(answer, question, profile)
|
| 351 |
+
if scope != 'eligible':
|
| 352 |
+
return scope
|
| 353 |
+
labels = [fact.get('label', ''), *fact.get('aliases', [])]
|
| 354 |
+
states = set()
|
| 355 |
+
for clause in evidence_clauses(answer):
|
| 356 |
+
# Bind each value to its asserted metric; nearby numbers are not evidence.
|
| 357 |
+
if not any(evidence_phrase(clause, label) for label in labels if label):
|
| 358 |
+
continue
|
| 359 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 360 |
+
continue
|
| 361 |
+
# Leave ambiguous multi-metric clauses unscored.
|
| 362 |
+
others = profile.get('facts', profile.get('numeric', []) + profile.get('boolean', []))
|
| 363 |
+
if any(other.get('topic') != fact.get('topic') and any(evidence_phrase(clause, label) for label in
|
| 364 |
+
[other.get('label', ''), *other.get('aliases', [])] if label) for other in others):
|
| 365 |
+
continue
|
| 366 |
+
text, matches = evidence_measurements(clause, fact.get('unit', ''))
|
| 367 |
+
for m in matches:
|
| 368 |
+
if evidence_exact_measurement(text, m) and not re.search(_RECOVERY_NEGATIVE, text[:m.start()], re.I):
|
| 369 |
+
states.add(Decimal(m[1]) == Decimal(str(fact['value'])))
|
| 370 |
+
if len(states) != 1:
|
| 371 |
+
return 'unknown'
|
| 372 |
+
return 'returned' if states.pop() else 'not_returned'
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _evidence_predicate(text):
|
| 376 |
+
text = re.sub(r'\b(?:is|are|was|were|has|have|had|been|the|a|an|already)\b', ' ', text.casefold())
|
| 377 |
+
return re.sub(r'\s+', ' ', text).strip(' .:')
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def boolean_evidence(answer, question, profile):
|
| 381 |
+
answer = evidence_text(answer)
|
| 382 |
+
scope = evidence_scope(answer, question, profile)
|
| 383 |
+
if scope != 'eligible':
|
| 384 |
+
return scope
|
| 385 |
+
labels = [profile['label'], *profile.get('aliases', [])]
|
| 386 |
+
states = set()
|
| 387 |
+
for clause in evidence_clauses(answer):
|
| 388 |
+
plain = _evidence_predicate(clause)
|
| 389 |
+
no_negative = _evidence_predicate(re.sub(_RECOVERY_NEGATIVE, ' ', clause, flags=re.I))
|
| 390 |
+
if not any(evidence_phrase(plain, _evidence_predicate(label)) or evidence_phrase(no_negative, _evidence_predicate(label)) for label in labels if label):
|
| 391 |
+
continue
|
| 392 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 393 |
+
continue
|
| 394 |
+
remainder = clause
|
| 395 |
+
for label in sorted(labels, key=len, reverse=True):
|
| 396 |
+
remainder = re.sub(re.escape(label), '', remainder, flags=re.I)
|
| 397 |
+
negative = bool(re.search(_RECOVERY_NEGATIVE, remainder, re.I))
|
| 398 |
+
explicit = bool(re.search(r'\b(?:true|yes|false|no)\b', remainder, re.I))
|
| 399 |
+
predicate = r'\b(?:enabled|issued|approved|valid|clear|ready|open|active|completed|available|installed|registered|signed|granted|confirmed|operational|compliant|meets|passed|released|equipped|connected|running|accepted)\b'
|
| 400 |
+
affirmative = evidence_phrase(no_negative, _evidence_predicate(profile['label'])) and bool(re.search(predicate, profile['label'], re.I))
|
| 401 |
+
label_match = evidence_phrase(no_negative, _evidence_predicate(profile['label']))
|
| 402 |
+
# Do not transfer negation between unrelated metrics.
|
| 403 |
+
opposites = {'disabled':'enabled', 'unavailable':'available', 'invalid':'valid',
|
| 404 |
+
'closed':'open', 'inactive':'active', 'blocked':'clear', 'revoked':'granted'}
|
| 405 |
+
opposite = False
|
| 406 |
+
for denied, affirmed in opposites.items():
|
| 407 |
+
if re.search(r'\b' + denied + r'\b', clause, re.I):
|
| 408 |
+
rewritten = re.sub(r'\b' + denied + r'\b', affirmed, clause, flags=re.I)
|
| 409 |
+
opposite |= evidence_phrase(_evidence_predicate(rewritten), _evidence_predicate(profile['label']))
|
| 410 |
+
bare_boolean = bool(explicit and re.fullmatch(r'(?:status\s*[:=]?\s*)?(?:true|yes|false|no)',
|
| 411 |
+
_evidence_predicate(remainder), re.I))
|
| 412 |
+
if affirmative or label_match and (negative or explicit) or opposite or bare_boolean:
|
| 413 |
+
states.add(not (negative or opposite))
|
| 414 |
+
if len(states) != 1:
|
| 415 |
+
return 'unknown'
|
| 416 |
+
return 'returned' if states.pop() == profile['value'] else 'not_returned'
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def recovery_number_present(answer, value):
|
| 420 |
+
"""Literal numeric occurrence, independent of unit, metric, scope or wording."""
|
| 421 |
+
text = re.sub(r'(?<![A-Z0-9])[A-Z]{2,10}-[A-Z]{2,10}-[A-Z0-9]{3}(?![A-Z0-9])', '', answer, flags=re.I)
|
| 422 |
+
text = evidence_text(text)
|
| 423 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 424 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')(?![0-9_]|\.\d|,\d)'
|
| 425 |
+
return any(Decimal(m[1]) == Decimal(str(value)) for m in re.finditer(pattern, text))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
import os
|
| 431 |
+
import random
|
| 432 |
+
from datetime import datetime
|
| 433 |
+
from pathlib import Path
|
| 434 |
+
from typing import Dict, List
|
| 435 |
+
|
| 436 |
+
from openai import OpenAI
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_project_env() -> None:
|
| 440 |
+
for parent in Path(__file__).resolve().parents:
|
| 441 |
+
env_path = parent / ".env"
|
| 442 |
+
if not env_path.is_file():
|
| 443 |
+
continue
|
| 444 |
+
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
| 445 |
+
line = raw_line.strip()
|
| 446 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 447 |
+
continue
|
| 448 |
+
key, value = line.split("=", 1)
|
| 449 |
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
load_project_env()
|
| 454 |
+
MAIN_AGENT_API_KEY = os.getenv("MAIN_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 455 |
+
MAIN_AGENT_MODEL_NAME = os.getenv("MAIN_AGENT_MODEL_NAME", "openai/gpt-5.5")
|
| 456 |
+
MAIN_AGENT_BASE_URL = os.getenv("MAIN_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 457 |
+
ROLE_AGENT_API_KEY = os.getenv("ROLE_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 458 |
+
ROLE_AGENT_MODEL_NAME = "deepseek/deepseek-v4-flash-0731"
|
| 459 |
+
ROLE_AGENT_BASE_URL = os.getenv("ROLE_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 460 |
+
LLM_REASONING_EFFORT = os.getenv("LLM_REASONING_EFFORT", "medium")
|
| 461 |
+
ROLE_REASONING_EFFORT = "low"
|
| 462 |
+
ROLE_MAX_TOKENS = 8192
|
| 463 |
+
LLM_REASONING_EXCLUDE = os.getenv("LLM_REASONING_EXCLUDE", "1") != "0"
|
| 464 |
+
MAIN_AGENT_ROLE_ORDER_SEED = os.getenv("MAIN_AGENT_ROLE_ORDER_SEED")
|
| 465 |
+
AGENT_DIR = str(Path(__file__).resolve().parent.parent / "role_agents")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def print_key_trace(title: str, content: Any = "") -> None:
|
| 469 |
+
print(f"\n========== {title} ==========\n", flush=True)
|
| 470 |
+
if content != "":
|
| 471 |
+
print(str(content), flush=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def format_metric_value(value: Any) -> str:
|
| 475 |
+
if isinstance(value, float):
|
| 476 |
+
return f"{value:.4f}"
|
| 477 |
+
if value is None:
|
| 478 |
+
return "None"
|
| 479 |
+
return str(value)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def format_llm_config() -> str:
|
| 483 |
+
return "\n".join([
|
| 484 |
+
f"main_agent_llm: {MAIN_AGENT_MODEL_NAME}",
|
| 485 |
+
f"role_agent_llm: {ROLE_AGENT_MODEL_NAME}",
|
| 486 |
+
f"reasoning_effort: {LLM_REASONING_EFFORT}",
|
| 487 |
+
f"role_reasoning_effort: {ROLE_REASONING_EFFORT}",
|
| 488 |
+
])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def format_available_roles(role_agents: Dict[str, Any]) -> str:
|
| 492 |
+
lines = []
|
| 493 |
+
for role_name, role in role_agents.items():
|
| 494 |
+
key_prefix = ROLE_KEY_PREFIXES.get(role_name, "")
|
| 495 |
+
lines.append(f"- {role_name}(Key 格式:{key_prefix}业务缩写-XXX):{role.config['abstract']}")
|
| 496 |
+
return "\n".join(lines)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def format_evaluation_summary(evaluation: Dict[str, Any]) -> str:
|
| 500 |
+
conclusion = evaluation.get("conclusion_evaluation", {})
|
| 501 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 502 |
+
fields = [
|
| 503 |
+
("ground_truth_conclusion", conclusion.get("ground_truth_conclusion")),
|
| 504 |
+
("ground_truth_numeric_result", conclusion.get("ground_truth_numeric_result")),
|
| 505 |
+
("final_conclusion", conclusion.get("final_conclusion")),
|
| 506 |
+
("parsed_numeric_result", conclusion.get("parsed_numeric_result")),
|
| 507 |
+
("conclusion_correct", conclusion.get("conclusion_correct")),
|
| 508 |
+
("numeric_result_correct", conclusion.get("numeric_result_correct")),
|
| 509 |
+
("turns_to_finalize", communication.get("turns_to_finalize")),
|
| 510 |
+
("total_role_agent_queries", communication.get("total_role_agent_queries")),
|
| 511 |
+
("total_questions", communication.get("total_questions")),
|
| 512 |
+
("duplicate_key_queries", communication.get("duplicate_key_queries")),
|
| 513 |
+
]
|
| 514 |
+
return "\n".join(f"{name}: {format_metric_value(value)}" for name, value in fields)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def format_key_metrics(evaluation: Dict[str, Any]) -> str:
|
| 518 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 519 |
+
correctness = int(bool(evaluation.get("joint_correctness")))
|
| 520 |
+
turns = communication.get("turns_to_finalize")
|
| 521 |
+
lines = [
|
| 522 |
+
f"正确率: {correctness}",
|
| 523 |
+
f"完成轮数: {format_metric_value(turns)} / {communication.get('max_turns', DEFAULT_MAX_TURNS)}(理想:{communication.get('finalize_ideal_round', FINALIZE_IDEAL_ROUND)})",
|
| 524 |
+
]
|
| 525 |
+
if SETTING in {"incomplete", "mixed"}:
|
| 526 |
+
lines.append(f"阈值补齐: {communication.get('incomplete_threshold_returned', False)};补齐轮次: {communication.get('incomplete_recovery_turn')};补救成功: {communication.get('incomplete_recovery_success')}")
|
| 527 |
+
if SETTING in {"missed", "mixed"}:
|
| 528 |
+
lines.append(f"忽略: {communication.get('neglect_ignored_count', 0)};交付: {communication.get('neglect_delivered_count', 0)};待答: {communication.get('neglect_pending_count', 0)}")
|
| 529 |
+
if SETTING not in {"misaligned", "mixed"}:
|
| 530 |
+
return "\n".join(lines)
|
| 531 |
+
|
| 532 |
+
if communication.get("error_recovery_status") == "unknown":
|
| 533 |
+
lines.append("Recovery result: UNKNOWN (evidence cannot be classified; excluded from recovery rates)")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
+
|
| 536 |
+
mismatch_queried = bool(communication.get("mismatch_key_queried"))
|
| 537 |
+
mismatch_turn = communication.get("mismatch_key_turn")
|
| 538 |
+
recovery_query_sent = bool(communication.get("recovery_query_sent"))
|
| 539 |
+
recovery_query_turn = communication.get("recovery_query_turn")
|
| 540 |
+
target_key_returned = bool(communication.get("error_fact_returned", communication.get("target_key_returned")))
|
| 541 |
+
recovery_turn = communication.get("recovery_turn")
|
| 542 |
+
finalized_early = bool(communication.get("finalized_before_recovery"))
|
| 543 |
+
|
| 544 |
+
def turn_suffix(turn: Any) -> str:
|
| 545 |
+
return f"(第{turn}轮)" if isinstance(turn, int) else ""
|
| 546 |
+
|
| 547 |
+
lines.extend(["", "恢复链路:"])
|
| 548 |
+
if not mismatch_queried:
|
| 549 |
+
lines.extend([
|
| 550 |
+
f"✗ 未访问错配 key:{ERROR_INJECTION.get('alternate_key')}",
|
| 551 |
+
"— 未触发补救询问",
|
| 552 |
+
"— Role 未返回目标 key",
|
| 553 |
+
"— 未进入恢复流程",
|
| 554 |
+
"",
|
| 555 |
+
"恢复延迟:N/A",
|
| 556 |
+
"恢复结果:NOT_TRIGGERED(Main 未访问错配 key)",
|
| 557 |
+
])
|
| 558 |
+
return "\n".join(lines)
|
| 559 |
+
|
| 560 |
+
lines.append(
|
| 561 |
+
f"✓ 已访问错配 key:{ERROR_INJECTION.get('alternate_key')}{turn_suffix(mismatch_turn)}"
|
| 562 |
+
)
|
| 563 |
+
lines.append(
|
| 564 |
+
("✓ 已发起补救询问" if recovery_query_sent else "✗ 未发起补救询问")
|
| 565 |
+
+ turn_suffix(recovery_query_turn)
|
| 566 |
+
)
|
| 567 |
+
lines.append(
|
| 568 |
+
(
|
| 569 |
+
f"✓ Role 已返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 570 |
+
if target_key_returned
|
| 571 |
+
else f"✗ Role 未返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 572 |
+
)
|
| 573 |
+
+ turn_suffix(recovery_turn)
|
| 574 |
+
)
|
| 575 |
+
lines.append("✗ 已在恢复前提前 finalize" if finalized_early else "✓ 未在恢复前提前 finalize")
|
| 576 |
+
if target_key_returned:
|
| 577 |
+
lines.append("✓ 恢复后最终答案正确" if correctness else "✗ 恢复后最终答案错误")
|
| 578 |
+
else:
|
| 579 |
+
lines.append("— 尚未完成恢复,无法判断恢复后答案")
|
| 580 |
+
|
| 581 |
+
recovery_latency = communication.get("recovery_latency")
|
| 582 |
+
recovery_method = communication.get("recovery_method")
|
| 583 |
+
if recovery_method:
|
| 584 |
+
target_query_turn = communication.get("target_key_query_turn")
|
| 585 |
+
if recovery_method == "keyless_query" and isinstance(target_query_turn, int) and isinstance(recovery_turn, int) and target_query_turn > recovery_turn:
|
| 586 |
+
method_label = "无 key 获取目录 → 正确 key 查询"
|
| 587 |
+
lines.append(f"取得目标 key:第{recovery_turn}轮")
|
| 588 |
+
lines.append(f"正确 key 查询取得答复:第{target_query_turn}轮")
|
| 589 |
+
recovery_latency = target_query_turn - mismatch_turn if isinstance(mismatch_turn, int) else recovery_latency
|
| 590 |
+
else:
|
| 591 |
+
method_label = {"keyless_query": "无 key 补充询问", "target_key_query": "目标 key 纠正查询"}.get(recovery_method, recovery_method)
|
| 592 |
+
lines.append(f"补救方式:{method_label}")
|
| 593 |
+
if communication.get("recovery_success"):
|
| 594 |
+
status = "SUCCESS"
|
| 595 |
+
elif finalized_early:
|
| 596 |
+
status = "FINALIZED_EARLY"
|
| 597 |
+
elif not recovery_query_sent:
|
| 598 |
+
status = "RECOVERY_NOT_REQUESTED"
|
| 599 |
+
elif not target_key_returned:
|
| 600 |
+
status = "TARGET_NOT_RETURNED"
|
| 601 |
+
else:
|
| 602 |
+
status = "RECOVERED_BUT_WRONG"
|
| 603 |
+
lines.extend([
|
| 604 |
+
"",
|
| 605 |
+
f"恢复延迟:{recovery_latency}轮" if isinstance(recovery_latency, int) else "恢复延迟:N/A",
|
| 606 |
+
f"恢复结果:{status}",
|
| 607 |
+
])
|
| 608 |
+
return "\n".join(lines)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def format_role_messages(action: Dict[str, Any], role_answers: List[Dict[str, Any]]) -> str:
|
| 612 |
+
requested = {
|
| 613 |
+
(message.get("role_agent"), question.get("id"), question.get("key")): question.get("question")
|
| 614 |
+
for message in action.get("messages", [])
|
| 615 |
+
for question in message.get("questions", [])
|
| 616 |
+
}
|
| 617 |
+
blocks = []
|
| 618 |
+
for item in role_answers:
|
| 619 |
+
question = item.get("question", {})
|
| 620 |
+
identity = (item.get("role_agent"), question.get("id"), question.get("key"))
|
| 621 |
+
blocks.append("\n".join([
|
| 622 |
+
f"role_agent: {item.get('role_agent')}",
|
| 623 |
+
f"question_id: {question.get('id')}",
|
| 624 |
+
f"key: {question.get('key')}",
|
| 625 |
+
f"question: {requested.get(identity, question.get('question'))}",
|
| 626 |
+
f"answer: {item.get('answer')}",
|
| 627 |
+
]))
|
| 628 |
+
return "\n\n".join(blocks)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def parse_numeric_result(value: Any) -> int | float | None:
|
| 632 |
+
if value is None or isinstance(value, bool):
|
| 633 |
+
return None
|
| 634 |
+
if isinstance(value, (int, float)):
|
| 635 |
+
number = float(value)
|
| 636 |
+
elif isinstance(value, str):
|
| 637 |
+
match = re.search(r"[-+]?\d+(?:\.\d+)?", value.strip())
|
| 638 |
+
if not match:
|
| 639 |
+
return None
|
| 640 |
+
number = float(match.group(0))
|
| 641 |
+
else:
|
| 642 |
+
return None
|
| 643 |
+
rounded = round(number, NUMERIC_PRECISION)
|
| 644 |
+
return int(rounded) if NUMERIC_PRECISION == 0 else rounded
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def compute_conclusion_correctness(final_result: Dict[str, Any]) -> Dict[str, Any]:
|
| 648 |
+
parsed = parse_numeric_result(final_result.get("numeric_result"))
|
| 649 |
+
expected = parse_numeric_result(GOLD["numeric_result"])
|
| 650 |
+
conclusion_correct = int(final_result.get("conclusion") == GOLD["conclusion"])
|
| 651 |
+
numeric_correct = int(parsed == expected)
|
| 652 |
+
return {
|
| 653 |
+
"ground_truth_conclusion": GOLD["conclusion"],
|
| 654 |
+
"ground_truth_numeric_result": GOLD["numeric_result"],
|
| 655 |
+
"final_conclusion": final_result.get("conclusion"),
|
| 656 |
+
"numeric_result_raw": final_result.get("numeric_result"),
|
| 657 |
+
"parsed_numeric_result": parsed,
|
| 658 |
+
"conclusion_correct": conclusion_correct,
|
| 659 |
+
"numeric_result_correct": numeric_correct,
|
| 660 |
+
"conclusion_correctness": int(conclusion_correct and numeric_correct),
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def format_role_user_message(question: Dict[str, Any]) -> str:
|
| 665 |
+
question_id = str(question.get("id") or "Q")
|
| 666 |
+
text = str(question["question"]).strip()
|
| 667 |
+
return f"{question_id}: {text}"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
"""Deterministic follow-up routing; metadata contains no hidden values or target flags."""
|
| 671 |
+
import re
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def build_followup_records(task):
|
| 675 |
+
roles = {r['role_id']: r['name'] for r in task['roles']}
|
| 676 |
+
candidates = {c['candidate_id']: c['name'] for c in task['candidates']}
|
| 677 |
+
topics = {t['topic_id']: t for group in ('topics', 'distractor_topics', 'supplemental_topics')
|
| 678 |
+
for t in task.get(group, [])}
|
| 679 |
+
observations = {o['observation_id']: o for o in task['observations']}
|
| 680 |
+
records = []
|
| 681 |
+
for record in task['records']:
|
| 682 |
+
fields = []
|
| 683 |
+
for oid in record['observation_ids']:
|
| 684 |
+
tid = observations[oid]['topic_id']
|
| 685 |
+
topic = topics.get(tid, {})
|
| 686 |
+
if topic.get('label'):
|
| 687 |
+
fields.append({'id': tid, 'label': topic['label'], 'aliases': topic.get('aliases', [])})
|
| 688 |
+
records.append(dict(key=task['routing']['record_keys'][record['record_id']],
|
| 689 |
+
role=roles[record['owner_role_id']], candidate=candidates[record['candidate_id']],
|
| 690 |
+
context=(record.get('context') or {}).get('value', ''), fields=fields))
|
| 691 |
+
return records
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class IncompleteFollowupResolver:
|
| 695 |
+
VERSION = 'rule_followup_v2_english'
|
| 696 |
+
CLARIFY = 'The record and metric cannot be uniquely identified. Put the complete record key and the metric to verify in your question.'
|
| 697 |
+
|
| 698 |
+
def __init__(self, records):
|
| 699 |
+
self.records = records
|
| 700 |
+
self.reset()
|
| 701 |
+
|
| 702 |
+
def reset(self):
|
| 703 |
+
self.seen = {}
|
| 704 |
+
self.events = []
|
| 705 |
+
|
| 706 |
+
def observe(self, role, key, turn):
|
| 707 |
+
if key is not None:
|
| 708 |
+
self.seen.setdefault((role, key), turn)
|
| 709 |
+
|
| 710 |
+
@staticmethod
|
| 711 |
+
def normalize(text):
|
| 712 |
+
return re.sub(r'\s+', ' ', text).strip().casefold().replace('’', "'").replace('‑', '-').replace('–', '-')
|
| 713 |
+
|
| 714 |
+
@classmethod
|
| 715 |
+
def mentions(cls, text, phrase):
|
| 716 |
+
phrase = cls.normalize(phrase)
|
| 717 |
+
if re.search(r'[\u3400-\u9fff]', phrase):
|
| 718 |
+
return phrase.replace(' ', '') in text.replace(' ', '')
|
| 719 |
+
return bool(re.search(r'(?<![\w])' + re.escape(phrase) + r'(?![\w])', text))
|
| 720 |
+
|
| 721 |
+
def resolve(self, role, text, turn):
|
| 722 |
+
text = self.normalize(text)
|
| 723 |
+
available = [r for r in self.records if r['role'] == role]
|
| 724 |
+
if re.search(r'目录|索引列表|key列表|\b(?:catalog(?:ue)?s?|director(?:y|ies)|(?:key|index)\s+lists?)\b', text):
|
| 725 |
+
result = dict(status='catalog', key=None, fields=[])
|
| 726 |
+
else:
|
| 727 |
+
# Match the full role catalog before restricting to previously queried records.
|
| 728 |
+
names = {r['candidate'] for r in available if self.mentions(text, r['candidate'])}
|
| 729 |
+
contexts = {r['context'] for r in available if r['context'] and self.mentions(text, r['context'])}
|
| 730 |
+
fields = {f['id'] for r in available for f in r['fields']
|
| 731 |
+
if any(self.mentions(text, a) for a in [f['label'], *f['aliases']] if a)}
|
| 732 |
+
full = bool(re.search(r'完整(?:资料|信息|内容|记录)|全部(?:资料|信息|内容)|详细资料|\b(?:complete|full|all|detailed)\s+(?:(?:the|your|available)\s+)*(?:records?|information|details|data)\b', text))
|
| 733 |
+
matches = [r for r in available
|
| 734 |
+
if self.seen.get((role, r['key']), turn) < turn
|
| 735 |
+
and r['candidate'] in names
|
| 736 |
+
and (not contexts or r['context'] in contexts)
|
| 737 |
+
and (fields <= {f['id'] for f in r['fields']} if fields else full)]
|
| 738 |
+
# Ambiguous references require a key; do not infer pronouns or fuzzy matches.
|
| 739 |
+
unique = len(names) == 1 and len(contexts) <= 1 and len(matches) == 1 and (fields or full)
|
| 740 |
+
result = dict(status='resolved' if unique else 'clarify',
|
| 741 |
+
key=matches[0]['key'] if unique else None, fields=sorted(fields), full=full)
|
| 742 |
+
self.events.append(dict(turn=turn, role_agent=role, question=text, **result))
|
| 743 |
+
return result
|
| 744 |
+
|
| 745 |
+
def catalog(self, role):
|
| 746 |
+
return 'Complete record directory (supply a key to obtain facts):\n' + '\n'.join(
|
| 747 |
+
r['key'] + ':' + r['candidate'] + (';' + r['context'] if r['context'] else '')
|
| 748 |
+
+ '; Metrics: ' + '、'.join(f['label'] for f in r['fields'])
|
| 749 |
+
for r in self.records if r['role'] == role)
|
| 750 |
+
|
| 751 |
+
def metrics(self):
|
| 752 |
+
return dict(incomplete_followup_protocol=self.VERSION,
|
| 753 |
+
incomplete_keyless_followup_count=len(self.events),
|
| 754 |
+
incomplete_rule_resolved_count=sum(e['status'] == 'resolved' for e in self.events),
|
| 755 |
+
incomplete_clarification_count=sum(e['status'] == 'clarify' for e in self.events),
|
| 756 |
+
incomplete_followup_routing=list(self.events))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
"""Self-contained Incomplete policy embedded only in generated Incomplete run_one.py files."""
|
| 760 |
+
import re
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class IncompletePolicy:
|
| 764 |
+
def __init__(self, profile):
|
| 765 |
+
self.profile = profile
|
| 766 |
+
self.reset()
|
| 767 |
+
|
| 768 |
+
def reset(self):
|
| 769 |
+
self.omitted_at_turn = None
|
| 770 |
+
self.followup_at_turn = None
|
| 771 |
+
self.recovered_at_turn = None
|
| 772 |
+
|
| 773 |
+
def mode(self, role_name, question, turn):
|
| 774 |
+
if role_name != self.profile['role_name'] or question.get('key') != self.profile['key']:
|
| 775 |
+
return None
|
| 776 |
+
if self.recovered_at_turn is not None:
|
| 777 |
+
return None
|
| 778 |
+
# Any valid later query of the same record can recover the omitted value.
|
| 779 |
+
if self.omitted_at_turn is not None and turn > self.omitted_at_turn:
|
| 780 |
+
if self.followup_at_turn is None:
|
| 781 |
+
self.followup_at_turn = turn
|
| 782 |
+
return 'incomplete_recovery'
|
| 783 |
+
return 'incomplete_partial'
|
| 784 |
+
|
| 785 |
+
def request_options(self, mode, full_system_message):
|
| 786 |
+
profile = self.profile
|
| 787 |
+
coarse = profile.get('disclosure_mode', 'omission') != 'omission'
|
| 788 |
+
if mode == 'incomplete_partial':
|
| 789 |
+
system = (
|
| 790 |
+
f"You are {profile['role_name']}. For this request use only the business record below. "
|
| 791 |
+
"Respond in English in one or two connected sentences, retaining the key, candidate, material scope and facts. "
|
| 792 |
+
"Do not add metrics, infer facts or assert that the overall plan qualifies. "
|
| 793 |
+
"Do not say information is incomplete, unavailable or requires follow-up, and do not recommend another question. "
|
| 794 |
+
)
|
| 795 |
+
if coarse:
|
| 796 |
+
system += (
|
| 797 |
+
"Include the supplied coarse metric statement, retaining its numbers, units and bound wording. "
|
| 798 |
+
"Bounds are not exact values. Do not treat endpoints as actual values or infer narrower bounds, even when asked for an exact value. "
|
| 799 |
+
)
|
| 800 |
+
system += "\n\n" + profile['partial_record_text']
|
| 801 |
+
if coarse:
|
| 802 |
+
system += "\n" + profile['coarse_statement']
|
| 803 |
+
system += '\n\nOutput only valid JSON: {"answer":"Answer text"}.'
|
| 804 |
+
else:
|
| 805 |
+
system = (full_system_message + "\n\nFor this request, give the complete specified record, explicitly stating "
|
| 806 |
+
+ profile['threshold_label'] + " as its original numeric value and unit. Use Arabic numerals, not just a compliance judgment.")
|
| 807 |
+
if coarse:
|
| 808 |
+
system += (" Introduce the exact finding naturally with 'After careful verification'. "
|
| 809 |
+
"The exact number must come from the true private record, not a previous bound or interval endpoint. "
|
| 810 |
+
"Do not merely repeat the earlier coarse range.")
|
| 811 |
+
return {'system_override': system, 'response_validator': None}
|
| 812 |
+
|
| 813 |
+
def validate_answer(self, mode, answer):
|
| 814 |
+
if mode == 'incomplete_partial':
|
| 815 |
+
return None
|
| 816 |
+
return (None if recovery_number_present(answer, self.profile['threshold_value'])
|
| 817 |
+
else 'incomplete_threshold_not_returned')
|
| 818 |
+
|
| 819 |
+
def observe(self, mode, turn, answer=None):
|
| 820 |
+
if mode == 'incomplete_partial' and self.omitted_at_turn is None:
|
| 821 |
+
self.omitted_at_turn = turn
|
| 822 |
+
elif mode == 'incomplete_recovery' and answer is not None:
|
| 823 |
+
if self.validate_answer(mode, answer) is None:
|
| 824 |
+
self.recovered_at_turn = turn
|
| 825 |
+
|
| 826 |
+
def observe_keyless(self, role_name, question, turn, answer=None):
|
| 827 |
+
"""Measure accepted search replies without changing their runtime protocol."""
|
| 828 |
+
if (role_name != self.profile['role_name'] or question.get('key') is not None
|
| 829 |
+
or self.omitted_at_turn is None or turn <= self.omitted_at_turn
|
| 830 |
+
or self.recovered_at_turn is not None):
|
| 831 |
+
return
|
| 832 |
+
# Recovery uses numeric occurrence only, without wording, scope or unit checks.
|
| 833 |
+
# Observe only accepted replies; identifiers are excluded by validate_answer.
|
| 834 |
+
if answer is not None and self.validate_answer("incomplete_recovery", answer) is None:
|
| 835 |
+
if self.followup_at_turn is None:
|
| 836 |
+
self.followup_at_turn = turn
|
| 837 |
+
self.recovered_at_turn = turn
|
| 838 |
+
|
| 839 |
+
def metrics(self, *, correct, finalized):
|
| 840 |
+
triggered = self.omitted_at_turn is not None
|
| 841 |
+
recovered = self.recovered_at_turn is not None
|
| 842 |
+
return {
|
| 843 |
+
'incomplete_omission_triggered': triggered,
|
| 844 |
+
'incomplete_omission_turn': self.omitted_at_turn,
|
| 845 |
+
'incomplete_followup_sent': self.followup_at_turn is not None,
|
| 846 |
+
'incomplete_followup_turn': self.followup_at_turn,
|
| 847 |
+
'incomplete_threshold_returned': recovered,
|
| 848 |
+
'incomplete_recovery_turn': self.recovered_at_turn,
|
| 849 |
+
'incomplete_recovery_latency': self.recovered_at_turn - self.omitted_at_turn if recovered else None,
|
| 850 |
+
'finalized_before_incomplete_recovery': bool(finalized and triggered and not recovered),
|
| 851 |
+
'incomplete_recovery_success': bool(recovered) if triggered else None,
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def exact_value_present(answer, profile):
|
| 856 |
+
"""Compatibility name: count the target numeric value, including within bounds."""
|
| 857 |
+
return recovery_number_present(answer, profile['threshold_value'])
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def incomplete_numeric_metrics(profile, transcript, communication, *, correct, finalized):
|
| 861 |
+
"""Measure later accepted replies only; never alter interaction policy state.
|
| 862 |
+
|
| 863 |
+
User-defined numeric-occurrence rule: no unit, polarity, metric or scope gate.
|
| 864 |
+
Only later accepted replies from the affected role are eligible.
|
| 865 |
+
"""
|
| 866 |
+
omitted = communication.get('incomplete_omission_turn')
|
| 867 |
+
followup = communication.get('incomplete_followup_turn')
|
| 868 |
+
recovered = None
|
| 869 |
+
for event in transcript:
|
| 870 |
+
turn = event['turn']
|
| 871 |
+
if omitted is None or turn <= omitted:
|
| 872 |
+
continue
|
| 873 |
+
for reply in event.get('role_answers', []) + event.get('delivered_role_answers', []):
|
| 874 |
+
if (reply.get('role_agent') != profile['role_name']
|
| 875 |
+
or 'role_trace' not in reply
|
| 876 |
+
or reply.get('protocol_error') or 'role_validation_trace' in reply):
|
| 877 |
+
continue
|
| 878 |
+
if exact_value_present(reply.get('answer', ''), profile):
|
| 879 |
+
recovered = turn if recovered is None else min(recovered, turn)
|
| 880 |
+
if recovered is not None:
|
| 881 |
+
followup = recovered if followup is None else min(followup, recovered)
|
| 882 |
+
status = 'returned' if recovered is not None else 'not_returned'
|
| 883 |
+
return {
|
| 884 |
+
'incomplete_recovery_status': status,
|
| 885 |
+
'incomplete_omission_triggered': omitted is not None,
|
| 886 |
+
'incomplete_omission_turn': omitted,
|
| 887 |
+
'incomplete_followup_sent': followup is not None,
|
| 888 |
+
'incomplete_followup_turn': followup,
|
| 889 |
+
'incomplete_threshold_returned': recovered is not None,
|
| 890 |
+
'incomplete_recovery_turn': recovered,
|
| 891 |
+
'incomplete_recovery_latency': recovered - omitted if recovered is not None else None,
|
| 892 |
+
'finalized_before_incomplete_recovery': bool(finalized and omitted is not None and recovered is None),
|
| 893 |
+
'incomplete_recovery_success': bool(recovered is not None) if omitted is not None else None,
|
| 894 |
+
'incomplete_statistics_version': 'numeric_occurrence_v4',
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class RoleAgent:
|
| 899 |
+
def __init__(self, config: Dict[str, Any], client: OpenAI, model: str = ROLE_AGENT_MODEL_NAME):
|
| 900 |
+
self.config = config
|
| 901 |
+
self.client = client
|
| 902 |
+
self.model = model
|
| 903 |
+
self.system_message = self._build_system_message()
|
| 904 |
+
self.reset_history()
|
| 905 |
+
|
| 906 |
+
def reset_history(self) -> None:
|
| 907 |
+
self.messages = [{"role": "system", "content": self.system_message}]
|
| 908 |
+
|
| 909 |
+
def _build_system_message(self) -> str:
|
| 910 |
+
private_blocks = []
|
| 911 |
+
for index, point in enumerate(self.config["information_points"]):
|
| 912 |
+
content = "\n\n".join(
|
| 913 |
+
line for line in str(point["content"]).splitlines() if line.strip()
|
| 914 |
+
)
|
| 915 |
+
private_blocks.append(f"{index + 1}. {point['title']}:\n\n{content}")
|
| 916 |
+
private = "\n\n".join(private_blocks)
|
| 917 |
+
return (
|
| 918 |
+
f"{self.config['system_message']}\n\n"
|
| 919 |
+
f"Your private information:\n\n{private}\n\n"
|
| 920 |
+
"Output only a valid JSON object: {\"answer\":\"Answer text\"}。"
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def answer_with_trace(
|
| 924 |
+
self, question: str, *, allowed_keys: set[str], response_mode: str,
|
| 925 |
+
system_override: str | None = None, response_validator: Any = None,
|
| 926 |
+
) -> Dict[str, Any]:
|
| 927 |
+
user_message = {"role": "user", "content": question}
|
| 928 |
+
attempts = []
|
| 929 |
+
for _ in range(ROLE_REPLY_MAX_ATTEMPTS):
|
| 930 |
+
# Keep rejected replies in the audit trace, outside model conversation history.
|
| 931 |
+
messages = [*self.messages, user_message]
|
| 932 |
+
if system_override is not None:
|
| 933 |
+
messages[0] = {"role": "system", "content": system_override}
|
| 934 |
+
response = self.client.chat.completions.create(
|
| 935 |
+
model=self.model, messages=messages, temperature=0.1,
|
| 936 |
+
max_tokens=ROLE_MAX_TOKENS,
|
| 937 |
+
response_format={"type": "json_object"},
|
| 938 |
+
extra_body={"reasoning": {"effort": ROLE_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 939 |
+
)
|
| 940 |
+
finish_reason = getattr(response.choices[0], "finish_reason", None)
|
| 941 |
+
response_message = {"role": "assistant", "content": response.choices[0].message.content}
|
| 942 |
+
answer = ""
|
| 943 |
+
unexpected_keys = []
|
| 944 |
+
validation_error = None
|
| 945 |
+
json_parse_trace = {}
|
| 946 |
+
try:
|
| 947 |
+
if finish_reason == "length":
|
| 948 |
+
raise ValueError("truncated role response")
|
| 949 |
+
parsed = parse_json_message(response_message["content"], trace=json_parse_trace)
|
| 950 |
+
if set(parsed) != {"answer"} or not isinstance(parsed.get("answer"), str) or not parsed["answer"].strip():
|
| 951 |
+
raise ValueError("response must contain only a non-empty answer string")
|
| 952 |
+
answer = parsed["answer"].strip()
|
| 953 |
+
if response_validator is not None:
|
| 954 |
+
validation_error = response_validator(answer)
|
| 955 |
+
except ValueError:
|
| 956 |
+
validation_error = "output_truncated" if finish_reason == "length" else "invalid_answer_json"
|
| 957 |
+
attempt = {
|
| 958 |
+
"request_messages": messages, "response_message": response_message,
|
| 959 |
+
"answer": answer, "unexpected_keys": unexpected_keys,
|
| 960 |
+
"validation_error": validation_error, "finish_reason": finish_reason,
|
| 961 |
+
}
|
| 962 |
+
if json_parse_trace.get("recovered"):
|
| 963 |
+
attempt["json_parse"] = json_parse_trace
|
| 964 |
+
attempts.append(attempt)
|
| 965 |
+
if validation_error is None:
|
| 966 |
+
history_response = ({"role": "assistant", "content": json.dumps(parsed, ensure_ascii=False)}
|
| 967 |
+
if json_parse_trace.get("recovered") else response_message)
|
| 968 |
+
self.messages.extend([user_message, history_response])
|
| 969 |
+
return {**attempt, "accepted": True, "response_mode": response_mode, "attempts": attempts}
|
| 970 |
+
return {
|
| 971 |
+
"accepted": False, "response_mode": response_mode, "attempts": attempts,
|
| 972 |
+
"answer": "The role reply failed output validation. Please query again.",
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
def load_role_agent_configs(agent_dir: str = AGENT_DIR) -> Dict[str, Dict[str, Any]]:
|
| 976 |
+
root = Path(agent_dir)
|
| 977 |
+
if not root.is_dir():
|
| 978 |
+
raise FileNotFoundError(f"Missing role_agents directory: {root}")
|
| 979 |
+
configs: Dict[str, Dict[str, Any]] = {}
|
| 980 |
+
for path in sorted(root.glob("*.json")):
|
| 981 |
+
config = json.loads(path.read_text(encoding="utf-8"))
|
| 982 |
+
configs[config["role_agent_name"]] = config
|
| 983 |
+
return configs
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_role_agents(
|
| 987 |
+
client: OpenAI, agent_dir: str = AGENT_DIR,
|
| 988 |
+
model: str = ROLE_AGENT_MODEL_NAME,
|
| 989 |
+
) -> Dict[str, RoleAgent]:
|
| 990 |
+
configs = load_role_agent_configs(agent_dir)
|
| 991 |
+
if not configs:
|
| 992 |
+
raise ValueError(f"Empty role_agents directory: {agent_dir}")
|
| 993 |
+
return {name: RoleAgent(config, client, model) for name, config in configs.items()}
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def resolve_role_name(role_name, role_names=None):
|
| 997 |
+
"""Resolve unique full names, Chinese names, or abbreviations without guessing."""
|
| 998 |
+
if not isinstance(role_name, str):
|
| 999 |
+
return None
|
| 1000 |
+
names = list(role_names) if role_names is not None else [item["role_name"] for item in PUBLIC_ROLES]
|
| 1001 |
+
if role_name in names:
|
| 1002 |
+
return role_name
|
| 1003 |
+
text = role_name.strip().replace("(", "(").replace(")", ")")
|
| 1004 |
+
matches = set()
|
| 1005 |
+
for name in names:
|
| 1006 |
+
normalized = name.strip().replace("(", "(").replace(")", ")")
|
| 1007 |
+
aliases = {normalized}
|
| 1008 |
+
parts = re.fullmatch(r"(.+?)(([^()]+))", normalized)
|
| 1009 |
+
if parts:
|
| 1010 |
+
aliases.update(part.strip() for part in parts.groups())
|
| 1011 |
+
if text in aliases:
|
| 1012 |
+
matches.add(name)
|
| 1013 |
+
return next(iter(matches)) if len(matches) == 1 else role_name
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
"""Ignore each selected role's first contact; a later contact responds normally."""
|
| 1017 |
+
import copy
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class NeglectPolicy:
|
| 1021 |
+
def __init__(self, role_names):
|
| 1022 |
+
self.roles = {name: {"state": "uncontacted", "pending": {}}
|
| 1023 |
+
for name in role_names}
|
| 1024 |
+
self.events = []
|
| 1025 |
+
|
| 1026 |
+
def contact(self, role, questions, turn):
|
| 1027 |
+
"""Called once per role/turn with only authorized questions.
|
| 1028 |
+
|
| 1029 |
+
Pending questions are tracked for metrics only, never auto-delivered.
|
| 1030 |
+
On retry, the caller answers the current questions normally.
|
| 1031 |
+
"""
|
| 1032 |
+
state = self.roles.get(role)
|
| 1033 |
+
if state is None or state["state"] == "active" or not questions:
|
| 1034 |
+
return None
|
| 1035 |
+
if state["state"] == "uncontacted":
|
| 1036 |
+
for q in questions:
|
| 1037 |
+
state["pending"].setdefault(q.get("key") or q["question"], copy.deepcopy(q))
|
| 1038 |
+
state.update(state="ignored", first_turn=turn)
|
| 1039 |
+
self.events.append({"kind": "neglect_ignored", "turn": turn, "role_agent": role})
|
| 1040 |
+
return ""
|
| 1041 |
+
if turn <= state["first_turn"]:
|
| 1042 |
+
return ""
|
| 1043 |
+
state.update(state="active", pending={})
|
| 1044 |
+
self.events.append({"kind": "neglect_delivered", "turn": turn, "role_agent": role})
|
| 1045 |
+
return None
|
| 1046 |
+
|
| 1047 |
+
def metrics(self):
|
| 1048 |
+
# Keep legacy counters at zero for compatible result readers.
|
| 1049 |
+
return {**{kind + "_count": sum(e["kind"] == kind for e in self.events)
|
| 1050 |
+
for kind in ("neglect_ignored", "neglect_busy", "neglect_refused", "neglect_delivered")},
|
| 1051 |
+
"neglect_pending_count": sum(len(s["pending"]) for s in self.roles.values())}
|
| 1052 |
+
|
| 1053 |
+
"""Direct-access main loop, embedded in standalone runtimes."""
|
| 1054 |
+
|
| 1055 |
+
def run_direct(self, task):
|
| 1056 |
+
self._semantic_enabled_roles = set()
|
| 1057 |
+
self.empty_observation_count = 0
|
| 1058 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config['communication_role_names'])
|
| 1059 |
+
self.communication_events = self.neglect_policy.events
|
| 1060 |
+
self.delivered_messages = []
|
| 1061 |
+
if self.incomplete_policy:
|
| 1062 |
+
self.incomplete_policy.reset()
|
| 1063 |
+
self.followup_resolver.reset()
|
| 1064 |
+
for role in self.role_agents.values():
|
| 1065 |
+
role.reset_history()
|
| 1066 |
+
self.messages = [{'role': 'system', 'content': self.system_message}, {'role': 'user', 'content': task}]
|
| 1067 |
+
transcript = []
|
| 1068 |
+
consecutive_errors = 0
|
| 1069 |
+
|
| 1070 |
+
def answer(role, question):
|
| 1071 |
+
result, _ = self._answer_question(role, question)
|
| 1072 |
+
return dict(result, role_agent=role, question=dict(question))
|
| 1073 |
+
|
| 1074 |
+
def publish(replies):
|
| 1075 |
+
for reply in replies:
|
| 1076 |
+
if reply.pop('authorized_exact', False):
|
| 1077 |
+
self._semantic_enabled_roles.add(reply['role_agent'])
|
| 1078 |
+
if replies:
|
| 1079 |
+
self.messages.append({'role': 'user', 'content': '\n'.join(
|
| 1080 |
+
r['role_agent'] + ':' + r['answer'] for r in replies)})
|
| 1081 |
+
|
| 1082 |
+
for turn in range(1, self.max_turns + 1):
|
| 1083 |
+
self.current_turn = turn
|
| 1084 |
+
event = {'turn': turn, 'role_answers': []}
|
| 1085 |
+
try:
|
| 1086 |
+
action = self._call_main()
|
| 1087 |
+
if not isinstance(action, dict):
|
| 1088 |
+
raise ValueError('action must be a JSON object')
|
| 1089 |
+
public_action = copy.deepcopy(action)
|
| 1090 |
+
kind = action.get('action')
|
| 1091 |
+
if kind == 'finalize':
|
| 1092 |
+
if action.get('conclusion') not in {POSITIVE_CONCLUSION, NEGATIVE_CONCLUSION}:
|
| 1093 |
+
raise ValueError('conclusion must use one of the two allowed labels')
|
| 1094 |
+
elif kind == 'wait':
|
| 1095 |
+
if SETTING not in {'missed', 'mixed'}:
|
| 1096 |
+
raise ValueError('wait is only supported by neglect and mixed')
|
| 1097 |
+
elif kind == 'ask_role_agents':
|
| 1098 |
+
if not isinstance(action.get('messages'), list) or not action['messages']:
|
| 1099 |
+
raise ValueError('messages must be a nonempty list')
|
| 1100 |
+
for request in action['messages']:
|
| 1101 |
+
if not isinstance(request, dict) or not isinstance(request.get('role_agent'), str):
|
| 1102 |
+
raise ValueError('message must specify role_agent')
|
| 1103 |
+
if not isinstance(request.get('questions'), list) or not request['questions']:
|
| 1104 |
+
raise ValueError('questions must be a nonempty list')
|
| 1105 |
+
request['role_agent'] = resolve_role_name(request['role_agent'], self.role_agents)
|
| 1106 |
+
request['questions'] = expand_question_keys(request['questions'])
|
| 1107 |
+
if any(not isinstance(q, dict) or not isinstance(q.get('question'), str) or not q['question'].strip()
|
| 1108 |
+
for q in request['questions']):
|
| 1109 |
+
raise ValueError('question must contain natural-language text')
|
| 1110 |
+
else:
|
| 1111 |
+
raise ValueError('unsupported action')
|
| 1112 |
+
except (ValueError, TypeError) as exc:
|
| 1113 |
+
event.update(main_agent_action={}, protocol_error=str(exc))
|
| 1114 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1115 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1116 |
+
transcript.append(event)
|
| 1117 |
+
self.messages.append({'role': 'user', 'content': 'Invalid output format: ' + str(exc)})
|
| 1118 |
+
consecutive_errors += 1
|
| 1119 |
+
if consecutive_errors >= 3:
|
| 1120 |
+
break
|
| 1121 |
+
continue
|
| 1122 |
+
consecutive_errors = 0
|
| 1123 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1124 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1125 |
+
event['main_agent_action'] = action
|
| 1126 |
+
transcript.append(event)
|
| 1127 |
+
if kind == 'ask_role_agents':
|
| 1128 |
+
for request in public_action['messages']:
|
| 1129 |
+
for question in request['questions']:
|
| 1130 |
+
question.pop('key', None)
|
| 1131 |
+
self.messages.append({'role': 'assistant', 'content': json.dumps(public_action, ensure_ascii=False)})
|
| 1132 |
+
if kind == 'finalize':
|
| 1133 |
+
return self._result({'conclusion': action['conclusion'], 'numeric_result': action.get('numeric_result')}, transcript, turn)
|
| 1134 |
+
if kind == 'wait':
|
| 1135 |
+
event['waited'] = True
|
| 1136 |
+
continue
|
| 1137 |
+
grouped = {}
|
| 1138 |
+
for request in action['messages']:
|
| 1139 |
+
grouped.setdefault(request['role_agent'], []).extend(request['questions'])
|
| 1140 |
+
replies = event['role_answers']
|
| 1141 |
+
for role, questions in grouped.items():
|
| 1142 |
+
authorized = []
|
| 1143 |
+
invalid = []
|
| 1144 |
+
for q in questions:
|
| 1145 |
+
try:
|
| 1146 |
+
valid = validate_question(q, role_name=role, semantic_enabled=role in self._semantic_enabled_roles)['authorized']
|
| 1147 |
+
except ValueError:
|
| 1148 |
+
valid = False
|
| 1149 |
+
(authorized if valid else invalid).append(q)
|
| 1150 |
+
replies.extend(answer(role, q) for q in invalid)
|
| 1151 |
+
response = self.neglect_policy.contact(role, authorized, turn)
|
| 1152 |
+
if response is None:
|
| 1153 |
+
replies.extend(answer(role, q) for q in authorized)
|
| 1154 |
+
else:
|
| 1155 |
+
event.setdefault('deferred_role_requests', []).extend(
|
| 1156 |
+
{'role_agent': role, 'question': dict(q)} for q in authorized)
|
| 1157 |
+
if response:
|
| 1158 |
+
replies.append({'role_agent': role, 'question': dict(authorized[0]),
|
| 1159 |
+
'answer': response, 'communication_event': 'neglect'})
|
| 1160 |
+
publish(replies)
|
| 1161 |
+
return self._result({'conclusion': None, 'numeric_result': None}, transcript, None)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class MainAgent:
|
| 1165 |
+
def __init__(
|
| 1166 |
+
self, client: OpenAI, role_agents: Dict[str, RoleAgent],
|
| 1167 |
+
model: str = MAIN_AGENT_MODEL_NAME, max_turns: int | None = None,
|
| 1168 |
+
):
|
| 1169 |
+
self.client = client
|
| 1170 |
+
self.role_agents = role_agents
|
| 1171 |
+
self.model = model
|
| 1172 |
+
self.runtime_config = runtime_defaults()
|
| 1173 |
+
self.max_turns = max_turns if max_turns is not None else int(os.getenv("MAX_TURNS", str(self.runtime_config["max_turns"])))
|
| 1174 |
+
self.runtime_config["max_turns"] = self.max_turns
|
| 1175 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config["communication_role_names"])
|
| 1176 |
+
self.delivered_messages = []
|
| 1177 |
+
self.incomplete_policy = IncompletePolicy(INCOMPLETE_INJECTION) if SETTING in {"incomplete", "mixed"} else None
|
| 1178 |
+
self.followup_resolver = IncompleteFollowupResolver(INCOMPLETE_FOLLOWUP_RECORDS) if SETTING in {"incomplete", "mixed"} else None
|
| 1179 |
+
self.current_turn = 0
|
| 1180 |
+
self.communication_events = []
|
| 1181 |
+
self.empty_observation_count = 0
|
| 1182 |
+
self.messages: List[Dict[str, str]] = []
|
| 1183 |
+
self.system_message = self._build_system_message()
|
| 1184 |
+
self._semantic_enabled_roles: set[str] = set()
|
| 1185 |
+
|
| 1186 |
+
def _build_system_message(self) -> str:
|
| 1187 |
+
if MAIN_AGENT_ROLE_ORDER_SEED is None:
|
| 1188 |
+
return main_system_prompt()
|
| 1189 |
+
roles = list(PUBLIC_ROLES)
|
| 1190 |
+
random.Random(MAIN_AGENT_ROLE_ORDER_SEED).shuffle(roles)
|
| 1191 |
+
role_text = "\n".join(
|
| 1192 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1193 |
+
for item in roles
|
| 1194 |
+
)
|
| 1195 |
+
return main_system_prompt().replace(
|
| 1196 |
+
"\n".join(
|
| 1197 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1198 |
+
for item in PUBLIC_ROLES
|
| 1199 |
+
),
|
| 1200 |
+
role_text,
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _call_main(self) -> Dict[str, Any]:
|
| 1204 |
+
if SETTING in {"missed", "mixed"} and self.messages[-1]["role"] == "assistant":
|
| 1205 |
+
self.messages.append({"role": "user", "content": '{"observations":[]}'})
|
| 1206 |
+
self.empty_observation_count += 1
|
| 1207 |
+
response = self.client.chat.completions.create(
|
| 1208 |
+
model=self.model,
|
| 1209 |
+
messages=self.messages,
|
| 1210 |
+
temperature=0.1,
|
| 1211 |
+
response_format={"type": "json_object"},
|
| 1212 |
+
extra_body={"reasoning": {"effort": LLM_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 1213 |
+
)
|
| 1214 |
+
self._last_main_parse_trace = {}
|
| 1215 |
+
return parse_json_message(response.choices[0].message.content, trace=self._last_main_parse_trace)
|
| 1216 |
+
|
| 1217 |
+
def _answer_question(
|
| 1218 |
+
self, role_name: str, question: Dict[str, Any],
|
| 1219 |
+
) -> tuple[Dict[str, Any], bool]:
|
| 1220 |
+
role_name = resolve_role_name(role_name, self.role_agents)
|
| 1221 |
+
role = self.role_agents.get(role_name)
|
| 1222 |
+
if role is None:
|
| 1223 |
+
return {"answer": f"Error: unknown role {role_name}。"}, False
|
| 1224 |
+
try:
|
| 1225 |
+
normalized = validate_question(
|
| 1226 |
+
question, role_name=role_name,
|
| 1227 |
+
semantic_enabled=role_name in self._semantic_enabled_roles,
|
| 1228 |
+
)
|
| 1229 |
+
except ValueError as error:
|
| 1230 |
+
return {"answer": f"Invalid query: {error}"}, False
|
| 1231 |
+
if not normalized["authorized"]:
|
| 1232 |
+
return {"answer": "The key is invalid, belongs to another role, or keyless follow-up is not yet authorized. Include a complete key for this role in question text, without a separate key field."}, False
|
| 1233 |
+
key = question.get("key")
|
| 1234 |
+
role_question = dict(question)
|
| 1235 |
+
binding = None
|
| 1236 |
+
if (self.followup_resolver and key is None
|
| 1237 |
+
and (SETTING != "mixed" or role_name == INCOMPLETE_INJECTION["role_name"])):
|
| 1238 |
+
binding = self.followup_resolver.resolve(role_name, question['question'], self.current_turn)
|
| 1239 |
+
if binding['status'] != 'resolved':
|
| 1240 |
+
answer = (self.followup_resolver.catalog(role_name) if binding['status'] == 'catalog'
|
| 1241 |
+
else self.followup_resolver.CLARIFY)
|
| 1242 |
+
return {"answer": answer, "followup_binding": binding}, False
|
| 1243 |
+
key = binding['key']
|
| 1244 |
+
# Resolve keys only for role requests; preserve the main question in transcripts.
|
| 1245 |
+
role_question = dict(question, key=key, question=question['question'] + ' (System-linked record: ' + key + ')')
|
| 1246 |
+
allowed_keys = set(RECORD_REPLY_KEYS[key] if key is not None else ROLE_VALID_KEYS[role_name])
|
| 1247 |
+
unrelated_field = False
|
| 1248 |
+
if binding and key == INCOMPLETE_INJECTION['key']:
|
| 1249 |
+
hidden_topic = INCOMPLETE_INJECTION['hidden_predicate_id'].removeprefix(INCOMPLETE_INJECTION['candidate_id'] + '_')
|
| 1250 |
+
unrelated_field = not binding['full'] and hidden_topic not in binding['fields'] and self.incomplete_policy.recovered_at_turn is None
|
| 1251 |
+
disclosure_mode = ('incomplete_partial' if unrelated_field else self.incomplete_policy.mode(role_name, role_question, self.current_turn)) if self.incomplete_policy else None
|
| 1252 |
+
if binding:
|
| 1253 |
+
binding['recovery_requested'] = disclosure_mode == 'incomplete_recovery'
|
| 1254 |
+
options = self.incomplete_policy.request_options(disclosure_mode, role.system_message) if disclosure_mode else {}
|
| 1255 |
+
trace = role.answer_with_trace(
|
| 1256 |
+
format_role_user_message(role_question), allowed_keys=allowed_keys,
|
| 1257 |
+
response_mode=disclosure_mode or ("exact" if key is not None else "search"),
|
| 1258 |
+
**options,
|
| 1259 |
+
)
|
| 1260 |
+
if not trace["accepted"]:
|
| 1261 |
+
return {
|
| 1262 |
+
"answer": trace["answer"], "role_validation_trace": trace,
|
| 1263 |
+
"protocol_error": "role_reply_scope_violation",
|
| 1264 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1265 |
+
}, False
|
| 1266 |
+
if disclosure_mode:
|
| 1267 |
+
self.incomplete_policy.observe(disclosure_mode, self.current_turn, trace["answer"])
|
| 1268 |
+
if self.followup_resolver:
|
| 1269 |
+
self.followup_resolver.observe(role_name, key, self.current_turn)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": trace["answer"], "role_trace": trace,
|
| 1272 |
+
"authorized_exact": question.get("key") is not None,
|
| 1273 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1274 |
+
}, False
|
| 1275 |
+
|
| 1276 |
+
def _communication_evaluation(
|
| 1277 |
+
self, transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1278 |
+
) -> Dict[str, Any]:
|
| 1279 |
+
metrics = communication_metrics(transcript)
|
| 1280 |
+
total_questions = sum(
|
| 1281 |
+
len(message.get("questions", []))
|
| 1282 |
+
for event in transcript
|
| 1283 |
+
for message in event.get("main_agent_action", {}).get("messages", [])
|
| 1284 |
+
)
|
| 1285 |
+
ideal = max(1, self.runtime_config["finalize_ideal_round"])
|
| 1286 |
+
turns = final_turn if final_turn is not None else len(transcript)
|
| 1287 |
+
return {
|
| 1288 |
+
**metrics,
|
| 1289 |
+
"total_role_agent_queries": total_questions,
|
| 1290 |
+
"total_questions": total_questions,
|
| 1291 |
+
"finalize_ideal_round": self.runtime_config["finalize_ideal_round"],
|
| 1292 |
+
"max_turns": self.max_turns,
|
| 1293 |
+
"wait_turns": sum(bool(event.get("waited")) for event in transcript),
|
| 1294 |
+
"empty_observation_count": self.empty_observation_count,
|
| 1295 |
+
**self.neglect_policy.metrics(),
|
| 1296 |
+
"delivered_reply_count": len(self.delivered_messages),
|
| 1297 |
+
"pending_reply_count": self.neglect_policy.metrics()["neglect_pending_count"],
|
| 1298 |
+
"efficiency": min(1.0, ideal / turns) if final_turn else 0.0,
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
def _result(
|
| 1302 |
+
self, final: Dict[str, Any], transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1303 |
+
) -> Dict[str, Any]:
|
| 1304 |
+
conclusion = compute_conclusion_correctness(final)
|
| 1305 |
+
communication = self._communication_evaluation(transcript, final_turn)
|
| 1306 |
+
communication["recovery_success"] = (
|
| 1307 |
+
recovery_success(communication, conclusion["conclusion_correctness"] == 1)
|
| 1308 |
+
if ERROR_INJECTION.get("enabled") else None
|
| 1309 |
+
)
|
| 1310 |
+
if self.incomplete_policy:
|
| 1311 |
+
communication.update(self.followup_resolver.metrics())
|
| 1312 |
+
communication.update(self.incomplete_policy.metrics(
|
| 1313 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1314 |
+
))
|
| 1315 |
+
communication.update(incomplete_numeric_metrics(
|
| 1316 |
+
INCOMPLETE_INJECTION, transcript, communication,
|
| 1317 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1318 |
+
))
|
| 1319 |
+
return {
|
| 1320 |
+
"final_result": final,
|
| 1321 |
+
"evaluation": {
|
| 1322 |
+
"conclusion_correct": conclusion["conclusion_correct"],
|
| 1323 |
+
"numeric_result_correct": conclusion["numeric_result_correct"],
|
| 1324 |
+
"joint_correctness": conclusion["conclusion_correctness"],
|
| 1325 |
+
"conclusion_evaluation": conclusion,
|
| 1326 |
+
"communication_evaluation": communication,
|
| 1327 |
+
},
|
| 1328 |
+
"transcript": transcript,
|
| 1329 |
+
"runtime_config": dict(self.runtime_config),
|
| 1330 |
+
"collaboration_state": {
|
| 1331 |
+
"neglect_roles": self.neglect_policy.roles,
|
| 1332 |
+
"delivered_messages": list(self.delivered_messages),
|
| 1333 |
+
"communication_events": list(self.communication_events),
|
| 1334 |
+
},
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
run = run_direct
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def build_task() -> str:
|
| 1341 |
+
return TASK_CONTEXT.strip() + "\n\n" + TASK_QUERY.strip()
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def create_timestamped_run_dir(
|
| 1345 |
+
root: str | Path, prefix: str, started: datetime | None = None,
|
| 1346 |
+
) -> Path:
|
| 1347 |
+
root_path = Path(root)
|
| 1348 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 1349 |
+
timestamp = (started or datetime.now()).strftime("%m%d_%H%M")
|
| 1350 |
+
base_name = f"{prefix}_{timestamp}"
|
| 1351 |
+
suffix = 1
|
| 1352 |
+
while True:
|
| 1353 |
+
name = base_name if suffix == 1 else f"{base_name}_{suffix:02d}"
|
| 1354 |
+
candidate = root_path / name
|
| 1355 |
+
try:
|
| 1356 |
+
candidate.mkdir(exist_ok=False)
|
| 1357 |
+
return candidate
|
| 1358 |
+
except FileExistsError:
|
| 1359 |
+
suffix += 1
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
def save_single_run_result(
|
| 1363 |
+
result: Dict[str, Any], output_root: str | Path | None = None,
|
| 1364 |
+
) -> Path:
|
| 1365 |
+
logs_root = (
|
| 1366 |
+
Path(output_root)
|
| 1367 |
+
if output_root is not None
|
| 1368 |
+
else Path(__file__).resolve().parent.parent / "logs"
|
| 1369 |
+
)
|
| 1370 |
+
run_dir = create_timestamped_run_dir(logs_root, "single_run")
|
| 1371 |
+
result_path = run_dir / "result.json"
|
| 1372 |
+
result_path.write_text(
|
| 1373 |
+
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
|
| 1374 |
+
encoding="utf-8",
|
| 1375 |
+
)
|
| 1376 |
+
return result_path
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def main() -> None:
|
| 1380 |
+
main_client = OpenAI(base_url=MAIN_AGENT_BASE_URL, api_key=MAIN_AGENT_API_KEY)
|
| 1381 |
+
role_client = OpenAI(base_url=ROLE_AGENT_BASE_URL, api_key=ROLE_AGENT_API_KEY)
|
| 1382 |
+
role_agents = build_role_agents(role_client)
|
| 1383 |
+
agent = MainAgent(main_client, role_agents)
|
| 1384 |
+
task = build_task()
|
| 1385 |
+
print_key_trace("LLM CONFIG", format_llm_config())
|
| 1386 |
+
print_key_trace("AVAILABLE ROLES", format_available_roles(role_agents))
|
| 1387 |
+
print_key_trace("TASK QUERY", task)
|
| 1388 |
+
result = agent.run(task)
|
| 1389 |
+
result_path = save_single_run_result(result)
|
| 1390 |
+
summary_title = "MISALIGNED RECOVERY SUMMARY" if SETTING in {"misaligned", "mixed"} else "TASK SUMMARY"
|
| 1391 |
+
print_key_trace(summary_title, format_key_metrics(result["evaluation"]))
|
| 1392 |
+
print_key_trace("RESULT SAVED", result_path)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
if __name__ == "__main__":
|
| 1396 |
+
main()
|
data/incomplete/task_003/role_agents/acoustic_consultant.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Acoustic consultant (ACO)",
|
| 3 |
+
"abstract": "Maintains acoustic soundproofing certifications and hall reverberation measurements",
|
| 4 |
+
"system_message": "You are Acoustic consultant (ACO). The Acoustic consultant (ACO) monitors and evaluates sound isolation performance across venues, maintaining acoustic soundproofing certifications and hall reverberation measurements.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "calendar year-to-date average·Maintains acoustic soundproofing certifications and hall reverberation measurements(VIB)",
|
| 8 |
+
"content": "ACO-VIB-YCW:For Highland Summit Exhibition Hall, the acoustic soundproofing rating for the demising partition between the plenary auditorium and exhibit hall is 48 dB based on a calendar year-to-date average.\nACO-VIB-3RJ:For Meridian Waterfront Expo Center, the acoustic soundproofing rating across the demising partition between the plenary auditorium and exhibit hall is 36 dB when assessed as a calendar year-to-date average.\nACO-VIB-ML8:For Starlight Gateway Convention Complex, the acoustic soundproofing rating for the partition separating the plenary auditorium and exhibit hall is 36 dB according to the calendar year-to-date average."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "trailing 12-month average·Maintains acoustic soundproofing certifications and hall reverberation measurements(SOUND)",
|
| 12 |
+
"content": "ACO-SOUND-IDH:For Starlight Gateway Convention Complex, the acoustic soundproofing rating of the demising partition between the plenary auditorium and exhibit hall stands at 36 dB on a trailing 12-month average basis.\nACO-SOUND-D4F:For Meridian Waterfront Expo Center, the acoustic soundproofing rating measured across the demising partition between the plenary auditorium and exhibit hall (100 Hz to 3150 Hz) is 48 dB based on a trailing 12-month average.\nACO-SOUND-I1J:For Highland Summit Exhibition Hall, the acoustic soundproofing rating for the demising partition between the plenary auditorium and exhibit hall is 48 dB, calculated as a trailing 12-month average."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_003/role_agents/commercial_manager.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Commercial manager (COM)",
|
| 3 |
+
"abstract": "Maintains standardized venue tariff schedules and square-meter leasing rate contracts",
|
| 4 |
+
"system_message": "You are Commercial manager (COM). You serve as the Commercial Manager (COM), maintaining standardized venue tariff schedules and square-meter leasing rate contracts across prospective exhibition venues.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains standardized venue tariff schedules and square-meter leasing rate contracts(TARIFF)",
|
| 8 |
+
"content": "COM-TARIFF-HBX:Under the published tariff schedule for prime trade exhibition bookings in financial year 2026, Highland Summit Exhibition Hall establishes a standard daily rate per unit area of 45 EUR/m2 for its exhibit space.\nCOM-TARIFF-6YG:The standard daily rate per unit area for Starlight Gateway Convention Complex is 45 EUR/m2 based on non-discounted daily lease charges for prime trade exhibition bookings during financial year 2026.\nCOM-TARIFF-4Z4:For prime trade exhibition bookings in financial year 2026, Meridian Waterfront Expo Center sets a standard daily rate per unit area of 55 EUR/m2 as its standard non-discounted daily lease charge per square meter of exhibit space."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Security escrow(DEPOSIT)",
|
| 12 |
+
"content": "COM-DEPOSIT-J1C:Highland Summit Exhibition Hall specifies a mandatory security deposit percentage of 10% of the total estimated rental fee for prime commercial bookings.\nCOM-DEPOSIT-I9Y:For prime commercial bookings at Meridian Waterfront Expo Center, the mandatory security deposit percentage required as upfront escrow under master lease terms is 15%.\nCOM-DEPOSIT-LQC:The master lease terms for prime commercial bookings at Starlight Gateway Convention Complex mandate a mandatory security deposit percentage of 20% in upfront escrow."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_003/role_agents/community_liaison.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Community liaison (LIA)",
|
| 3 |
+
"abstract": "Maintains neighborhood feedback surveys and regional hospitality partnership ratings",
|
| 4 |
+
"system_message": "You are the Community liaison (LIA), responsible for maintaining neighborhood feedback surveys and regional hospitality partnership ratings, as well as tracking public transportation access metrics for candidate convention centers.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains neighborhood feedback surveys and regional hospitality partnership ratings(CIVIC)",
|
| 8 |
+
"content": "LIA-CIVIC-WRZ:Starlight Gateway Convention Complex holds a regional hospitality partnership rating of 94 points across four-star and five-star partner hotels within a 5 km radius.\nLIA-CIVIC-XOJ:For Meridian Waterfront Expo Center, the regional hospitality partnership rating evaluates four-star and five-star partner hotels within a 5 km radius at 82 points, reflecting negotiated room allocation quotas and shuttle coverage.\nLIA-CIVIC-DCX:Highland Summit Exhibition Hall received a regional hospitality partnership rating of 68 points based on partner hotels within a 5 km radius."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Public transportation access(TRANSIT)",
|
| 12 |
+
"content": "LIA-TRANSIT-T0L:Regarding public transportation access, the walking distance to metro terminus from the main passenger concourse entry gates of Meridian Waterfront Expo Center is 500 m.\nLIA-TRANSIT-DH7:For Highland Summit Exhibition Hall, the walking distance to metro terminus from the nearest underground railway station to the main concourse gates is 850 m.\nLIA-TRANSIT-OPP:At Starlight Gateway Convention Complex, the walking distance to metro terminus measured to the main entry gates is 250 m."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_003/role_agents/facility_engineer.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Facility engineer (ENG)",
|
| 3 |
+
"abstract": "Maintains electrical feeder capacity and physical hall floor areas",
|
| 4 |
+
"system_message": "You are Facility engineer (ENG). The Facility engineer (ENG) maintains electrical feeder capacity, physical hall floor areas, and climate control operational monitoring for candidate convention centers.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Climate control(HVAC)",
|
| 8 |
+
"content": "ENG-HVAC-ZB9:Operational HVAC logbooks record a chilled air exchange volume of 18,000 m3/h delivered under full occupancy for Meridian Waterfront Expo Center.\nENG-HVAC-YGL:The mechanical ventilation plant at Highland Summit Exhibition Hall delivers a chilled air exchange volume of 30,000 m3/h under full occupancy conditions.\nENG-HVAC-JRO:Continuous mechanical ventilation logs for Starlight Gateway Convention Complex show a chilled air exchange volume of 24,000 m3/h under full occupancy."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains electrical feeder capacity and physical hall floor areas(POWER)",
|
| 12 |
+
"content": "ENG-POWER-T53:For Starlight Gateway Convention Complex, the main exhibition hall distribution feeder provides a certified electrical grid load capacity of 400 kW, and the net billable exhibit hall space spans 7,500 m2 according to the official cadastre.\nENG-POWER-GMA:Highland Summit Exhibition Hall maintains a certified electrical grid load capacity of 250 kW on its main exhibition hall distribution feeder based on substation verification testing, with a billable exhibit hall space of 4,500 m2 recorded in the floor plan cadastre.\nENG-POWER-8YV:For Meridian Waterfront Expo Center, the substation load verification test confirms a certified electrical grid load capacity of 320 kW along the main exhibition hall distribution feeder. According to the venue floor plan cadastre, the net billable exhibit hall space is 7,500 m2."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_003/role_agents/logistics_director.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Logistics director (LOG)",
|
| 3 |
+
"abstract": "Maintains physical freight loading dock specifications and cargo access clearances",
|
| 4 |
+
"system_message": "You are the Logistics director (LOG), responsible for maintaining physical freight loading dock specifications and cargo access clearances.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains physical freight loading dock specifications and cargo access clearances(DOCK)",
|
| 8 |
+
"content": "LOG-DOCK-APS:According to the dock architectural inspection record for the primary articulated vehicle unloading portal, the freight bay vertical clearance at Meridian Waterfront Expo Center provides a lowest overhead unobstructed height of 5.2 m at the bay entry threshold.\nLOG-DOCK-XPL:For Highland Summit Exhibition Hall, the dock architectural inspection record indicates that the primary articulated vehicle unloading portal offers a freight bay vertical clearance of 5.6 m at the lowest overhead unobstructed bay entry threshold.\nLOG-DOCK-MJY:The dock architectural inspection record confirms that the freight bay vertical clearance for Starlight Gateway Convention Complex is 4.2 m, measured at the lowest overhead unobstructed height of the primary articulated vehicle unloading portal threshold."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Heavy lifting equipment(CRANE)",
|
| 12 |
+
"content": "LOG-CRANE-LQL:The equipment certification register for the main freight marshalling yard indicates that Meridian Waterfront Expo Center has an overhead gantry crane safe working load of 15 t.\nLOG-CRANE-BTR:Regarding Starlight Gateway Convention Complex, the equipment certification register shows an overhead gantry crane safe working load of 25 t within the main freight marshalling yard.\nLOG-CRANE-EX9:For Highland Summit Exhibition Hall, the equipment certification register lists the overhead gantry crane safe working load in the main freight marshalling yard as 40 t."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_003/role_agents/safety_commissioner.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Safety commissioner (SAF)",
|
| 3 |
+
"abstract": "Maintains municipal life safety compliance, emergency egress, and on-site paramedic station records",
|
| 4 |
+
"system_message": "You are Safety commissioner (SAF). The Safety commissioner (SAF) maintains municipal life safety compliance, emergency egress, and on-site paramedic station records.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Fire suppression systems(SPRINK)",
|
| 8 |
+
"content": "SAF-SPRINK-T84:At Meridian Waterfront Expo Center, the sprinkler system delivery pressure measured across ceiling deluge systems is 750 kPa.\nSAF-SPRINK-AQW:At Starlight Gateway Convention Complex, the sprinkler system delivery pressure across ceiling deluge systems is 850 kPa.\nSAF-SPRINK-1DQ:At Highland Summit Exhibition Hall, the sprinkler system delivery pressure across ceiling deluge systems is 650 kPa."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains municipal life safety compliance, emergency egress, and on-site paramedic station records(EGRESS)",
|
| 12 |
+
"content": "SAF-EGRESS-XGT:For Meridian Waterfront Expo Center, registered on-site health station availability is true based on the municipal health authority registry, and fire evacuation clearance approval is true according to the fire safety bureau certificate. The emergency paramedic response time from the on-site station to the farthest pavilion corner is 6 min.\nSAF-EGRESS-ZF3:For Highland Summit Exhibition Hall, registered on-site health station availability is true and fire evacuation clearance approval is true, while the emergency paramedic response time to the farthest corner is 12 min.\nSAF-EGRESS-C1D:For Starlight Gateway Convention Complex, registered on-site health station availability is true and fire evacuation clearance approval is true, with an emergency paramedic response time of 4 min."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_003/tasks/run_one.py
ADDED
|
@@ -0,0 +1,1396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from typing import Any
|
| 5 |
+
COMMUNICATION_ROLE_NAMES = []
|
| 6 |
+
GOLD = {'conclusion': 'Select', 'numeric_result': 412500}
|
| 7 |
+
POSITIVE_CONCLUSION = 'Select'
|
| 8 |
+
NEGATIVE_CONCLUSION = 'Do not select'
|
| 9 |
+
NUMERIC_PRECISION = 0
|
| 10 |
+
PUBLIC_ROLES = [{'role_name': 'Logistics director (LOG)', 'responsibility': 'Maintains physical freight loading dock specifications and cargo access clearances', 'role_abbreviation': 'LOG'}, {'role_name': 'Safety commissioner (SAF)', 'responsibility': 'Maintains municipal life safety compliance, emergency egress, and on-site paramedic station records', 'role_abbreviation': 'SAF'}, {'role_name': 'Facility engineer (ENG)', 'responsibility': 'Maintains electrical feeder capacity and physical hall floor areas', 'role_abbreviation': 'ENG'}, {'role_name': 'Acoustic consultant (ACO)', 'responsibility': 'Maintains acoustic soundproofing certifications and hall reverberation measurements', 'role_abbreviation': 'ACO'}, {'role_name': 'Commercial manager (COM)', 'responsibility': 'Maintains standardized venue tariff schedules and square-meter leasing rate contracts', 'role_abbreviation': 'COM'}, {'role_name': 'Community liaison (LIA)', 'responsibility': 'Maintains neighborhood feedback surveys and regional hospitality partnership ratings', 'role_abbreviation': 'LIA'}]
|
| 11 |
+
ROLE_KEY_PREFIXES = {'Logistics director (LOG)': 'LOG-', 'Safety commissioner (SAF)': 'SAF-', 'Facility engineer (ENG)': 'ENG-', 'Acoustic consultant (ACO)': 'ACO-', 'Commercial manager (COM)': 'COM-', 'Community liaison (LIA)': 'LIA-'}
|
| 12 |
+
ROLE_VALID_KEYS = {'Logistics director (LOG)': ['LOG-DOCK-APS', 'LOG-DOCK-XPL', 'LOG-DOCK-MJY', 'LOG-CRANE-LQL', 'LOG-CRANE-BTR', 'LOG-CRANE-EX9'], 'Safety commissioner (SAF)': ['SAF-SPRINK-T84', 'SAF-SPRINK-AQW', 'SAF-SPRINK-1DQ', 'SAF-EGRESS-XGT', 'SAF-EGRESS-ZF3', 'SAF-EGRESS-C1D'], 'Facility engineer (ENG)': ['ENG-HVAC-ZB9', 'ENG-HVAC-YGL', 'ENG-HVAC-JRO', 'ENG-POWER-T53', 'ENG-POWER-GMA', 'ENG-POWER-8YV'], 'Acoustic consultant (ACO)': ['ACO-VIB-YCW', 'ACO-VIB-3RJ', 'ACO-VIB-ML8', 'ACO-SOUND-IDH', 'ACO-SOUND-D4F', 'ACO-SOUND-I1J'], 'Commercial manager (COM)': ['COM-TARIFF-HBX', 'COM-TARIFF-6YG', 'COM-TARIFF-4Z4', 'COM-DEPOSIT-J1C', 'COM-DEPOSIT-I9Y', 'COM-DEPOSIT-LQC'], 'Community liaison (LIA)': ['LIA-CIVIC-WRZ', 'LIA-CIVIC-XOJ', 'LIA-CIVIC-DCX', 'LIA-TRANSIT-T0L', 'LIA-TRANSIT-DH7', 'LIA-TRANSIT-OPP']}
|
| 13 |
+
RECORD_REPLY_KEYS = {'LOG-DOCK-APS': ['LOG-DOCK-APS'], 'LOG-DOCK-XPL': ['LOG-DOCK-XPL'], 'LOG-DOCK-MJY': ['LOG-DOCK-MJY'], 'SAF-EGRESS-XGT': ['SAF-EGRESS-XGT'], 'SAF-EGRESS-ZF3': ['SAF-EGRESS-ZF3'], 'SAF-EGRESS-C1D': ['SAF-EGRESS-C1D'], 'ENG-POWER-8YV': ['ENG-POWER-8YV'], 'ENG-POWER-GMA': ['ENG-POWER-GMA'], 'ENG-POWER-T53': ['ENG-POWER-T53'], 'ACO-SOUND-D4F': ['ACO-SOUND-D4F'], 'ACO-SOUND-I1J': ['ACO-SOUND-I1J'], 'ACO-SOUND-IDH': ['ACO-SOUND-IDH'], 'COM-TARIFF-4Z4': ['COM-TARIFF-4Z4'], 'COM-TARIFF-HBX': ['COM-TARIFF-HBX'], 'COM-TARIFF-6YG': ['COM-TARIFF-6YG'], 'LIA-CIVIC-XOJ': ['LIA-CIVIC-XOJ'], 'LIA-CIVIC-DCX': ['LIA-CIVIC-DCX'], 'LIA-CIVIC-WRZ': ['LIA-CIVIC-WRZ'], 'LOG-CRANE-LQL': ['LOG-CRANE-LQL'], 'LOG-CRANE-EX9': ['LOG-CRANE-EX9'], 'LOG-CRANE-BTR': ['LOG-CRANE-BTR'], 'SAF-SPRINK-T84': ['SAF-SPRINK-T84'], 'SAF-SPRINK-1DQ': ['SAF-SPRINK-1DQ'], 'SAF-SPRINK-AQW': ['SAF-SPRINK-AQW'], 'ENG-HVAC-ZB9': ['ENG-HVAC-ZB9'], 'ENG-HVAC-YGL': ['ENG-HVAC-YGL'], 'ENG-HVAC-JRO': ['ENG-HVAC-JRO'], 'COM-DEPOSIT-I9Y': ['COM-DEPOSIT-I9Y'], 'COM-DEPOSIT-J1C': ['COM-DEPOSIT-J1C'], 'COM-DEPOSIT-LQC': ['COM-DEPOSIT-LQC'], 'LIA-TRANSIT-T0L': ['LIA-TRANSIT-T0L'], 'LIA-TRANSIT-DH7': ['LIA-TRANSIT-DH7'], 'LIA-TRANSIT-OPP': ['LIA-TRANSIT-OPP'], 'ACO-VIB-3RJ': ['ACO-VIB-3RJ'], 'ACO-VIB-YCW': ['ACO-VIB-YCW'], 'ACO-VIB-ML8': ['ACO-VIB-ML8']}
|
| 14 |
+
REQUIRED_KEYS = ['ACO-SOUND-D4F', 'COM-TARIFF-4Z4', 'ENG-POWER-8YV', 'LOG-DOCK-APS', 'LOG-DOCK-MJY', 'SAF-EGRESS-XGT', 'SAF-EGRESS-ZF3']
|
| 15 |
+
DISTRACTOR_KEYS = ['LIA-CIVIC-DCX', 'LIA-CIVIC-WRZ', 'LIA-CIVIC-XOJ', 'LIA-TRANSIT-DH7', 'LIA-TRANSIT-OPP', 'LIA-TRANSIT-T0L']
|
| 16 |
+
SETTING = 'incomplete'
|
| 17 |
+
|
| 18 |
+
def runtime_defaults() -> dict[str, Any]:
|
| 19 |
+
return {
|
| 20 |
+
"setting": SETTING,
|
| 21 |
+
"communication_role_names": list(COMMUNICATION_ROLE_NAMES),
|
| 22 |
+
"finalize_ideal_round": 3,
|
| 23 |
+
"max_turns": 6,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
FINALIZE_IDEAL_ROUND = runtime_defaults()["finalize_ideal_round"]
|
| 27 |
+
DEFAULT_MAX_TURNS = runtime_defaults()["max_turns"]
|
| 28 |
+
ERROR_INJECTION = {'enabled': False, 'role_name': 'Acoustic consultant (ACO)', 'target_key': 'ACO-SOUND-D4F', 'alternate_key': 'ACO-VIB-3RJ', 'target_context': 'trailing 12-month average', 'alternate_context': 'calendar year-to-date average'}
|
| 29 |
+
INCOMPLETE_INJECTION = {'record_id': 'rec_safety_commissioner_A', 'role_id': 'safety_commissioner', 'candidate_id': 'A', 'key': 'SAF-EGRESS-XGT', 'boolean_predicate_id': 'A_health_station_available', 'boolean_label': 'Registered on-site health station availability', 'hidden_predicate_id': 'A_emergency_response_time', 'threshold_label': 'Emergency paramedic response time', 'threshold_aliases': ['First aid arrival time', 'Medical incident response duration'], 'threshold_value': 6, 'threshold_unit': 'min', 'partial_record_text': 'SAF-EGRESS-XGT: Meridian Waterfront Expo Center.Meridian Waterfront Expo Center: Registered on-site health station availability = true .Source: Municipal health authority registry; Scope: Designated on-site medical treatment post; Measurement: Formal registration status of permanent first aid clinic facility.Meridian Waterfront Expo Center: Fire evacuation clearance approval = true .Source: Fire safety bureau certificate; Scope: Entire indoor exhibition pavilion complex; Measurement: Formal compliance approval for maximum occupancy emergency egress pathways.', 'alternative_outputs': [{'conclusion': 'Do not select', 'numeric_result': None, 'qualified_candidate_id': None}], 'role_name': 'Safety commissioner (SAF)', 'candidate_name': 'Meridian Waterfront Expo Center', 'other_candidate_names': ['Highland Summit Exhibition Hall', 'Starlight Gateway Convention Complex'], 'context_value': None, 'other_context_values': [], 'language': 'en'}
|
| 30 |
+
INCOMPLETE_FOLLOWUP_RECORDS = [{'key': 'LOG-DOCK-APS', 'role': 'Logistics director (LOG)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'freight_bay_clearance', 'label': 'Freight bay vertical clearance', 'aliases': ['Loading bay clearance', 'Cargo door height']}]}, {'key': 'LOG-DOCK-XPL', 'role': 'Logistics director (LOG)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'freight_bay_clearance', 'label': 'Freight bay vertical clearance', 'aliases': ['Loading bay clearance', 'Cargo door height']}]}, {'key': 'LOG-DOCK-MJY', 'role': 'Logistics director (LOG)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'freight_bay_clearance', 'label': 'Freight bay vertical clearance', 'aliases': ['Loading bay clearance', 'Cargo door height']}]}, {'key': 'SAF-EGRESS-XGT', 'role': 'Safety commissioner (SAF)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'health_station_available', 'label': 'Registered on-site health station availability', 'aliases': ['Medical station presence', 'First aid clinic existence']}, {'id': 'emergency_response_time', 'label': 'Emergency paramedic response time', 'aliases': ['First aid arrival time', 'Medical incident response duration']}, {'id': 'evacuation_clearance_approved', 'label': 'Fire evacuation clearance approval', 'aliases': ['Life safety egress approval', 'Emergency evacuation certificate']}]}, {'key': 'SAF-EGRESS-ZF3', 'role': 'Safety commissioner (SAF)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'health_station_available', 'label': 'Registered on-site health station availability', 'aliases': ['Medical station presence', 'First aid clinic existence']}, {'id': 'emergency_response_time', 'label': 'Emergency paramedic response time', 'aliases': ['First aid arrival time', 'Medical incident response duration']}, {'id': 'evacuation_clearance_approved', 'label': 'Fire evacuation clearance approval', 'aliases': ['Life safety egress approval', 'Emergency evacuation certificate']}]}, {'key': 'SAF-EGRESS-C1D', 'role': 'Safety commissioner (SAF)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'health_station_available', 'label': 'Registered on-site health station availability', 'aliases': ['Medical station presence', 'First aid clinic existence']}, {'id': 'emergency_response_time', 'label': 'Emergency paramedic response time', 'aliases': ['First aid arrival time', 'Medical incident response duration']}, {'id': 'evacuation_clearance_approved', 'label': 'Fire evacuation clearance approval', 'aliases': ['Life safety egress approval', 'Emergency evacuation certificate']}]}, {'key': 'ENG-POWER-8YV', 'role': 'Facility engineer (ENG)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'electrical_grid_load', 'label': 'Certified electrical grid load capacity', 'aliases': ['Exhibition grid power', 'Continuous electrical capacity']}, {'id': 'billable_exhibit_space', 'label': 'Billable exhibit hall space', 'aliases': ['Usable exhibition area', 'Net booth floor area']}]}, {'key': 'ENG-POWER-GMA', 'role': 'Facility engineer (ENG)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'electrical_grid_load', 'label': 'Certified electrical grid load capacity', 'aliases': ['Exhibition grid power', 'Continuous electrical capacity']}, {'id': 'billable_exhibit_space', 'label': 'Billable exhibit hall space', 'aliases': ['Usable exhibition area', 'Net booth floor area']}]}, {'key': 'ENG-POWER-T53', 'role': 'Facility engineer (ENG)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'electrical_grid_load', 'label': 'Certified electrical grid load capacity', 'aliases': ['Exhibition grid power', 'Continuous electrical capacity']}, {'id': 'billable_exhibit_space', 'label': 'Billable exhibit hall space', 'aliases': ['Usable exhibition area', 'Net booth floor area']}]}, {'key': 'ACO-SOUND-D4F', 'role': 'Acoustic consultant (ACO)', 'candidate': 'Meridian Waterfront Expo Center', 'context': 'trailing 12-month average', 'fields': [{'id': 'acoustic_soundproofing_rating', 'label': 'Acoustic soundproofing rating', 'aliases': ['Wall acoustic attenuation', 'Sound transmission loss']}]}, {'key': 'ACO-SOUND-I1J', 'role': 'Acoustic consultant (ACO)', 'candidate': 'Highland Summit Exhibition Hall', 'context': 'trailing 12-month average', 'fields': [{'id': 'acoustic_soundproofing_rating', 'label': 'Acoustic soundproofing rating', 'aliases': ['Wall acoustic attenuation', 'Sound transmission loss']}]}, {'key': 'ACO-SOUND-IDH', 'role': 'Acoustic consultant (ACO)', 'candidate': 'Starlight Gateway Convention Complex', 'context': 'trailing 12-month average', 'fields': [{'id': 'acoustic_soundproofing_rating', 'label': 'Acoustic soundproofing rating', 'aliases': ['Wall acoustic attenuation', 'Sound transmission loss']}]}, {'key': 'COM-TARIFF-4Z4', 'role': 'Commercial manager (COM)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'daily_booth_rate', 'label': 'Standard daily rate per unit area', 'aliases': ['Unit area daily rental tariff', 'Square meter lease rate']}]}, {'key': 'COM-TARIFF-HBX', 'role': 'Commercial manager (COM)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'daily_booth_rate', 'label': 'Standard daily rate per unit area', 'aliases': ['Unit area daily rental tariff', 'Square meter lease rate']}]}, {'key': 'COM-TARIFF-6YG', 'role': 'Commercial manager (COM)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'daily_booth_rate', 'label': 'Standard daily rate per unit area', 'aliases': ['Unit area daily rental tariff', 'Square meter lease rate']}]}, {'key': 'LIA-CIVIC-XOJ', 'role': 'Community liaison (LIA)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'hotel_partnership_score', 'label': 'Regional hospitality partnership rating', 'aliases': ['Nearby hotel affiliation score', 'Accommodation partner rating']}]}, {'key': 'LIA-CIVIC-DCX', 'role': 'Community liaison (LIA)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'hotel_partnership_score', 'label': 'Regional hospitality partnership rating', 'aliases': ['Nearby hotel affiliation score', 'Accommodation partner rating']}]}, {'key': 'LIA-CIVIC-WRZ', 'role': 'Community liaison (LIA)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'hotel_partnership_score', 'label': 'Regional hospitality partnership rating', 'aliases': ['Nearby hotel affiliation score', 'Accommodation partner rating']}]}, {'key': 'LOG-CRANE-LQL', 'role': 'Logistics director (LOG)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'supplemental_logistics_director', 'label': 'Overhead gantry crane safe working load', 'aliases': []}]}, {'key': 'LOG-CRANE-EX9', 'role': 'Logistics director (LOG)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'supplemental_logistics_director', 'label': 'Overhead gantry crane safe working load', 'aliases': []}]}, {'key': 'LOG-CRANE-BTR', 'role': 'Logistics director (LOG)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'supplemental_logistics_director', 'label': 'Overhead gantry crane safe working load', 'aliases': []}]}, {'key': 'SAF-SPRINK-T84', 'role': 'Safety commissioner (SAF)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'supplemental_safety_commissioner', 'label': 'Sprinkler system delivery pressure', 'aliases': []}]}, {'key': 'SAF-SPRINK-1DQ', 'role': 'Safety commissioner (SAF)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'supplemental_safety_commissioner', 'label': 'Sprinkler system delivery pressure', 'aliases': []}]}, {'key': 'SAF-SPRINK-AQW', 'role': 'Safety commissioner (SAF)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'supplemental_safety_commissioner', 'label': 'Sprinkler system delivery pressure', 'aliases': []}]}, {'key': 'ENG-HVAC-ZB9', 'role': 'Facility engineer (ENG)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'supplemental_facility_engineer', 'label': 'Chilled air exchange volume', 'aliases': []}]}, {'key': 'ENG-HVAC-YGL', 'role': 'Facility engineer (ENG)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'supplemental_facility_engineer', 'label': 'Chilled air exchange volume', 'aliases': []}]}, {'key': 'ENG-HVAC-JRO', 'role': 'Facility engineer (ENG)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'supplemental_facility_engineer', 'label': 'Chilled air exchange volume', 'aliases': []}]}, {'key': 'COM-DEPOSIT-I9Y', 'role': 'Commercial manager (COM)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'supplemental_commercial_manager', 'label': 'Mandatory security deposit percentage', 'aliases': []}]}, {'key': 'COM-DEPOSIT-J1C', 'role': 'Commercial manager (COM)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'supplemental_commercial_manager', 'label': 'Mandatory security deposit percentage', 'aliases': []}]}, {'key': 'COM-DEPOSIT-LQC', 'role': 'Commercial manager (COM)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'supplemental_commercial_manager', 'label': 'Mandatory security deposit percentage', 'aliases': []}]}, {'key': 'LIA-TRANSIT-T0L', 'role': 'Community liaison (LIA)', 'candidate': 'Meridian Waterfront Expo Center', 'context': '', 'fields': [{'id': 'supplemental_community_liaison', 'label': 'Walking distance to metro terminus', 'aliases': []}]}, {'key': 'LIA-TRANSIT-DH7', 'role': 'Community liaison (LIA)', 'candidate': 'Highland Summit Exhibition Hall', 'context': '', 'fields': [{'id': 'supplemental_community_liaison', 'label': 'Walking distance to metro terminus', 'aliases': []}]}, {'key': 'LIA-TRANSIT-OPP', 'role': 'Community liaison (LIA)', 'candidate': 'Starlight Gateway Convention Complex', 'context': '', 'fields': [{'id': 'supplemental_community_liaison', 'label': 'Walking distance to metro terminus', 'aliases': []}]}, {'key': 'ACO-VIB-3RJ', 'role': 'Acoustic consultant (ACO)', 'candidate': 'Meridian Waterfront Expo Center', 'context': 'calendar year-to-date average', 'fields': [{'id': 'acoustic_soundproofing_rating', 'label': 'Acoustic soundproofing rating', 'aliases': ['Wall acoustic attenuation', 'Sound transmission loss']}]}, {'key': 'ACO-VIB-YCW', 'role': 'Acoustic consultant (ACO)', 'candidate': 'Highland Summit Exhibition Hall', 'context': 'calendar year-to-date average', 'fields': [{'id': 'acoustic_soundproofing_rating', 'label': 'Acoustic soundproofing rating', 'aliases': ['Wall acoustic attenuation', 'Sound transmission loss']}]}, {'key': 'ACO-VIB-ML8', 'role': 'Acoustic consultant (ACO)', 'candidate': 'Starlight Gateway Convention Complex', 'context': 'calendar year-to-date average', 'fields': [{'id': 'acoustic_soundproofing_rating', 'label': 'Acoustic soundproofing rating', 'aliases': ['Wall acoustic attenuation', 'Sound transmission loss']}]}]
|
| 31 |
+
KEY_PATTERN = re.compile(r"^[A-Z]+-[A-Z]+-[A-Z0-9]{3}$")
|
| 32 |
+
REPLY_KEY_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z]+-[A-Z]+-[A-Z0-9]{3}(?![A-Z0-9])", re.IGNORECASE)
|
| 33 |
+
ROLE_REPLY_MAX_ATTEMPTS = 3
|
| 34 |
+
TASK_QUERY = "Evaluate whether exactly one convention center satisfies all of the following operational and technical requirements: freight bay vertical clearance of at least 4.8 m, fire evacuation clearance approval is true, a registered on-site health station is available and the emergency paramedic response time is at most 6 min, certified electrical grid load capacity of at least 320 kW, and an acoustic soundproofing rating of at least 42 dB based on the trailing 12-month average. If exactly one convention center meets these requirements, report 'Select' along with its total baseline booth rental revenue in EUR, calculated by multiplying billable exhibit hall space by standard daily rate per unit area. Otherwise, report 'Do not select' and null for the numeric result.\n\nNumeric calculation rule: Compute only for the unique eligible candidate: [Billable exhibit hall space] * [Standard daily rate per unit area]. Result unit: EUR. Round only the final result to 0 decimal places (ties to even). If no candidate qualifies, numeric_result is null.\n\nCandidates and records to verify:\n- Starlight Gateway Convention Complex:LOG-DOCK-MJY、SAF-EGRESS-C1D、ENG-POWER-T53、ACO-SOUND-IDH、COM-TARIFF-6YG、LIA-CIVIC-WRZ\n- Meridian Waterfront Expo Center:LOG-DOCK-APS、SAF-EGRESS-XGT、ENG-POWER-8YV、ACO-SOUND-D4F、COM-TARIFF-4Z4、LIA-CIVIC-XOJ\n- Highland Summit Exhibition Hall:LOG-DOCK-XPL、SAF-EGRESS-ZF3、ENG-POWER-GMA、ACO-SOUND-I1J、COM-TARIFF-HBX、LIA-CIVIC-DCX"
|
| 35 |
+
TASK_CONTEXT = 'As part of the international exhibition pavilion venue evaluation, venue management oversees the technical and operational assessment of prospective convention centers to host large-scale trade exhibitions. The review requires verifying logistical access, life safety compliance, medical readiness, utility reliability, and acoustic separation between major event zones, alongside computing baseline commercial revenue metrics.'
|
| 36 |
+
|
| 37 |
+
"""Parse one model message without treating trailing generation noise as an action."""
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from typing import Any
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_json_message(content: Any, *, trace: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 44 |
+
if trace is not None:
|
| 45 |
+
trace.clear()
|
| 46 |
+
trace.update(policy="first_complete_object", raw_response=content, recovered=False)
|
| 47 |
+
if not isinstance(content, str):
|
| 48 |
+
raise ValueError("model response must be text")
|
| 49 |
+
text = content.strip().lstrip("\ufeff").strip()
|
| 50 |
+
# Parse the first complete object; never recover a nested fragment.
|
| 51 |
+
try:
|
| 52 |
+
value, end = json.JSONDecoder().raw_decode(text)
|
| 53 |
+
start = 0
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
if text.startswith(("{", "[", '"')):
|
| 56 |
+
raise
|
| 57 |
+
opening = re.search(r"[\{\[]", text)
|
| 58 |
+
if opening is None:
|
| 59 |
+
raise
|
| 60 |
+
start = opening.start()
|
| 61 |
+
value, consumed = json.JSONDecoder().raw_decode(text[start:])
|
| 62 |
+
end = start + consumed
|
| 63 |
+
if not isinstance(value, dict):
|
| 64 |
+
raise ValueError("model response must be a JSON object")
|
| 65 |
+
prefix, suffix = text[:start], text[end:]
|
| 66 |
+
if trace is not None:
|
| 67 |
+
trace.update(recovered=bool(prefix.strip() or suffix.strip()),
|
| 68 |
+
ignored_prefix=prefix, ignored_suffix=suffix)
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def expand_question_keys(questions):
|
| 73 |
+
expanded = []
|
| 74 |
+
for question in questions:
|
| 75 |
+
if not isinstance(question, dict):
|
| 76 |
+
expanded.append(question)
|
| 77 |
+
continue
|
| 78 |
+
text = question.get("question")
|
| 79 |
+
keys = list(dict.fromkeys(REPLY_KEY_PATTERN.findall(text))) if isinstance(text, str) else []
|
| 80 |
+
for key in keys or [None]:
|
| 81 |
+
expanded.append(dict(question, key=key))
|
| 82 |
+
return expanded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def validate_question(question, *, role_name, semantic_enabled=False):
|
| 86 |
+
if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
|
| 87 |
+
raise ValueError("question must contain natural-language text")
|
| 88 |
+
if role_name not in ROLE_KEY_PREFIXES:
|
| 89 |
+
raise ValueError("unknown Role")
|
| 90 |
+
key = question.get("key")
|
| 91 |
+
authorized = semantic_enabled if key is None else (
|
| 92 |
+
isinstance(key, str) and key in ROLE_VALID_KEYS[role_name] and key in question["question"])
|
| 93 |
+
return {"authorized": bool(authorized)}
|
| 94 |
+
|
| 95 |
+
def recovery_key_match(answer: str) -> str | None:
|
| 96 |
+
target = ERROR_INJECTION.get("target_key")
|
| 97 |
+
if not target:
|
| 98 |
+
return None
|
| 99 |
+
def contains(key: str) -> bool:
|
| 100 |
+
return bool(re.search(r"(?<![A-Z0-9-])" + re.escape(key) + r"(?![A-Z0-9-])", answer, re.IGNORECASE))
|
| 101 |
+
if contains(target):
|
| 102 |
+
return "full_key"
|
| 103 |
+
parts = target.split("-")
|
| 104 |
+
alias = parts[0] + "-" + parts[-1]
|
| 105 |
+
matches = [key for key in ROLE_VALID_KEYS.get(ERROR_INJECTION.get("role_name"), [])
|
| 106 |
+
if key.split("-")[0] + "-" + key.split("-")[-1] == alias]
|
| 107 |
+
if matches == [target] and contains(alias):
|
| 108 |
+
return "abbreviated_key"
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
def communication_metrics(transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 112 |
+
key_query_rounds: dict[str, int] = {}
|
| 113 |
+
key_query_counts: dict[str, int] = {}
|
| 114 |
+
queried_roles: set[str] = set()
|
| 115 |
+
mismatch_round: int | None = None
|
| 116 |
+
recovery_query_sent = False
|
| 117 |
+
recovery_query_turn: int | None = None
|
| 118 |
+
target_key_returned = False
|
| 119 |
+
recovery_turn: int | None = None
|
| 120 |
+
recovery_method: str | None = None
|
| 121 |
+
recovery_reference: str | None = None
|
| 122 |
+
target_key_query_turn: int | None = None
|
| 123 |
+
finalized_before_recovery = False
|
| 124 |
+
for event in transcript:
|
| 125 |
+
turn = int(event.get("turn", len(transcript)))
|
| 126 |
+
action = event.get("main_agent_action", {})
|
| 127 |
+
if (
|
| 128 |
+
ERROR_INJECTION.get("enabled")
|
| 129 |
+
and action.get("action") == "finalize"
|
| 130 |
+
and not target_key_returned
|
| 131 |
+
):
|
| 132 |
+
finalized_before_recovery = True
|
| 133 |
+
if action.get("action") != "ask_role_agents": continue
|
| 134 |
+
for answer in event.get("role_answers", []):
|
| 135 |
+
role_name = answer.get("role_agent")
|
| 136 |
+
if role_name: queried_roles.add(role_name)
|
| 137 |
+
if (
|
| 138 |
+
ERROR_INJECTION.get("enabled") and mismatch_round is not None and turn > mismatch_round
|
| 139 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 140 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("target_key")
|
| 141 |
+
and "role_trace" in answer
|
| 142 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 143 |
+
):
|
| 144 |
+
target_key_query_turn = target_key_query_turn or turn
|
| 145 |
+
if (
|
| 146 |
+
ERROR_INJECTION.get("enabled")
|
| 147 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 148 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("alternate_key")
|
| 149 |
+
and "role_trace" in answer
|
| 150 |
+
):
|
| 151 |
+
mismatch_round = mismatch_round or turn
|
| 152 |
+
for message in action.get("messages", []):
|
| 153 |
+
for question in message.get("questions", []):
|
| 154 |
+
key = question.get("key")
|
| 155 |
+
if (
|
| 156 |
+
ERROR_INJECTION.get("enabled")
|
| 157 |
+
and resolve_role_name(message.get("role_agent")) == ERROR_INJECTION.get("role_name")
|
| 158 |
+
and (key is None or key == ERROR_INJECTION.get("target_key"))
|
| 159 |
+
and mismatch_round is not None
|
| 160 |
+
and turn > mismatch_round
|
| 161 |
+
):
|
| 162 |
+
recovery_query_sent = True
|
| 163 |
+
recovery_query_turn = recovery_query_turn or turn
|
| 164 |
+
if not isinstance(key, str) or not KEY_PATTERN.fullmatch(key): continue
|
| 165 |
+
key_query_rounds.setdefault(key, turn)
|
| 166 |
+
key_query_counts[key] = key_query_counts.get(key, 0) + 1
|
| 167 |
+
if recovery_query_sent and not target_key_returned and mismatch_round is not None and turn > mismatch_round:
|
| 168 |
+
for answer in event.get("role_answers", []):
|
| 169 |
+
question = answer.get("question", {})
|
| 170 |
+
if (
|
| 171 |
+
answer.get("role_agent") == ERROR_INJECTION.get("role_name")
|
| 172 |
+
and (question.get("key") is None or question.get("key") == ERROR_INJECTION.get("target_key"))
|
| 173 |
+
and "role_trace" in answer
|
| 174 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 175 |
+
):
|
| 176 |
+
target_key_returned = True
|
| 177 |
+
recovery_reference = recovery_key_match(str(answer.get("answer", "")))
|
| 178 |
+
recovery_turn = turn
|
| 179 |
+
recovery_method = "keyless_query" if question.get("key") is None else "target_key_query"
|
| 180 |
+
break
|
| 181 |
+
queried = set(key_query_counts)
|
| 182 |
+
required = set(REQUIRED_KEYS)
|
| 183 |
+
relevant = queried & required
|
| 184 |
+
return {
|
| 185 |
+
"required_key_recall":len(relevant)/len(required) if required else 1.0,
|
| 186 |
+
"required_key_precision":len(relevant)/len(queried) if queried else 0.0,
|
| 187 |
+
"key_query_rounds":key_query_rounds,
|
| 188 |
+
"key_query_counts":key_query_counts,
|
| 189 |
+
"duplicate_key_queries":sum(max(0, count-1) for count in key_query_counts.values()),
|
| 190 |
+
"distractor_key_queries":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS),
|
| 191 |
+
"distractor_key_query_rate":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS)/sum(key_query_counts.values()) if key_query_counts else 0.0,
|
| 192 |
+
"turns_to_finalize":len(transcript),
|
| 193 |
+
"mismatch_key_queried":mismatch_round is not None,
|
| 194 |
+
"mismatch_key_turn":mismatch_round,
|
| 195 |
+
"recovery_query_sent":recovery_query_sent,
|
| 196 |
+
"recovery_query_turn":recovery_query_turn,
|
| 197 |
+
"target_key_returned":target_key_returned,
|
| 198 |
+
"recovery_turn":recovery_turn,
|
| 199 |
+
"recovery_method":recovery_method,
|
| 200 |
+
"target_key_query_turn":target_key_query_turn,
|
| 201 |
+
"recovery_key_match":recovery_reference,
|
| 202 |
+
"recovery_metrics_version":"keyed_and_keyless_v3",
|
| 203 |
+
"recovery_latency":recovery_turn - mismatch_round if recovery_turn is not None and mismatch_round is not None else None,
|
| 204 |
+
"finalized_before_recovery":finalized_before_recovery,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
def main_system_prompt() -> str:
|
| 208 |
+
role_text = "\n".join(f"- {item['role_name']}: {item['responsibility']}" for item in PUBLIC_ROLES)
|
| 209 |
+
ask_example = json.dumps({"action":"ask_role_agents","messages":[{"role_agent":"Role name","questions":[{"id":"Q1","question":"Please provide the record for ABC-DATA-A1B using the supplied key."}]}]}, ensure_ascii=False)
|
| 210 |
+
final_example = json.dumps({"action":"finalize","conclusion":"Exactly: " + POSITIVE_CONCLUSION + " or " + NEGATIVE_CONCLUSION,"numeric_result":None}, ensure_ascii=False).replace('"numeric_result": null', '"numeric_result": null/number')
|
| 211 |
+
communication_protocol = ('You may output {"action":"wait"} to advance one logical turn. An empty observation {"observations":[]} means no new visible messages; it does not imply receipt, processing or any future reply.' if SETTING in {'missed', 'mixed'} else '')
|
| 212 |
+
followup = ('For keyless follow-ups, name the candidate in full and the metric explicitly, or request that candidate\'s complete records. A unique previously queried record can be checked directly; otherwise supply a full key and metric when asked to clarify. Explicit directory requests return the complete directory.' if SETTING == 'incomplete' else
|
| 213 |
+
'Authorized keyless follow-ups may name the candidate and metric or request complete records. A role may retrieve facts, request clarification or return a directory. If given a directory, select a valid key to obtain facts.' if SETTING == 'mixed' else
|
| 214 |
+
'Authorized keyless questions return that role\'s complete directory. Choose a key from the directory to obtain concrete facts.')
|
| 215 |
+
return "\n\n".join([
|
| 216 |
+
'You are the Main Agent. Integrate information from independent role agents and make the final decision. Communicate in English.',
|
| 217 |
+
'You cannot see private role information directly. Obtain it only by explicitly messaging the role agents.',
|
| 218 |
+
'Key protocol:\n1. Candidate names and record keys are supplied in the task. Initial access requires a valid key; authorized later follow-ups are the exception.\n'
|
| 219 |
+
'2. Keys use ROLE-BUSINESS-XXX: role abbreviation, business abbreviation and three random alphanumeric characters. Use complete supplied keys; do not invent them.\n'
|
| 220 |
+
'3. Send each key to its owning business role. Use valid keys supplied by roles for subsequent checks.\n'
|
| 221 |
+
'4. Do not output a separate key field. Put the complete key in question text; the system extracts it and checks ownership. Separate different keys into individual questions, preferably one record per question.\n'
|
| 222 |
+
'5. After a successful keyed query to a role, keyless natural-language follow-ups to that role are authorized starting from the next turn.\n6. ' + followup,
|
| 223 |
+
'Available independent role agents:\n\n' + role_text,
|
| 224 |
+
'To ask questions, output only JSON in this form:\n\n' + ask_example,
|
| 225 |
+
*([communication_protocol] if communication_protocol else []),
|
| 226 |
+
'Final answer format (output only valid JSON):\n\n' + final_example,
|
| 227 |
+
'Use exactly one of these conclusion labels: ' + POSITIVE_CONCLUSION + ' or ' + NEGATIVE_CONCLUSION + '. '
|
| 228 |
+
'Do not append a candidate name, explanation or other text. null/number means choose one, not literal syntax. '
|
| 229 |
+
'For a positive conclusion provide the computed number; for a negative conclusion use null. Do not include units or explanations in numeric_result.',
|
| 230 |
+
])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
"""Conservative English evidence rules shared by standalone generated runtimes.
|
| 234 |
+
|
| 235 |
+
This is attribution of explicit statements, not arbitrary semantic entailment.
|
| 236 |
+
Unsupported or conflicting statements remain unknown; no model calls are made.
|
| 237 |
+
"""
|
| 238 |
+
import re
|
| 239 |
+
from decimal import Decimal
|
| 240 |
+
|
| 241 |
+
_RECOVERY_NUMBER = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?'
|
| 242 |
+
_RECOVERY_UNCERTAIN = r"\b(?:unknown|uncertain|unclear|may|might|could|should|would|must|expected|possibly|whether|cannot|unable|unconfirmed|approximately|about|around|roughly|estimated|not confirmed|not known|not established)\b"
|
| 243 |
+
_RECOVERY_NEGATIVE = r'\b(?:not|no|never|false|invalid|blocked|failed|denied|unavailable|unapproved|revoked|inactive|disabled|noncompliant)\b'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def evidence_text(text):
|
| 247 |
+
text = text.replace('’', "'").replace('−', '-').replace('‑', '-')
|
| 248 |
+
text = re.sub(r"\bcan't\b", 'cannot', text, flags=re.I)
|
| 249 |
+
text = re.sub(r"n't\b", ' not', text, flags=re.I)
|
| 250 |
+
text = re.sub(r'(?<![\w.,])[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,]|\.\d)',
|
| 251 |
+
lambda m: m[0].replace(',', ''), text)
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def evidence_phrase(text, phrase):
|
| 256 |
+
if not phrase:
|
| 257 |
+
return False
|
| 258 |
+
return bool(re.search(r'(?<!\w)' + re.escape(phrase).replace(r'\ ', r'\s+') + r'(?!\w)', text, re.I))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def evidence_nonasserted(text):
|
| 262 |
+
"""Questions, hypotheses and unconfirmed claims are not returned facts."""
|
| 263 |
+
return bool('?' in text or re.search(_RECOVERY_UNCERTAIN, text, re.I)
|
| 264 |
+
or re.search(r'\b(?:if|unless|assuming|suppose|supposing|hypothetically)\b', text, re.I)
|
| 265 |
+
or re.search(r'\b(?:do|does|did|has|have|had)\s+not\s+(?:confirm|verify|establish)(?:ed)?\b', text, re.I))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def evidence_clauses(text):
|
| 269 |
+
# Preserve questions and uncertainty when splitting assertions.
|
| 270 |
+
sentences = re.split(r'[。\n]|\.(?!\d)|(?<=[!?])\s+', text)
|
| 271 |
+
clauses = []
|
| 272 |
+
for sentence in sentences:
|
| 273 |
+
if evidence_nonasserted(sentence):
|
| 274 |
+
clauses.append(sentence)
|
| 275 |
+
else:
|
| 276 |
+
clauses.extend(re.split(r'[;;]|,?\s+\b(?:but|and)\b\s+(?![+-]?\d)', sentence, flags=re.I))
|
| 277 |
+
return clauses
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def evidence_scope(answer, question, profile):
|
| 281 |
+
for target in [profile.get('candidate', ''), profile.get('target_context', '')]:
|
| 282 |
+
if target and re.search(r'\b(?:not|outside|excluding|except)(?:\s+(?:for|the))?\s+' + re.escape(target) + r'(?!\w)', answer, re.I):
|
| 283 |
+
return 'not_returned'
|
| 284 |
+
candidates = profile.get('other_candidates', [])
|
| 285 |
+
contexts = profile.get('other_contexts', [profile.get('alternate_context', '')])
|
| 286 |
+
if any(evidence_phrase(answer, c) for c in [*candidates, *contexts] if c):
|
| 287 |
+
target_also_present = evidence_phrase(answer, profile.get('candidate', '')) and (
|
| 288 |
+
not profile.get('target_context') or evidence_phrase(answer, profile['target_context']))
|
| 289 |
+
return 'unknown' if target_also_present else 'not_returned'
|
| 290 |
+
combined = question.get('question', '') + '\n' + answer
|
| 291 |
+
target_key = profile.get('target_key', '')
|
| 292 |
+
if target_key and (question.get('key') == target_key or evidence_phrase(combined, target_key)):
|
| 293 |
+
return 'eligible'
|
| 294 |
+
if evidence_phrase(combined, profile.get('candidate', '')) and (
|
| 295 |
+
not profile.get('target_context') or evidence_phrase(combined, profile['target_context'])):
|
| 296 |
+
return 'eligible'
|
| 297 |
+
return 'unknown'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def evidence_unit_pattern(unit):
|
| 301 |
+
# Unit names may inflect; canonical symbols remain case-sensitive.
|
| 302 |
+
groups = [('h', 'hour', 'hours'), ('min', 'minute', 'minutes'), ('s', 'second', 'seconds'),
|
| 303 |
+
('kg', 'kilogram', 'kilograms'), ('m', 'meter', 'meters', 'metre', 'metres'),
|
| 304 |
+
('%', 'percent', 'per cent'), ('instances', 'instance'), ('items', 'item'),
|
| 305 |
+
('people', 'person', 'persons'), ('days', 'day')]
|
| 306 |
+
for group in groups:
|
| 307 |
+
if unit in group:
|
| 308 |
+
canonical, *words = group
|
| 309 |
+
if canonical in {'instances', 'items', 'people', 'days'}:
|
| 310 |
+
words.append(canonical)
|
| 311 |
+
canonical = None
|
| 312 |
+
parts = ([re.escape(canonical)] if canonical else []) + ['(?i:' + re.escape(w) + ')' for w in words]
|
| 313 |
+
if unit == '%': parts.append('%')
|
| 314 |
+
return '(?:' + '|'.join(sorted(parts, key=len, reverse=True)) + ')'
|
| 315 |
+
return re.escape(unit)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evidence_measurements(text, unit):
|
| 319 |
+
text = evidence_text(text)
|
| 320 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 321 |
+
suffix = (r'(?:\s+(?:1|(?i:dimensionless)))?' if unit == '1'
|
| 322 |
+
else r'\s*' + evidence_unit_pattern(unit))
|
| 323 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')' + suffix + r'(?![A-Za-z0-9_/%]|\.\d|,\d)'
|
| 324 |
+
return text, list(re.finditer(pattern, text))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def evidence_exact_measurement(text, match):
|
| 328 |
+
before, after = text[max(0, match.start()-60):match.start()], text[match.end():match.end()+45]
|
| 329 |
+
if evidence_nonasserted(text):
|
| 330 |
+
return False
|
| 331 |
+
if re.search(r'(?:\b(?:under|over|below|above|less than|more than|at most|at least|up to|between|to|and|not|no more than|no less than)|不超过|不低于|小于等于|大于等于|小于|大于|至少|至多|最多|最少|低于|高于|介于|至|到|[<>≤≥~~–—])\s*$', before, re.I):
|
| 332 |
+
return False
|
| 333 |
+
if re.search(r'\d\s*[-–—]\s*$', before):
|
| 334 |
+
return False
|
| 335 |
+
if re.match(r'\s*(?:\b(?:maximum|minimum|max|min)\b|\bor (?:less|more|lower|higher)\b|\b(?:to|through)\s+[+-]?\d|[-–—~~]\s*\d)', after, re.I):
|
| 336 |
+
return False
|
| 337 |
+
return True
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def english_exact_value(answer, value, unit):
|
| 341 |
+
for clause in evidence_clauses(evidence_text(answer)):
|
| 342 |
+
text, matches = evidence_measurements(clause, unit)
|
| 343 |
+
if any(Decimal(m[1]) == Decimal(str(value)) and evidence_exact_measurement(text, m) for m in matches):
|
| 344 |
+
return True
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def numeric_evidence(answer, question, profile, fact):
|
| 349 |
+
answer = evidence_text(answer)
|
| 350 |
+
scope = evidence_scope(answer, question, profile)
|
| 351 |
+
if scope != 'eligible':
|
| 352 |
+
return scope
|
| 353 |
+
labels = [fact.get('label', ''), *fact.get('aliases', [])]
|
| 354 |
+
states = set()
|
| 355 |
+
for clause in evidence_clauses(answer):
|
| 356 |
+
# Bind each value to its asserted metric; nearby numbers are not evidence.
|
| 357 |
+
if not any(evidence_phrase(clause, label) for label in labels if label):
|
| 358 |
+
continue
|
| 359 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 360 |
+
continue
|
| 361 |
+
# Leave ambiguous multi-metric clauses unscored.
|
| 362 |
+
others = profile.get('facts', profile.get('numeric', []) + profile.get('boolean', []))
|
| 363 |
+
if any(other.get('topic') != fact.get('topic') and any(evidence_phrase(clause, label) for label in
|
| 364 |
+
[other.get('label', ''), *other.get('aliases', [])] if label) for other in others):
|
| 365 |
+
continue
|
| 366 |
+
text, matches = evidence_measurements(clause, fact.get('unit', ''))
|
| 367 |
+
for m in matches:
|
| 368 |
+
if evidence_exact_measurement(text, m) and not re.search(_RECOVERY_NEGATIVE, text[:m.start()], re.I):
|
| 369 |
+
states.add(Decimal(m[1]) == Decimal(str(fact['value'])))
|
| 370 |
+
if len(states) != 1:
|
| 371 |
+
return 'unknown'
|
| 372 |
+
return 'returned' if states.pop() else 'not_returned'
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _evidence_predicate(text):
|
| 376 |
+
text = re.sub(r'\b(?:is|are|was|were|has|have|had|been|the|a|an|already)\b', ' ', text.casefold())
|
| 377 |
+
return re.sub(r'\s+', ' ', text).strip(' .:')
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def boolean_evidence(answer, question, profile):
|
| 381 |
+
answer = evidence_text(answer)
|
| 382 |
+
scope = evidence_scope(answer, question, profile)
|
| 383 |
+
if scope != 'eligible':
|
| 384 |
+
return scope
|
| 385 |
+
labels = [profile['label'], *profile.get('aliases', [])]
|
| 386 |
+
states = set()
|
| 387 |
+
for clause in evidence_clauses(answer):
|
| 388 |
+
plain = _evidence_predicate(clause)
|
| 389 |
+
no_negative = _evidence_predicate(re.sub(_RECOVERY_NEGATIVE, ' ', clause, flags=re.I))
|
| 390 |
+
if not any(evidence_phrase(plain, _evidence_predicate(label)) or evidence_phrase(no_negative, _evidence_predicate(label)) for label in labels if label):
|
| 391 |
+
continue
|
| 392 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 393 |
+
continue
|
| 394 |
+
remainder = clause
|
| 395 |
+
for label in sorted(labels, key=len, reverse=True):
|
| 396 |
+
remainder = re.sub(re.escape(label), '', remainder, flags=re.I)
|
| 397 |
+
negative = bool(re.search(_RECOVERY_NEGATIVE, remainder, re.I))
|
| 398 |
+
explicit = bool(re.search(r'\b(?:true|yes|false|no)\b', remainder, re.I))
|
| 399 |
+
predicate = r'\b(?:enabled|issued|approved|valid|clear|ready|open|active|completed|available|installed|registered|signed|granted|confirmed|operational|compliant|meets|passed|released|equipped|connected|running|accepted)\b'
|
| 400 |
+
affirmative = evidence_phrase(no_negative, _evidence_predicate(profile['label'])) and bool(re.search(predicate, profile['label'], re.I))
|
| 401 |
+
label_match = evidence_phrase(no_negative, _evidence_predicate(profile['label']))
|
| 402 |
+
# Do not transfer negation between unrelated metrics.
|
| 403 |
+
opposites = {'disabled':'enabled', 'unavailable':'available', 'invalid':'valid',
|
| 404 |
+
'closed':'open', 'inactive':'active', 'blocked':'clear', 'revoked':'granted'}
|
| 405 |
+
opposite = False
|
| 406 |
+
for denied, affirmed in opposites.items():
|
| 407 |
+
if re.search(r'\b' + denied + r'\b', clause, re.I):
|
| 408 |
+
rewritten = re.sub(r'\b' + denied + r'\b', affirmed, clause, flags=re.I)
|
| 409 |
+
opposite |= evidence_phrase(_evidence_predicate(rewritten), _evidence_predicate(profile['label']))
|
| 410 |
+
bare_boolean = bool(explicit and re.fullmatch(r'(?:status\s*[:=]?\s*)?(?:true|yes|false|no)',
|
| 411 |
+
_evidence_predicate(remainder), re.I))
|
| 412 |
+
if affirmative or label_match and (negative or explicit) or opposite or bare_boolean:
|
| 413 |
+
states.add(not (negative or opposite))
|
| 414 |
+
if len(states) != 1:
|
| 415 |
+
return 'unknown'
|
| 416 |
+
return 'returned' if states.pop() == profile['value'] else 'not_returned'
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def recovery_number_present(answer, value):
|
| 420 |
+
"""Literal numeric occurrence, independent of unit, metric, scope or wording."""
|
| 421 |
+
text = re.sub(r'(?<![A-Z0-9])[A-Z]{2,10}-[A-Z]{2,10}-[A-Z0-9]{3}(?![A-Z0-9])', '', answer, flags=re.I)
|
| 422 |
+
text = evidence_text(text)
|
| 423 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 424 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')(?![0-9_]|\.\d|,\d)'
|
| 425 |
+
return any(Decimal(m[1]) == Decimal(str(value)) for m in re.finditer(pattern, text))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
import os
|
| 431 |
+
import random
|
| 432 |
+
from datetime import datetime
|
| 433 |
+
from pathlib import Path
|
| 434 |
+
from typing import Dict, List
|
| 435 |
+
|
| 436 |
+
from openai import OpenAI
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_project_env() -> None:
|
| 440 |
+
for parent in Path(__file__).resolve().parents:
|
| 441 |
+
env_path = parent / ".env"
|
| 442 |
+
if not env_path.is_file():
|
| 443 |
+
continue
|
| 444 |
+
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
| 445 |
+
line = raw_line.strip()
|
| 446 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 447 |
+
continue
|
| 448 |
+
key, value = line.split("=", 1)
|
| 449 |
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
load_project_env()
|
| 454 |
+
MAIN_AGENT_API_KEY = os.getenv("MAIN_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 455 |
+
MAIN_AGENT_MODEL_NAME = os.getenv("MAIN_AGENT_MODEL_NAME", "openai/gpt-5.5")
|
| 456 |
+
MAIN_AGENT_BASE_URL = os.getenv("MAIN_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 457 |
+
ROLE_AGENT_API_KEY = os.getenv("ROLE_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 458 |
+
ROLE_AGENT_MODEL_NAME = "deepseek/deepseek-v4-flash-0731"
|
| 459 |
+
ROLE_AGENT_BASE_URL = os.getenv("ROLE_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 460 |
+
LLM_REASONING_EFFORT = os.getenv("LLM_REASONING_EFFORT", "medium")
|
| 461 |
+
ROLE_REASONING_EFFORT = "low"
|
| 462 |
+
ROLE_MAX_TOKENS = 8192
|
| 463 |
+
LLM_REASONING_EXCLUDE = os.getenv("LLM_REASONING_EXCLUDE", "1") != "0"
|
| 464 |
+
MAIN_AGENT_ROLE_ORDER_SEED = os.getenv("MAIN_AGENT_ROLE_ORDER_SEED")
|
| 465 |
+
AGENT_DIR = str(Path(__file__).resolve().parent.parent / "role_agents")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def print_key_trace(title: str, content: Any = "") -> None:
|
| 469 |
+
print(f"\n========== {title} ==========\n", flush=True)
|
| 470 |
+
if content != "":
|
| 471 |
+
print(str(content), flush=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def format_metric_value(value: Any) -> str:
|
| 475 |
+
if isinstance(value, float):
|
| 476 |
+
return f"{value:.4f}"
|
| 477 |
+
if value is None:
|
| 478 |
+
return "None"
|
| 479 |
+
return str(value)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def format_llm_config() -> str:
|
| 483 |
+
return "\n".join([
|
| 484 |
+
f"main_agent_llm: {MAIN_AGENT_MODEL_NAME}",
|
| 485 |
+
f"role_agent_llm: {ROLE_AGENT_MODEL_NAME}",
|
| 486 |
+
f"reasoning_effort: {LLM_REASONING_EFFORT}",
|
| 487 |
+
f"role_reasoning_effort: {ROLE_REASONING_EFFORT}",
|
| 488 |
+
])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def format_available_roles(role_agents: Dict[str, Any]) -> str:
|
| 492 |
+
lines = []
|
| 493 |
+
for role_name, role in role_agents.items():
|
| 494 |
+
key_prefix = ROLE_KEY_PREFIXES.get(role_name, "")
|
| 495 |
+
lines.append(f"- {role_name}(Key 格式:{key_prefix}业务缩写-XXX):{role.config['abstract']}")
|
| 496 |
+
return "\n".join(lines)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def format_evaluation_summary(evaluation: Dict[str, Any]) -> str:
|
| 500 |
+
conclusion = evaluation.get("conclusion_evaluation", {})
|
| 501 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 502 |
+
fields = [
|
| 503 |
+
("ground_truth_conclusion", conclusion.get("ground_truth_conclusion")),
|
| 504 |
+
("ground_truth_numeric_result", conclusion.get("ground_truth_numeric_result")),
|
| 505 |
+
("final_conclusion", conclusion.get("final_conclusion")),
|
| 506 |
+
("parsed_numeric_result", conclusion.get("parsed_numeric_result")),
|
| 507 |
+
("conclusion_correct", conclusion.get("conclusion_correct")),
|
| 508 |
+
("numeric_result_correct", conclusion.get("numeric_result_correct")),
|
| 509 |
+
("turns_to_finalize", communication.get("turns_to_finalize")),
|
| 510 |
+
("total_role_agent_queries", communication.get("total_role_agent_queries")),
|
| 511 |
+
("total_questions", communication.get("total_questions")),
|
| 512 |
+
("duplicate_key_queries", communication.get("duplicate_key_queries")),
|
| 513 |
+
]
|
| 514 |
+
return "\n".join(f"{name}: {format_metric_value(value)}" for name, value in fields)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def format_key_metrics(evaluation: Dict[str, Any]) -> str:
|
| 518 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 519 |
+
correctness = int(bool(evaluation.get("joint_correctness")))
|
| 520 |
+
turns = communication.get("turns_to_finalize")
|
| 521 |
+
lines = [
|
| 522 |
+
f"正确率: {correctness}",
|
| 523 |
+
f"完成轮数: {format_metric_value(turns)} / {communication.get('max_turns', DEFAULT_MAX_TURNS)}(理想:{communication.get('finalize_ideal_round', FINALIZE_IDEAL_ROUND)})",
|
| 524 |
+
]
|
| 525 |
+
if SETTING in {"incomplete", "mixed"}:
|
| 526 |
+
lines.append(f"阈值补齐: {communication.get('incomplete_threshold_returned', False)};补齐轮次: {communication.get('incomplete_recovery_turn')};补救成功: {communication.get('incomplete_recovery_success')}")
|
| 527 |
+
if SETTING in {"missed", "mixed"}:
|
| 528 |
+
lines.append(f"忽略: {communication.get('neglect_ignored_count', 0)};交付: {communication.get('neglect_delivered_count', 0)};待答: {communication.get('neglect_pending_count', 0)}")
|
| 529 |
+
if SETTING not in {"misaligned", "mixed"}:
|
| 530 |
+
return "\n".join(lines)
|
| 531 |
+
|
| 532 |
+
if communication.get("error_recovery_status") == "unknown":
|
| 533 |
+
lines.append("Recovery result: UNKNOWN (evidence cannot be classified; excluded from recovery rates)")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
+
|
| 536 |
+
mismatch_queried = bool(communication.get("mismatch_key_queried"))
|
| 537 |
+
mismatch_turn = communication.get("mismatch_key_turn")
|
| 538 |
+
recovery_query_sent = bool(communication.get("recovery_query_sent"))
|
| 539 |
+
recovery_query_turn = communication.get("recovery_query_turn")
|
| 540 |
+
target_key_returned = bool(communication.get("error_fact_returned", communication.get("target_key_returned")))
|
| 541 |
+
recovery_turn = communication.get("recovery_turn")
|
| 542 |
+
finalized_early = bool(communication.get("finalized_before_recovery"))
|
| 543 |
+
|
| 544 |
+
def turn_suffix(turn: Any) -> str:
|
| 545 |
+
return f"(第{turn}轮)" if isinstance(turn, int) else ""
|
| 546 |
+
|
| 547 |
+
lines.extend(["", "恢复链路:"])
|
| 548 |
+
if not mismatch_queried:
|
| 549 |
+
lines.extend([
|
| 550 |
+
f"✗ 未访问错配 key:{ERROR_INJECTION.get('alternate_key')}",
|
| 551 |
+
"— 未触发补救询问",
|
| 552 |
+
"— Role 未返回目标 key",
|
| 553 |
+
"— 未进入恢复流程",
|
| 554 |
+
"",
|
| 555 |
+
"恢复延迟:N/A",
|
| 556 |
+
"恢复结果:NOT_TRIGGERED(Main 未访问错配 key)",
|
| 557 |
+
])
|
| 558 |
+
return "\n".join(lines)
|
| 559 |
+
|
| 560 |
+
lines.append(
|
| 561 |
+
f"✓ 已访问错配 key:{ERROR_INJECTION.get('alternate_key')}{turn_suffix(mismatch_turn)}"
|
| 562 |
+
)
|
| 563 |
+
lines.append(
|
| 564 |
+
("✓ 已发起补救询问" if recovery_query_sent else "✗ 未发起补救询问")
|
| 565 |
+
+ turn_suffix(recovery_query_turn)
|
| 566 |
+
)
|
| 567 |
+
lines.append(
|
| 568 |
+
(
|
| 569 |
+
f"✓ Role 已返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 570 |
+
if target_key_returned
|
| 571 |
+
else f"✗ Role 未返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 572 |
+
)
|
| 573 |
+
+ turn_suffix(recovery_turn)
|
| 574 |
+
)
|
| 575 |
+
lines.append("✗ 已在恢复前提前 finalize" if finalized_early else "✓ 未在恢复前提前 finalize")
|
| 576 |
+
if target_key_returned:
|
| 577 |
+
lines.append("✓ 恢复后最终答案正确" if correctness else "✗ 恢复后最终答案错误")
|
| 578 |
+
else:
|
| 579 |
+
lines.append("— 尚未完成恢复,无法判断恢复后答案")
|
| 580 |
+
|
| 581 |
+
recovery_latency = communication.get("recovery_latency")
|
| 582 |
+
recovery_method = communication.get("recovery_method")
|
| 583 |
+
if recovery_method:
|
| 584 |
+
target_query_turn = communication.get("target_key_query_turn")
|
| 585 |
+
if recovery_method == "keyless_query" and isinstance(target_query_turn, int) and isinstance(recovery_turn, int) and target_query_turn > recovery_turn:
|
| 586 |
+
method_label = "无 key 获取目录 → 正确 key 查询"
|
| 587 |
+
lines.append(f"取得目标 key:第{recovery_turn}轮")
|
| 588 |
+
lines.append(f"正确 key 查询取得答复:第{target_query_turn}轮")
|
| 589 |
+
recovery_latency = target_query_turn - mismatch_turn if isinstance(mismatch_turn, int) else recovery_latency
|
| 590 |
+
else:
|
| 591 |
+
method_label = {"keyless_query": "无 key 补充询问", "target_key_query": "目标 key 纠正查询"}.get(recovery_method, recovery_method)
|
| 592 |
+
lines.append(f"补救方式:{method_label}")
|
| 593 |
+
if communication.get("recovery_success"):
|
| 594 |
+
status = "SUCCESS"
|
| 595 |
+
elif finalized_early:
|
| 596 |
+
status = "FINALIZED_EARLY"
|
| 597 |
+
elif not recovery_query_sent:
|
| 598 |
+
status = "RECOVERY_NOT_REQUESTED"
|
| 599 |
+
elif not target_key_returned:
|
| 600 |
+
status = "TARGET_NOT_RETURNED"
|
| 601 |
+
else:
|
| 602 |
+
status = "RECOVERED_BUT_WRONG"
|
| 603 |
+
lines.extend([
|
| 604 |
+
"",
|
| 605 |
+
f"恢复延迟:{recovery_latency}轮" if isinstance(recovery_latency, int) else "恢复延迟:N/A",
|
| 606 |
+
f"恢复结果:{status}",
|
| 607 |
+
])
|
| 608 |
+
return "\n".join(lines)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def format_role_messages(action: Dict[str, Any], role_answers: List[Dict[str, Any]]) -> str:
|
| 612 |
+
requested = {
|
| 613 |
+
(message.get("role_agent"), question.get("id"), question.get("key")): question.get("question")
|
| 614 |
+
for message in action.get("messages", [])
|
| 615 |
+
for question in message.get("questions", [])
|
| 616 |
+
}
|
| 617 |
+
blocks = []
|
| 618 |
+
for item in role_answers:
|
| 619 |
+
question = item.get("question", {})
|
| 620 |
+
identity = (item.get("role_agent"), question.get("id"), question.get("key"))
|
| 621 |
+
blocks.append("\n".join([
|
| 622 |
+
f"role_agent: {item.get('role_agent')}",
|
| 623 |
+
f"question_id: {question.get('id')}",
|
| 624 |
+
f"key: {question.get('key')}",
|
| 625 |
+
f"question: {requested.get(identity, question.get('question'))}",
|
| 626 |
+
f"answer: {item.get('answer')}",
|
| 627 |
+
]))
|
| 628 |
+
return "\n\n".join(blocks)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def parse_numeric_result(value: Any) -> int | float | None:
|
| 632 |
+
if value is None or isinstance(value, bool):
|
| 633 |
+
return None
|
| 634 |
+
if isinstance(value, (int, float)):
|
| 635 |
+
number = float(value)
|
| 636 |
+
elif isinstance(value, str):
|
| 637 |
+
match = re.search(r"[-+]?\d+(?:\.\d+)?", value.strip())
|
| 638 |
+
if not match:
|
| 639 |
+
return None
|
| 640 |
+
number = float(match.group(0))
|
| 641 |
+
else:
|
| 642 |
+
return None
|
| 643 |
+
rounded = round(number, NUMERIC_PRECISION)
|
| 644 |
+
return int(rounded) if NUMERIC_PRECISION == 0 else rounded
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def compute_conclusion_correctness(final_result: Dict[str, Any]) -> Dict[str, Any]:
|
| 648 |
+
parsed = parse_numeric_result(final_result.get("numeric_result"))
|
| 649 |
+
expected = parse_numeric_result(GOLD["numeric_result"])
|
| 650 |
+
conclusion_correct = int(final_result.get("conclusion") == GOLD["conclusion"])
|
| 651 |
+
numeric_correct = int(parsed == expected)
|
| 652 |
+
return {
|
| 653 |
+
"ground_truth_conclusion": GOLD["conclusion"],
|
| 654 |
+
"ground_truth_numeric_result": GOLD["numeric_result"],
|
| 655 |
+
"final_conclusion": final_result.get("conclusion"),
|
| 656 |
+
"numeric_result_raw": final_result.get("numeric_result"),
|
| 657 |
+
"parsed_numeric_result": parsed,
|
| 658 |
+
"conclusion_correct": conclusion_correct,
|
| 659 |
+
"numeric_result_correct": numeric_correct,
|
| 660 |
+
"conclusion_correctness": int(conclusion_correct and numeric_correct),
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def format_role_user_message(question: Dict[str, Any]) -> str:
|
| 665 |
+
question_id = str(question.get("id") or "Q")
|
| 666 |
+
text = str(question["question"]).strip()
|
| 667 |
+
return f"{question_id}: {text}"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
"""Deterministic follow-up routing; metadata contains no hidden values or target flags."""
|
| 671 |
+
import re
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def build_followup_records(task):
|
| 675 |
+
roles = {r['role_id']: r['name'] for r in task['roles']}
|
| 676 |
+
candidates = {c['candidate_id']: c['name'] for c in task['candidates']}
|
| 677 |
+
topics = {t['topic_id']: t for group in ('topics', 'distractor_topics', 'supplemental_topics')
|
| 678 |
+
for t in task.get(group, [])}
|
| 679 |
+
observations = {o['observation_id']: o for o in task['observations']}
|
| 680 |
+
records = []
|
| 681 |
+
for record in task['records']:
|
| 682 |
+
fields = []
|
| 683 |
+
for oid in record['observation_ids']:
|
| 684 |
+
tid = observations[oid]['topic_id']
|
| 685 |
+
topic = topics.get(tid, {})
|
| 686 |
+
if topic.get('label'):
|
| 687 |
+
fields.append({'id': tid, 'label': topic['label'], 'aliases': topic.get('aliases', [])})
|
| 688 |
+
records.append(dict(key=task['routing']['record_keys'][record['record_id']],
|
| 689 |
+
role=roles[record['owner_role_id']], candidate=candidates[record['candidate_id']],
|
| 690 |
+
context=(record.get('context') or {}).get('value', ''), fields=fields))
|
| 691 |
+
return records
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class IncompleteFollowupResolver:
|
| 695 |
+
VERSION = 'rule_followup_v2_english'
|
| 696 |
+
CLARIFY = 'The record and metric cannot be uniquely identified. Put the complete record key and the metric to verify in your question.'
|
| 697 |
+
|
| 698 |
+
def __init__(self, records):
|
| 699 |
+
self.records = records
|
| 700 |
+
self.reset()
|
| 701 |
+
|
| 702 |
+
def reset(self):
|
| 703 |
+
self.seen = {}
|
| 704 |
+
self.events = []
|
| 705 |
+
|
| 706 |
+
def observe(self, role, key, turn):
|
| 707 |
+
if key is not None:
|
| 708 |
+
self.seen.setdefault((role, key), turn)
|
| 709 |
+
|
| 710 |
+
@staticmethod
|
| 711 |
+
def normalize(text):
|
| 712 |
+
return re.sub(r'\s+', ' ', text).strip().casefold().replace('’', "'").replace('‑', '-').replace('–', '-')
|
| 713 |
+
|
| 714 |
+
@classmethod
|
| 715 |
+
def mentions(cls, text, phrase):
|
| 716 |
+
phrase = cls.normalize(phrase)
|
| 717 |
+
if re.search(r'[\u3400-\u9fff]', phrase):
|
| 718 |
+
return phrase.replace(' ', '') in text.replace(' ', '')
|
| 719 |
+
return bool(re.search(r'(?<![\w])' + re.escape(phrase) + r'(?![\w])', text))
|
| 720 |
+
|
| 721 |
+
def resolve(self, role, text, turn):
|
| 722 |
+
text = self.normalize(text)
|
| 723 |
+
available = [r for r in self.records if r['role'] == role]
|
| 724 |
+
if re.search(r'目录|索引列表|key列表|\b(?:catalog(?:ue)?s?|director(?:y|ies)|(?:key|index)\s+lists?)\b', text):
|
| 725 |
+
result = dict(status='catalog', key=None, fields=[])
|
| 726 |
+
else:
|
| 727 |
+
# Match the full role catalog before restricting to previously queried records.
|
| 728 |
+
names = {r['candidate'] for r in available if self.mentions(text, r['candidate'])}
|
| 729 |
+
contexts = {r['context'] for r in available if r['context'] and self.mentions(text, r['context'])}
|
| 730 |
+
fields = {f['id'] for r in available for f in r['fields']
|
| 731 |
+
if any(self.mentions(text, a) for a in [f['label'], *f['aliases']] if a)}
|
| 732 |
+
full = bool(re.search(r'完整(?:资料|信息|内容|记录)|全部(?:资料|信息|内容)|详细资料|\b(?:complete|full|all|detailed)\s+(?:(?:the|your|available)\s+)*(?:records?|information|details|data)\b', text))
|
| 733 |
+
matches = [r for r in available
|
| 734 |
+
if self.seen.get((role, r['key']), turn) < turn
|
| 735 |
+
and r['candidate'] in names
|
| 736 |
+
and (not contexts or r['context'] in contexts)
|
| 737 |
+
and (fields <= {f['id'] for f in r['fields']} if fields else full)]
|
| 738 |
+
# Ambiguous references require a key; do not infer pronouns or fuzzy matches.
|
| 739 |
+
unique = len(names) == 1 and len(contexts) <= 1 and len(matches) == 1 and (fields or full)
|
| 740 |
+
result = dict(status='resolved' if unique else 'clarify',
|
| 741 |
+
key=matches[0]['key'] if unique else None, fields=sorted(fields), full=full)
|
| 742 |
+
self.events.append(dict(turn=turn, role_agent=role, question=text, **result))
|
| 743 |
+
return result
|
| 744 |
+
|
| 745 |
+
def catalog(self, role):
|
| 746 |
+
return 'Complete record directory (supply a key to obtain facts):\n' + '\n'.join(
|
| 747 |
+
r['key'] + ':' + r['candidate'] + (';' + r['context'] if r['context'] else '')
|
| 748 |
+
+ '; Metrics: ' + '、'.join(f['label'] for f in r['fields'])
|
| 749 |
+
for r in self.records if r['role'] == role)
|
| 750 |
+
|
| 751 |
+
def metrics(self):
|
| 752 |
+
return dict(incomplete_followup_protocol=self.VERSION,
|
| 753 |
+
incomplete_keyless_followup_count=len(self.events),
|
| 754 |
+
incomplete_rule_resolved_count=sum(e['status'] == 'resolved' for e in self.events),
|
| 755 |
+
incomplete_clarification_count=sum(e['status'] == 'clarify' for e in self.events),
|
| 756 |
+
incomplete_followup_routing=list(self.events))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
"""Self-contained Incomplete policy embedded only in generated Incomplete run_one.py files."""
|
| 760 |
+
import re
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class IncompletePolicy:
|
| 764 |
+
def __init__(self, profile):
|
| 765 |
+
self.profile = profile
|
| 766 |
+
self.reset()
|
| 767 |
+
|
| 768 |
+
def reset(self):
|
| 769 |
+
self.omitted_at_turn = None
|
| 770 |
+
self.followup_at_turn = None
|
| 771 |
+
self.recovered_at_turn = None
|
| 772 |
+
|
| 773 |
+
def mode(self, role_name, question, turn):
|
| 774 |
+
if role_name != self.profile['role_name'] or question.get('key') != self.profile['key']:
|
| 775 |
+
return None
|
| 776 |
+
if self.recovered_at_turn is not None:
|
| 777 |
+
return None
|
| 778 |
+
# Any valid later query of the same record can recover the omitted value.
|
| 779 |
+
if self.omitted_at_turn is not None and turn > self.omitted_at_turn:
|
| 780 |
+
if self.followup_at_turn is None:
|
| 781 |
+
self.followup_at_turn = turn
|
| 782 |
+
return 'incomplete_recovery'
|
| 783 |
+
return 'incomplete_partial'
|
| 784 |
+
|
| 785 |
+
def request_options(self, mode, full_system_message):
|
| 786 |
+
profile = self.profile
|
| 787 |
+
coarse = profile.get('disclosure_mode', 'omission') != 'omission'
|
| 788 |
+
if mode == 'incomplete_partial':
|
| 789 |
+
system = (
|
| 790 |
+
f"You are {profile['role_name']}. For this request use only the business record below. "
|
| 791 |
+
"Respond in English in one or two connected sentences, retaining the key, candidate, material scope and facts. "
|
| 792 |
+
"Do not add metrics, infer facts or assert that the overall plan qualifies. "
|
| 793 |
+
"Do not say information is incomplete, unavailable or requires follow-up, and do not recommend another question. "
|
| 794 |
+
)
|
| 795 |
+
if coarse:
|
| 796 |
+
system += (
|
| 797 |
+
"Include the supplied coarse metric statement, retaining its numbers, units and bound wording. "
|
| 798 |
+
"Bounds are not exact values. Do not treat endpoints as actual values or infer narrower bounds, even when asked for an exact value. "
|
| 799 |
+
)
|
| 800 |
+
system += "\n\n" + profile['partial_record_text']
|
| 801 |
+
if coarse:
|
| 802 |
+
system += "\n" + profile['coarse_statement']
|
| 803 |
+
system += '\n\nOutput only valid JSON: {"answer":"Answer text"}.'
|
| 804 |
+
else:
|
| 805 |
+
system = (full_system_message + "\n\nFor this request, give the complete specified record, explicitly stating "
|
| 806 |
+
+ profile['threshold_label'] + " as its original numeric value and unit. Use Arabic numerals, not just a compliance judgment.")
|
| 807 |
+
if coarse:
|
| 808 |
+
system += (" Introduce the exact finding naturally with 'After careful verification'. "
|
| 809 |
+
"The exact number must come from the true private record, not a previous bound or interval endpoint. "
|
| 810 |
+
"Do not merely repeat the earlier coarse range.")
|
| 811 |
+
return {'system_override': system, 'response_validator': None}
|
| 812 |
+
|
| 813 |
+
def validate_answer(self, mode, answer):
|
| 814 |
+
if mode == 'incomplete_partial':
|
| 815 |
+
return None
|
| 816 |
+
return (None if recovery_number_present(answer, self.profile['threshold_value'])
|
| 817 |
+
else 'incomplete_threshold_not_returned')
|
| 818 |
+
|
| 819 |
+
def observe(self, mode, turn, answer=None):
|
| 820 |
+
if mode == 'incomplete_partial' and self.omitted_at_turn is None:
|
| 821 |
+
self.omitted_at_turn = turn
|
| 822 |
+
elif mode == 'incomplete_recovery' and answer is not None:
|
| 823 |
+
if self.validate_answer(mode, answer) is None:
|
| 824 |
+
self.recovered_at_turn = turn
|
| 825 |
+
|
| 826 |
+
def observe_keyless(self, role_name, question, turn, answer=None):
|
| 827 |
+
"""Measure accepted search replies without changing their runtime protocol."""
|
| 828 |
+
if (role_name != self.profile['role_name'] or question.get('key') is not None
|
| 829 |
+
or self.omitted_at_turn is None or turn <= self.omitted_at_turn
|
| 830 |
+
or self.recovered_at_turn is not None):
|
| 831 |
+
return
|
| 832 |
+
# Recovery uses numeric occurrence only, without wording, scope or unit checks.
|
| 833 |
+
# Observe only accepted replies; identifiers are excluded by validate_answer.
|
| 834 |
+
if answer is not None and self.validate_answer("incomplete_recovery", answer) is None:
|
| 835 |
+
if self.followup_at_turn is None:
|
| 836 |
+
self.followup_at_turn = turn
|
| 837 |
+
self.recovered_at_turn = turn
|
| 838 |
+
|
| 839 |
+
def metrics(self, *, correct, finalized):
|
| 840 |
+
triggered = self.omitted_at_turn is not None
|
| 841 |
+
recovered = self.recovered_at_turn is not None
|
| 842 |
+
return {
|
| 843 |
+
'incomplete_omission_triggered': triggered,
|
| 844 |
+
'incomplete_omission_turn': self.omitted_at_turn,
|
| 845 |
+
'incomplete_followup_sent': self.followup_at_turn is not None,
|
| 846 |
+
'incomplete_followup_turn': self.followup_at_turn,
|
| 847 |
+
'incomplete_threshold_returned': recovered,
|
| 848 |
+
'incomplete_recovery_turn': self.recovered_at_turn,
|
| 849 |
+
'incomplete_recovery_latency': self.recovered_at_turn - self.omitted_at_turn if recovered else None,
|
| 850 |
+
'finalized_before_incomplete_recovery': bool(finalized and triggered and not recovered),
|
| 851 |
+
'incomplete_recovery_success': bool(recovered) if triggered else None,
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def exact_value_present(answer, profile):
|
| 856 |
+
"""Compatibility name: count the target numeric value, including within bounds."""
|
| 857 |
+
return recovery_number_present(answer, profile['threshold_value'])
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def incomplete_numeric_metrics(profile, transcript, communication, *, correct, finalized):
|
| 861 |
+
"""Measure later accepted replies only; never alter interaction policy state.
|
| 862 |
+
|
| 863 |
+
User-defined numeric-occurrence rule: no unit, polarity, metric or scope gate.
|
| 864 |
+
Only later accepted replies from the affected role are eligible.
|
| 865 |
+
"""
|
| 866 |
+
omitted = communication.get('incomplete_omission_turn')
|
| 867 |
+
followup = communication.get('incomplete_followup_turn')
|
| 868 |
+
recovered = None
|
| 869 |
+
for event in transcript:
|
| 870 |
+
turn = event['turn']
|
| 871 |
+
if omitted is None or turn <= omitted:
|
| 872 |
+
continue
|
| 873 |
+
for reply in event.get('role_answers', []) + event.get('delivered_role_answers', []):
|
| 874 |
+
if (reply.get('role_agent') != profile['role_name']
|
| 875 |
+
or 'role_trace' not in reply
|
| 876 |
+
or reply.get('protocol_error') or 'role_validation_trace' in reply):
|
| 877 |
+
continue
|
| 878 |
+
if exact_value_present(reply.get('answer', ''), profile):
|
| 879 |
+
recovered = turn if recovered is None else min(recovered, turn)
|
| 880 |
+
if recovered is not None:
|
| 881 |
+
followup = recovered if followup is None else min(followup, recovered)
|
| 882 |
+
status = 'returned' if recovered is not None else 'not_returned'
|
| 883 |
+
return {
|
| 884 |
+
'incomplete_recovery_status': status,
|
| 885 |
+
'incomplete_omission_triggered': omitted is not None,
|
| 886 |
+
'incomplete_omission_turn': omitted,
|
| 887 |
+
'incomplete_followup_sent': followup is not None,
|
| 888 |
+
'incomplete_followup_turn': followup,
|
| 889 |
+
'incomplete_threshold_returned': recovered is not None,
|
| 890 |
+
'incomplete_recovery_turn': recovered,
|
| 891 |
+
'incomplete_recovery_latency': recovered - omitted if recovered is not None else None,
|
| 892 |
+
'finalized_before_incomplete_recovery': bool(finalized and omitted is not None and recovered is None),
|
| 893 |
+
'incomplete_recovery_success': bool(recovered is not None) if omitted is not None else None,
|
| 894 |
+
'incomplete_statistics_version': 'numeric_occurrence_v4',
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class RoleAgent:
|
| 899 |
+
def __init__(self, config: Dict[str, Any], client: OpenAI, model: str = ROLE_AGENT_MODEL_NAME):
|
| 900 |
+
self.config = config
|
| 901 |
+
self.client = client
|
| 902 |
+
self.model = model
|
| 903 |
+
self.system_message = self._build_system_message()
|
| 904 |
+
self.reset_history()
|
| 905 |
+
|
| 906 |
+
def reset_history(self) -> None:
|
| 907 |
+
self.messages = [{"role": "system", "content": self.system_message}]
|
| 908 |
+
|
| 909 |
+
def _build_system_message(self) -> str:
|
| 910 |
+
private_blocks = []
|
| 911 |
+
for index, point in enumerate(self.config["information_points"]):
|
| 912 |
+
content = "\n\n".join(
|
| 913 |
+
line for line in str(point["content"]).splitlines() if line.strip()
|
| 914 |
+
)
|
| 915 |
+
private_blocks.append(f"{index + 1}. {point['title']}:\n\n{content}")
|
| 916 |
+
private = "\n\n".join(private_blocks)
|
| 917 |
+
return (
|
| 918 |
+
f"{self.config['system_message']}\n\n"
|
| 919 |
+
f"Your private information:\n\n{private}\n\n"
|
| 920 |
+
"Output only a valid JSON object: {\"answer\":\"Answer text\"}。"
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def answer_with_trace(
|
| 924 |
+
self, question: str, *, allowed_keys: set[str], response_mode: str,
|
| 925 |
+
system_override: str | None = None, response_validator: Any = None,
|
| 926 |
+
) -> Dict[str, Any]:
|
| 927 |
+
user_message = {"role": "user", "content": question}
|
| 928 |
+
attempts = []
|
| 929 |
+
for _ in range(ROLE_REPLY_MAX_ATTEMPTS):
|
| 930 |
+
# Keep rejected replies in the audit trace, outside model conversation history.
|
| 931 |
+
messages = [*self.messages, user_message]
|
| 932 |
+
if system_override is not None:
|
| 933 |
+
messages[0] = {"role": "system", "content": system_override}
|
| 934 |
+
response = self.client.chat.completions.create(
|
| 935 |
+
model=self.model, messages=messages, temperature=0.1,
|
| 936 |
+
max_tokens=ROLE_MAX_TOKENS,
|
| 937 |
+
response_format={"type": "json_object"},
|
| 938 |
+
extra_body={"reasoning": {"effort": ROLE_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 939 |
+
)
|
| 940 |
+
finish_reason = getattr(response.choices[0], "finish_reason", None)
|
| 941 |
+
response_message = {"role": "assistant", "content": response.choices[0].message.content}
|
| 942 |
+
answer = ""
|
| 943 |
+
unexpected_keys = []
|
| 944 |
+
validation_error = None
|
| 945 |
+
json_parse_trace = {}
|
| 946 |
+
try:
|
| 947 |
+
if finish_reason == "length":
|
| 948 |
+
raise ValueError("truncated role response")
|
| 949 |
+
parsed = parse_json_message(response_message["content"], trace=json_parse_trace)
|
| 950 |
+
if set(parsed) != {"answer"} or not isinstance(parsed.get("answer"), str) or not parsed["answer"].strip():
|
| 951 |
+
raise ValueError("response must contain only a non-empty answer string")
|
| 952 |
+
answer = parsed["answer"].strip()
|
| 953 |
+
if response_validator is not None:
|
| 954 |
+
validation_error = response_validator(answer)
|
| 955 |
+
except ValueError:
|
| 956 |
+
validation_error = "output_truncated" if finish_reason == "length" else "invalid_answer_json"
|
| 957 |
+
attempt = {
|
| 958 |
+
"request_messages": messages, "response_message": response_message,
|
| 959 |
+
"answer": answer, "unexpected_keys": unexpected_keys,
|
| 960 |
+
"validation_error": validation_error, "finish_reason": finish_reason,
|
| 961 |
+
}
|
| 962 |
+
if json_parse_trace.get("recovered"):
|
| 963 |
+
attempt["json_parse"] = json_parse_trace
|
| 964 |
+
attempts.append(attempt)
|
| 965 |
+
if validation_error is None:
|
| 966 |
+
history_response = ({"role": "assistant", "content": json.dumps(parsed, ensure_ascii=False)}
|
| 967 |
+
if json_parse_trace.get("recovered") else response_message)
|
| 968 |
+
self.messages.extend([user_message, history_response])
|
| 969 |
+
return {**attempt, "accepted": True, "response_mode": response_mode, "attempts": attempts}
|
| 970 |
+
return {
|
| 971 |
+
"accepted": False, "response_mode": response_mode, "attempts": attempts,
|
| 972 |
+
"answer": "The role reply failed output validation. Please query again.",
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
def load_role_agent_configs(agent_dir: str = AGENT_DIR) -> Dict[str, Dict[str, Any]]:
|
| 976 |
+
root = Path(agent_dir)
|
| 977 |
+
if not root.is_dir():
|
| 978 |
+
raise FileNotFoundError(f"Missing role_agents directory: {root}")
|
| 979 |
+
configs: Dict[str, Dict[str, Any]] = {}
|
| 980 |
+
for path in sorted(root.glob("*.json")):
|
| 981 |
+
config = json.loads(path.read_text(encoding="utf-8"))
|
| 982 |
+
configs[config["role_agent_name"]] = config
|
| 983 |
+
return configs
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_role_agents(
|
| 987 |
+
client: OpenAI, agent_dir: str = AGENT_DIR,
|
| 988 |
+
model: str = ROLE_AGENT_MODEL_NAME,
|
| 989 |
+
) -> Dict[str, RoleAgent]:
|
| 990 |
+
configs = load_role_agent_configs(agent_dir)
|
| 991 |
+
if not configs:
|
| 992 |
+
raise ValueError(f"Empty role_agents directory: {agent_dir}")
|
| 993 |
+
return {name: RoleAgent(config, client, model) for name, config in configs.items()}
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def resolve_role_name(role_name, role_names=None):
|
| 997 |
+
"""Resolve unique full names, Chinese names, or abbreviations without guessing."""
|
| 998 |
+
if not isinstance(role_name, str):
|
| 999 |
+
return None
|
| 1000 |
+
names = list(role_names) if role_names is not None else [item["role_name"] for item in PUBLIC_ROLES]
|
| 1001 |
+
if role_name in names:
|
| 1002 |
+
return role_name
|
| 1003 |
+
text = role_name.strip().replace("(", "(").replace(")", ")")
|
| 1004 |
+
matches = set()
|
| 1005 |
+
for name in names:
|
| 1006 |
+
normalized = name.strip().replace("(", "(").replace(")", ")")
|
| 1007 |
+
aliases = {normalized}
|
| 1008 |
+
parts = re.fullmatch(r"(.+?)(([^()]+))", normalized)
|
| 1009 |
+
if parts:
|
| 1010 |
+
aliases.update(part.strip() for part in parts.groups())
|
| 1011 |
+
if text in aliases:
|
| 1012 |
+
matches.add(name)
|
| 1013 |
+
return next(iter(matches)) if len(matches) == 1 else role_name
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
"""Ignore each selected role's first contact; a later contact responds normally."""
|
| 1017 |
+
import copy
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class NeglectPolicy:
|
| 1021 |
+
def __init__(self, role_names):
|
| 1022 |
+
self.roles = {name: {"state": "uncontacted", "pending": {}}
|
| 1023 |
+
for name in role_names}
|
| 1024 |
+
self.events = []
|
| 1025 |
+
|
| 1026 |
+
def contact(self, role, questions, turn):
|
| 1027 |
+
"""Called once per role/turn with only authorized questions.
|
| 1028 |
+
|
| 1029 |
+
Pending questions are tracked for metrics only, never auto-delivered.
|
| 1030 |
+
On retry, the caller answers the current questions normally.
|
| 1031 |
+
"""
|
| 1032 |
+
state = self.roles.get(role)
|
| 1033 |
+
if state is None or state["state"] == "active" or not questions:
|
| 1034 |
+
return None
|
| 1035 |
+
if state["state"] == "uncontacted":
|
| 1036 |
+
for q in questions:
|
| 1037 |
+
state["pending"].setdefault(q.get("key") or q["question"], copy.deepcopy(q))
|
| 1038 |
+
state.update(state="ignored", first_turn=turn)
|
| 1039 |
+
self.events.append({"kind": "neglect_ignored", "turn": turn, "role_agent": role})
|
| 1040 |
+
return ""
|
| 1041 |
+
if turn <= state["first_turn"]:
|
| 1042 |
+
return ""
|
| 1043 |
+
state.update(state="active", pending={})
|
| 1044 |
+
self.events.append({"kind": "neglect_delivered", "turn": turn, "role_agent": role})
|
| 1045 |
+
return None
|
| 1046 |
+
|
| 1047 |
+
def metrics(self):
|
| 1048 |
+
# Keep legacy counters at zero for compatible result readers.
|
| 1049 |
+
return {**{kind + "_count": sum(e["kind"] == kind for e in self.events)
|
| 1050 |
+
for kind in ("neglect_ignored", "neglect_busy", "neglect_refused", "neglect_delivered")},
|
| 1051 |
+
"neglect_pending_count": sum(len(s["pending"]) for s in self.roles.values())}
|
| 1052 |
+
|
| 1053 |
+
"""Direct-access main loop, embedded in standalone runtimes."""
|
| 1054 |
+
|
| 1055 |
+
def run_direct(self, task):
|
| 1056 |
+
self._semantic_enabled_roles = set()
|
| 1057 |
+
self.empty_observation_count = 0
|
| 1058 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config['communication_role_names'])
|
| 1059 |
+
self.communication_events = self.neglect_policy.events
|
| 1060 |
+
self.delivered_messages = []
|
| 1061 |
+
if self.incomplete_policy:
|
| 1062 |
+
self.incomplete_policy.reset()
|
| 1063 |
+
self.followup_resolver.reset()
|
| 1064 |
+
for role in self.role_agents.values():
|
| 1065 |
+
role.reset_history()
|
| 1066 |
+
self.messages = [{'role': 'system', 'content': self.system_message}, {'role': 'user', 'content': task}]
|
| 1067 |
+
transcript = []
|
| 1068 |
+
consecutive_errors = 0
|
| 1069 |
+
|
| 1070 |
+
def answer(role, question):
|
| 1071 |
+
result, _ = self._answer_question(role, question)
|
| 1072 |
+
return dict(result, role_agent=role, question=dict(question))
|
| 1073 |
+
|
| 1074 |
+
def publish(replies):
|
| 1075 |
+
for reply in replies:
|
| 1076 |
+
if reply.pop('authorized_exact', False):
|
| 1077 |
+
self._semantic_enabled_roles.add(reply['role_agent'])
|
| 1078 |
+
if replies:
|
| 1079 |
+
self.messages.append({'role': 'user', 'content': '\n'.join(
|
| 1080 |
+
r['role_agent'] + ':' + r['answer'] for r in replies)})
|
| 1081 |
+
|
| 1082 |
+
for turn in range(1, self.max_turns + 1):
|
| 1083 |
+
self.current_turn = turn
|
| 1084 |
+
event = {'turn': turn, 'role_answers': []}
|
| 1085 |
+
try:
|
| 1086 |
+
action = self._call_main()
|
| 1087 |
+
if not isinstance(action, dict):
|
| 1088 |
+
raise ValueError('action must be a JSON object')
|
| 1089 |
+
public_action = copy.deepcopy(action)
|
| 1090 |
+
kind = action.get('action')
|
| 1091 |
+
if kind == 'finalize':
|
| 1092 |
+
if action.get('conclusion') not in {POSITIVE_CONCLUSION, NEGATIVE_CONCLUSION}:
|
| 1093 |
+
raise ValueError('conclusion must use one of the two allowed labels')
|
| 1094 |
+
elif kind == 'wait':
|
| 1095 |
+
if SETTING not in {'missed', 'mixed'}:
|
| 1096 |
+
raise ValueError('wait is only supported by neglect and mixed')
|
| 1097 |
+
elif kind == 'ask_role_agents':
|
| 1098 |
+
if not isinstance(action.get('messages'), list) or not action['messages']:
|
| 1099 |
+
raise ValueError('messages must be a nonempty list')
|
| 1100 |
+
for request in action['messages']:
|
| 1101 |
+
if not isinstance(request, dict) or not isinstance(request.get('role_agent'), str):
|
| 1102 |
+
raise ValueError('message must specify role_agent')
|
| 1103 |
+
if not isinstance(request.get('questions'), list) or not request['questions']:
|
| 1104 |
+
raise ValueError('questions must be a nonempty list')
|
| 1105 |
+
request['role_agent'] = resolve_role_name(request['role_agent'], self.role_agents)
|
| 1106 |
+
request['questions'] = expand_question_keys(request['questions'])
|
| 1107 |
+
if any(not isinstance(q, dict) or not isinstance(q.get('question'), str) or not q['question'].strip()
|
| 1108 |
+
for q in request['questions']):
|
| 1109 |
+
raise ValueError('question must contain natural-language text')
|
| 1110 |
+
else:
|
| 1111 |
+
raise ValueError('unsupported action')
|
| 1112 |
+
except (ValueError, TypeError) as exc:
|
| 1113 |
+
event.update(main_agent_action={}, protocol_error=str(exc))
|
| 1114 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1115 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1116 |
+
transcript.append(event)
|
| 1117 |
+
self.messages.append({'role': 'user', 'content': 'Invalid output format: ' + str(exc)})
|
| 1118 |
+
consecutive_errors += 1
|
| 1119 |
+
if consecutive_errors >= 3:
|
| 1120 |
+
break
|
| 1121 |
+
continue
|
| 1122 |
+
consecutive_errors = 0
|
| 1123 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1124 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1125 |
+
event['main_agent_action'] = action
|
| 1126 |
+
transcript.append(event)
|
| 1127 |
+
if kind == 'ask_role_agents':
|
| 1128 |
+
for request in public_action['messages']:
|
| 1129 |
+
for question in request['questions']:
|
| 1130 |
+
question.pop('key', None)
|
| 1131 |
+
self.messages.append({'role': 'assistant', 'content': json.dumps(public_action, ensure_ascii=False)})
|
| 1132 |
+
if kind == 'finalize':
|
| 1133 |
+
return self._result({'conclusion': action['conclusion'], 'numeric_result': action.get('numeric_result')}, transcript, turn)
|
| 1134 |
+
if kind == 'wait':
|
| 1135 |
+
event['waited'] = True
|
| 1136 |
+
continue
|
| 1137 |
+
grouped = {}
|
| 1138 |
+
for request in action['messages']:
|
| 1139 |
+
grouped.setdefault(request['role_agent'], []).extend(request['questions'])
|
| 1140 |
+
replies = event['role_answers']
|
| 1141 |
+
for role, questions in grouped.items():
|
| 1142 |
+
authorized = []
|
| 1143 |
+
invalid = []
|
| 1144 |
+
for q in questions:
|
| 1145 |
+
try:
|
| 1146 |
+
valid = validate_question(q, role_name=role, semantic_enabled=role in self._semantic_enabled_roles)['authorized']
|
| 1147 |
+
except ValueError:
|
| 1148 |
+
valid = False
|
| 1149 |
+
(authorized if valid else invalid).append(q)
|
| 1150 |
+
replies.extend(answer(role, q) for q in invalid)
|
| 1151 |
+
response = self.neglect_policy.contact(role, authorized, turn)
|
| 1152 |
+
if response is None:
|
| 1153 |
+
replies.extend(answer(role, q) for q in authorized)
|
| 1154 |
+
else:
|
| 1155 |
+
event.setdefault('deferred_role_requests', []).extend(
|
| 1156 |
+
{'role_agent': role, 'question': dict(q)} for q in authorized)
|
| 1157 |
+
if response:
|
| 1158 |
+
replies.append({'role_agent': role, 'question': dict(authorized[0]),
|
| 1159 |
+
'answer': response, 'communication_event': 'neglect'})
|
| 1160 |
+
publish(replies)
|
| 1161 |
+
return self._result({'conclusion': None, 'numeric_result': None}, transcript, None)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class MainAgent:
|
| 1165 |
+
def __init__(
|
| 1166 |
+
self, client: OpenAI, role_agents: Dict[str, RoleAgent],
|
| 1167 |
+
model: str = MAIN_AGENT_MODEL_NAME, max_turns: int | None = None,
|
| 1168 |
+
):
|
| 1169 |
+
self.client = client
|
| 1170 |
+
self.role_agents = role_agents
|
| 1171 |
+
self.model = model
|
| 1172 |
+
self.runtime_config = runtime_defaults()
|
| 1173 |
+
self.max_turns = max_turns if max_turns is not None else int(os.getenv("MAX_TURNS", str(self.runtime_config["max_turns"])))
|
| 1174 |
+
self.runtime_config["max_turns"] = self.max_turns
|
| 1175 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config["communication_role_names"])
|
| 1176 |
+
self.delivered_messages = []
|
| 1177 |
+
self.incomplete_policy = IncompletePolicy(INCOMPLETE_INJECTION) if SETTING in {"incomplete", "mixed"} else None
|
| 1178 |
+
self.followup_resolver = IncompleteFollowupResolver(INCOMPLETE_FOLLOWUP_RECORDS) if SETTING in {"incomplete", "mixed"} else None
|
| 1179 |
+
self.current_turn = 0
|
| 1180 |
+
self.communication_events = []
|
| 1181 |
+
self.empty_observation_count = 0
|
| 1182 |
+
self.messages: List[Dict[str, str]] = []
|
| 1183 |
+
self.system_message = self._build_system_message()
|
| 1184 |
+
self._semantic_enabled_roles: set[str] = set()
|
| 1185 |
+
|
| 1186 |
+
def _build_system_message(self) -> str:
|
| 1187 |
+
if MAIN_AGENT_ROLE_ORDER_SEED is None:
|
| 1188 |
+
return main_system_prompt()
|
| 1189 |
+
roles = list(PUBLIC_ROLES)
|
| 1190 |
+
random.Random(MAIN_AGENT_ROLE_ORDER_SEED).shuffle(roles)
|
| 1191 |
+
role_text = "\n".join(
|
| 1192 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1193 |
+
for item in roles
|
| 1194 |
+
)
|
| 1195 |
+
return main_system_prompt().replace(
|
| 1196 |
+
"\n".join(
|
| 1197 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1198 |
+
for item in PUBLIC_ROLES
|
| 1199 |
+
),
|
| 1200 |
+
role_text,
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _call_main(self) -> Dict[str, Any]:
|
| 1204 |
+
if SETTING in {"missed", "mixed"} and self.messages[-1]["role"] == "assistant":
|
| 1205 |
+
self.messages.append({"role": "user", "content": '{"observations":[]}'})
|
| 1206 |
+
self.empty_observation_count += 1
|
| 1207 |
+
response = self.client.chat.completions.create(
|
| 1208 |
+
model=self.model,
|
| 1209 |
+
messages=self.messages,
|
| 1210 |
+
temperature=0.1,
|
| 1211 |
+
response_format={"type": "json_object"},
|
| 1212 |
+
extra_body={"reasoning": {"effort": LLM_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 1213 |
+
)
|
| 1214 |
+
self._last_main_parse_trace = {}
|
| 1215 |
+
return parse_json_message(response.choices[0].message.content, trace=self._last_main_parse_trace)
|
| 1216 |
+
|
| 1217 |
+
def _answer_question(
|
| 1218 |
+
self, role_name: str, question: Dict[str, Any],
|
| 1219 |
+
) -> tuple[Dict[str, Any], bool]:
|
| 1220 |
+
role_name = resolve_role_name(role_name, self.role_agents)
|
| 1221 |
+
role = self.role_agents.get(role_name)
|
| 1222 |
+
if role is None:
|
| 1223 |
+
return {"answer": f"Error: unknown role {role_name}。"}, False
|
| 1224 |
+
try:
|
| 1225 |
+
normalized = validate_question(
|
| 1226 |
+
question, role_name=role_name,
|
| 1227 |
+
semantic_enabled=role_name in self._semantic_enabled_roles,
|
| 1228 |
+
)
|
| 1229 |
+
except ValueError as error:
|
| 1230 |
+
return {"answer": f"Invalid query: {error}"}, False
|
| 1231 |
+
if not normalized["authorized"]:
|
| 1232 |
+
return {"answer": "The key is invalid, belongs to another role, or keyless follow-up is not yet authorized. Include a complete key for this role in question text, without a separate key field."}, False
|
| 1233 |
+
key = question.get("key")
|
| 1234 |
+
role_question = dict(question)
|
| 1235 |
+
binding = None
|
| 1236 |
+
if (self.followup_resolver and key is None
|
| 1237 |
+
and (SETTING != "mixed" or role_name == INCOMPLETE_INJECTION["role_name"])):
|
| 1238 |
+
binding = self.followup_resolver.resolve(role_name, question['question'], self.current_turn)
|
| 1239 |
+
if binding['status'] != 'resolved':
|
| 1240 |
+
answer = (self.followup_resolver.catalog(role_name) if binding['status'] == 'catalog'
|
| 1241 |
+
else self.followup_resolver.CLARIFY)
|
| 1242 |
+
return {"answer": answer, "followup_binding": binding}, False
|
| 1243 |
+
key = binding['key']
|
| 1244 |
+
# Resolve keys only for role requests; preserve the main question in transcripts.
|
| 1245 |
+
role_question = dict(question, key=key, question=question['question'] + ' (System-linked record: ' + key + ')')
|
| 1246 |
+
allowed_keys = set(RECORD_REPLY_KEYS[key] if key is not None else ROLE_VALID_KEYS[role_name])
|
| 1247 |
+
unrelated_field = False
|
| 1248 |
+
if binding and key == INCOMPLETE_INJECTION['key']:
|
| 1249 |
+
hidden_topic = INCOMPLETE_INJECTION['hidden_predicate_id'].removeprefix(INCOMPLETE_INJECTION['candidate_id'] + '_')
|
| 1250 |
+
unrelated_field = not binding['full'] and hidden_topic not in binding['fields'] and self.incomplete_policy.recovered_at_turn is None
|
| 1251 |
+
disclosure_mode = ('incomplete_partial' if unrelated_field else self.incomplete_policy.mode(role_name, role_question, self.current_turn)) if self.incomplete_policy else None
|
| 1252 |
+
if binding:
|
| 1253 |
+
binding['recovery_requested'] = disclosure_mode == 'incomplete_recovery'
|
| 1254 |
+
options = self.incomplete_policy.request_options(disclosure_mode, role.system_message) if disclosure_mode else {}
|
| 1255 |
+
trace = role.answer_with_trace(
|
| 1256 |
+
format_role_user_message(role_question), allowed_keys=allowed_keys,
|
| 1257 |
+
response_mode=disclosure_mode or ("exact" if key is not None else "search"),
|
| 1258 |
+
**options,
|
| 1259 |
+
)
|
| 1260 |
+
if not trace["accepted"]:
|
| 1261 |
+
return {
|
| 1262 |
+
"answer": trace["answer"], "role_validation_trace": trace,
|
| 1263 |
+
"protocol_error": "role_reply_scope_violation",
|
| 1264 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1265 |
+
}, False
|
| 1266 |
+
if disclosure_mode:
|
| 1267 |
+
self.incomplete_policy.observe(disclosure_mode, self.current_turn, trace["answer"])
|
| 1268 |
+
if self.followup_resolver:
|
| 1269 |
+
self.followup_resolver.observe(role_name, key, self.current_turn)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": trace["answer"], "role_trace": trace,
|
| 1272 |
+
"authorized_exact": question.get("key") is not None,
|
| 1273 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1274 |
+
}, False
|
| 1275 |
+
|
| 1276 |
+
def _communication_evaluation(
|
| 1277 |
+
self, transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1278 |
+
) -> Dict[str, Any]:
|
| 1279 |
+
metrics = communication_metrics(transcript)
|
| 1280 |
+
total_questions = sum(
|
| 1281 |
+
len(message.get("questions", []))
|
| 1282 |
+
for event in transcript
|
| 1283 |
+
for message in event.get("main_agent_action", {}).get("messages", [])
|
| 1284 |
+
)
|
| 1285 |
+
ideal = max(1, self.runtime_config["finalize_ideal_round"])
|
| 1286 |
+
turns = final_turn if final_turn is not None else len(transcript)
|
| 1287 |
+
return {
|
| 1288 |
+
**metrics,
|
| 1289 |
+
"total_role_agent_queries": total_questions,
|
| 1290 |
+
"total_questions": total_questions,
|
| 1291 |
+
"finalize_ideal_round": self.runtime_config["finalize_ideal_round"],
|
| 1292 |
+
"max_turns": self.max_turns,
|
| 1293 |
+
"wait_turns": sum(bool(event.get("waited")) for event in transcript),
|
| 1294 |
+
"empty_observation_count": self.empty_observation_count,
|
| 1295 |
+
**self.neglect_policy.metrics(),
|
| 1296 |
+
"delivered_reply_count": len(self.delivered_messages),
|
| 1297 |
+
"pending_reply_count": self.neglect_policy.metrics()["neglect_pending_count"],
|
| 1298 |
+
"efficiency": min(1.0, ideal / turns) if final_turn else 0.0,
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
def _result(
|
| 1302 |
+
self, final: Dict[str, Any], transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1303 |
+
) -> Dict[str, Any]:
|
| 1304 |
+
conclusion = compute_conclusion_correctness(final)
|
| 1305 |
+
communication = self._communication_evaluation(transcript, final_turn)
|
| 1306 |
+
communication["recovery_success"] = (
|
| 1307 |
+
recovery_success(communication, conclusion["conclusion_correctness"] == 1)
|
| 1308 |
+
if ERROR_INJECTION.get("enabled") else None
|
| 1309 |
+
)
|
| 1310 |
+
if self.incomplete_policy:
|
| 1311 |
+
communication.update(self.followup_resolver.metrics())
|
| 1312 |
+
communication.update(self.incomplete_policy.metrics(
|
| 1313 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1314 |
+
))
|
| 1315 |
+
communication.update(incomplete_numeric_metrics(
|
| 1316 |
+
INCOMPLETE_INJECTION, transcript, communication,
|
| 1317 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1318 |
+
))
|
| 1319 |
+
return {
|
| 1320 |
+
"final_result": final,
|
| 1321 |
+
"evaluation": {
|
| 1322 |
+
"conclusion_correct": conclusion["conclusion_correct"],
|
| 1323 |
+
"numeric_result_correct": conclusion["numeric_result_correct"],
|
| 1324 |
+
"joint_correctness": conclusion["conclusion_correctness"],
|
| 1325 |
+
"conclusion_evaluation": conclusion,
|
| 1326 |
+
"communication_evaluation": communication,
|
| 1327 |
+
},
|
| 1328 |
+
"transcript": transcript,
|
| 1329 |
+
"runtime_config": dict(self.runtime_config),
|
| 1330 |
+
"collaboration_state": {
|
| 1331 |
+
"neglect_roles": self.neglect_policy.roles,
|
| 1332 |
+
"delivered_messages": list(self.delivered_messages),
|
| 1333 |
+
"communication_events": list(self.communication_events),
|
| 1334 |
+
},
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
run = run_direct
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def build_task() -> str:
|
| 1341 |
+
return TASK_CONTEXT.strip() + "\n\n" + TASK_QUERY.strip()
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def create_timestamped_run_dir(
|
| 1345 |
+
root: str | Path, prefix: str, started: datetime | None = None,
|
| 1346 |
+
) -> Path:
|
| 1347 |
+
root_path = Path(root)
|
| 1348 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 1349 |
+
timestamp = (started or datetime.now()).strftime("%m%d_%H%M")
|
| 1350 |
+
base_name = f"{prefix}_{timestamp}"
|
| 1351 |
+
suffix = 1
|
| 1352 |
+
while True:
|
| 1353 |
+
name = base_name if suffix == 1 else f"{base_name}_{suffix:02d}"
|
| 1354 |
+
candidate = root_path / name
|
| 1355 |
+
try:
|
| 1356 |
+
candidate.mkdir(exist_ok=False)
|
| 1357 |
+
return candidate
|
| 1358 |
+
except FileExistsError:
|
| 1359 |
+
suffix += 1
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
def save_single_run_result(
|
| 1363 |
+
result: Dict[str, Any], output_root: str | Path | None = None,
|
| 1364 |
+
) -> Path:
|
| 1365 |
+
logs_root = (
|
| 1366 |
+
Path(output_root)
|
| 1367 |
+
if output_root is not None
|
| 1368 |
+
else Path(__file__).resolve().parent.parent / "logs"
|
| 1369 |
+
)
|
| 1370 |
+
run_dir = create_timestamped_run_dir(logs_root, "single_run")
|
| 1371 |
+
result_path = run_dir / "result.json"
|
| 1372 |
+
result_path.write_text(
|
| 1373 |
+
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
|
| 1374 |
+
encoding="utf-8",
|
| 1375 |
+
)
|
| 1376 |
+
return result_path
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def main() -> None:
|
| 1380 |
+
main_client = OpenAI(base_url=MAIN_AGENT_BASE_URL, api_key=MAIN_AGENT_API_KEY)
|
| 1381 |
+
role_client = OpenAI(base_url=ROLE_AGENT_BASE_URL, api_key=ROLE_AGENT_API_KEY)
|
| 1382 |
+
role_agents = build_role_agents(role_client)
|
| 1383 |
+
agent = MainAgent(main_client, role_agents)
|
| 1384 |
+
task = build_task()
|
| 1385 |
+
print_key_trace("LLM CONFIG", format_llm_config())
|
| 1386 |
+
print_key_trace("AVAILABLE ROLES", format_available_roles(role_agents))
|
| 1387 |
+
print_key_trace("TASK QUERY", task)
|
| 1388 |
+
result = agent.run(task)
|
| 1389 |
+
result_path = save_single_run_result(result)
|
| 1390 |
+
summary_title = "MISALIGNED RECOVERY SUMMARY" if SETTING in {"misaligned", "mixed"} else "TASK SUMMARY"
|
| 1391 |
+
print_key_trace(summary_title, format_key_metrics(result["evaluation"]))
|
| 1392 |
+
print_key_trace("RESULT SAVED", result_path)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
if __name__ == "__main__":
|
| 1396 |
+
main()
|
data/incomplete/task_004/role_agents/dockside_stevedoring.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Stevedoring superintendent (STV)",
|
| 3 |
+
"abstract": "Monitors quayside container crane throughput and cargo handling speeds",
|
| 4 |
+
"system_message": "You are Stevedoring superintendent (STV). The stevedoring superintendent (STV) oversees quayside container crane operations, monitoring cargo handling rates and handling equipment readiness across expedition bases.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Monitors quayside container crane throughput and cargo handling speeds(CRANE)",
|
| 8 |
+
"content": "STV-CRANE-DD4:For Falkland Sound Support Depot, the stevedoring audit indicates a quayside crane container cycle rate of 22 moves/h during standard container lifts over cargo holds.\nSTV-CRANE-ARF:At Kerguelen Marine Research Haven, the quayside crane container cycle rate for gantry cranes operating over cargo hold hatches is 14 moves/h.\nSTV-CRANE-GBY:At South Georgia Staging Facility, quayside gantry cranes achieve a quayside crane container cycle rate of 28 moves/h over cargo hold hatches."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Forklift fleet readiness(FORK)",
|
| 12 |
+
"content": "STV-FORK-OJI:South Georgia Staging Facility has an operational rough-terrain forklift count of 8 vehicles available in its quayside cargo marshalling yard.\nSTV-FORK-ROH:The quayside cargo marshalling yard at Kerguelen Marine Research Haven maintains an operational rough-terrain forklift count of 5 vehicles.\nSTV-FORK-5XC:At Falkland Sound Support Depot, the fleet maintenance ledger records an operational rough-terrain forklift count of 3 vehicles in the quayside cargo marshalling yard."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/role_agents/environmental_compliance.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Sanctuary compliance officer (ENV)",
|
| 3 |
+
"abstract": "Evaluates environmental impact reviews and wildlife sanctuary transit permits",
|
| 4 |
+
"system_message": "You are the Sanctuary compliance officer (ENV). Your business responsibilities include evaluating environmental impact reviews and wildlife sanctuary transit permits, as well as tracking bio-waste incinerator specifications across candidate facilities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Bio-waste incinerator(WASTE)",
|
| 8 |
+
"content": "ENV-WASTE-4AT:For South Georgia Staging Facility, the incineration plant rating plate records a daily waste processing capacity of 150 kg for biological waste mass incinerated per day.\nENV-WASTE-BGE:Per the incineration plant rating plate for daily operational hazardous waste disposal, Kerguelen Marine Research Haven has a daily waste processing capacity of 250 kg of biological waste mass.\nENV-WASTE-TXM:The incineration plant rating plate indicates that Falkland Sound Support Depot possesses a daily waste processing capacity of 350 kg for daily operational hazardous waste disposal."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Evaluates environmental impact reviews and wildlife sanctuary transit permits(PERM)",
|
| 12 |
+
"content": "ENV-PERM-LS0:The conservation authority environmental review confirms that sanctuary transit clearance across designated coastal transit corridors through protected marine areas is formally granted for Falkland Sound Support Depot.\nENV-PERM-M4K:According to the conservation authority environmental review for designated coastal transit corridors through protected marine areas, sanctuary transit clearance has been formally granted for Kerguelen Marine Research Haven.\nENV-PERM-K40:Based on the conservation authority environmental review for designated coastal transit corridors through protected marine areas, sanctuary transit clearance has not been granted for South Georgia Staging Facility."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/role_agents/expedition_logistics.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Expedition logistics coordinator (LOG)",
|
| 3 |
+
"abstract": "Maintains dock draft depth and sample cold storage certification records",
|
| 4 |
+
"system_message": "You are Expedition logistics coordinator (LOG). You serve as the expedition logistics coordinator (LOG), responsible for maintaining dock draft depths, hydrographic access specifications, and specimen cold storage certification records for sub-Antarctic marine staging bases.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains dock draft depth and sample cold storage certification records(STG)",
|
| 8 |
+
"content": "LOG-STG-2JX:For Kerguelen Marine Research Haven under the operational deployment environment, cold storage certification is confirmed, and the minimum harbor draft depth across the berth fairway and turnaround basin is 12 m.\nLOG-STG-AZ6:For Kerguelen Marine Research Haven evaluated under the simulation test environment, cold storage certification is met, but the recorded harbor draft depth is 9 m.\nLOG-STG-NY3:For South Georgia Staging Facility under the operational deployment environment, cold storage certification is verified, and the minimum harbor draft depth reaches 14 m.\nLOG-STG-BLI:For Falkland Sound Support Depot under the operational deployment environment, cold storage certification is not held, while the minimum harbor draft depth is 12 m."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Deep freeze storage(CHILL)",
|
| 12 |
+
"content": "LOG-CHILL-ROP:At Falkland Sound Support Depot, telemetry records indicate a deep freeze temperature stability of -60 degC in the biological archive freezers.\nLOG-CHILL-0HF:At Kerguelen Marine Research Haven, telemetry logs show a deep freeze temperature stability of -70 degC sustained across biological archive freezers.\nLOG-CHILL-EIZ:At South Georgia Staging Facility, cryogenic telemetry confirms a deep freeze temperature stability of -80 degC within the biological archive freezers."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/role_agents/harbour_master.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Port infrastructure superintendent (PRT)",
|
| 3 |
+
"abstract": "Regulates ballast deadweight requirements and harbor navigation channel safety limits",
|
| 4 |
+
"system_message": "You are the Port infrastructure superintendent (PRT). Your official responsibilities cover regulating ballast deadweight requirements, overseeing harbor navigation channel safety limits, and recording harbor tug availability for port operations.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Regulates ballast deadweight requirements and harbor navigation channel safety limits(PORT)",
|
| 8 |
+
"content": "PRT-PORT-8I3:For the Falkland Sound Support Depot, the required unladen water ballast deadweight reservation for deep ocean passage stability tanks is 40 t under harbor trim directives.\nPRT-PORT-C6J:Under the port hydrodynamics trim directive for deep ocean passage stability tanks, the mandatory ballast deadweight reservation for Kerguelen Marine Research Haven is set at 40 t subtracted from cargo headroom.\nPRT-PORT-75D:In accordance with the port hydrodynamics trim directive for deep ocean passage stability tanks, the ballast deadweight reservation for South Georgia Staging Facility is designated as 40 t."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Harbor tug availability(TUG)",
|
| 12 |
+
"content": "PRT-TUG-FOX:According to the port towing authority certificate for stationed harbor assistance vessels, the tug escort bollard pull at Kerguelen Marine Research Haven is rated at 65 t continuous maximum bollard pull.\nPRT-TUG-8AO:The port towing authority certificate records a continuous maximum tug escort bollard pull rating of 80 t for stationed harbor assistance vessels at Falkland Sound Support Depot.\nPRT-TUG-1XS:At South Georgia Staging Facility, stationed harbor assistance vessels provide a continuous maximum tug escort bollard pull rating of 40 t according to the port towing authority certificate."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/role_agents/marine_safety.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Maritime safety officer (SAF)",
|
| 3 |
+
"abstract": "Maintains emergency evacuation protocol and survival shelter endurance evaluations",
|
| 4 |
+
"system_message": "You are the Maritime safety officer (SAF), responsible for maintaining emergency evacuation protocol records and survival shelter endurance evaluations, as well as tracking telemedicine communications support.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Telemedicine support(MED)",
|
| 8 |
+
"content": "SAF-MED-UX7:Emergency comms link testing indicates that the Falkland Sound Support Depot provides a guaranteed satellite telemedicine bandwidth of 512 kbps for its base infirmary uplink.\nSAF-MED-FMA:Emergency comms link testing confirms that the South Georgia Staging Facility sustains a dedicated satellite telemedicine bandwidth of 1024 kbps between the base infirmary and the regional trauma center.\nSAF-MED-8IE:Emergency comms link testing indicates that the Kerguelen Marine Research Haven maintains a satellite telemedicine bandwidth of 256 kbps dedicated to the base infirmary uplink."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains emergency evacuation protocol and survival shelter endurance evaluations(SURV)",
|
| 12 |
+
"content": "SAF-SURV-ADP:For the South Georgia Staging Facility, a certified emergency evacuation protocol is formally in place covering the base perimeter and ice shelf access corridors, and on-site shelter endurance provides 96 h of autonomous life support in the reinforced storm bunker during complete power cutoff.\nSAF-SURV-MGB:For the Falkland Sound Support Depot, the certified emergency evacuation protocol is active and signed across base perimeter and ice shelf access corridors, while on-site shelter endurance in the reinforced storm bunker is rated at 48 h under total power cutoff.\nSAF-SURV-F3D:For the Kerguelen Marine Research Haven, the certified emergency evacuation protocol is active and verified under the maritime safety audit endorsement covering the staging base perimeter and ice shelf access corridors, and its reinforced storm bunker provides 96 h of autonomous on-site shelter endurance under total power cutoff."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/role_agents/polar_quartermaster.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Polar expedition quartermaster (QMR)",
|
| 3 |
+
"abstract": "Manages severe weather survival gear allocations and consumable staging",
|
| 4 |
+
"system_message": "You are Polar expedition quartermaster (QMR). The polar expedition quartermaster (QMR) manages severe weather survival gear allocations and oversees consumable staging and ration warehouse reserves for potential staging bases.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Manages severe weather survival gear allocations and consumable staging(GEAR)",
|
| 8 |
+
"content": "QMR-GEAR-OCW:For Kerguelen Marine Research Haven, the survival gear payload allowance covering crew survival pods, emergency dry food packs, and immersion gear is designated at 110 t.\nQMR-GEAR-O71:For South Georgia Staging Facility, the survival gear payload allowance covering crew survival pods, emergency dry food packs, and immersion gear is designated at 130 t.\nQMR-GEAR-HV4:For Falkland Sound Support Depot, the survival gear payload allowance covering crew survival pods, emergency dry food packs, and immersion gear is designated at 70 t."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Ration warehouse reserves(RATION)",
|
| 12 |
+
"content": "QMR-RATION-FED:For Kerguelen Marine Research Haven, the reserve emergency food stores for the standard expedition crew complement provide 60 d of nutritional ration reserves.\nQMR-RATION-Q5B:For Falkland Sound Support Depot, the reserve emergency food stores for the standard expedition crew complement provide 90 d of nutritional ration reserves.\nQMR-RATION-JFV:For South Georgia Staging Facility, the reserve emergency food stores for the standard expedition crew complement provide 45 d of nutritional ration reserves."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/role_agents/technical_operations.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Marine engineering lead (ENG)",
|
| 3 |
+
"abstract": "Tracks marine fuel bunkering readiness and science equipment payload allowances",
|
| 4 |
+
"system_message": "You are the Marine engineering lead (ENG). Your responsibilities include tracking marine fuel bunkering readiness, monitoring science equipment payload allowances, and reviewing shore power generation capabilities across proposed staging base plans.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Tracks marine fuel bunkering readiness and science equipment payload allowances(TECH)",
|
| 8 |
+
"content": "ENG-TECH-EPG:For Falkland Sound Support Depot, fuel bunkering readiness is confirmed with signed-off connection valves on the low-sulfur polar marine gas oil line, and the science equipment payload allowance for the main working deck and wet labs is established at 180 t.\nENG-TECH-7R8:For South Georgia Staging Facility, fuel bunkering readiness is not verified as the connection valves on the low-sulfur polar marine gas oil line lack operational sign-off, while the science equipment payload allowance across the main working deck and wet labs is 180 t.\nENG-TECH-ZK3:For Kerguelen Marine Research Haven, fuel bunkering readiness via the dedicated low-sulfur polar marine gas oil pipeline is confirmed based on operational sign-off of bunkering connection valves, and the science equipment payload allowance for the main working deck and wet labs is 220 t."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Shore power generation(POWER)",
|
| 12 |
+
"content": "ENG-POWER-X4G:For Kerguelen Marine Research Haven, the continuous shore-to-ship power output delivered to docked polar vessels is 200 kW.\nENG-POWER-OOF:For South Georgia Staging Facility, the continuous shore-to-ship power output supplied to docked polar vessels is 500 kW.\nENG-POWER-FDI:For Falkland Sound Support Depot, the continuous stable shore-to-ship power output available for docked polar vessels is 350 kW."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_004/tasks/run_one.py
ADDED
|
@@ -0,0 +1,1396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from typing import Any
|
| 5 |
+
COMMUNICATION_ROLE_NAMES = []
|
| 6 |
+
GOLD = {'conclusion': 'Select', 'numeric_result': 290}
|
| 7 |
+
POSITIVE_CONCLUSION = 'Select'
|
| 8 |
+
NEGATIVE_CONCLUSION = 'Do not select'
|
| 9 |
+
NUMERIC_PRECISION = 0
|
| 10 |
+
PUBLIC_ROLES = [{'role_name': 'Expedition logistics coordinator (LOG)', 'responsibility': 'Maintains dock draft depth and sample cold storage certification records', 'role_abbreviation': 'LOG'}, {'role_name': 'Maritime safety officer (SAF)', 'responsibility': 'Maintains emergency evacuation protocol and survival shelter endurance evaluations', 'role_abbreviation': 'SAF'}, {'role_name': 'Sanctuary compliance officer (ENV)', 'responsibility': 'Evaluates environmental impact reviews and wildlife sanctuary transit permits', 'role_abbreviation': 'ENV'}, {'role_name': 'Marine engineering lead (ENG)', 'responsibility': 'Tracks marine fuel bunkering readiness and science equipment payload allowances', 'role_abbreviation': 'ENG'}, {'role_name': 'Polar expedition quartermaster (QMR)', 'responsibility': 'Manages severe weather survival gear allocations and consumable staging', 'role_abbreviation': 'QMR'}, {'role_name': 'Port infrastructure superintendent (PRT)', 'responsibility': 'Regulates ballast deadweight requirements and harbor navigation channel safety limits', 'role_abbreviation': 'PRT'}, {'role_name': 'Stevedoring superintendent (STV)', 'responsibility': 'Monitors quayside container crane throughput and cargo handling speeds', 'role_abbreviation': 'STV'}]
|
| 11 |
+
ROLE_KEY_PREFIXES = {'Expedition logistics coordinator (LOG)': 'LOG-', 'Maritime safety officer (SAF)': 'SAF-', 'Sanctuary compliance officer (ENV)': 'ENV-', 'Marine engineering lead (ENG)': 'ENG-', 'Polar expedition quartermaster (QMR)': 'QMR-', 'Port infrastructure superintendent (PRT)': 'PRT-', 'Stevedoring superintendent (STV)': 'STV-'}
|
| 12 |
+
ROLE_VALID_KEYS = {'Expedition logistics coordinator (LOG)': ['LOG-STG-2JX', 'LOG-STG-AZ6', 'LOG-STG-NY3', 'LOG-STG-BLI', 'LOG-CHILL-ROP', 'LOG-CHILL-0HF', 'LOG-CHILL-EIZ'], 'Maritime safety officer (SAF)': ['SAF-MED-UX7', 'SAF-MED-FMA', 'SAF-MED-8IE', 'SAF-SURV-ADP', 'SAF-SURV-MGB', 'SAF-SURV-F3D'], 'Sanctuary compliance officer (ENV)': ['ENV-WASTE-4AT', 'ENV-WASTE-BGE', 'ENV-WASTE-TXM', 'ENV-PERM-LS0', 'ENV-PERM-M4K', 'ENV-PERM-K40'], 'Marine engineering lead (ENG)': ['ENG-TECH-EPG', 'ENG-TECH-7R8', 'ENG-TECH-ZK3', 'ENG-POWER-X4G', 'ENG-POWER-OOF', 'ENG-POWER-FDI'], 'Polar expedition quartermaster (QMR)': ['QMR-GEAR-OCW', 'QMR-GEAR-O71', 'QMR-GEAR-HV4', 'QMR-RATION-FED', 'QMR-RATION-Q5B', 'QMR-RATION-JFV'], 'Port infrastructure superintendent (PRT)': ['PRT-PORT-8I3', 'PRT-PORT-C6J', 'PRT-PORT-75D', 'PRT-TUG-FOX', 'PRT-TUG-8AO', 'PRT-TUG-1XS'], 'Stevedoring superintendent (STV)': ['STV-CRANE-DD4', 'STV-CRANE-ARF', 'STV-CRANE-GBY', 'STV-FORK-OJI', 'STV-FORK-ROH', 'STV-FORK-5XC']}
|
| 13 |
+
RECORD_REPLY_KEYS = {'LOG-STG-2JX': ['LOG-STG-2JX'], 'LOG-STG-BLI': ['LOG-STG-BLI'], 'LOG-STG-NY3': ['LOG-STG-NY3'], 'SAF-SURV-F3D': ['SAF-SURV-F3D'], 'SAF-SURV-MGB': ['SAF-SURV-MGB'], 'SAF-SURV-ADP': ['SAF-SURV-ADP'], 'ENV-PERM-M4K': ['ENV-PERM-M4K'], 'ENV-PERM-LS0': ['ENV-PERM-LS0'], 'ENV-PERM-K40': ['ENV-PERM-K40'], 'ENG-TECH-ZK3': ['ENG-TECH-ZK3'], 'ENG-TECH-EPG': ['ENG-TECH-EPG'], 'ENG-TECH-7R8': ['ENG-TECH-7R8'], 'QMR-GEAR-OCW': ['QMR-GEAR-OCW'], 'QMR-GEAR-HV4': ['QMR-GEAR-HV4'], 'QMR-GEAR-O71': ['QMR-GEAR-O71'], 'PRT-PORT-C6J': ['PRT-PORT-C6J'], 'PRT-PORT-8I3': ['PRT-PORT-8I3'], 'PRT-PORT-75D': ['PRT-PORT-75D'], 'STV-CRANE-ARF': ['STV-CRANE-ARF'], 'STV-CRANE-DD4': ['STV-CRANE-DD4'], 'STV-CRANE-GBY': ['STV-CRANE-GBY'], 'LOG-CHILL-0HF': ['LOG-CHILL-0HF'], 'LOG-CHILL-ROP': ['LOG-CHILL-ROP'], 'LOG-CHILL-EIZ': ['LOG-CHILL-EIZ'], 'SAF-MED-8IE': ['SAF-MED-8IE'], 'SAF-MED-UX7': ['SAF-MED-UX7'], 'SAF-MED-FMA': ['SAF-MED-FMA'], 'ENV-WASTE-BGE': ['ENV-WASTE-BGE'], 'ENV-WASTE-TXM': ['ENV-WASTE-TXM'], 'ENV-WASTE-4AT': ['ENV-WASTE-4AT'], 'ENG-POWER-X4G': ['ENG-POWER-X4G'], 'ENG-POWER-FDI': ['ENG-POWER-FDI'], 'ENG-POWER-OOF': ['ENG-POWER-OOF'], 'QMR-RATION-FED': ['QMR-RATION-FED'], 'QMR-RATION-Q5B': ['QMR-RATION-Q5B'], 'QMR-RATION-JFV': ['QMR-RATION-JFV'], 'PRT-TUG-FOX': ['PRT-TUG-FOX'], 'PRT-TUG-8AO': ['PRT-TUG-8AO'], 'PRT-TUG-1XS': ['PRT-TUG-1XS'], 'STV-FORK-ROH': ['STV-FORK-ROH'], 'STV-FORK-5XC': ['STV-FORK-5XC'], 'STV-FORK-OJI': ['STV-FORK-OJI'], 'LOG-STG-AZ6': ['LOG-STG-AZ6']}
|
| 14 |
+
REQUIRED_KEYS = ['ENG-TECH-ZK3', 'ENV-PERM-K40', 'ENV-PERM-M4K', 'LOG-STG-2JX', 'LOG-STG-BLI', 'PRT-PORT-C6J', 'QMR-GEAR-OCW', 'SAF-SURV-F3D']
|
| 15 |
+
DISTRACTOR_KEYS = ['STV-CRANE-ARF', 'STV-CRANE-DD4', 'STV-CRANE-GBY', 'STV-FORK-5XC', 'STV-FORK-OJI', 'STV-FORK-ROH']
|
| 16 |
+
SETTING = 'incomplete'
|
| 17 |
+
|
| 18 |
+
def runtime_defaults() -> dict[str, Any]:
|
| 19 |
+
return {
|
| 20 |
+
"setting": SETTING,
|
| 21 |
+
"communication_role_names": list(COMMUNICATION_ROLE_NAMES),
|
| 22 |
+
"finalize_ideal_round": 3,
|
| 23 |
+
"max_turns": 6,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
FINALIZE_IDEAL_ROUND = runtime_defaults()["finalize_ideal_round"]
|
| 27 |
+
DEFAULT_MAX_TURNS = runtime_defaults()["max_turns"]
|
| 28 |
+
ERROR_INJECTION = {'enabled': False, 'role_name': 'Expedition logistics coordinator (LOG)', 'target_key': 'LOG-STG-2JX', 'alternate_key': 'LOG-STG-AZ6', 'target_context': 'operational deployment environment', 'alternate_context': 'simulation test environment'}
|
| 29 |
+
INCOMPLETE_INJECTION = {'record_id': 'rec_marine_safety_A', 'role_id': 'marine_safety', 'candidate_id': 'A', 'key': 'SAF-SURV-F3D', 'boolean_predicate_id': 'A_evacuation_protocol_certified', 'boolean_label': 'Certified emergency evacuation protocol', 'hidden_predicate_id': 'A_shelter_endurance_hours', 'threshold_label': 'On-site shelter endurance', 'threshold_aliases': ['Emergency shelter survival duration', 'Survival shelter autonomous endurance'], 'threshold_value': 96, 'threshold_unit': 'h', 'partial_record_text': 'SAF-SURV-F3D: Kerguelen Marine Research Haven.Kerguelen Marine Research Haven: Certified emergency evacuation protocol = true .Source: Maritime safety audit endorsement; Scope: Staging base perimeter and ice shelf access corridors; Measurement: Presence of an active signed emergency evacuation operational plan.', 'alternative_outputs': [{'conclusion': 'Do not select', 'numeric_result': None, 'qualified_candidate_id': None}], 'disclosure_mode': 'upper_bound', 'disclosure_version': 'truthful_bounds_v3_domain_bounds', 'disclosure_bounds': {'lower': None, 'upper': 300}, 'coarse_statement': 'On-site shelter endurance is at most 300 h.', 'role_name': 'Maritime safety officer (SAF)', 'candidate_name': 'Kerguelen Marine Research Haven', 'other_candidate_names': ['Falkland Sound Support Depot', 'South Georgia Staging Facility'], 'context_value': None, 'other_context_values': [], 'language': 'en'}
|
| 30 |
+
INCOMPLETE_FOLLOWUP_RECORDS = [{'key': 'LOG-STG-2JX', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'Kerguelen Marine Research Haven', 'context': 'operational deployment environment', 'fields': [{'id': 'cold_storage_certified', 'label': 'Cold storage certification', 'aliases': ['Specimen cold storage status', 'Refrigerated archive compliance']}, {'id': 'harbor_draft_depth', 'label': 'Harbor draft depth', 'aliases': ['Approach channel draft', 'Quayside water depth']}]}, {'key': 'LOG-STG-BLI', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'Falkland Sound Support Depot', 'context': 'operational deployment environment', 'fields': [{'id': 'cold_storage_certified', 'label': 'Cold storage certification', 'aliases': ['Specimen cold storage status', 'Refrigerated archive compliance']}, {'id': 'harbor_draft_depth', 'label': 'Harbor draft depth', 'aliases': ['Approach channel draft', 'Quayside water depth']}]}, {'key': 'LOG-STG-NY3', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'South Georgia Staging Facility', 'context': 'operational deployment environment', 'fields': [{'id': 'cold_storage_certified', 'label': 'Cold storage certification', 'aliases': ['Specimen cold storage status', 'Refrigerated archive compliance']}, {'id': 'harbor_draft_depth', 'label': 'Harbor draft depth', 'aliases': ['Approach channel draft', 'Quayside water depth']}]}, {'key': 'SAF-SURV-F3D', 'role': 'Maritime safety officer (SAF)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'evacuation_protocol_certified', 'label': 'Certified emergency evacuation protocol', 'aliases': ['Evacuation protocol status', 'Emergency medevac plan compliance']}, {'id': 'shelter_endurance_hours', 'label': 'On-site shelter endurance', 'aliases': ['Emergency shelter survival duration', 'Survival shelter autonomous endurance']}]}, {'key': 'SAF-SURV-MGB', 'role': 'Maritime safety officer (SAF)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'evacuation_protocol_certified', 'label': 'Certified emergency evacuation protocol', 'aliases': ['Evacuation protocol status', 'Emergency medevac plan compliance']}, {'id': 'shelter_endurance_hours', 'label': 'On-site shelter endurance', 'aliases': ['Emergency shelter survival duration', 'Survival shelter autonomous endurance']}]}, {'key': 'SAF-SURV-ADP', 'role': 'Maritime safety officer (SAF)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'evacuation_protocol_certified', 'label': 'Certified emergency evacuation protocol', 'aliases': ['Evacuation protocol status', 'Emergency medevac plan compliance']}, {'id': 'shelter_endurance_hours', 'label': 'On-site shelter endurance', 'aliases': ['Emergency shelter survival duration', 'Survival shelter autonomous endurance']}]}, {'key': 'ENV-PERM-M4K', 'role': 'Sanctuary compliance officer (ENV)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'sanctuary_transit_cleared', 'label': 'Sanctuary transit clearance', 'aliases': ['Wildlife sanctuary transit approval', 'Marine protected area clearance']}]}, {'key': 'ENV-PERM-LS0', 'role': 'Sanctuary compliance officer (ENV)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'sanctuary_transit_cleared', 'label': 'Sanctuary transit clearance', 'aliases': ['Wildlife sanctuary transit approval', 'Marine protected area clearance']}]}, {'key': 'ENV-PERM-K40', 'role': 'Sanctuary compliance officer (ENV)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'sanctuary_transit_cleared', 'label': 'Sanctuary transit clearance', 'aliases': ['Wildlife sanctuary transit approval', 'Marine protected area clearance']}]}, {'key': 'ENG-TECH-ZK3', 'role': 'Marine engineering lead (ENG)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'fuel_bunkering_ready', 'label': 'Fuel bunkering readiness', 'aliases': ['Marine gas oil bunkering readiness', 'Quayside fuel line availability']}, {'id': 'science_payload_allowance', 'label': 'Science equipment payload allowance', 'aliases': ['Scientific instrumentation quota', 'Research gear deck allowance']}]}, {'key': 'ENG-TECH-EPG', 'role': 'Marine engineering lead (ENG)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'fuel_bunkering_ready', 'label': 'Fuel bunkering readiness', 'aliases': ['Marine gas oil bunkering readiness', 'Quayside fuel line availability']}, {'id': 'science_payload_allowance', 'label': 'Science equipment payload allowance', 'aliases': ['Scientific instrumentation quota', 'Research gear deck allowance']}]}, {'key': 'ENG-TECH-7R8', 'role': 'Marine engineering lead (ENG)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'fuel_bunkering_ready', 'label': 'Fuel bunkering readiness', 'aliases': ['Marine gas oil bunkering readiness', 'Quayside fuel line availability']}, {'id': 'science_payload_allowance', 'label': 'Science equipment payload allowance', 'aliases': ['Scientific instrumentation quota', 'Research gear deck allowance']}]}, {'key': 'QMR-GEAR-OCW', 'role': 'Polar expedition quartermaster (QMR)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'survival_payload_allowance', 'label': 'Survival gear payload allowance', 'aliases': ['Polar survival gear allotment', 'Extreme-weather supply allocation']}]}, {'key': 'QMR-GEAR-HV4', 'role': 'Polar expedition quartermaster (QMR)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'survival_payload_allowance', 'label': 'Survival gear payload allowance', 'aliases': ['Polar survival gear allotment', 'Extreme-weather supply allocation']}]}, {'key': 'QMR-GEAR-O71', 'role': 'Polar expedition quartermaster (QMR)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'survival_payload_allowance', 'label': 'Survival gear payload allowance', 'aliases': ['Polar survival gear allotment', 'Extreme-weather supply allocation']}]}, {'key': 'PRT-PORT-C6J', 'role': 'Port infrastructure superintendent (PRT)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'ballast_deadweight_reservation', 'label': 'Ballast deadweight reservation', 'aliases': ['Mandatory sea ballast deduction', 'Minimum trim ballast allocation']}]}, {'key': 'PRT-PORT-8I3', 'role': 'Port infrastructure superintendent (PRT)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'ballast_deadweight_reservation', 'label': 'Ballast deadweight reservation', 'aliases': ['Mandatory sea ballast deduction', 'Minimum trim ballast allocation']}]}, {'key': 'PRT-PORT-75D', 'role': 'Port infrastructure superintendent (PRT)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'ballast_deadweight_reservation', 'label': 'Ballast deadweight reservation', 'aliases': ['Mandatory sea ballast deduction', 'Minimum trim ballast allocation']}]}, {'key': 'STV-CRANE-ARF', 'role': 'Stevedoring superintendent (STV)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'quay_crane_cycle_speed', 'label': 'Quayside crane container cycle rate', 'aliases': ['Crane loading cycle velocity', 'Hourly crane moves']}]}, {'key': 'STV-CRANE-DD4', 'role': 'Stevedoring superintendent (STV)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'quay_crane_cycle_speed', 'label': 'Quayside crane container cycle rate', 'aliases': ['Crane loading cycle velocity', 'Hourly crane moves']}]}, {'key': 'STV-CRANE-GBY', 'role': 'Stevedoring superintendent (STV)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'quay_crane_cycle_speed', 'label': 'Quayside crane container cycle rate', 'aliases': ['Crane loading cycle velocity', 'Hourly crane moves']}]}, {'key': 'LOG-CHILL-0HF', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_expedition_logistics', 'label': 'Deep freeze temperature stability', 'aliases': []}]}, {'key': 'LOG-CHILL-ROP', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_expedition_logistics', 'label': 'Deep freeze temperature stability', 'aliases': []}]}, {'key': 'LOG-CHILL-EIZ', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_expedition_logistics', 'label': 'Deep freeze temperature stability', 'aliases': []}]}, {'key': 'SAF-MED-8IE', 'role': 'Maritime safety officer (SAF)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_marine_safety', 'label': 'Satellite telemedicine bandwidth', 'aliases': []}]}, {'key': 'SAF-MED-UX7', 'role': 'Maritime safety officer (SAF)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_marine_safety', 'label': 'Satellite telemedicine bandwidth', 'aliases': []}]}, {'key': 'SAF-MED-FMA', 'role': 'Maritime safety officer (SAF)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_marine_safety', 'label': 'Satellite telemedicine bandwidth', 'aliases': []}]}, {'key': 'ENV-WASTE-BGE', 'role': 'Sanctuary compliance officer (ENV)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_environmental_compliance', 'label': 'Daily waste processing capacity', 'aliases': []}]}, {'key': 'ENV-WASTE-TXM', 'role': 'Sanctuary compliance officer (ENV)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_environmental_compliance', 'label': 'Daily waste processing capacity', 'aliases': []}]}, {'key': 'ENV-WASTE-4AT', 'role': 'Sanctuary compliance officer (ENV)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_environmental_compliance', 'label': 'Daily waste processing capacity', 'aliases': []}]}, {'key': 'ENG-POWER-X4G', 'role': 'Marine engineering lead (ENG)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_technical_operations', 'label': 'Shore-to-ship power output', 'aliases': []}]}, {'key': 'ENG-POWER-FDI', 'role': 'Marine engineering lead (ENG)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_technical_operations', 'label': 'Shore-to-ship power output', 'aliases': []}]}, {'key': 'ENG-POWER-OOF', 'role': 'Marine engineering lead (ENG)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_technical_operations', 'label': 'Shore-to-ship power output', 'aliases': []}]}, {'key': 'QMR-RATION-FED', 'role': 'Polar expedition quartermaster (QMR)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_polar_quartermaster', 'label': 'Reserve emergency food stores', 'aliases': []}]}, {'key': 'QMR-RATION-Q5B', 'role': 'Polar expedition quartermaster (QMR)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_polar_quartermaster', 'label': 'Reserve emergency food stores', 'aliases': []}]}, {'key': 'QMR-RATION-JFV', 'role': 'Polar expedition quartermaster (QMR)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_polar_quartermaster', 'label': 'Reserve emergency food stores', 'aliases': []}]}, {'key': 'PRT-TUG-FOX', 'role': 'Port infrastructure superintendent (PRT)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_harbour_master', 'label': 'Tug escort bollard pull', 'aliases': []}]}, {'key': 'PRT-TUG-8AO', 'role': 'Port infrastructure superintendent (PRT)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_harbour_master', 'label': 'Tug escort bollard pull', 'aliases': []}]}, {'key': 'PRT-TUG-1XS', 'role': 'Port infrastructure superintendent (PRT)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_harbour_master', 'label': 'Tug escort bollard pull', 'aliases': []}]}, {'key': 'STV-FORK-ROH', 'role': 'Stevedoring superintendent (STV)', 'candidate': 'Kerguelen Marine Research Haven', 'context': '', 'fields': [{'id': 'supplemental_dockside_stevedoring', 'label': 'Operational rough-terrain forklift count', 'aliases': []}]}, {'key': 'STV-FORK-5XC', 'role': 'Stevedoring superintendent (STV)', 'candidate': 'Falkland Sound Support Depot', 'context': '', 'fields': [{'id': 'supplemental_dockside_stevedoring', 'label': 'Operational rough-terrain forklift count', 'aliases': []}]}, {'key': 'STV-FORK-OJI', 'role': 'Stevedoring superintendent (STV)', 'candidate': 'South Georgia Staging Facility', 'context': '', 'fields': [{'id': 'supplemental_dockside_stevedoring', 'label': 'Operational rough-terrain forklift count', 'aliases': []}]}, {'key': 'LOG-STG-AZ6', 'role': 'Expedition logistics coordinator (LOG)', 'candidate': 'Kerguelen Marine Research Haven', 'context': 'simulation test environment', 'fields': [{'id': 'cold_storage_certified', 'label': 'Cold storage certification', 'aliases': ['Specimen cold storage status', 'Refrigerated archive compliance']}, {'id': 'harbor_draft_depth', 'label': 'Harbor draft depth', 'aliases': ['Approach channel draft', 'Quayside water depth']}]}]
|
| 31 |
+
KEY_PATTERN = re.compile(r"^[A-Z]+-[A-Z]+-[A-Z0-9]{3}$")
|
| 32 |
+
REPLY_KEY_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z]+-[A-Z]+-[A-Z0-9]{3}(?![A-Z0-9])", re.IGNORECASE)
|
| 33 |
+
ROLE_REPLY_MAX_ATTEMPTS = 3
|
| 34 |
+
TASK_QUERY = 'Determine whether to Select or Do not select a staging base plan that meets cold storage certification in the operational deployment environment, provides a harbor draft depth of at least 12 m in the operational deployment environment, has a certified emergency evacuation protocol and an on-site shelter endurance of at least 72 h, possesses sanctuary transit clearance, and maintains fuel bunkering readiness, where satisfying these criteria is sufficient for selection without further approval. If an eligible staging base plan qualifies, calculate its net expedition payload capacity by determining the science equipment payload allowance plus survival gear payload allowance minus ballast deadweight reservation (in t). State the selection decision and the resulting net expedition payload capacity.\n\nNumeric calculation rule: Compute only for the unique eligible candidate: ([Science equipment payload allowance] + [Survival gear payload allowance]) - ([Ballast deadweight reservation]). Result unit: t. Round only the final result to 0 decimal places (ties to even). If no candidate qualifies, numeric_result is null.\n\nCandidates and records to verify:\n- South Georgia Staging Facility:LOG-STG-NY3、SAF-SURV-ADP、ENV-PERM-K40、ENG-TECH-7R8、QMR-GEAR-O71、PRT-PORT-75D、STV-CRANE-GBY\n- Kerguelen Marine Research Haven:LOG-STG-2JX、SAF-SURV-F3D、ENV-PERM-M4K、ENG-TECH-ZK3、QMR-GEAR-OCW、PRT-PORT-C6J、STV-CRANE-ARF\n- Falkland Sound Support Depot:LOG-STG-BLI、SAF-SURV-MGB、ENV-PERM-LS0、ENG-TECH-EPG、QMR-GEAR-HV4、PRT-PORT-8I3、STV-CRANE-DD4'
|
| 35 |
+
TASK_CONTEXT = 'In polar research logistics and marine operations, selecting an appropriate staging base plan is vital for safeguarding science personnel, meeting maritime safety standards, and ensuring uninterrupted vessel operations during sub-Antarctic research expeditions. Logistics teams evaluate potential staging base plans against stringent environmental certifications, life-support endurance thresholds, deep-draft access requirements, and marine sanctuary transit clearances before committing expedition resources.'
|
| 36 |
+
|
| 37 |
+
"""Parse one model message without treating trailing generation noise as an action."""
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from typing import Any
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_json_message(content: Any, *, trace: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 44 |
+
if trace is not None:
|
| 45 |
+
trace.clear()
|
| 46 |
+
trace.update(policy="first_complete_object", raw_response=content, recovered=False)
|
| 47 |
+
if not isinstance(content, str):
|
| 48 |
+
raise ValueError("model response must be text")
|
| 49 |
+
text = content.strip().lstrip("\ufeff").strip()
|
| 50 |
+
# Parse the first complete object; never recover a nested fragment.
|
| 51 |
+
try:
|
| 52 |
+
value, end = json.JSONDecoder().raw_decode(text)
|
| 53 |
+
start = 0
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
if text.startswith(("{", "[", '"')):
|
| 56 |
+
raise
|
| 57 |
+
opening = re.search(r"[\{\[]", text)
|
| 58 |
+
if opening is None:
|
| 59 |
+
raise
|
| 60 |
+
start = opening.start()
|
| 61 |
+
value, consumed = json.JSONDecoder().raw_decode(text[start:])
|
| 62 |
+
end = start + consumed
|
| 63 |
+
if not isinstance(value, dict):
|
| 64 |
+
raise ValueError("model response must be a JSON object")
|
| 65 |
+
prefix, suffix = text[:start], text[end:]
|
| 66 |
+
if trace is not None:
|
| 67 |
+
trace.update(recovered=bool(prefix.strip() or suffix.strip()),
|
| 68 |
+
ignored_prefix=prefix, ignored_suffix=suffix)
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def expand_question_keys(questions):
|
| 73 |
+
expanded = []
|
| 74 |
+
for question in questions:
|
| 75 |
+
if not isinstance(question, dict):
|
| 76 |
+
expanded.append(question)
|
| 77 |
+
continue
|
| 78 |
+
text = question.get("question")
|
| 79 |
+
keys = list(dict.fromkeys(REPLY_KEY_PATTERN.findall(text))) if isinstance(text, str) else []
|
| 80 |
+
for key in keys or [None]:
|
| 81 |
+
expanded.append(dict(question, key=key))
|
| 82 |
+
return expanded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def validate_question(question, *, role_name, semantic_enabled=False):
|
| 86 |
+
if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
|
| 87 |
+
raise ValueError("question must contain natural-language text")
|
| 88 |
+
if role_name not in ROLE_KEY_PREFIXES:
|
| 89 |
+
raise ValueError("unknown Role")
|
| 90 |
+
key = question.get("key")
|
| 91 |
+
authorized = semantic_enabled if key is None else (
|
| 92 |
+
isinstance(key, str) and key in ROLE_VALID_KEYS[role_name] and key in question["question"])
|
| 93 |
+
return {"authorized": bool(authorized)}
|
| 94 |
+
|
| 95 |
+
def recovery_key_match(answer: str) -> str | None:
|
| 96 |
+
target = ERROR_INJECTION.get("target_key")
|
| 97 |
+
if not target:
|
| 98 |
+
return None
|
| 99 |
+
def contains(key: str) -> bool:
|
| 100 |
+
return bool(re.search(r"(?<![A-Z0-9-])" + re.escape(key) + r"(?![A-Z0-9-])", answer, re.IGNORECASE))
|
| 101 |
+
if contains(target):
|
| 102 |
+
return "full_key"
|
| 103 |
+
parts = target.split("-")
|
| 104 |
+
alias = parts[0] + "-" + parts[-1]
|
| 105 |
+
matches = [key for key in ROLE_VALID_KEYS.get(ERROR_INJECTION.get("role_name"), [])
|
| 106 |
+
if key.split("-")[0] + "-" + key.split("-")[-1] == alias]
|
| 107 |
+
if matches == [target] and contains(alias):
|
| 108 |
+
return "abbreviated_key"
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
def communication_metrics(transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 112 |
+
key_query_rounds: dict[str, int] = {}
|
| 113 |
+
key_query_counts: dict[str, int] = {}
|
| 114 |
+
queried_roles: set[str] = set()
|
| 115 |
+
mismatch_round: int | None = None
|
| 116 |
+
recovery_query_sent = False
|
| 117 |
+
recovery_query_turn: int | None = None
|
| 118 |
+
target_key_returned = False
|
| 119 |
+
recovery_turn: int | None = None
|
| 120 |
+
recovery_method: str | None = None
|
| 121 |
+
recovery_reference: str | None = None
|
| 122 |
+
target_key_query_turn: int | None = None
|
| 123 |
+
finalized_before_recovery = False
|
| 124 |
+
for event in transcript:
|
| 125 |
+
turn = int(event.get("turn", len(transcript)))
|
| 126 |
+
action = event.get("main_agent_action", {})
|
| 127 |
+
if (
|
| 128 |
+
ERROR_INJECTION.get("enabled")
|
| 129 |
+
and action.get("action") == "finalize"
|
| 130 |
+
and not target_key_returned
|
| 131 |
+
):
|
| 132 |
+
finalized_before_recovery = True
|
| 133 |
+
if action.get("action") != "ask_role_agents": continue
|
| 134 |
+
for answer in event.get("role_answers", []):
|
| 135 |
+
role_name = answer.get("role_agent")
|
| 136 |
+
if role_name: queried_roles.add(role_name)
|
| 137 |
+
if (
|
| 138 |
+
ERROR_INJECTION.get("enabled") and mismatch_round is not None and turn > mismatch_round
|
| 139 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 140 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("target_key")
|
| 141 |
+
and "role_trace" in answer
|
| 142 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 143 |
+
):
|
| 144 |
+
target_key_query_turn = target_key_query_turn or turn
|
| 145 |
+
if (
|
| 146 |
+
ERROR_INJECTION.get("enabled")
|
| 147 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 148 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("alternate_key")
|
| 149 |
+
and "role_trace" in answer
|
| 150 |
+
):
|
| 151 |
+
mismatch_round = mismatch_round or turn
|
| 152 |
+
for message in action.get("messages", []):
|
| 153 |
+
for question in message.get("questions", []):
|
| 154 |
+
key = question.get("key")
|
| 155 |
+
if (
|
| 156 |
+
ERROR_INJECTION.get("enabled")
|
| 157 |
+
and resolve_role_name(message.get("role_agent")) == ERROR_INJECTION.get("role_name")
|
| 158 |
+
and (key is None or key == ERROR_INJECTION.get("target_key"))
|
| 159 |
+
and mismatch_round is not None
|
| 160 |
+
and turn > mismatch_round
|
| 161 |
+
):
|
| 162 |
+
recovery_query_sent = True
|
| 163 |
+
recovery_query_turn = recovery_query_turn or turn
|
| 164 |
+
if not isinstance(key, str) or not KEY_PATTERN.fullmatch(key): continue
|
| 165 |
+
key_query_rounds.setdefault(key, turn)
|
| 166 |
+
key_query_counts[key] = key_query_counts.get(key, 0) + 1
|
| 167 |
+
if recovery_query_sent and not target_key_returned and mismatch_round is not None and turn > mismatch_round:
|
| 168 |
+
for answer in event.get("role_answers", []):
|
| 169 |
+
question = answer.get("question", {})
|
| 170 |
+
if (
|
| 171 |
+
answer.get("role_agent") == ERROR_INJECTION.get("role_name")
|
| 172 |
+
and (question.get("key") is None or question.get("key") == ERROR_INJECTION.get("target_key"))
|
| 173 |
+
and "role_trace" in answer
|
| 174 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 175 |
+
):
|
| 176 |
+
target_key_returned = True
|
| 177 |
+
recovery_reference = recovery_key_match(str(answer.get("answer", "")))
|
| 178 |
+
recovery_turn = turn
|
| 179 |
+
recovery_method = "keyless_query" if question.get("key") is None else "target_key_query"
|
| 180 |
+
break
|
| 181 |
+
queried = set(key_query_counts)
|
| 182 |
+
required = set(REQUIRED_KEYS)
|
| 183 |
+
relevant = queried & required
|
| 184 |
+
return {
|
| 185 |
+
"required_key_recall":len(relevant)/len(required) if required else 1.0,
|
| 186 |
+
"required_key_precision":len(relevant)/len(queried) if queried else 0.0,
|
| 187 |
+
"key_query_rounds":key_query_rounds,
|
| 188 |
+
"key_query_counts":key_query_counts,
|
| 189 |
+
"duplicate_key_queries":sum(max(0, count-1) for count in key_query_counts.values()),
|
| 190 |
+
"distractor_key_queries":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS),
|
| 191 |
+
"distractor_key_query_rate":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS)/sum(key_query_counts.values()) if key_query_counts else 0.0,
|
| 192 |
+
"turns_to_finalize":len(transcript),
|
| 193 |
+
"mismatch_key_queried":mismatch_round is not None,
|
| 194 |
+
"mismatch_key_turn":mismatch_round,
|
| 195 |
+
"recovery_query_sent":recovery_query_sent,
|
| 196 |
+
"recovery_query_turn":recovery_query_turn,
|
| 197 |
+
"target_key_returned":target_key_returned,
|
| 198 |
+
"recovery_turn":recovery_turn,
|
| 199 |
+
"recovery_method":recovery_method,
|
| 200 |
+
"target_key_query_turn":target_key_query_turn,
|
| 201 |
+
"recovery_key_match":recovery_reference,
|
| 202 |
+
"recovery_metrics_version":"keyed_and_keyless_v3",
|
| 203 |
+
"recovery_latency":recovery_turn - mismatch_round if recovery_turn is not None and mismatch_round is not None else None,
|
| 204 |
+
"finalized_before_recovery":finalized_before_recovery,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
def main_system_prompt() -> str:
|
| 208 |
+
role_text = "\n".join(f"- {item['role_name']}: {item['responsibility']}" for item in PUBLIC_ROLES)
|
| 209 |
+
ask_example = json.dumps({"action":"ask_role_agents","messages":[{"role_agent":"Role name","questions":[{"id":"Q1","question":"Please provide the record for ABC-DATA-A1B using the supplied key."}]}]}, ensure_ascii=False)
|
| 210 |
+
final_example = json.dumps({"action":"finalize","conclusion":"Exactly: " + POSITIVE_CONCLUSION + " or " + NEGATIVE_CONCLUSION,"numeric_result":None}, ensure_ascii=False).replace('"numeric_result": null', '"numeric_result": null/number')
|
| 211 |
+
communication_protocol = ('You may output {"action":"wait"} to advance one logical turn. An empty observation {"observations":[]} means no new visible messages; it does not imply receipt, processing or any future reply.' if SETTING in {'missed', 'mixed'} else '')
|
| 212 |
+
followup = ('For keyless follow-ups, name the candidate in full and the metric explicitly, or request that candidate\'s complete records. A unique previously queried record can be checked directly; otherwise supply a full key and metric when asked to clarify. Explicit directory requests return the complete directory.' if SETTING == 'incomplete' else
|
| 213 |
+
'Authorized keyless follow-ups may name the candidate and metric or request complete records. A role may retrieve facts, request clarification or return a directory. If given a directory, select a valid key to obtain facts.' if SETTING == 'mixed' else
|
| 214 |
+
'Authorized keyless questions return that role\'s complete directory. Choose a key from the directory to obtain concrete facts.')
|
| 215 |
+
return "\n\n".join([
|
| 216 |
+
'You are the Main Agent. Integrate information from independent role agents and make the final decision. Communicate in English.',
|
| 217 |
+
'You cannot see private role information directly. Obtain it only by explicitly messaging the role agents.',
|
| 218 |
+
'Key protocol:\n1. Candidate names and record keys are supplied in the task. Initial access requires a valid key; authorized later follow-ups are the exception.\n'
|
| 219 |
+
'2. Keys use ROLE-BUSINESS-XXX: role abbreviation, business abbreviation and three random alphanumeric characters. Use complete supplied keys; do not invent them.\n'
|
| 220 |
+
'3. Send each key to its owning business role. Use valid keys supplied by roles for subsequent checks.\n'
|
| 221 |
+
'4. Do not output a separate key field. Put the complete key in question text; the system extracts it and checks ownership. Separate different keys into individual questions, preferably one record per question.\n'
|
| 222 |
+
'5. After a successful keyed query to a role, keyless natural-language follow-ups to that role are authorized starting from the next turn.\n6. ' + followup,
|
| 223 |
+
'Available independent role agents:\n\n' + role_text,
|
| 224 |
+
'To ask questions, output only JSON in this form:\n\n' + ask_example,
|
| 225 |
+
*([communication_protocol] if communication_protocol else []),
|
| 226 |
+
'Final answer format (output only valid JSON):\n\n' + final_example,
|
| 227 |
+
'Use exactly one of these conclusion labels: ' + POSITIVE_CONCLUSION + ' or ' + NEGATIVE_CONCLUSION + '. '
|
| 228 |
+
'Do not append a candidate name, explanation or other text. null/number means choose one, not literal syntax. '
|
| 229 |
+
'For a positive conclusion provide the computed number; for a negative conclusion use null. Do not include units or explanations in numeric_result.',
|
| 230 |
+
])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
"""Conservative English evidence rules shared by standalone generated runtimes.
|
| 234 |
+
|
| 235 |
+
This is attribution of explicit statements, not arbitrary semantic entailment.
|
| 236 |
+
Unsupported or conflicting statements remain unknown; no model calls are made.
|
| 237 |
+
"""
|
| 238 |
+
import re
|
| 239 |
+
from decimal import Decimal
|
| 240 |
+
|
| 241 |
+
_RECOVERY_NUMBER = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?'
|
| 242 |
+
_RECOVERY_UNCERTAIN = r"\b(?:unknown|uncertain|unclear|may|might|could|should|would|must|expected|possibly|whether|cannot|unable|unconfirmed|approximately|about|around|roughly|estimated|not confirmed|not known|not established)\b"
|
| 243 |
+
_RECOVERY_NEGATIVE = r'\b(?:not|no|never|false|invalid|blocked|failed|denied|unavailable|unapproved|revoked|inactive|disabled|noncompliant)\b'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def evidence_text(text):
|
| 247 |
+
text = text.replace('’', "'").replace('−', '-').replace('‑', '-')
|
| 248 |
+
text = re.sub(r"\bcan't\b", 'cannot', text, flags=re.I)
|
| 249 |
+
text = re.sub(r"n't\b", ' not', text, flags=re.I)
|
| 250 |
+
text = re.sub(r'(?<![\w.,])[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,]|\.\d)',
|
| 251 |
+
lambda m: m[0].replace(',', ''), text)
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def evidence_phrase(text, phrase):
|
| 256 |
+
if not phrase:
|
| 257 |
+
return False
|
| 258 |
+
return bool(re.search(r'(?<!\w)' + re.escape(phrase).replace(r'\ ', r'\s+') + r'(?!\w)', text, re.I))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def evidence_nonasserted(text):
|
| 262 |
+
"""Questions, hypotheses and unconfirmed claims are not returned facts."""
|
| 263 |
+
return bool('?' in text or re.search(_RECOVERY_UNCERTAIN, text, re.I)
|
| 264 |
+
or re.search(r'\b(?:if|unless|assuming|suppose|supposing|hypothetically)\b', text, re.I)
|
| 265 |
+
or re.search(r'\b(?:do|does|did|has|have|had)\s+not\s+(?:confirm|verify|establish)(?:ed)?\b', text, re.I))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def evidence_clauses(text):
|
| 269 |
+
# Preserve questions and uncertainty when splitting assertions.
|
| 270 |
+
sentences = re.split(r'[。\n]|\.(?!\d)|(?<=[!?])\s+', text)
|
| 271 |
+
clauses = []
|
| 272 |
+
for sentence in sentences:
|
| 273 |
+
if evidence_nonasserted(sentence):
|
| 274 |
+
clauses.append(sentence)
|
| 275 |
+
else:
|
| 276 |
+
clauses.extend(re.split(r'[;;]|,?\s+\b(?:but|and)\b\s+(?![+-]?\d)', sentence, flags=re.I))
|
| 277 |
+
return clauses
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def evidence_scope(answer, question, profile):
|
| 281 |
+
for target in [profile.get('candidate', ''), profile.get('target_context', '')]:
|
| 282 |
+
if target and re.search(r'\b(?:not|outside|excluding|except)(?:\s+(?:for|the))?\s+' + re.escape(target) + r'(?!\w)', answer, re.I):
|
| 283 |
+
return 'not_returned'
|
| 284 |
+
candidates = profile.get('other_candidates', [])
|
| 285 |
+
contexts = profile.get('other_contexts', [profile.get('alternate_context', '')])
|
| 286 |
+
if any(evidence_phrase(answer, c) for c in [*candidates, *contexts] if c):
|
| 287 |
+
target_also_present = evidence_phrase(answer, profile.get('candidate', '')) and (
|
| 288 |
+
not profile.get('target_context') or evidence_phrase(answer, profile['target_context']))
|
| 289 |
+
return 'unknown' if target_also_present else 'not_returned'
|
| 290 |
+
combined = question.get('question', '') + '\n' + answer
|
| 291 |
+
target_key = profile.get('target_key', '')
|
| 292 |
+
if target_key and (question.get('key') == target_key or evidence_phrase(combined, target_key)):
|
| 293 |
+
return 'eligible'
|
| 294 |
+
if evidence_phrase(combined, profile.get('candidate', '')) and (
|
| 295 |
+
not profile.get('target_context') or evidence_phrase(combined, profile['target_context'])):
|
| 296 |
+
return 'eligible'
|
| 297 |
+
return 'unknown'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def evidence_unit_pattern(unit):
|
| 301 |
+
# Unit names may inflect; canonical symbols remain case-sensitive.
|
| 302 |
+
groups = [('h', 'hour', 'hours'), ('min', 'minute', 'minutes'), ('s', 'second', 'seconds'),
|
| 303 |
+
('kg', 'kilogram', 'kilograms'), ('m', 'meter', 'meters', 'metre', 'metres'),
|
| 304 |
+
('%', 'percent', 'per cent'), ('instances', 'instance'), ('items', 'item'),
|
| 305 |
+
('people', 'person', 'persons'), ('days', 'day')]
|
| 306 |
+
for group in groups:
|
| 307 |
+
if unit in group:
|
| 308 |
+
canonical, *words = group
|
| 309 |
+
if canonical in {'instances', 'items', 'people', 'days'}:
|
| 310 |
+
words.append(canonical)
|
| 311 |
+
canonical = None
|
| 312 |
+
parts = ([re.escape(canonical)] if canonical else []) + ['(?i:' + re.escape(w) + ')' for w in words]
|
| 313 |
+
if unit == '%': parts.append('%')
|
| 314 |
+
return '(?:' + '|'.join(sorted(parts, key=len, reverse=True)) + ')'
|
| 315 |
+
return re.escape(unit)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evidence_measurements(text, unit):
|
| 319 |
+
text = evidence_text(text)
|
| 320 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 321 |
+
suffix = (r'(?:\s+(?:1|(?i:dimensionless)))?' if unit == '1'
|
| 322 |
+
else r'\s*' + evidence_unit_pattern(unit))
|
| 323 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')' + suffix + r'(?![A-Za-z0-9_/%]|\.\d|,\d)'
|
| 324 |
+
return text, list(re.finditer(pattern, text))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def evidence_exact_measurement(text, match):
|
| 328 |
+
before, after = text[max(0, match.start()-60):match.start()], text[match.end():match.end()+45]
|
| 329 |
+
if evidence_nonasserted(text):
|
| 330 |
+
return False
|
| 331 |
+
if re.search(r'(?:\b(?:under|over|below|above|less than|more than|at most|at least|up to|between|to|and|not|no more than|no less than)|不超过|不低于|小于等于|大于等于|小于|大于|至少|至多|最多|最少|低于|高于|介于|至|到|[<>≤≥~~–—])\s*$', before, re.I):
|
| 332 |
+
return False
|
| 333 |
+
if re.search(r'\d\s*[-–—]\s*$', before):
|
| 334 |
+
return False
|
| 335 |
+
if re.match(r'\s*(?:\b(?:maximum|minimum|max|min)\b|\bor (?:less|more|lower|higher)\b|\b(?:to|through)\s+[+-]?\d|[-–—~~]\s*\d)', after, re.I):
|
| 336 |
+
return False
|
| 337 |
+
return True
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def english_exact_value(answer, value, unit):
|
| 341 |
+
for clause in evidence_clauses(evidence_text(answer)):
|
| 342 |
+
text, matches = evidence_measurements(clause, unit)
|
| 343 |
+
if any(Decimal(m[1]) == Decimal(str(value)) and evidence_exact_measurement(text, m) for m in matches):
|
| 344 |
+
return True
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def numeric_evidence(answer, question, profile, fact):
|
| 349 |
+
answer = evidence_text(answer)
|
| 350 |
+
scope = evidence_scope(answer, question, profile)
|
| 351 |
+
if scope != 'eligible':
|
| 352 |
+
return scope
|
| 353 |
+
labels = [fact.get('label', ''), *fact.get('aliases', [])]
|
| 354 |
+
states = set()
|
| 355 |
+
for clause in evidence_clauses(answer):
|
| 356 |
+
# Bind each value to its asserted metric; nearby numbers are not evidence.
|
| 357 |
+
if not any(evidence_phrase(clause, label) for label in labels if label):
|
| 358 |
+
continue
|
| 359 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 360 |
+
continue
|
| 361 |
+
# Leave ambiguous multi-metric clauses unscored.
|
| 362 |
+
others = profile.get('facts', profile.get('numeric', []) + profile.get('boolean', []))
|
| 363 |
+
if any(other.get('topic') != fact.get('topic') and any(evidence_phrase(clause, label) for label in
|
| 364 |
+
[other.get('label', ''), *other.get('aliases', [])] if label) for other in others):
|
| 365 |
+
continue
|
| 366 |
+
text, matches = evidence_measurements(clause, fact.get('unit', ''))
|
| 367 |
+
for m in matches:
|
| 368 |
+
if evidence_exact_measurement(text, m) and not re.search(_RECOVERY_NEGATIVE, text[:m.start()], re.I):
|
| 369 |
+
states.add(Decimal(m[1]) == Decimal(str(fact['value'])))
|
| 370 |
+
if len(states) != 1:
|
| 371 |
+
return 'unknown'
|
| 372 |
+
return 'returned' if states.pop() else 'not_returned'
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _evidence_predicate(text):
|
| 376 |
+
text = re.sub(r'\b(?:is|are|was|were|has|have|had|been|the|a|an|already)\b', ' ', text.casefold())
|
| 377 |
+
return re.sub(r'\s+', ' ', text).strip(' .:')
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def boolean_evidence(answer, question, profile):
|
| 381 |
+
answer = evidence_text(answer)
|
| 382 |
+
scope = evidence_scope(answer, question, profile)
|
| 383 |
+
if scope != 'eligible':
|
| 384 |
+
return scope
|
| 385 |
+
labels = [profile['label'], *profile.get('aliases', [])]
|
| 386 |
+
states = set()
|
| 387 |
+
for clause in evidence_clauses(answer):
|
| 388 |
+
plain = _evidence_predicate(clause)
|
| 389 |
+
no_negative = _evidence_predicate(re.sub(_RECOVERY_NEGATIVE, ' ', clause, flags=re.I))
|
| 390 |
+
if not any(evidence_phrase(plain, _evidence_predicate(label)) or evidence_phrase(no_negative, _evidence_predicate(label)) for label in labels if label):
|
| 391 |
+
continue
|
| 392 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 393 |
+
continue
|
| 394 |
+
remainder = clause
|
| 395 |
+
for label in sorted(labels, key=len, reverse=True):
|
| 396 |
+
remainder = re.sub(re.escape(label), '', remainder, flags=re.I)
|
| 397 |
+
negative = bool(re.search(_RECOVERY_NEGATIVE, remainder, re.I))
|
| 398 |
+
explicit = bool(re.search(r'\b(?:true|yes|false|no)\b', remainder, re.I))
|
| 399 |
+
predicate = r'\b(?:enabled|issued|approved|valid|clear|ready|open|active|completed|available|installed|registered|signed|granted|confirmed|operational|compliant|meets|passed|released|equipped|connected|running|accepted)\b'
|
| 400 |
+
affirmative = evidence_phrase(no_negative, _evidence_predicate(profile['label'])) and bool(re.search(predicate, profile['label'], re.I))
|
| 401 |
+
label_match = evidence_phrase(no_negative, _evidence_predicate(profile['label']))
|
| 402 |
+
# Do not transfer negation between unrelated metrics.
|
| 403 |
+
opposites = {'disabled':'enabled', 'unavailable':'available', 'invalid':'valid',
|
| 404 |
+
'closed':'open', 'inactive':'active', 'blocked':'clear', 'revoked':'granted'}
|
| 405 |
+
opposite = False
|
| 406 |
+
for denied, affirmed in opposites.items():
|
| 407 |
+
if re.search(r'\b' + denied + r'\b', clause, re.I):
|
| 408 |
+
rewritten = re.sub(r'\b' + denied + r'\b', affirmed, clause, flags=re.I)
|
| 409 |
+
opposite |= evidence_phrase(_evidence_predicate(rewritten), _evidence_predicate(profile['label']))
|
| 410 |
+
bare_boolean = bool(explicit and re.fullmatch(r'(?:status\s*[:=]?\s*)?(?:true|yes|false|no)',
|
| 411 |
+
_evidence_predicate(remainder), re.I))
|
| 412 |
+
if affirmative or label_match and (negative or explicit) or opposite or bare_boolean:
|
| 413 |
+
states.add(not (negative or opposite))
|
| 414 |
+
if len(states) != 1:
|
| 415 |
+
return 'unknown'
|
| 416 |
+
return 'returned' if states.pop() == profile['value'] else 'not_returned'
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def recovery_number_present(answer, value):
|
| 420 |
+
"""Literal numeric occurrence, independent of unit, metric, scope or wording."""
|
| 421 |
+
text = re.sub(r'(?<![A-Z0-9])[A-Z]{2,10}-[A-Z]{2,10}-[A-Z0-9]{3}(?![A-Z0-9])', '', answer, flags=re.I)
|
| 422 |
+
text = evidence_text(text)
|
| 423 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 424 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')(?![0-9_]|\.\d|,\d)'
|
| 425 |
+
return any(Decimal(m[1]) == Decimal(str(value)) for m in re.finditer(pattern, text))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
import os
|
| 431 |
+
import random
|
| 432 |
+
from datetime import datetime
|
| 433 |
+
from pathlib import Path
|
| 434 |
+
from typing import Dict, List
|
| 435 |
+
|
| 436 |
+
from openai import OpenAI
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_project_env() -> None:
|
| 440 |
+
for parent in Path(__file__).resolve().parents:
|
| 441 |
+
env_path = parent / ".env"
|
| 442 |
+
if not env_path.is_file():
|
| 443 |
+
continue
|
| 444 |
+
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
| 445 |
+
line = raw_line.strip()
|
| 446 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 447 |
+
continue
|
| 448 |
+
key, value = line.split("=", 1)
|
| 449 |
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
load_project_env()
|
| 454 |
+
MAIN_AGENT_API_KEY = os.getenv("MAIN_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 455 |
+
MAIN_AGENT_MODEL_NAME = os.getenv("MAIN_AGENT_MODEL_NAME", "openai/gpt-5.5")
|
| 456 |
+
MAIN_AGENT_BASE_URL = os.getenv("MAIN_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 457 |
+
ROLE_AGENT_API_KEY = os.getenv("ROLE_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 458 |
+
ROLE_AGENT_MODEL_NAME = "deepseek/deepseek-v4-flash-0731"
|
| 459 |
+
ROLE_AGENT_BASE_URL = os.getenv("ROLE_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 460 |
+
LLM_REASONING_EFFORT = os.getenv("LLM_REASONING_EFFORT", "medium")
|
| 461 |
+
ROLE_REASONING_EFFORT = "low"
|
| 462 |
+
ROLE_MAX_TOKENS = 8192
|
| 463 |
+
LLM_REASONING_EXCLUDE = os.getenv("LLM_REASONING_EXCLUDE", "1") != "0"
|
| 464 |
+
MAIN_AGENT_ROLE_ORDER_SEED = os.getenv("MAIN_AGENT_ROLE_ORDER_SEED")
|
| 465 |
+
AGENT_DIR = str(Path(__file__).resolve().parent.parent / "role_agents")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def print_key_trace(title: str, content: Any = "") -> None:
|
| 469 |
+
print(f"\n========== {title} ==========\n", flush=True)
|
| 470 |
+
if content != "":
|
| 471 |
+
print(str(content), flush=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def format_metric_value(value: Any) -> str:
|
| 475 |
+
if isinstance(value, float):
|
| 476 |
+
return f"{value:.4f}"
|
| 477 |
+
if value is None:
|
| 478 |
+
return "None"
|
| 479 |
+
return str(value)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def format_llm_config() -> str:
|
| 483 |
+
return "\n".join([
|
| 484 |
+
f"main_agent_llm: {MAIN_AGENT_MODEL_NAME}",
|
| 485 |
+
f"role_agent_llm: {ROLE_AGENT_MODEL_NAME}",
|
| 486 |
+
f"reasoning_effort: {LLM_REASONING_EFFORT}",
|
| 487 |
+
f"role_reasoning_effort: {ROLE_REASONING_EFFORT}",
|
| 488 |
+
])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def format_available_roles(role_agents: Dict[str, Any]) -> str:
|
| 492 |
+
lines = []
|
| 493 |
+
for role_name, role in role_agents.items():
|
| 494 |
+
key_prefix = ROLE_KEY_PREFIXES.get(role_name, "")
|
| 495 |
+
lines.append(f"- {role_name}(Key 格式:{key_prefix}业务缩写-XXX):{role.config['abstract']}")
|
| 496 |
+
return "\n".join(lines)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def format_evaluation_summary(evaluation: Dict[str, Any]) -> str:
|
| 500 |
+
conclusion = evaluation.get("conclusion_evaluation", {})
|
| 501 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 502 |
+
fields = [
|
| 503 |
+
("ground_truth_conclusion", conclusion.get("ground_truth_conclusion")),
|
| 504 |
+
("ground_truth_numeric_result", conclusion.get("ground_truth_numeric_result")),
|
| 505 |
+
("final_conclusion", conclusion.get("final_conclusion")),
|
| 506 |
+
("parsed_numeric_result", conclusion.get("parsed_numeric_result")),
|
| 507 |
+
("conclusion_correct", conclusion.get("conclusion_correct")),
|
| 508 |
+
("numeric_result_correct", conclusion.get("numeric_result_correct")),
|
| 509 |
+
("turns_to_finalize", communication.get("turns_to_finalize")),
|
| 510 |
+
("total_role_agent_queries", communication.get("total_role_agent_queries")),
|
| 511 |
+
("total_questions", communication.get("total_questions")),
|
| 512 |
+
("duplicate_key_queries", communication.get("duplicate_key_queries")),
|
| 513 |
+
]
|
| 514 |
+
return "\n".join(f"{name}: {format_metric_value(value)}" for name, value in fields)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def format_key_metrics(evaluation: Dict[str, Any]) -> str:
|
| 518 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 519 |
+
correctness = int(bool(evaluation.get("joint_correctness")))
|
| 520 |
+
turns = communication.get("turns_to_finalize")
|
| 521 |
+
lines = [
|
| 522 |
+
f"正确率: {correctness}",
|
| 523 |
+
f"完成轮数: {format_metric_value(turns)} / {communication.get('max_turns', DEFAULT_MAX_TURNS)}(理想:{communication.get('finalize_ideal_round', FINALIZE_IDEAL_ROUND)})",
|
| 524 |
+
]
|
| 525 |
+
if SETTING in {"incomplete", "mixed"}:
|
| 526 |
+
lines.append(f"阈值补齐: {communication.get('incomplete_threshold_returned', False)};补齐轮次: {communication.get('incomplete_recovery_turn')};补救成功: {communication.get('incomplete_recovery_success')}")
|
| 527 |
+
if SETTING in {"missed", "mixed"}:
|
| 528 |
+
lines.append(f"忽略: {communication.get('neglect_ignored_count', 0)};交付: {communication.get('neglect_delivered_count', 0)};待答: {communication.get('neglect_pending_count', 0)}")
|
| 529 |
+
if SETTING not in {"misaligned", "mixed"}:
|
| 530 |
+
return "\n".join(lines)
|
| 531 |
+
|
| 532 |
+
if communication.get("error_recovery_status") == "unknown":
|
| 533 |
+
lines.append("Recovery result: UNKNOWN (evidence cannot be classified; excluded from recovery rates)")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
+
|
| 536 |
+
mismatch_queried = bool(communication.get("mismatch_key_queried"))
|
| 537 |
+
mismatch_turn = communication.get("mismatch_key_turn")
|
| 538 |
+
recovery_query_sent = bool(communication.get("recovery_query_sent"))
|
| 539 |
+
recovery_query_turn = communication.get("recovery_query_turn")
|
| 540 |
+
target_key_returned = bool(communication.get("error_fact_returned", communication.get("target_key_returned")))
|
| 541 |
+
recovery_turn = communication.get("recovery_turn")
|
| 542 |
+
finalized_early = bool(communication.get("finalized_before_recovery"))
|
| 543 |
+
|
| 544 |
+
def turn_suffix(turn: Any) -> str:
|
| 545 |
+
return f"(第{turn}轮)" if isinstance(turn, int) else ""
|
| 546 |
+
|
| 547 |
+
lines.extend(["", "恢复链路:"])
|
| 548 |
+
if not mismatch_queried:
|
| 549 |
+
lines.extend([
|
| 550 |
+
f"✗ 未访问错配 key:{ERROR_INJECTION.get('alternate_key')}",
|
| 551 |
+
"— 未触发补救询问",
|
| 552 |
+
"— Role 未返回目标 key",
|
| 553 |
+
"— 未进入恢复流程",
|
| 554 |
+
"",
|
| 555 |
+
"恢复延迟:N/A",
|
| 556 |
+
"恢复结果:NOT_TRIGGERED(Main 未访问错配 key)",
|
| 557 |
+
])
|
| 558 |
+
return "\n".join(lines)
|
| 559 |
+
|
| 560 |
+
lines.append(
|
| 561 |
+
f"✓ 已访问错配 key:{ERROR_INJECTION.get('alternate_key')}{turn_suffix(mismatch_turn)}"
|
| 562 |
+
)
|
| 563 |
+
lines.append(
|
| 564 |
+
("✓ 已发起补救询问" if recovery_query_sent else "✗ 未发起补救询问")
|
| 565 |
+
+ turn_suffix(recovery_query_turn)
|
| 566 |
+
)
|
| 567 |
+
lines.append(
|
| 568 |
+
(
|
| 569 |
+
f"✓ Role 已返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 570 |
+
if target_key_returned
|
| 571 |
+
else f"✗ Role 未返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 572 |
+
)
|
| 573 |
+
+ turn_suffix(recovery_turn)
|
| 574 |
+
)
|
| 575 |
+
lines.append("✗ 已在恢复前提前 finalize" if finalized_early else "✓ 未在恢复前提前 finalize")
|
| 576 |
+
if target_key_returned:
|
| 577 |
+
lines.append("✓ 恢复后最终答案正确" if correctness else "✗ 恢复后最终答案错误")
|
| 578 |
+
else:
|
| 579 |
+
lines.append("— 尚未完成恢复,无法判断恢复后答案")
|
| 580 |
+
|
| 581 |
+
recovery_latency = communication.get("recovery_latency")
|
| 582 |
+
recovery_method = communication.get("recovery_method")
|
| 583 |
+
if recovery_method:
|
| 584 |
+
target_query_turn = communication.get("target_key_query_turn")
|
| 585 |
+
if recovery_method == "keyless_query" and isinstance(target_query_turn, int) and isinstance(recovery_turn, int) and target_query_turn > recovery_turn:
|
| 586 |
+
method_label = "无 key 获取目录 → 正确 key 查询"
|
| 587 |
+
lines.append(f"取得目标 key:第{recovery_turn}轮")
|
| 588 |
+
lines.append(f"正确 key 查询取得答复:第{target_query_turn}轮")
|
| 589 |
+
recovery_latency = target_query_turn - mismatch_turn if isinstance(mismatch_turn, int) else recovery_latency
|
| 590 |
+
else:
|
| 591 |
+
method_label = {"keyless_query": "无 key 补充询问", "target_key_query": "目标 key 纠正查询"}.get(recovery_method, recovery_method)
|
| 592 |
+
lines.append(f"补救方式:{method_label}")
|
| 593 |
+
if communication.get("recovery_success"):
|
| 594 |
+
status = "SUCCESS"
|
| 595 |
+
elif finalized_early:
|
| 596 |
+
status = "FINALIZED_EARLY"
|
| 597 |
+
elif not recovery_query_sent:
|
| 598 |
+
status = "RECOVERY_NOT_REQUESTED"
|
| 599 |
+
elif not target_key_returned:
|
| 600 |
+
status = "TARGET_NOT_RETURNED"
|
| 601 |
+
else:
|
| 602 |
+
status = "RECOVERED_BUT_WRONG"
|
| 603 |
+
lines.extend([
|
| 604 |
+
"",
|
| 605 |
+
f"恢复延迟:{recovery_latency}轮" if isinstance(recovery_latency, int) else "恢复延迟:N/A",
|
| 606 |
+
f"恢复结果:{status}",
|
| 607 |
+
])
|
| 608 |
+
return "\n".join(lines)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def format_role_messages(action: Dict[str, Any], role_answers: List[Dict[str, Any]]) -> str:
|
| 612 |
+
requested = {
|
| 613 |
+
(message.get("role_agent"), question.get("id"), question.get("key")): question.get("question")
|
| 614 |
+
for message in action.get("messages", [])
|
| 615 |
+
for question in message.get("questions", [])
|
| 616 |
+
}
|
| 617 |
+
blocks = []
|
| 618 |
+
for item in role_answers:
|
| 619 |
+
question = item.get("question", {})
|
| 620 |
+
identity = (item.get("role_agent"), question.get("id"), question.get("key"))
|
| 621 |
+
blocks.append("\n".join([
|
| 622 |
+
f"role_agent: {item.get('role_agent')}",
|
| 623 |
+
f"question_id: {question.get('id')}",
|
| 624 |
+
f"key: {question.get('key')}",
|
| 625 |
+
f"question: {requested.get(identity, question.get('question'))}",
|
| 626 |
+
f"answer: {item.get('answer')}",
|
| 627 |
+
]))
|
| 628 |
+
return "\n\n".join(blocks)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def parse_numeric_result(value: Any) -> int | float | None:
|
| 632 |
+
if value is None or isinstance(value, bool):
|
| 633 |
+
return None
|
| 634 |
+
if isinstance(value, (int, float)):
|
| 635 |
+
number = float(value)
|
| 636 |
+
elif isinstance(value, str):
|
| 637 |
+
match = re.search(r"[-+]?\d+(?:\.\d+)?", value.strip())
|
| 638 |
+
if not match:
|
| 639 |
+
return None
|
| 640 |
+
number = float(match.group(0))
|
| 641 |
+
else:
|
| 642 |
+
return None
|
| 643 |
+
rounded = round(number, NUMERIC_PRECISION)
|
| 644 |
+
return int(rounded) if NUMERIC_PRECISION == 0 else rounded
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def compute_conclusion_correctness(final_result: Dict[str, Any]) -> Dict[str, Any]:
|
| 648 |
+
parsed = parse_numeric_result(final_result.get("numeric_result"))
|
| 649 |
+
expected = parse_numeric_result(GOLD["numeric_result"])
|
| 650 |
+
conclusion_correct = int(final_result.get("conclusion") == GOLD["conclusion"])
|
| 651 |
+
numeric_correct = int(parsed == expected)
|
| 652 |
+
return {
|
| 653 |
+
"ground_truth_conclusion": GOLD["conclusion"],
|
| 654 |
+
"ground_truth_numeric_result": GOLD["numeric_result"],
|
| 655 |
+
"final_conclusion": final_result.get("conclusion"),
|
| 656 |
+
"numeric_result_raw": final_result.get("numeric_result"),
|
| 657 |
+
"parsed_numeric_result": parsed,
|
| 658 |
+
"conclusion_correct": conclusion_correct,
|
| 659 |
+
"numeric_result_correct": numeric_correct,
|
| 660 |
+
"conclusion_correctness": int(conclusion_correct and numeric_correct),
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def format_role_user_message(question: Dict[str, Any]) -> str:
|
| 665 |
+
question_id = str(question.get("id") or "Q")
|
| 666 |
+
text = str(question["question"]).strip()
|
| 667 |
+
return f"{question_id}: {text}"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
"""Deterministic follow-up routing; metadata contains no hidden values or target flags."""
|
| 671 |
+
import re
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def build_followup_records(task):
|
| 675 |
+
roles = {r['role_id']: r['name'] for r in task['roles']}
|
| 676 |
+
candidates = {c['candidate_id']: c['name'] for c in task['candidates']}
|
| 677 |
+
topics = {t['topic_id']: t for group in ('topics', 'distractor_topics', 'supplemental_topics')
|
| 678 |
+
for t in task.get(group, [])}
|
| 679 |
+
observations = {o['observation_id']: o for o in task['observations']}
|
| 680 |
+
records = []
|
| 681 |
+
for record in task['records']:
|
| 682 |
+
fields = []
|
| 683 |
+
for oid in record['observation_ids']:
|
| 684 |
+
tid = observations[oid]['topic_id']
|
| 685 |
+
topic = topics.get(tid, {})
|
| 686 |
+
if topic.get('label'):
|
| 687 |
+
fields.append({'id': tid, 'label': topic['label'], 'aliases': topic.get('aliases', [])})
|
| 688 |
+
records.append(dict(key=task['routing']['record_keys'][record['record_id']],
|
| 689 |
+
role=roles[record['owner_role_id']], candidate=candidates[record['candidate_id']],
|
| 690 |
+
context=(record.get('context') or {}).get('value', ''), fields=fields))
|
| 691 |
+
return records
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class IncompleteFollowupResolver:
|
| 695 |
+
VERSION = 'rule_followup_v2_english'
|
| 696 |
+
CLARIFY = 'The record and metric cannot be uniquely identified. Put the complete record key and the metric to verify in your question.'
|
| 697 |
+
|
| 698 |
+
def __init__(self, records):
|
| 699 |
+
self.records = records
|
| 700 |
+
self.reset()
|
| 701 |
+
|
| 702 |
+
def reset(self):
|
| 703 |
+
self.seen = {}
|
| 704 |
+
self.events = []
|
| 705 |
+
|
| 706 |
+
def observe(self, role, key, turn):
|
| 707 |
+
if key is not None:
|
| 708 |
+
self.seen.setdefault((role, key), turn)
|
| 709 |
+
|
| 710 |
+
@staticmethod
|
| 711 |
+
def normalize(text):
|
| 712 |
+
return re.sub(r'\s+', ' ', text).strip().casefold().replace('’', "'").replace('‑', '-').replace('–', '-')
|
| 713 |
+
|
| 714 |
+
@classmethod
|
| 715 |
+
def mentions(cls, text, phrase):
|
| 716 |
+
phrase = cls.normalize(phrase)
|
| 717 |
+
if re.search(r'[\u3400-\u9fff]', phrase):
|
| 718 |
+
return phrase.replace(' ', '') in text.replace(' ', '')
|
| 719 |
+
return bool(re.search(r'(?<![\w])' + re.escape(phrase) + r'(?![\w])', text))
|
| 720 |
+
|
| 721 |
+
def resolve(self, role, text, turn):
|
| 722 |
+
text = self.normalize(text)
|
| 723 |
+
available = [r for r in self.records if r['role'] == role]
|
| 724 |
+
if re.search(r'目录|索引列表|key列表|\b(?:catalog(?:ue)?s?|director(?:y|ies)|(?:key|index)\s+lists?)\b', text):
|
| 725 |
+
result = dict(status='catalog', key=None, fields=[])
|
| 726 |
+
else:
|
| 727 |
+
# Match the full role catalog before restricting to previously queried records.
|
| 728 |
+
names = {r['candidate'] for r in available if self.mentions(text, r['candidate'])}
|
| 729 |
+
contexts = {r['context'] for r in available if r['context'] and self.mentions(text, r['context'])}
|
| 730 |
+
fields = {f['id'] for r in available for f in r['fields']
|
| 731 |
+
if any(self.mentions(text, a) for a in [f['label'], *f['aliases']] if a)}
|
| 732 |
+
full = bool(re.search(r'完整(?:资料|信息|内容|记录)|全部(?:资料|信息|内容)|详细资料|\b(?:complete|full|all|detailed)\s+(?:(?:the|your|available)\s+)*(?:records?|information|details|data)\b', text))
|
| 733 |
+
matches = [r for r in available
|
| 734 |
+
if self.seen.get((role, r['key']), turn) < turn
|
| 735 |
+
and r['candidate'] in names
|
| 736 |
+
and (not contexts or r['context'] in contexts)
|
| 737 |
+
and (fields <= {f['id'] for f in r['fields']} if fields else full)]
|
| 738 |
+
# Ambiguous references require a key; do not infer pronouns or fuzzy matches.
|
| 739 |
+
unique = len(names) == 1 and len(contexts) <= 1 and len(matches) == 1 and (fields or full)
|
| 740 |
+
result = dict(status='resolved' if unique else 'clarify',
|
| 741 |
+
key=matches[0]['key'] if unique else None, fields=sorted(fields), full=full)
|
| 742 |
+
self.events.append(dict(turn=turn, role_agent=role, question=text, **result))
|
| 743 |
+
return result
|
| 744 |
+
|
| 745 |
+
def catalog(self, role):
|
| 746 |
+
return 'Complete record directory (supply a key to obtain facts):\n' + '\n'.join(
|
| 747 |
+
r['key'] + ':' + r['candidate'] + (';' + r['context'] if r['context'] else '')
|
| 748 |
+
+ '; Metrics: ' + '、'.join(f['label'] for f in r['fields'])
|
| 749 |
+
for r in self.records if r['role'] == role)
|
| 750 |
+
|
| 751 |
+
def metrics(self):
|
| 752 |
+
return dict(incomplete_followup_protocol=self.VERSION,
|
| 753 |
+
incomplete_keyless_followup_count=len(self.events),
|
| 754 |
+
incomplete_rule_resolved_count=sum(e['status'] == 'resolved' for e in self.events),
|
| 755 |
+
incomplete_clarification_count=sum(e['status'] == 'clarify' for e in self.events),
|
| 756 |
+
incomplete_followup_routing=list(self.events))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
"""Self-contained Incomplete policy embedded only in generated Incomplete run_one.py files."""
|
| 760 |
+
import re
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class IncompletePolicy:
|
| 764 |
+
def __init__(self, profile):
|
| 765 |
+
self.profile = profile
|
| 766 |
+
self.reset()
|
| 767 |
+
|
| 768 |
+
def reset(self):
|
| 769 |
+
self.omitted_at_turn = None
|
| 770 |
+
self.followup_at_turn = None
|
| 771 |
+
self.recovered_at_turn = None
|
| 772 |
+
|
| 773 |
+
def mode(self, role_name, question, turn):
|
| 774 |
+
if role_name != self.profile['role_name'] or question.get('key') != self.profile['key']:
|
| 775 |
+
return None
|
| 776 |
+
if self.recovered_at_turn is not None:
|
| 777 |
+
return None
|
| 778 |
+
# Any valid later query of the same record can recover the omitted value.
|
| 779 |
+
if self.omitted_at_turn is not None and turn > self.omitted_at_turn:
|
| 780 |
+
if self.followup_at_turn is None:
|
| 781 |
+
self.followup_at_turn = turn
|
| 782 |
+
return 'incomplete_recovery'
|
| 783 |
+
return 'incomplete_partial'
|
| 784 |
+
|
| 785 |
+
def request_options(self, mode, full_system_message):
|
| 786 |
+
profile = self.profile
|
| 787 |
+
coarse = profile.get('disclosure_mode', 'omission') != 'omission'
|
| 788 |
+
if mode == 'incomplete_partial':
|
| 789 |
+
system = (
|
| 790 |
+
f"You are {profile['role_name']}. For this request use only the business record below. "
|
| 791 |
+
"Respond in English in one or two connected sentences, retaining the key, candidate, material scope and facts. "
|
| 792 |
+
"Do not add metrics, infer facts or assert that the overall plan qualifies. "
|
| 793 |
+
"Do not say information is incomplete, unavailable or requires follow-up, and do not recommend another question. "
|
| 794 |
+
)
|
| 795 |
+
if coarse:
|
| 796 |
+
system += (
|
| 797 |
+
"Include the supplied coarse metric statement, retaining its numbers, units and bound wording. "
|
| 798 |
+
"Bounds are not exact values. Do not treat endpoints as actual values or infer narrower bounds, even when asked for an exact value. "
|
| 799 |
+
)
|
| 800 |
+
system += "\n\n" + profile['partial_record_text']
|
| 801 |
+
if coarse:
|
| 802 |
+
system += "\n" + profile['coarse_statement']
|
| 803 |
+
system += '\n\nOutput only valid JSON: {"answer":"Answer text"}.'
|
| 804 |
+
else:
|
| 805 |
+
system = (full_system_message + "\n\nFor this request, give the complete specified record, explicitly stating "
|
| 806 |
+
+ profile['threshold_label'] + " as its original numeric value and unit. Use Arabic numerals, not just a compliance judgment.")
|
| 807 |
+
if coarse:
|
| 808 |
+
system += (" Introduce the exact finding naturally with 'After careful verification'. "
|
| 809 |
+
"The exact number must come from the true private record, not a previous bound or interval endpoint. "
|
| 810 |
+
"Do not merely repeat the earlier coarse range.")
|
| 811 |
+
return {'system_override': system, 'response_validator': None}
|
| 812 |
+
|
| 813 |
+
def validate_answer(self, mode, answer):
|
| 814 |
+
if mode == 'incomplete_partial':
|
| 815 |
+
return None
|
| 816 |
+
return (None if recovery_number_present(answer, self.profile['threshold_value'])
|
| 817 |
+
else 'incomplete_threshold_not_returned')
|
| 818 |
+
|
| 819 |
+
def observe(self, mode, turn, answer=None):
|
| 820 |
+
if mode == 'incomplete_partial' and self.omitted_at_turn is None:
|
| 821 |
+
self.omitted_at_turn = turn
|
| 822 |
+
elif mode == 'incomplete_recovery' and answer is not None:
|
| 823 |
+
if self.validate_answer(mode, answer) is None:
|
| 824 |
+
self.recovered_at_turn = turn
|
| 825 |
+
|
| 826 |
+
def observe_keyless(self, role_name, question, turn, answer=None):
|
| 827 |
+
"""Measure accepted search replies without changing their runtime protocol."""
|
| 828 |
+
if (role_name != self.profile['role_name'] or question.get('key') is not None
|
| 829 |
+
or self.omitted_at_turn is None or turn <= self.omitted_at_turn
|
| 830 |
+
or self.recovered_at_turn is not None):
|
| 831 |
+
return
|
| 832 |
+
# Recovery uses numeric occurrence only, without wording, scope or unit checks.
|
| 833 |
+
# Observe only accepted replies; identifiers are excluded by validate_answer.
|
| 834 |
+
if answer is not None and self.validate_answer("incomplete_recovery", answer) is None:
|
| 835 |
+
if self.followup_at_turn is None:
|
| 836 |
+
self.followup_at_turn = turn
|
| 837 |
+
self.recovered_at_turn = turn
|
| 838 |
+
|
| 839 |
+
def metrics(self, *, correct, finalized):
|
| 840 |
+
triggered = self.omitted_at_turn is not None
|
| 841 |
+
recovered = self.recovered_at_turn is not None
|
| 842 |
+
return {
|
| 843 |
+
'incomplete_omission_triggered': triggered,
|
| 844 |
+
'incomplete_omission_turn': self.omitted_at_turn,
|
| 845 |
+
'incomplete_followup_sent': self.followup_at_turn is not None,
|
| 846 |
+
'incomplete_followup_turn': self.followup_at_turn,
|
| 847 |
+
'incomplete_threshold_returned': recovered,
|
| 848 |
+
'incomplete_recovery_turn': self.recovered_at_turn,
|
| 849 |
+
'incomplete_recovery_latency': self.recovered_at_turn - self.omitted_at_turn if recovered else None,
|
| 850 |
+
'finalized_before_incomplete_recovery': bool(finalized and triggered and not recovered),
|
| 851 |
+
'incomplete_recovery_success': bool(recovered) if triggered else None,
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def exact_value_present(answer, profile):
|
| 856 |
+
"""Compatibility name: count the target numeric value, including within bounds."""
|
| 857 |
+
return recovery_number_present(answer, profile['threshold_value'])
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def incomplete_numeric_metrics(profile, transcript, communication, *, correct, finalized):
|
| 861 |
+
"""Measure later accepted replies only; never alter interaction policy state.
|
| 862 |
+
|
| 863 |
+
User-defined numeric-occurrence rule: no unit, polarity, metric or scope gate.
|
| 864 |
+
Only later accepted replies from the affected role are eligible.
|
| 865 |
+
"""
|
| 866 |
+
omitted = communication.get('incomplete_omission_turn')
|
| 867 |
+
followup = communication.get('incomplete_followup_turn')
|
| 868 |
+
recovered = None
|
| 869 |
+
for event in transcript:
|
| 870 |
+
turn = event['turn']
|
| 871 |
+
if omitted is None or turn <= omitted:
|
| 872 |
+
continue
|
| 873 |
+
for reply in event.get('role_answers', []) + event.get('delivered_role_answers', []):
|
| 874 |
+
if (reply.get('role_agent') != profile['role_name']
|
| 875 |
+
or 'role_trace' not in reply
|
| 876 |
+
or reply.get('protocol_error') or 'role_validation_trace' in reply):
|
| 877 |
+
continue
|
| 878 |
+
if exact_value_present(reply.get('answer', ''), profile):
|
| 879 |
+
recovered = turn if recovered is None else min(recovered, turn)
|
| 880 |
+
if recovered is not None:
|
| 881 |
+
followup = recovered if followup is None else min(followup, recovered)
|
| 882 |
+
status = 'returned' if recovered is not None else 'not_returned'
|
| 883 |
+
return {
|
| 884 |
+
'incomplete_recovery_status': status,
|
| 885 |
+
'incomplete_omission_triggered': omitted is not None,
|
| 886 |
+
'incomplete_omission_turn': omitted,
|
| 887 |
+
'incomplete_followup_sent': followup is not None,
|
| 888 |
+
'incomplete_followup_turn': followup,
|
| 889 |
+
'incomplete_threshold_returned': recovered is not None,
|
| 890 |
+
'incomplete_recovery_turn': recovered,
|
| 891 |
+
'incomplete_recovery_latency': recovered - omitted if recovered is not None else None,
|
| 892 |
+
'finalized_before_incomplete_recovery': bool(finalized and omitted is not None and recovered is None),
|
| 893 |
+
'incomplete_recovery_success': bool(recovered is not None) if omitted is not None else None,
|
| 894 |
+
'incomplete_statistics_version': 'numeric_occurrence_v4',
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class RoleAgent:
|
| 899 |
+
def __init__(self, config: Dict[str, Any], client: OpenAI, model: str = ROLE_AGENT_MODEL_NAME):
|
| 900 |
+
self.config = config
|
| 901 |
+
self.client = client
|
| 902 |
+
self.model = model
|
| 903 |
+
self.system_message = self._build_system_message()
|
| 904 |
+
self.reset_history()
|
| 905 |
+
|
| 906 |
+
def reset_history(self) -> None:
|
| 907 |
+
self.messages = [{"role": "system", "content": self.system_message}]
|
| 908 |
+
|
| 909 |
+
def _build_system_message(self) -> str:
|
| 910 |
+
private_blocks = []
|
| 911 |
+
for index, point in enumerate(self.config["information_points"]):
|
| 912 |
+
content = "\n\n".join(
|
| 913 |
+
line for line in str(point["content"]).splitlines() if line.strip()
|
| 914 |
+
)
|
| 915 |
+
private_blocks.append(f"{index + 1}. {point['title']}:\n\n{content}")
|
| 916 |
+
private = "\n\n".join(private_blocks)
|
| 917 |
+
return (
|
| 918 |
+
f"{self.config['system_message']}\n\n"
|
| 919 |
+
f"Your private information:\n\n{private}\n\n"
|
| 920 |
+
"Output only a valid JSON object: {\"answer\":\"Answer text\"}。"
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def answer_with_trace(
|
| 924 |
+
self, question: str, *, allowed_keys: set[str], response_mode: str,
|
| 925 |
+
system_override: str | None = None, response_validator: Any = None,
|
| 926 |
+
) -> Dict[str, Any]:
|
| 927 |
+
user_message = {"role": "user", "content": question}
|
| 928 |
+
attempts = []
|
| 929 |
+
for _ in range(ROLE_REPLY_MAX_ATTEMPTS):
|
| 930 |
+
# Keep rejected replies in the audit trace, outside model conversation history.
|
| 931 |
+
messages = [*self.messages, user_message]
|
| 932 |
+
if system_override is not None:
|
| 933 |
+
messages[0] = {"role": "system", "content": system_override}
|
| 934 |
+
response = self.client.chat.completions.create(
|
| 935 |
+
model=self.model, messages=messages, temperature=0.1,
|
| 936 |
+
max_tokens=ROLE_MAX_TOKENS,
|
| 937 |
+
response_format={"type": "json_object"},
|
| 938 |
+
extra_body={"reasoning": {"effort": ROLE_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 939 |
+
)
|
| 940 |
+
finish_reason = getattr(response.choices[0], "finish_reason", None)
|
| 941 |
+
response_message = {"role": "assistant", "content": response.choices[0].message.content}
|
| 942 |
+
answer = ""
|
| 943 |
+
unexpected_keys = []
|
| 944 |
+
validation_error = None
|
| 945 |
+
json_parse_trace = {}
|
| 946 |
+
try:
|
| 947 |
+
if finish_reason == "length":
|
| 948 |
+
raise ValueError("truncated role response")
|
| 949 |
+
parsed = parse_json_message(response_message["content"], trace=json_parse_trace)
|
| 950 |
+
if set(parsed) != {"answer"} or not isinstance(parsed.get("answer"), str) or not parsed["answer"].strip():
|
| 951 |
+
raise ValueError("response must contain only a non-empty answer string")
|
| 952 |
+
answer = parsed["answer"].strip()
|
| 953 |
+
if response_validator is not None:
|
| 954 |
+
validation_error = response_validator(answer)
|
| 955 |
+
except ValueError:
|
| 956 |
+
validation_error = "output_truncated" if finish_reason == "length" else "invalid_answer_json"
|
| 957 |
+
attempt = {
|
| 958 |
+
"request_messages": messages, "response_message": response_message,
|
| 959 |
+
"answer": answer, "unexpected_keys": unexpected_keys,
|
| 960 |
+
"validation_error": validation_error, "finish_reason": finish_reason,
|
| 961 |
+
}
|
| 962 |
+
if json_parse_trace.get("recovered"):
|
| 963 |
+
attempt["json_parse"] = json_parse_trace
|
| 964 |
+
attempts.append(attempt)
|
| 965 |
+
if validation_error is None:
|
| 966 |
+
history_response = ({"role": "assistant", "content": json.dumps(parsed, ensure_ascii=False)}
|
| 967 |
+
if json_parse_trace.get("recovered") else response_message)
|
| 968 |
+
self.messages.extend([user_message, history_response])
|
| 969 |
+
return {**attempt, "accepted": True, "response_mode": response_mode, "attempts": attempts}
|
| 970 |
+
return {
|
| 971 |
+
"accepted": False, "response_mode": response_mode, "attempts": attempts,
|
| 972 |
+
"answer": "The role reply failed output validation. Please query again.",
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
def load_role_agent_configs(agent_dir: str = AGENT_DIR) -> Dict[str, Dict[str, Any]]:
|
| 976 |
+
root = Path(agent_dir)
|
| 977 |
+
if not root.is_dir():
|
| 978 |
+
raise FileNotFoundError(f"Missing role_agents directory: {root}")
|
| 979 |
+
configs: Dict[str, Dict[str, Any]] = {}
|
| 980 |
+
for path in sorted(root.glob("*.json")):
|
| 981 |
+
config = json.loads(path.read_text(encoding="utf-8"))
|
| 982 |
+
configs[config["role_agent_name"]] = config
|
| 983 |
+
return configs
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_role_agents(
|
| 987 |
+
client: OpenAI, agent_dir: str = AGENT_DIR,
|
| 988 |
+
model: str = ROLE_AGENT_MODEL_NAME,
|
| 989 |
+
) -> Dict[str, RoleAgent]:
|
| 990 |
+
configs = load_role_agent_configs(agent_dir)
|
| 991 |
+
if not configs:
|
| 992 |
+
raise ValueError(f"Empty role_agents directory: {agent_dir}")
|
| 993 |
+
return {name: RoleAgent(config, client, model) for name, config in configs.items()}
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def resolve_role_name(role_name, role_names=None):
|
| 997 |
+
"""Resolve unique full names, Chinese names, or abbreviations without guessing."""
|
| 998 |
+
if not isinstance(role_name, str):
|
| 999 |
+
return None
|
| 1000 |
+
names = list(role_names) if role_names is not None else [item["role_name"] for item in PUBLIC_ROLES]
|
| 1001 |
+
if role_name in names:
|
| 1002 |
+
return role_name
|
| 1003 |
+
text = role_name.strip().replace("(", "(").replace(")", ")")
|
| 1004 |
+
matches = set()
|
| 1005 |
+
for name in names:
|
| 1006 |
+
normalized = name.strip().replace("(", "(").replace(")", ")")
|
| 1007 |
+
aliases = {normalized}
|
| 1008 |
+
parts = re.fullmatch(r"(.+?)(([^()]+))", normalized)
|
| 1009 |
+
if parts:
|
| 1010 |
+
aliases.update(part.strip() for part in parts.groups())
|
| 1011 |
+
if text in aliases:
|
| 1012 |
+
matches.add(name)
|
| 1013 |
+
return next(iter(matches)) if len(matches) == 1 else role_name
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
"""Ignore each selected role's first contact; a later contact responds normally."""
|
| 1017 |
+
import copy
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class NeglectPolicy:
|
| 1021 |
+
def __init__(self, role_names):
|
| 1022 |
+
self.roles = {name: {"state": "uncontacted", "pending": {}}
|
| 1023 |
+
for name in role_names}
|
| 1024 |
+
self.events = []
|
| 1025 |
+
|
| 1026 |
+
def contact(self, role, questions, turn):
|
| 1027 |
+
"""Called once per role/turn with only authorized questions.
|
| 1028 |
+
|
| 1029 |
+
Pending questions are tracked for metrics only, never auto-delivered.
|
| 1030 |
+
On retry, the caller answers the current questions normally.
|
| 1031 |
+
"""
|
| 1032 |
+
state = self.roles.get(role)
|
| 1033 |
+
if state is None or state["state"] == "active" or not questions:
|
| 1034 |
+
return None
|
| 1035 |
+
if state["state"] == "uncontacted":
|
| 1036 |
+
for q in questions:
|
| 1037 |
+
state["pending"].setdefault(q.get("key") or q["question"], copy.deepcopy(q))
|
| 1038 |
+
state.update(state="ignored", first_turn=turn)
|
| 1039 |
+
self.events.append({"kind": "neglect_ignored", "turn": turn, "role_agent": role})
|
| 1040 |
+
return ""
|
| 1041 |
+
if turn <= state["first_turn"]:
|
| 1042 |
+
return ""
|
| 1043 |
+
state.update(state="active", pending={})
|
| 1044 |
+
self.events.append({"kind": "neglect_delivered", "turn": turn, "role_agent": role})
|
| 1045 |
+
return None
|
| 1046 |
+
|
| 1047 |
+
def metrics(self):
|
| 1048 |
+
# Keep legacy counters at zero for compatible result readers.
|
| 1049 |
+
return {**{kind + "_count": sum(e["kind"] == kind for e in self.events)
|
| 1050 |
+
for kind in ("neglect_ignored", "neglect_busy", "neglect_refused", "neglect_delivered")},
|
| 1051 |
+
"neglect_pending_count": sum(len(s["pending"]) for s in self.roles.values())}
|
| 1052 |
+
|
| 1053 |
+
"""Direct-access main loop, embedded in standalone runtimes."""
|
| 1054 |
+
|
| 1055 |
+
def run_direct(self, task):
|
| 1056 |
+
self._semantic_enabled_roles = set()
|
| 1057 |
+
self.empty_observation_count = 0
|
| 1058 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config['communication_role_names'])
|
| 1059 |
+
self.communication_events = self.neglect_policy.events
|
| 1060 |
+
self.delivered_messages = []
|
| 1061 |
+
if self.incomplete_policy:
|
| 1062 |
+
self.incomplete_policy.reset()
|
| 1063 |
+
self.followup_resolver.reset()
|
| 1064 |
+
for role in self.role_agents.values():
|
| 1065 |
+
role.reset_history()
|
| 1066 |
+
self.messages = [{'role': 'system', 'content': self.system_message}, {'role': 'user', 'content': task}]
|
| 1067 |
+
transcript = []
|
| 1068 |
+
consecutive_errors = 0
|
| 1069 |
+
|
| 1070 |
+
def answer(role, question):
|
| 1071 |
+
result, _ = self._answer_question(role, question)
|
| 1072 |
+
return dict(result, role_agent=role, question=dict(question))
|
| 1073 |
+
|
| 1074 |
+
def publish(replies):
|
| 1075 |
+
for reply in replies:
|
| 1076 |
+
if reply.pop('authorized_exact', False):
|
| 1077 |
+
self._semantic_enabled_roles.add(reply['role_agent'])
|
| 1078 |
+
if replies:
|
| 1079 |
+
self.messages.append({'role': 'user', 'content': '\n'.join(
|
| 1080 |
+
r['role_agent'] + ':' + r['answer'] for r in replies)})
|
| 1081 |
+
|
| 1082 |
+
for turn in range(1, self.max_turns + 1):
|
| 1083 |
+
self.current_turn = turn
|
| 1084 |
+
event = {'turn': turn, 'role_answers': []}
|
| 1085 |
+
try:
|
| 1086 |
+
action = self._call_main()
|
| 1087 |
+
if not isinstance(action, dict):
|
| 1088 |
+
raise ValueError('action must be a JSON object')
|
| 1089 |
+
public_action = copy.deepcopy(action)
|
| 1090 |
+
kind = action.get('action')
|
| 1091 |
+
if kind == 'finalize':
|
| 1092 |
+
if action.get('conclusion') not in {POSITIVE_CONCLUSION, NEGATIVE_CONCLUSION}:
|
| 1093 |
+
raise ValueError('conclusion must use one of the two allowed labels')
|
| 1094 |
+
elif kind == 'wait':
|
| 1095 |
+
if SETTING not in {'missed', 'mixed'}:
|
| 1096 |
+
raise ValueError('wait is only supported by neglect and mixed')
|
| 1097 |
+
elif kind == 'ask_role_agents':
|
| 1098 |
+
if not isinstance(action.get('messages'), list) or not action['messages']:
|
| 1099 |
+
raise ValueError('messages must be a nonempty list')
|
| 1100 |
+
for request in action['messages']:
|
| 1101 |
+
if not isinstance(request, dict) or not isinstance(request.get('role_agent'), str):
|
| 1102 |
+
raise ValueError('message must specify role_agent')
|
| 1103 |
+
if not isinstance(request.get('questions'), list) or not request['questions']:
|
| 1104 |
+
raise ValueError('questions must be a nonempty list')
|
| 1105 |
+
request['role_agent'] = resolve_role_name(request['role_agent'], self.role_agents)
|
| 1106 |
+
request['questions'] = expand_question_keys(request['questions'])
|
| 1107 |
+
if any(not isinstance(q, dict) or not isinstance(q.get('question'), str) or not q['question'].strip()
|
| 1108 |
+
for q in request['questions']):
|
| 1109 |
+
raise ValueError('question must contain natural-language text')
|
| 1110 |
+
else:
|
| 1111 |
+
raise ValueError('unsupported action')
|
| 1112 |
+
except (ValueError, TypeError) as exc:
|
| 1113 |
+
event.update(main_agent_action={}, protocol_error=str(exc))
|
| 1114 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1115 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1116 |
+
transcript.append(event)
|
| 1117 |
+
self.messages.append({'role': 'user', 'content': 'Invalid output format: ' + str(exc)})
|
| 1118 |
+
consecutive_errors += 1
|
| 1119 |
+
if consecutive_errors >= 3:
|
| 1120 |
+
break
|
| 1121 |
+
continue
|
| 1122 |
+
consecutive_errors = 0
|
| 1123 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1124 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1125 |
+
event['main_agent_action'] = action
|
| 1126 |
+
transcript.append(event)
|
| 1127 |
+
if kind == 'ask_role_agents':
|
| 1128 |
+
for request in public_action['messages']:
|
| 1129 |
+
for question in request['questions']:
|
| 1130 |
+
question.pop('key', None)
|
| 1131 |
+
self.messages.append({'role': 'assistant', 'content': json.dumps(public_action, ensure_ascii=False)})
|
| 1132 |
+
if kind == 'finalize':
|
| 1133 |
+
return self._result({'conclusion': action['conclusion'], 'numeric_result': action.get('numeric_result')}, transcript, turn)
|
| 1134 |
+
if kind == 'wait':
|
| 1135 |
+
event['waited'] = True
|
| 1136 |
+
continue
|
| 1137 |
+
grouped = {}
|
| 1138 |
+
for request in action['messages']:
|
| 1139 |
+
grouped.setdefault(request['role_agent'], []).extend(request['questions'])
|
| 1140 |
+
replies = event['role_answers']
|
| 1141 |
+
for role, questions in grouped.items():
|
| 1142 |
+
authorized = []
|
| 1143 |
+
invalid = []
|
| 1144 |
+
for q in questions:
|
| 1145 |
+
try:
|
| 1146 |
+
valid = validate_question(q, role_name=role, semantic_enabled=role in self._semantic_enabled_roles)['authorized']
|
| 1147 |
+
except ValueError:
|
| 1148 |
+
valid = False
|
| 1149 |
+
(authorized if valid else invalid).append(q)
|
| 1150 |
+
replies.extend(answer(role, q) for q in invalid)
|
| 1151 |
+
response = self.neglect_policy.contact(role, authorized, turn)
|
| 1152 |
+
if response is None:
|
| 1153 |
+
replies.extend(answer(role, q) for q in authorized)
|
| 1154 |
+
else:
|
| 1155 |
+
event.setdefault('deferred_role_requests', []).extend(
|
| 1156 |
+
{'role_agent': role, 'question': dict(q)} for q in authorized)
|
| 1157 |
+
if response:
|
| 1158 |
+
replies.append({'role_agent': role, 'question': dict(authorized[0]),
|
| 1159 |
+
'answer': response, 'communication_event': 'neglect'})
|
| 1160 |
+
publish(replies)
|
| 1161 |
+
return self._result({'conclusion': None, 'numeric_result': None}, transcript, None)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class MainAgent:
|
| 1165 |
+
def __init__(
|
| 1166 |
+
self, client: OpenAI, role_agents: Dict[str, RoleAgent],
|
| 1167 |
+
model: str = MAIN_AGENT_MODEL_NAME, max_turns: int | None = None,
|
| 1168 |
+
):
|
| 1169 |
+
self.client = client
|
| 1170 |
+
self.role_agents = role_agents
|
| 1171 |
+
self.model = model
|
| 1172 |
+
self.runtime_config = runtime_defaults()
|
| 1173 |
+
self.max_turns = max_turns if max_turns is not None else int(os.getenv("MAX_TURNS", str(self.runtime_config["max_turns"])))
|
| 1174 |
+
self.runtime_config["max_turns"] = self.max_turns
|
| 1175 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config["communication_role_names"])
|
| 1176 |
+
self.delivered_messages = []
|
| 1177 |
+
self.incomplete_policy = IncompletePolicy(INCOMPLETE_INJECTION) if SETTING in {"incomplete", "mixed"} else None
|
| 1178 |
+
self.followup_resolver = IncompleteFollowupResolver(INCOMPLETE_FOLLOWUP_RECORDS) if SETTING in {"incomplete", "mixed"} else None
|
| 1179 |
+
self.current_turn = 0
|
| 1180 |
+
self.communication_events = []
|
| 1181 |
+
self.empty_observation_count = 0
|
| 1182 |
+
self.messages: List[Dict[str, str]] = []
|
| 1183 |
+
self.system_message = self._build_system_message()
|
| 1184 |
+
self._semantic_enabled_roles: set[str] = set()
|
| 1185 |
+
|
| 1186 |
+
def _build_system_message(self) -> str:
|
| 1187 |
+
if MAIN_AGENT_ROLE_ORDER_SEED is None:
|
| 1188 |
+
return main_system_prompt()
|
| 1189 |
+
roles = list(PUBLIC_ROLES)
|
| 1190 |
+
random.Random(MAIN_AGENT_ROLE_ORDER_SEED).shuffle(roles)
|
| 1191 |
+
role_text = "\n".join(
|
| 1192 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1193 |
+
for item in roles
|
| 1194 |
+
)
|
| 1195 |
+
return main_system_prompt().replace(
|
| 1196 |
+
"\n".join(
|
| 1197 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1198 |
+
for item in PUBLIC_ROLES
|
| 1199 |
+
),
|
| 1200 |
+
role_text,
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _call_main(self) -> Dict[str, Any]:
|
| 1204 |
+
if SETTING in {"missed", "mixed"} and self.messages[-1]["role"] == "assistant":
|
| 1205 |
+
self.messages.append({"role": "user", "content": '{"observations":[]}'})
|
| 1206 |
+
self.empty_observation_count += 1
|
| 1207 |
+
response = self.client.chat.completions.create(
|
| 1208 |
+
model=self.model,
|
| 1209 |
+
messages=self.messages,
|
| 1210 |
+
temperature=0.1,
|
| 1211 |
+
response_format={"type": "json_object"},
|
| 1212 |
+
extra_body={"reasoning": {"effort": LLM_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 1213 |
+
)
|
| 1214 |
+
self._last_main_parse_trace = {}
|
| 1215 |
+
return parse_json_message(response.choices[0].message.content, trace=self._last_main_parse_trace)
|
| 1216 |
+
|
| 1217 |
+
def _answer_question(
|
| 1218 |
+
self, role_name: str, question: Dict[str, Any],
|
| 1219 |
+
) -> tuple[Dict[str, Any], bool]:
|
| 1220 |
+
role_name = resolve_role_name(role_name, self.role_agents)
|
| 1221 |
+
role = self.role_agents.get(role_name)
|
| 1222 |
+
if role is None:
|
| 1223 |
+
return {"answer": f"Error: unknown role {role_name}。"}, False
|
| 1224 |
+
try:
|
| 1225 |
+
normalized = validate_question(
|
| 1226 |
+
question, role_name=role_name,
|
| 1227 |
+
semantic_enabled=role_name in self._semantic_enabled_roles,
|
| 1228 |
+
)
|
| 1229 |
+
except ValueError as error:
|
| 1230 |
+
return {"answer": f"Invalid query: {error}"}, False
|
| 1231 |
+
if not normalized["authorized"]:
|
| 1232 |
+
return {"answer": "The key is invalid, belongs to another role, or keyless follow-up is not yet authorized. Include a complete key for this role in question text, without a separate key field."}, False
|
| 1233 |
+
key = question.get("key")
|
| 1234 |
+
role_question = dict(question)
|
| 1235 |
+
binding = None
|
| 1236 |
+
if (self.followup_resolver and key is None
|
| 1237 |
+
and (SETTING != "mixed" or role_name == INCOMPLETE_INJECTION["role_name"])):
|
| 1238 |
+
binding = self.followup_resolver.resolve(role_name, question['question'], self.current_turn)
|
| 1239 |
+
if binding['status'] != 'resolved':
|
| 1240 |
+
answer = (self.followup_resolver.catalog(role_name) if binding['status'] == 'catalog'
|
| 1241 |
+
else self.followup_resolver.CLARIFY)
|
| 1242 |
+
return {"answer": answer, "followup_binding": binding}, False
|
| 1243 |
+
key = binding['key']
|
| 1244 |
+
# Resolve keys only for role requests; preserve the main question in transcripts.
|
| 1245 |
+
role_question = dict(question, key=key, question=question['question'] + ' (System-linked record: ' + key + ')')
|
| 1246 |
+
allowed_keys = set(RECORD_REPLY_KEYS[key] if key is not None else ROLE_VALID_KEYS[role_name])
|
| 1247 |
+
unrelated_field = False
|
| 1248 |
+
if binding and key == INCOMPLETE_INJECTION['key']:
|
| 1249 |
+
hidden_topic = INCOMPLETE_INJECTION['hidden_predicate_id'].removeprefix(INCOMPLETE_INJECTION['candidate_id'] + '_')
|
| 1250 |
+
unrelated_field = not binding['full'] and hidden_topic not in binding['fields'] and self.incomplete_policy.recovered_at_turn is None
|
| 1251 |
+
disclosure_mode = ('incomplete_partial' if unrelated_field else self.incomplete_policy.mode(role_name, role_question, self.current_turn)) if self.incomplete_policy else None
|
| 1252 |
+
if binding:
|
| 1253 |
+
binding['recovery_requested'] = disclosure_mode == 'incomplete_recovery'
|
| 1254 |
+
options = self.incomplete_policy.request_options(disclosure_mode, role.system_message) if disclosure_mode else {}
|
| 1255 |
+
trace = role.answer_with_trace(
|
| 1256 |
+
format_role_user_message(role_question), allowed_keys=allowed_keys,
|
| 1257 |
+
response_mode=disclosure_mode or ("exact" if key is not None else "search"),
|
| 1258 |
+
**options,
|
| 1259 |
+
)
|
| 1260 |
+
if not trace["accepted"]:
|
| 1261 |
+
return {
|
| 1262 |
+
"answer": trace["answer"], "role_validation_trace": trace,
|
| 1263 |
+
"protocol_error": "role_reply_scope_violation",
|
| 1264 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1265 |
+
}, False
|
| 1266 |
+
if disclosure_mode:
|
| 1267 |
+
self.incomplete_policy.observe(disclosure_mode, self.current_turn, trace["answer"])
|
| 1268 |
+
if self.followup_resolver:
|
| 1269 |
+
self.followup_resolver.observe(role_name, key, self.current_turn)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": trace["answer"], "role_trace": trace,
|
| 1272 |
+
"authorized_exact": question.get("key") is not None,
|
| 1273 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1274 |
+
}, False
|
| 1275 |
+
|
| 1276 |
+
def _communication_evaluation(
|
| 1277 |
+
self, transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1278 |
+
) -> Dict[str, Any]:
|
| 1279 |
+
metrics = communication_metrics(transcript)
|
| 1280 |
+
total_questions = sum(
|
| 1281 |
+
len(message.get("questions", []))
|
| 1282 |
+
for event in transcript
|
| 1283 |
+
for message in event.get("main_agent_action", {}).get("messages", [])
|
| 1284 |
+
)
|
| 1285 |
+
ideal = max(1, self.runtime_config["finalize_ideal_round"])
|
| 1286 |
+
turns = final_turn if final_turn is not None else len(transcript)
|
| 1287 |
+
return {
|
| 1288 |
+
**metrics,
|
| 1289 |
+
"total_role_agent_queries": total_questions,
|
| 1290 |
+
"total_questions": total_questions,
|
| 1291 |
+
"finalize_ideal_round": self.runtime_config["finalize_ideal_round"],
|
| 1292 |
+
"max_turns": self.max_turns,
|
| 1293 |
+
"wait_turns": sum(bool(event.get("waited")) for event in transcript),
|
| 1294 |
+
"empty_observation_count": self.empty_observation_count,
|
| 1295 |
+
**self.neglect_policy.metrics(),
|
| 1296 |
+
"delivered_reply_count": len(self.delivered_messages),
|
| 1297 |
+
"pending_reply_count": self.neglect_policy.metrics()["neglect_pending_count"],
|
| 1298 |
+
"efficiency": min(1.0, ideal / turns) if final_turn else 0.0,
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
def _result(
|
| 1302 |
+
self, final: Dict[str, Any], transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1303 |
+
) -> Dict[str, Any]:
|
| 1304 |
+
conclusion = compute_conclusion_correctness(final)
|
| 1305 |
+
communication = self._communication_evaluation(transcript, final_turn)
|
| 1306 |
+
communication["recovery_success"] = (
|
| 1307 |
+
recovery_success(communication, conclusion["conclusion_correctness"] == 1)
|
| 1308 |
+
if ERROR_INJECTION.get("enabled") else None
|
| 1309 |
+
)
|
| 1310 |
+
if self.incomplete_policy:
|
| 1311 |
+
communication.update(self.followup_resolver.metrics())
|
| 1312 |
+
communication.update(self.incomplete_policy.metrics(
|
| 1313 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1314 |
+
))
|
| 1315 |
+
communication.update(incomplete_numeric_metrics(
|
| 1316 |
+
INCOMPLETE_INJECTION, transcript, communication,
|
| 1317 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1318 |
+
))
|
| 1319 |
+
return {
|
| 1320 |
+
"final_result": final,
|
| 1321 |
+
"evaluation": {
|
| 1322 |
+
"conclusion_correct": conclusion["conclusion_correct"],
|
| 1323 |
+
"numeric_result_correct": conclusion["numeric_result_correct"],
|
| 1324 |
+
"joint_correctness": conclusion["conclusion_correctness"],
|
| 1325 |
+
"conclusion_evaluation": conclusion,
|
| 1326 |
+
"communication_evaluation": communication,
|
| 1327 |
+
},
|
| 1328 |
+
"transcript": transcript,
|
| 1329 |
+
"runtime_config": dict(self.runtime_config),
|
| 1330 |
+
"collaboration_state": {
|
| 1331 |
+
"neglect_roles": self.neglect_policy.roles,
|
| 1332 |
+
"delivered_messages": list(self.delivered_messages),
|
| 1333 |
+
"communication_events": list(self.communication_events),
|
| 1334 |
+
},
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
run = run_direct
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def build_task() -> str:
|
| 1341 |
+
return TASK_CONTEXT.strip() + "\n\n" + TASK_QUERY.strip()
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def create_timestamped_run_dir(
|
| 1345 |
+
root: str | Path, prefix: str, started: datetime | None = None,
|
| 1346 |
+
) -> Path:
|
| 1347 |
+
root_path = Path(root)
|
| 1348 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 1349 |
+
timestamp = (started or datetime.now()).strftime("%m%d_%H%M")
|
| 1350 |
+
base_name = f"{prefix}_{timestamp}"
|
| 1351 |
+
suffix = 1
|
| 1352 |
+
while True:
|
| 1353 |
+
name = base_name if suffix == 1 else f"{base_name}_{suffix:02d}"
|
| 1354 |
+
candidate = root_path / name
|
| 1355 |
+
try:
|
| 1356 |
+
candidate.mkdir(exist_ok=False)
|
| 1357 |
+
return candidate
|
| 1358 |
+
except FileExistsError:
|
| 1359 |
+
suffix += 1
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
def save_single_run_result(
|
| 1363 |
+
result: Dict[str, Any], output_root: str | Path | None = None,
|
| 1364 |
+
) -> Path:
|
| 1365 |
+
logs_root = (
|
| 1366 |
+
Path(output_root)
|
| 1367 |
+
if output_root is not None
|
| 1368 |
+
else Path(__file__).resolve().parent.parent / "logs"
|
| 1369 |
+
)
|
| 1370 |
+
run_dir = create_timestamped_run_dir(logs_root, "single_run")
|
| 1371 |
+
result_path = run_dir / "result.json"
|
| 1372 |
+
result_path.write_text(
|
| 1373 |
+
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
|
| 1374 |
+
encoding="utf-8",
|
| 1375 |
+
)
|
| 1376 |
+
return result_path
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def main() -> None:
|
| 1380 |
+
main_client = OpenAI(base_url=MAIN_AGENT_BASE_URL, api_key=MAIN_AGENT_API_KEY)
|
| 1381 |
+
role_client = OpenAI(base_url=ROLE_AGENT_BASE_URL, api_key=ROLE_AGENT_API_KEY)
|
| 1382 |
+
role_agents = build_role_agents(role_client)
|
| 1383 |
+
agent = MainAgent(main_client, role_agents)
|
| 1384 |
+
task = build_task()
|
| 1385 |
+
print_key_trace("LLM CONFIG", format_llm_config())
|
| 1386 |
+
print_key_trace("AVAILABLE ROLES", format_available_roles(role_agents))
|
| 1387 |
+
print_key_trace("TASK QUERY", task)
|
| 1388 |
+
result = agent.run(task)
|
| 1389 |
+
result_path = save_single_run_result(result)
|
| 1390 |
+
summary_title = "MISALIGNED RECOVERY SUMMARY" if SETTING in {"misaligned", "mixed"} else "TASK SUMMARY"
|
| 1391 |
+
print_key_trace(summary_title, format_key_metrics(result["evaluation"]))
|
| 1392 |
+
print_key_trace("RESULT SAVED", result_path)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
if __name__ == "__main__":
|
| 1396 |
+
main()
|
data/incomplete/task_005/role_agents/climate_systems_engineer.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "HVAC and environmental systems lead (HVAC)",
|
| 3 |
+
"abstract": "Maintains auxiliary climate conditioning power systems and thermal regulation equipment",
|
| 4 |
+
"system_message": "You are HVAC and environmental systems lead (HVAC). The HVAC and environmental systems lead manages auxiliary climate conditioning power systems, thermal regulation equipment, and backup power generation reserves for archive facilities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains auxiliary climate conditioning power systems and thermal regulation equipment(THERM)",
|
| 8 |
+
"content": "HVAC-THERM-9PD:For the Severn Valley Subterranean Vault, the specialized climate conditioning fee covering nitrogen purging and pre-stabilization across storage modules is 11,000 GBP.\nHVAC-THERM-HHK:For the Pennine Deep Geologic Repository, the specialized climate conditioning fee covering nitrogen purging and pre-stabilization across storage modules is 14,000 GBP.\nHVAC-THERM-FSB:For the Cotswold Heritage Preservation Bunker, the specialized climate conditioning fee covering nitrogen purging and pre-stabilization across storage modules is 17,000 GBP."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Backup power generation reserves(GEN)",
|
| 12 |
+
"content": "HVAC-GEN-M8J:The Severn Valley Subterranean Vault maintains an on-site diesel generator runtime reserve of 240 h under full emergency electrical load.\nHVAC-GEN-NXE:The Cotswold Heritage Preservation Bunker maintains an on-site diesel generator runtime reserve of 168 h under full emergency electrical load.\nHVAC-GEN-F4A:The Pennine Deep Geologic Repository maintains an on-site diesel generator runtime reserve of 120 h under full emergency electrical load."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/role_agents/heritage_liaison.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Public heritage liaison (PUB)",
|
| 3 |
+
"abstract": "Tracks community engagement metrics, academic visitation approvals, and exhibition quotas",
|
| 4 |
+
"system_message": "You are the Public heritage liaison (PUB), responsible for tracking community engagement metrics, academic visitation approvals, and exhibition quotas.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Public educational outreach seminars(EXHIB)",
|
| 8 |
+
"content": "PUB-EXHIB-SHO:For Cotswold Heritage Preservation Bunker, the annual conservation seminar frequency across public awareness events conducted in academic year 2025-2026 is 24 sessions.\nPUB-EXHIB-4FH:For Severn Valley Subterranean Vault, the annual conservation seminar frequency recorded across public awareness events conducted in academic year 2025-2026 is 36 sessions.\nPUB-EXHIB-JYP:For Pennine Deep Geologic Repository, the annual conservation seminar frequency documented for public awareness events conducted in academic year 2025-2026 is 12 sessions."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Tracks community engagement metrics, academic visitation approvals, and exhibition quotas(COMM)",
|
| 12 |
+
"content": "PUB-COMM-GZR:For Pennine Deep Geologic Repository, the academic researcher visitation index reflecting annual scholarly visitor accommodations and reading room slots is 92 score.\nPUB-COMM-BCC:For Severn Valley Subterranean Vault, the academic researcher visitation index, which evaluates annual scholarly visitor accommodations and reading room slots, is 45 score.\nPUB-COMM-KLT:For Cotswold Heritage Preservation Bunker, the academic researcher visitation index based on annual scholarly visitor accommodations and reading room slots is 45 score."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/role_agents/logistics_estimator.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Recovery logistics estimator (LOG)",
|
| 3 |
+
"abstract": "Calculates primary transit tariffs, intake transfer handling charges, and specialized climate conditioning costs",
|
| 4 |
+
"system_message": "You are the Recovery logistics estimator (LOG), responsible for calculating primary transit tariffs, intake transfer handling charges, and specialized climate conditioning costs for potential emergency disaster recovery repository sites.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Calculates primary transit tariffs, intake transfer handling charges, and specialized climate conditioning costs(TARIFF)",
|
| 8 |
+
"content": "LOG-TARIFF-99E:For a single emergency archive deployment, the base intake transfer fee for Cotswold Heritage Preservation Bunker is 26000 GBP, covering standard flat charges for offloading, quarantine inspection, and palletized vault transfer.\nLOG-TARIFF-FXE:For a single emergency archive deployment, the base intake transfer fee for Severn Valley Subterranean Vault is 15000 GBP, covering standard flat charges for offloading, quarantine inspection, and palletized vault transfer.\nLOG-TARIFF-DRP:For a single emergency archive deployment, the base intake transfer fee for Pennine Deep Geologic Repository is 15000 GBP, covering standard flat charges for offloading, quarantine inspection, and palletized vault transfer."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Armoured transport convoy allocation(FLEET)",
|
| 12 |
+
"content": "LOG-FLEET-EQ5:Regarding armoured transport convoy allocation on immediate standby for emergency artifact transit, Cotswold Heritage Preservation Bunker has a dedicated climate-controlled vehicle count of 8 vehicles.\nLOG-FLEET-GAS:Regarding armoured transport convoy allocation on immediate standby for emergency artifact transit, Pennine Deep Geologic Repository has a dedicated climate-controlled vehicle count of 4 vehicles.\nLOG-FLEET-JNS:Regarding armoured transport convoy allocation on immediate standby for emergency artifact transit, Severn Valley Subterranean Vault has a dedicated climate-controlled vehicle count of 6 vehicles."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/role_agents/preservation_conservator.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Senior preservation conservator (CONS)",
|
| 3 |
+
"abstract": "Manages preservation microclimate integrity, environmental seals, and continuous climate stabilization verification",
|
| 4 |
+
"system_message": "You are Senior preservation conservator (CONS). The senior preservation conservator oversees preservation microclimate integrity, environmental seals, and continuous climate stabilization verification, alongside microbial remediation and deacidification processing capacities.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Microbial remediation deacidification(DEAC)",
|
| 8 |
+
"content": "CONS-DEAC-I74:Under the fiscal year 2026 processing quotas, the Cotswold Heritage Preservation Bunker has an annual deacidification volume capacity of 1200 linear_metres.\nCONS-DEAC-SU6:The Pennine Deep Geologic Repository provides an annual deacidification volume capacity of 2400 linear_metres under the fiscal year 2026 laboratory processing audit.\nCONS-DEAC-5EC:According to the chemical laboratory audit for fiscal year 2026 processing quotas, the Severn Valley Subterranean Vault provides an annual deacidification volume capacity of 1800 linear_metres."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Manages preservation microclimate integrity, environmental seals, and continuous climate stabilization verification(ENV)",
|
| 12 |
+
"content": "CONS-ENV-3QT:The Cotswold Heritage Preservation Bunker possesses environmental seal certification for its sub-surface containment envelope and maintains active humidity control telemetry. Its off-grid testing recorded a continuous climate stabilization duration of 48 h within BS 4971 limits.\nCONS-ENV-SZY:At the Pennine Deep Geologic Repository, environmental seal certification is formally approved for the containment envelope, and active humidity control telemetry is actively transmitting. In off-grid stress evaluations, its continuous climate stabilization duration sustained BS 4971 standards for 96 h.\nCONS-ENV-IZN:For the Severn Valley Subterranean Vault, environmental seal certification is verified for the primary sub-surface archive containment envelope, and active humidity control telemetry is functional with real-time psychrometric data transmission. During off-grid autonomous environmental stress testing, its continuous climate stabilization duration reached 96 h within BS 4971 standards."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/role_agents/security_director.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Physical security director (SEC)",
|
| 3 |
+
"abstract": "Audits physical vault access controls, perimeter defences, and security clearances",
|
| 4 |
+
"system_message": "You are the Physical security director (SEC). Your responsibilities include auditing physical vault access controls, perimeter defences, and security clearances, as well as tracking operational response drills across archive storage locations.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Audits physical vault access controls, perimeter defences, and security clearances(VAULT)",
|
| 8 |
+
"content": "SEC-VAULT-R9A:For the Cotswold Heritage Preservation Bunker, the certified physical vault security clearance is confirmed as true across its outer security perimeter, airlock controls, and biometric vault chambers.\nSEC-VAULT-IFY:For the Severn Valley Subterranean Vault, the certified physical vault security clearance is confirmed as true across its outer security perimeter, airlock controls, and biometric vault chambers.\nSEC-VAULT-R5E:For the Pennine Deep Geologic Repository, the certified physical vault security clearance is false, as formal accreditation covering its outer security perimeter, airlock controls, and biometric vault chambers is not held."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Armed response drill exercises(GUARD)",
|
| 12 |
+
"content": "SEC-GUARD-A87:Operational drills at the Cotswold Heritage Preservation Bunker demonstrated an emergency tactical response response time of 5 min.\nSEC-GUARD-OQK:Operational drills at the Severn Valley Subterranean Vault demonstrated an emergency tactical response response time of 15 min.\nSEC-GUARD-89M:Operational drills at the Pennine Deep Geologic Repository demonstrated an emergency tactical response response time of 10 min."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/role_agents/statutory_compliance_officer.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Statutory compliance officer (COMP)",
|
| 3 |
+
"abstract": "Monitors local environmental permissions, heritage compliance, and hazardous materials containment permits",
|
| 4 |
+
"system_message": "You are the Statutory compliance officer (COMP), responsible for monitoring local environmental permissions, heritage compliance, and hazardous materials containment permits across candidate disaster recovery repositories.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Q1 2026·Monitors local environmental permissions, heritage compliance, and hazardous materials containment permits(PERM)",
|
| 8 |
+
"content": "COMP-PERM-OAT:For the Q1 2026 statutory audit period, the Cotswold Heritage Preservation Bunker does not hold local environmental permit clearance under its land-use and underground preservation license status.\nCOMP-PERM-FT1:For the Q1 2026 statutory audit period, the Pennine Deep Geologic Repository maintains local environmental permit clearance, with no active environmental enforcement orders or hazardous water runoff violations recorded.\nCOMP-PERM-1N5:For the Q1 2026 statutory audit period, the Severn Valley Subterranean Vault holds local environmental permit clearance, confirming no active environmental enforcement orders or hazardous water runoff violations under its land-use and underground preservation license."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Q2 2026·Monitors local environmental permissions, heritage compliance, and hazardous materials containment permits(AUDIT)",
|
| 12 |
+
"content": "COMP-AUDIT-5NA:Regarding the Q2 2026 statutory audit period, the Cotswold Heritage Preservation Bunker does not possess local environmental permit clearance on the statutory planning register.\nCOMP-AUDIT-PTN:Regarding the Q2 2026 statutory audit period, the Pennine Deep Geologic Repository possesses local environmental permit clearance confirming full statutory compliance without active enforcement orders.\nCOMP-AUDIT-7AW:Regarding the Q2 2026 statutory audit period, the Severn Valley Subterranean Vault does not possess local environmental permit clearance under its underground preservation license status."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/role_agents/structural_engineer.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Geotechnical and structural engineer (ENG)",
|
| 3 |
+
"abstract": "Evaluates subterranean seismic isolation ratings and structural integrity under stress",
|
| 4 |
+
"system_message": "You are Geotechnical and structural engineer (ENG). The Geotechnical and structural engineer (ENG) evaluates subterranean seismic isolation ratings and structural integrity under stress, and conducts subsurface bedrock borehole surveying.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Evaluates subterranean seismic isolation ratings and structural integrity under stress(STRUC)",
|
| 8 |
+
"content": "ENG-STRUC-0L6:Based on geotechnical evaluations of foundation structural elastomer bearings and subterranean bedrock dampers, Severn Valley Subterranean Vault achieved a seismic isolation rating of 9 grade.\nENG-STRUC-MHK:Evaluations of foundation elastomer bearings and bedrock dampers confirm that Cotswold Heritage Preservation Bunker has a seismic isolation rating of 8 grade.\nENG-STRUC-5NY:According to geotechnical resilience assessments of foundation structural bearings and dampers, Pennine Deep Geologic Repository has a seismic isolation rating of 6 grade."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Subsurface bedrock borehole surveying(FOUND)",
|
| 12 |
+
"content": "ENG-FOUND-X3N:Geological borehole survey logs for Pennine Deep Geologic Repository show a bedrock borehole compressive strength of 65 MPa across subterranean bedrock core samples.\nENG-FOUND-N61:Subterranean bedrock core sampling beneath the archive foundation indicates a bedrock borehole compressive strength of 85 MPa for Severn Valley Subterranean Vault.\nENG-FOUND-NSG:Core sample surveys of the subterranean bedrock strata beneath the foundation confirm a bedrock borehole compressive strength of 110 MPa for Cotswold Heritage Preservation Bunker."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_005/tasks/run_one.py
ADDED
|
@@ -0,0 +1,1396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from typing import Any
|
| 5 |
+
COMMUNICATION_ROLE_NAMES = []
|
| 6 |
+
GOLD = {'conclusion': 'Exists', 'numeric_result': 67000}
|
| 7 |
+
POSITIVE_CONCLUSION = 'Exists'
|
| 8 |
+
NEGATIVE_CONCLUSION = 'Does not exist'
|
| 9 |
+
NUMERIC_PRECISION = 0
|
| 10 |
+
PUBLIC_ROLES = [{'role_name': 'Senior preservation conservator (CONS)', 'responsibility': 'Manages preservation microclimate integrity, environmental seals, and continuous climate stabilization verification', 'role_abbreviation': 'CONS'}, {'role_name': 'Geotechnical and structural engineer (ENG)', 'responsibility': 'Evaluates subterranean seismic isolation ratings and structural integrity under stress', 'role_abbreviation': 'ENG'}, {'role_name': 'Physical security director (SEC)', 'responsibility': 'Audits physical vault access controls, perimeter defences, and security clearances', 'role_abbreviation': 'SEC'}, {'role_name': 'Statutory compliance officer (COMP)', 'responsibility': 'Monitors local environmental permissions, heritage compliance, and hazardous materials containment permits', 'role_abbreviation': 'COMP'}, {'role_name': 'Recovery logistics estimator (LOG)', 'responsibility': 'Calculates primary transit tariffs, intake transfer handling charges, and specialized climate conditioning costs', 'role_abbreviation': 'LOG'}, {'role_name': 'HVAC and environmental systems lead (HVAC)', 'responsibility': 'Maintains auxiliary climate conditioning power systems and thermal regulation equipment', 'role_abbreviation': 'HVAC'}, {'role_name': 'Public heritage liaison (PUB)', 'responsibility': 'Tracks community engagement metrics, academic visitation approvals, and exhibition quotas', 'role_abbreviation': 'PUB'}]
|
| 11 |
+
ROLE_KEY_PREFIXES = {'Senior preservation conservator (CONS)': 'CONS-', 'Geotechnical and structural engineer (ENG)': 'ENG-', 'Physical security director (SEC)': 'SEC-', 'Statutory compliance officer (COMP)': 'COMP-', 'Recovery logistics estimator (LOG)': 'LOG-', 'HVAC and environmental systems lead (HVAC)': 'HVAC-', 'Public heritage liaison (PUB)': 'PUB-'}
|
| 12 |
+
ROLE_VALID_KEYS = {'Senior preservation conservator (CONS)': ['CONS-DEAC-I74', 'CONS-DEAC-SU6', 'CONS-DEAC-5EC', 'CONS-ENV-3QT', 'CONS-ENV-SZY', 'CONS-ENV-IZN'], 'Geotechnical and structural engineer (ENG)': ['ENG-STRUC-0L6', 'ENG-STRUC-MHK', 'ENG-STRUC-5NY', 'ENG-FOUND-X3N', 'ENG-FOUND-N61', 'ENG-FOUND-NSG'], 'Physical security director (SEC)': ['SEC-VAULT-R9A', 'SEC-VAULT-IFY', 'SEC-VAULT-R5E', 'SEC-GUARD-A87', 'SEC-GUARD-OQK', 'SEC-GUARD-89M'], 'Statutory compliance officer (COMP)': ['COMP-PERM-OAT', 'COMP-PERM-FT1', 'COMP-PERM-1N5', 'COMP-AUDIT-5NA', 'COMP-AUDIT-PTN', 'COMP-AUDIT-7AW'], 'Recovery logistics estimator (LOG)': ['LOG-TARIFF-99E', 'LOG-TARIFF-FXE', 'LOG-TARIFF-DRP', 'LOG-FLEET-EQ5', 'LOG-FLEET-GAS', 'LOG-FLEET-JNS'], 'HVAC and environmental systems lead (HVAC)': ['HVAC-THERM-9PD', 'HVAC-THERM-HHK', 'HVAC-THERM-FSB', 'HVAC-GEN-M8J', 'HVAC-GEN-NXE', 'HVAC-GEN-F4A'], 'Public heritage liaison (PUB)': ['PUB-EXHIB-SHO', 'PUB-EXHIB-4FH', 'PUB-EXHIB-JYP', 'PUB-COMM-GZR', 'PUB-COMM-BCC', 'PUB-COMM-KLT']}
|
| 13 |
+
RECORD_REPLY_KEYS = {'CONS-ENV-IZN': ['CONS-ENV-IZN'], 'CONS-ENV-3QT': ['CONS-ENV-3QT'], 'CONS-ENV-SZY': ['CONS-ENV-SZY'], 'ENG-STRUC-0L6': ['ENG-STRUC-0L6'], 'ENG-STRUC-MHK': ['ENG-STRUC-MHK'], 'ENG-STRUC-5NY': ['ENG-STRUC-5NY'], 'SEC-VAULT-IFY': ['SEC-VAULT-IFY'], 'SEC-VAULT-R9A': ['SEC-VAULT-R9A'], 'SEC-VAULT-R5E': ['SEC-VAULT-R5E'], 'COMP-PERM-1N5': ['COMP-PERM-1N5'], 'COMP-PERM-OAT': ['COMP-PERM-OAT'], 'COMP-PERM-FT1': ['COMP-PERM-FT1'], 'LOG-TARIFF-FXE': ['LOG-TARIFF-FXE'], 'LOG-TARIFF-99E': ['LOG-TARIFF-99E'], 'LOG-TARIFF-DRP': ['LOG-TARIFF-DRP'], 'HVAC-THERM-9PD': ['HVAC-THERM-9PD'], 'HVAC-THERM-FSB': ['HVAC-THERM-FSB'], 'HVAC-THERM-HHK': ['HVAC-THERM-HHK'], 'PUB-COMM-BCC': ['PUB-COMM-BCC'], 'PUB-COMM-KLT': ['PUB-COMM-KLT'], 'PUB-COMM-GZR': ['PUB-COMM-GZR'], 'CONS-DEAC-5EC': ['CONS-DEAC-5EC'], 'CONS-DEAC-I74': ['CONS-DEAC-I74'], 'CONS-DEAC-SU6': ['CONS-DEAC-SU6'], 'ENG-FOUND-N61': ['ENG-FOUND-N61'], 'ENG-FOUND-NSG': ['ENG-FOUND-NSG'], 'ENG-FOUND-X3N': ['ENG-FOUND-X3N'], 'SEC-GUARD-OQK': ['SEC-GUARD-OQK'], 'SEC-GUARD-A87': ['SEC-GUARD-A87'], 'SEC-GUARD-89M': ['SEC-GUARD-89M'], 'LOG-FLEET-JNS': ['LOG-FLEET-JNS'], 'LOG-FLEET-EQ5': ['LOG-FLEET-EQ5'], 'LOG-FLEET-GAS': ['LOG-FLEET-GAS'], 'HVAC-GEN-M8J': ['HVAC-GEN-M8J'], 'HVAC-GEN-NXE': ['HVAC-GEN-NXE'], 'HVAC-GEN-F4A': ['HVAC-GEN-F4A'], 'PUB-EXHIB-4FH': ['PUB-EXHIB-4FH'], 'PUB-EXHIB-SHO': ['PUB-EXHIB-SHO'], 'PUB-EXHIB-JYP': ['PUB-EXHIB-JYP'], 'COMP-AUDIT-7AW': ['COMP-AUDIT-7AW'], 'COMP-AUDIT-5NA': ['COMP-AUDIT-5NA'], 'COMP-AUDIT-PTN': ['COMP-AUDIT-PTN']}
|
| 14 |
+
REQUIRED_KEYS = ['COMP-PERM-1N5', 'CONS-ENV-3QT', 'CONS-ENV-IZN', 'ENG-STRUC-0L6', 'ENG-STRUC-5NY', 'HVAC-THERM-9PD', 'LOG-TARIFF-FXE', 'SEC-VAULT-IFY']
|
| 15 |
+
DISTRACTOR_KEYS = ['PUB-COMM-BCC', 'PUB-COMM-GZR', 'PUB-COMM-KLT', 'PUB-EXHIB-4FH', 'PUB-EXHIB-JYP', 'PUB-EXHIB-SHO']
|
| 16 |
+
SETTING = 'incomplete'
|
| 17 |
+
|
| 18 |
+
def runtime_defaults() -> dict[str, Any]:
|
| 19 |
+
return {
|
| 20 |
+
"setting": SETTING,
|
| 21 |
+
"communication_role_names": list(COMMUNICATION_ROLE_NAMES),
|
| 22 |
+
"finalize_ideal_round": 3,
|
| 23 |
+
"max_turns": 6,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
FINALIZE_IDEAL_ROUND = runtime_defaults()["finalize_ideal_round"]
|
| 27 |
+
DEFAULT_MAX_TURNS = runtime_defaults()["max_turns"]
|
| 28 |
+
ERROR_INJECTION = {'enabled': False, 'role_name': 'Statutory compliance officer (COMP)', 'target_key': 'COMP-PERM-1N5', 'alternate_key': 'COMP-AUDIT-7AW', 'target_context': 'Q1 2026', 'alternate_context': 'Q2 2026'}
|
| 29 |
+
INCOMPLETE_INJECTION = {'record_id': 'rec_preservation_conservator_A', 'role_id': 'preservation_conservator', 'candidate_id': 'A', 'key': 'CONS-ENV-IZN', 'boolean_predicate_id': 'A_humidity_telemetry_active', 'boolean_label': 'Active humidity control telemetry', 'hidden_predicate_id': 'A_climate_stabilization_duration', 'threshold_label': 'Continuous climate stabilization duration', 'threshold_aliases': ['Stabilization endurance', 'Climate autonomy duration'], 'threshold_value': 96, 'threshold_unit': 'h', 'partial_record_text': 'CONS-ENV-IZN: Severn Valley Subterranean Vault.Severn Valley Subterranean Vault: Environmental seal certification = true .Source: Preservation chamber seal integrity certificate; Scope: Primary sub-surface archive containment envelope; Measurement: Formal validation that chamber boundaries achieve airtight isolation against external air contaminants.Severn Valley Subterranean Vault: Active humidity control telemetry = true .Source: Telemetry interface verification record; Scope: Automated psychrometric sensor array inside storage vaults; Measurement: Active real-time transmission status of relative humidity data packets to the conservator console.', 'alternative_outputs': [{'conclusion': 'Does not exist', 'numeric_result': None, 'qualified_candidate_id': None}], 'disclosure_mode': 'interval', 'disclosure_version': 'truthful_bounds_v3_domain_bounds', 'disclosure_bounds': {'lower': 20, 'upper': 300}, 'coarse_statement': 'Continuous climate stabilization duration is between 20 h and 300 h, inclusive.', 'role_name': 'Senior preservation conservator (CONS)', 'candidate_name': 'Severn Valley Subterranean Vault', 'other_candidate_names': ['Cotswold Heritage Preservation Bunker', 'Pennine Deep Geologic Repository'], 'context_value': None, 'other_context_values': [], 'language': 'en'}
|
| 30 |
+
INCOMPLETE_FOLLOWUP_RECORDS = [{'key': 'CONS-ENV-IZN', 'role': 'Senior preservation conservator (CONS)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'environmental_seal_certified', 'label': 'Environmental seal certification', 'aliases': ['Seal certification', 'Atmospheric barrier certification']}, {'id': 'humidity_telemetry_active', 'label': 'Active humidity control telemetry', 'aliases': ['Humidity telemetry link', 'Microclimate telemetry presence']}, {'id': 'climate_stabilization_duration', 'label': 'Continuous climate stabilization duration', 'aliases': ['Stabilization endurance', 'Climate autonomy duration']}]}, {'key': 'CONS-ENV-3QT', 'role': 'Senior preservation conservator (CONS)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'environmental_seal_certified', 'label': 'Environmental seal certification', 'aliases': ['Seal certification', 'Atmospheric barrier certification']}, {'id': 'humidity_telemetry_active', 'label': 'Active humidity control telemetry', 'aliases': ['Humidity telemetry link', 'Microclimate telemetry presence']}, {'id': 'climate_stabilization_duration', 'label': 'Continuous climate stabilization duration', 'aliases': ['Stabilization endurance', 'Climate autonomy duration']}]}, {'key': 'CONS-ENV-SZY', 'role': 'Senior preservation conservator (CONS)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'environmental_seal_certified', 'label': 'Environmental seal certification', 'aliases': ['Seal certification', 'Atmospheric barrier certification']}, {'id': 'humidity_telemetry_active', 'label': 'Active humidity control telemetry', 'aliases': ['Humidity telemetry link', 'Microclimate telemetry presence']}, {'id': 'climate_stabilization_duration', 'label': 'Continuous climate stabilization duration', 'aliases': ['Stabilization endurance', 'Climate autonomy duration']}]}, {'key': 'ENG-STRUC-0L6', 'role': 'Geotechnical and structural engineer (ENG)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'seismic_isolation_rating', 'label': 'Seismic isolation rating', 'aliases': ['Seismic rating', 'Ground motion attenuation grade']}]}, {'key': 'ENG-STRUC-MHK', 'role': 'Geotechnical and structural engineer (ENG)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'seismic_isolation_rating', 'label': 'Seismic isolation rating', 'aliases': ['Seismic rating', 'Ground motion attenuation grade']}]}, {'key': 'ENG-STRUC-5NY', 'role': 'Geotechnical and structural engineer (ENG)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'seismic_isolation_rating', 'label': 'Seismic isolation rating', 'aliases': ['Seismic rating', 'Ground motion attenuation grade']}]}, {'key': 'SEC-VAULT-IFY', 'role': 'Physical security director (SEC)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'physical_vault_clearance', 'label': 'Certified physical vault security clearance', 'aliases': ['Vault clearance', 'Physical security rating clearance']}]}, {'key': 'SEC-VAULT-R9A', 'role': 'Physical security director (SEC)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'physical_vault_clearance', 'label': 'Certified physical vault security clearance', 'aliases': ['Vault clearance', 'Physical security rating clearance']}]}, {'key': 'SEC-VAULT-R5E', 'role': 'Physical security director (SEC)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'physical_vault_clearance', 'label': 'Certified physical vault security clearance', 'aliases': ['Vault clearance', 'Physical security rating clearance']}]}, {'key': 'COMP-PERM-1N5', 'role': 'Statutory compliance officer (COMP)', 'candidate': 'Severn Valley Subterranean Vault', 'context': 'Q1 2026', 'fields': [{'id': 'environmental_permit_cleared', 'label': 'Local environmental permit clearance', 'aliases': ['Environmental permit clearance', 'Statutory environmental license']}]}, {'key': 'COMP-PERM-OAT', 'role': 'Statutory compliance officer (COMP)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': 'Q1 2026', 'fields': [{'id': 'environmental_permit_cleared', 'label': 'Local environmental permit clearance', 'aliases': ['Environmental permit clearance', 'Statutory environmental license']}]}, {'key': 'COMP-PERM-FT1', 'role': 'Statutory compliance officer (COMP)', 'candidate': 'Pennine Deep Geologic Repository', 'context': 'Q1 2026', 'fields': [{'id': 'environmental_permit_cleared', 'label': 'Local environmental permit clearance', 'aliases': ['Environmental permit clearance', 'Statutory environmental license']}]}, {'key': 'LOG-TARIFF-FXE', 'role': 'Recovery logistics estimator (LOG)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'intake_transfer_fee', 'label': 'Base intake transfer fee', 'aliases': ['Intake handling tariff', 'Initial intake fee']}]}, {'key': 'LOG-TARIFF-99E', 'role': 'Recovery logistics estimator (LOG)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'intake_transfer_fee', 'label': 'Base intake transfer fee', 'aliases': ['Intake handling tariff', 'Initial intake fee']}]}, {'key': 'LOG-TARIFF-DRP', 'role': 'Recovery logistics estimator (LOG)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'intake_transfer_fee', 'label': 'Base intake transfer fee', 'aliases': ['Intake handling tariff', 'Initial intake fee']}]}, {'key': 'HVAC-THERM-9PD', 'role': 'HVAC and environmental systems lead (HVAC)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'climate_conditioning_fee', 'label': 'Specialized climate conditioning fee', 'aliases': ['Climate conditioning surcharge', 'Microclimate conditioning charge']}]}, {'key': 'HVAC-THERM-FSB', 'role': 'HVAC and environmental systems lead (HVAC)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'climate_conditioning_fee', 'label': 'Specialized climate conditioning fee', 'aliases': ['Climate conditioning surcharge', 'Microclimate conditioning charge']}]}, {'key': 'HVAC-THERM-HHK', 'role': 'HVAC and environmental systems lead (HVAC)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'climate_conditioning_fee', 'label': 'Specialized climate conditioning fee', 'aliases': ['Climate conditioning surcharge', 'Microclimate conditioning charge']}]}, {'key': 'PUB-COMM-BCC', 'role': 'Public heritage liaison (PUB)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'academic_visitation_index', 'label': 'Academic researcher visitation index', 'aliases': ['Researcher accessibility index', 'Scholarly access score']}]}, {'key': 'PUB-COMM-KLT', 'role': 'Public heritage liaison (PUB)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'academic_visitation_index', 'label': 'Academic researcher visitation index', 'aliases': ['Researcher accessibility index', 'Scholarly access score']}]}, {'key': 'PUB-COMM-GZR', 'role': 'Public heritage liaison (PUB)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'academic_visitation_index', 'label': 'Academic researcher visitation index', 'aliases': ['Researcher accessibility index', 'Scholarly access score']}]}, {'key': 'CONS-DEAC-5EC', 'role': 'Senior preservation conservator (CONS)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'supplemental_preservation_conservator', 'label': 'Annual deacidification volume capacity', 'aliases': []}]}, {'key': 'CONS-DEAC-I74', 'role': 'Senior preservation conservator (CONS)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'supplemental_preservation_conservator', 'label': 'Annual deacidification volume capacity', 'aliases': []}]}, {'key': 'CONS-DEAC-SU6', 'role': 'Senior preservation conservator (CONS)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'supplemental_preservation_conservator', 'label': 'Annual deacidification volume capacity', 'aliases': []}]}, {'key': 'ENG-FOUND-N61', 'role': 'Geotechnical and structural engineer (ENG)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'supplemental_structural_engineer', 'label': 'Bedrock borehole compressive strength', 'aliases': []}]}, {'key': 'ENG-FOUND-NSG', 'role': 'Geotechnical and structural engineer (ENG)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'supplemental_structural_engineer', 'label': 'Bedrock borehole compressive strength', 'aliases': []}]}, {'key': 'ENG-FOUND-X3N', 'role': 'Geotechnical and structural engineer (ENG)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'supplemental_structural_engineer', 'label': 'Bedrock borehole compressive strength', 'aliases': []}]}, {'key': 'SEC-GUARD-OQK', 'role': 'Physical security director (SEC)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'supplemental_security_director', 'label': 'Emergency tactical response response time', 'aliases': []}]}, {'key': 'SEC-GUARD-A87', 'role': 'Physical security director (SEC)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'supplemental_security_director', 'label': 'Emergency tactical response response time', 'aliases': []}]}, {'key': 'SEC-GUARD-89M', 'role': 'Physical security director (SEC)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'supplemental_security_director', 'label': 'Emergency tactical response response time', 'aliases': []}]}, {'key': 'LOG-FLEET-JNS', 'role': 'Recovery logistics estimator (LOG)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'supplemental_logistics_estimator', 'label': 'Dedicated climate-controlled vehicle count', 'aliases': []}]}, {'key': 'LOG-FLEET-EQ5', 'role': 'Recovery logistics estimator (LOG)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'supplemental_logistics_estimator', 'label': 'Dedicated climate-controlled vehicle count', 'aliases': []}]}, {'key': 'LOG-FLEET-GAS', 'role': 'Recovery logistics estimator (LOG)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'supplemental_logistics_estimator', 'label': 'Dedicated climate-controlled vehicle count', 'aliases': []}]}, {'key': 'HVAC-GEN-M8J', 'role': 'HVAC and environmental systems lead (HVAC)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'supplemental_climate_systems_engineer', 'label': 'Diesel generator runtime reserve', 'aliases': []}]}, {'key': 'HVAC-GEN-NXE', 'role': 'HVAC and environmental systems lead (HVAC)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'supplemental_climate_systems_engineer', 'label': 'Diesel generator runtime reserve', 'aliases': []}]}, {'key': 'HVAC-GEN-F4A', 'role': 'HVAC and environmental systems lead (HVAC)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'supplemental_climate_systems_engineer', 'label': 'Diesel generator runtime reserve', 'aliases': []}]}, {'key': 'PUB-EXHIB-4FH', 'role': 'Public heritage liaison (PUB)', 'candidate': 'Severn Valley Subterranean Vault', 'context': '', 'fields': [{'id': 'supplemental_heritage_liaison', 'label': 'Annual conservation seminar frequency', 'aliases': []}]}, {'key': 'PUB-EXHIB-SHO', 'role': 'Public heritage liaison (PUB)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': '', 'fields': [{'id': 'supplemental_heritage_liaison', 'label': 'Annual conservation seminar frequency', 'aliases': []}]}, {'key': 'PUB-EXHIB-JYP', 'role': 'Public heritage liaison (PUB)', 'candidate': 'Pennine Deep Geologic Repository', 'context': '', 'fields': [{'id': 'supplemental_heritage_liaison', 'label': 'Annual conservation seminar frequency', 'aliases': []}]}, {'key': 'COMP-AUDIT-7AW', 'role': 'Statutory compliance officer (COMP)', 'candidate': 'Severn Valley Subterranean Vault', 'context': 'Q2 2026', 'fields': [{'id': 'environmental_permit_cleared', 'label': 'Local environmental permit clearance', 'aliases': ['Environmental permit clearance', 'Statutory environmental license']}]}, {'key': 'COMP-AUDIT-5NA', 'role': 'Statutory compliance officer (COMP)', 'candidate': 'Cotswold Heritage Preservation Bunker', 'context': 'Q2 2026', 'fields': [{'id': 'environmental_permit_cleared', 'label': 'Local environmental permit clearance', 'aliases': ['Environmental permit clearance', 'Statutory environmental license']}]}, {'key': 'COMP-AUDIT-PTN', 'role': 'Statutory compliance officer (COMP)', 'candidate': 'Pennine Deep Geologic Repository', 'context': 'Q2 2026', 'fields': [{'id': 'environmental_permit_cleared', 'label': 'Local environmental permit clearance', 'aliases': ['Environmental permit clearance', 'Statutory environmental license']}]}]
|
| 31 |
+
KEY_PATTERN = re.compile(r"^[A-Z]+-[A-Z]+-[A-Z0-9]{3}$")
|
| 32 |
+
REPLY_KEY_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z]+-[A-Z]+-[A-Z0-9]{3}(?![A-Z0-9])", re.IGNORECASE)
|
| 33 |
+
ROLE_REPLY_MAX_ATTEMPTS = 3
|
| 34 |
+
TASK_QUERY = 'Determine whether there exists a unique disaster recovery repository site meeting all of the following qualification criteria: environmental seal certification is verified, active humidity control telemetry is enabled and continuous climate stabilization duration is at least 72 h, seismic isolation rating is at least 8 grade, certified physical vault security clearance is held, and local environmental permit clearance is granted for the Q1 2026 statutory audit period. If such a repository site exists, conclude with "Exists" and calculate its total weighted staging cost in GBP by taking 3 times its base intake transfer fee plus 2 times its specialized climate conditioning fee; otherwise, conclude with "Does not exist" and set the numeric result to null.\n\nNumeric calculation rule: Compute only for the unique eligible candidate: 3 * [Base intake transfer fee] + 2 * [Specialized climate conditioning fee] (sum directly; do not divide by the sum of weights). Result unit: GBP. Round only the final result to 0 decimal places (ties to even). If no candidate qualifies, numeric_result is null.\n\nCandidates and records to verify:\n- Cotswold Heritage Preservation Bunker:CONS-ENV-3QT、ENG-STRUC-MHK、SEC-VAULT-R9A、COMP-PERM-OAT、LOG-TARIFF-99E、HVAC-THERM-FSB、PUB-COMM-KLT\n- Pennine Deep Geologic Repository:CONS-ENV-SZY、ENG-STRUC-5NY、SEC-VAULT-R5E、COMP-PERM-FT1、LOG-TARIFF-DRP、HVAC-THERM-HHK、PUB-COMM-GZR\n- Severn Valley Subterranean Vault:CONS-ENV-IZN、ENG-STRUC-0L6、SEC-VAULT-IFY、COMP-PERM-1N5、LOG-TARIFF-FXE、HVAC-THERM-9PD、PUB-COMM-BCC'
|
| 35 |
+
TASK_CONTEXT = 'Disaster recovery repositories are evaluated to safeguard emergency archive assets under adverse environmental and geotechnical conditions. Facility assessment requires validating airtight containment seals, uninterrupted climate stabilization capabilities, seismic dampening thresholds, physical security credentials, and statutory environmental clearances. For qualifying facilities, staging costs are analyzed using weighted intake transfer and microclimate pre-conditioning charges to determine initial relocation expenditures.'
|
| 36 |
+
|
| 37 |
+
"""Parse one model message without treating trailing generation noise as an action."""
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from typing import Any
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_json_message(content: Any, *, trace: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 44 |
+
if trace is not None:
|
| 45 |
+
trace.clear()
|
| 46 |
+
trace.update(policy="first_complete_object", raw_response=content, recovered=False)
|
| 47 |
+
if not isinstance(content, str):
|
| 48 |
+
raise ValueError("model response must be text")
|
| 49 |
+
text = content.strip().lstrip("\ufeff").strip()
|
| 50 |
+
# Parse the first complete object; never recover a nested fragment.
|
| 51 |
+
try:
|
| 52 |
+
value, end = json.JSONDecoder().raw_decode(text)
|
| 53 |
+
start = 0
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
if text.startswith(("{", "[", '"')):
|
| 56 |
+
raise
|
| 57 |
+
opening = re.search(r"[\{\[]", text)
|
| 58 |
+
if opening is None:
|
| 59 |
+
raise
|
| 60 |
+
start = opening.start()
|
| 61 |
+
value, consumed = json.JSONDecoder().raw_decode(text[start:])
|
| 62 |
+
end = start + consumed
|
| 63 |
+
if not isinstance(value, dict):
|
| 64 |
+
raise ValueError("model response must be a JSON object")
|
| 65 |
+
prefix, suffix = text[:start], text[end:]
|
| 66 |
+
if trace is not None:
|
| 67 |
+
trace.update(recovered=bool(prefix.strip() or suffix.strip()),
|
| 68 |
+
ignored_prefix=prefix, ignored_suffix=suffix)
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def expand_question_keys(questions):
|
| 73 |
+
expanded = []
|
| 74 |
+
for question in questions:
|
| 75 |
+
if not isinstance(question, dict):
|
| 76 |
+
expanded.append(question)
|
| 77 |
+
continue
|
| 78 |
+
text = question.get("question")
|
| 79 |
+
keys = list(dict.fromkeys(REPLY_KEY_PATTERN.findall(text))) if isinstance(text, str) else []
|
| 80 |
+
for key in keys or [None]:
|
| 81 |
+
expanded.append(dict(question, key=key))
|
| 82 |
+
return expanded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def validate_question(question, *, role_name, semantic_enabled=False):
|
| 86 |
+
if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
|
| 87 |
+
raise ValueError("question must contain natural-language text")
|
| 88 |
+
if role_name not in ROLE_KEY_PREFIXES:
|
| 89 |
+
raise ValueError("unknown Role")
|
| 90 |
+
key = question.get("key")
|
| 91 |
+
authorized = semantic_enabled if key is None else (
|
| 92 |
+
isinstance(key, str) and key in ROLE_VALID_KEYS[role_name] and key in question["question"])
|
| 93 |
+
return {"authorized": bool(authorized)}
|
| 94 |
+
|
| 95 |
+
def recovery_key_match(answer: str) -> str | None:
|
| 96 |
+
target = ERROR_INJECTION.get("target_key")
|
| 97 |
+
if not target:
|
| 98 |
+
return None
|
| 99 |
+
def contains(key: str) -> bool:
|
| 100 |
+
return bool(re.search(r"(?<![A-Z0-9-])" + re.escape(key) + r"(?![A-Z0-9-])", answer, re.IGNORECASE))
|
| 101 |
+
if contains(target):
|
| 102 |
+
return "full_key"
|
| 103 |
+
parts = target.split("-")
|
| 104 |
+
alias = parts[0] + "-" + parts[-1]
|
| 105 |
+
matches = [key for key in ROLE_VALID_KEYS.get(ERROR_INJECTION.get("role_name"), [])
|
| 106 |
+
if key.split("-")[0] + "-" + key.split("-")[-1] == alias]
|
| 107 |
+
if matches == [target] and contains(alias):
|
| 108 |
+
return "abbreviated_key"
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
def communication_metrics(transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 112 |
+
key_query_rounds: dict[str, int] = {}
|
| 113 |
+
key_query_counts: dict[str, int] = {}
|
| 114 |
+
queried_roles: set[str] = set()
|
| 115 |
+
mismatch_round: int | None = None
|
| 116 |
+
recovery_query_sent = False
|
| 117 |
+
recovery_query_turn: int | None = None
|
| 118 |
+
target_key_returned = False
|
| 119 |
+
recovery_turn: int | None = None
|
| 120 |
+
recovery_method: str | None = None
|
| 121 |
+
recovery_reference: str | None = None
|
| 122 |
+
target_key_query_turn: int | None = None
|
| 123 |
+
finalized_before_recovery = False
|
| 124 |
+
for event in transcript:
|
| 125 |
+
turn = int(event.get("turn", len(transcript)))
|
| 126 |
+
action = event.get("main_agent_action", {})
|
| 127 |
+
if (
|
| 128 |
+
ERROR_INJECTION.get("enabled")
|
| 129 |
+
and action.get("action") == "finalize"
|
| 130 |
+
and not target_key_returned
|
| 131 |
+
):
|
| 132 |
+
finalized_before_recovery = True
|
| 133 |
+
if action.get("action") != "ask_role_agents": continue
|
| 134 |
+
for answer in event.get("role_answers", []):
|
| 135 |
+
role_name = answer.get("role_agent")
|
| 136 |
+
if role_name: queried_roles.add(role_name)
|
| 137 |
+
if (
|
| 138 |
+
ERROR_INJECTION.get("enabled") and mismatch_round is not None and turn > mismatch_round
|
| 139 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 140 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("target_key")
|
| 141 |
+
and "role_trace" in answer
|
| 142 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 143 |
+
):
|
| 144 |
+
target_key_query_turn = target_key_query_turn or turn
|
| 145 |
+
if (
|
| 146 |
+
ERROR_INJECTION.get("enabled")
|
| 147 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 148 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("alternate_key")
|
| 149 |
+
and "role_trace" in answer
|
| 150 |
+
):
|
| 151 |
+
mismatch_round = mismatch_round or turn
|
| 152 |
+
for message in action.get("messages", []):
|
| 153 |
+
for question in message.get("questions", []):
|
| 154 |
+
key = question.get("key")
|
| 155 |
+
if (
|
| 156 |
+
ERROR_INJECTION.get("enabled")
|
| 157 |
+
and resolve_role_name(message.get("role_agent")) == ERROR_INJECTION.get("role_name")
|
| 158 |
+
and (key is None or key == ERROR_INJECTION.get("target_key"))
|
| 159 |
+
and mismatch_round is not None
|
| 160 |
+
and turn > mismatch_round
|
| 161 |
+
):
|
| 162 |
+
recovery_query_sent = True
|
| 163 |
+
recovery_query_turn = recovery_query_turn or turn
|
| 164 |
+
if not isinstance(key, str) or not KEY_PATTERN.fullmatch(key): continue
|
| 165 |
+
key_query_rounds.setdefault(key, turn)
|
| 166 |
+
key_query_counts[key] = key_query_counts.get(key, 0) + 1
|
| 167 |
+
if recovery_query_sent and not target_key_returned and mismatch_round is not None and turn > mismatch_round:
|
| 168 |
+
for answer in event.get("role_answers", []):
|
| 169 |
+
question = answer.get("question", {})
|
| 170 |
+
if (
|
| 171 |
+
answer.get("role_agent") == ERROR_INJECTION.get("role_name")
|
| 172 |
+
and (question.get("key") is None or question.get("key") == ERROR_INJECTION.get("target_key"))
|
| 173 |
+
and "role_trace" in answer
|
| 174 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 175 |
+
):
|
| 176 |
+
target_key_returned = True
|
| 177 |
+
recovery_reference = recovery_key_match(str(answer.get("answer", "")))
|
| 178 |
+
recovery_turn = turn
|
| 179 |
+
recovery_method = "keyless_query" if question.get("key") is None else "target_key_query"
|
| 180 |
+
break
|
| 181 |
+
queried = set(key_query_counts)
|
| 182 |
+
required = set(REQUIRED_KEYS)
|
| 183 |
+
relevant = queried & required
|
| 184 |
+
return {
|
| 185 |
+
"required_key_recall":len(relevant)/len(required) if required else 1.0,
|
| 186 |
+
"required_key_precision":len(relevant)/len(queried) if queried else 0.0,
|
| 187 |
+
"key_query_rounds":key_query_rounds,
|
| 188 |
+
"key_query_counts":key_query_counts,
|
| 189 |
+
"duplicate_key_queries":sum(max(0, count-1) for count in key_query_counts.values()),
|
| 190 |
+
"distractor_key_queries":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS),
|
| 191 |
+
"distractor_key_query_rate":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS)/sum(key_query_counts.values()) if key_query_counts else 0.0,
|
| 192 |
+
"turns_to_finalize":len(transcript),
|
| 193 |
+
"mismatch_key_queried":mismatch_round is not None,
|
| 194 |
+
"mismatch_key_turn":mismatch_round,
|
| 195 |
+
"recovery_query_sent":recovery_query_sent,
|
| 196 |
+
"recovery_query_turn":recovery_query_turn,
|
| 197 |
+
"target_key_returned":target_key_returned,
|
| 198 |
+
"recovery_turn":recovery_turn,
|
| 199 |
+
"recovery_method":recovery_method,
|
| 200 |
+
"target_key_query_turn":target_key_query_turn,
|
| 201 |
+
"recovery_key_match":recovery_reference,
|
| 202 |
+
"recovery_metrics_version":"keyed_and_keyless_v3",
|
| 203 |
+
"recovery_latency":recovery_turn - mismatch_round if recovery_turn is not None and mismatch_round is not None else None,
|
| 204 |
+
"finalized_before_recovery":finalized_before_recovery,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
def main_system_prompt() -> str:
|
| 208 |
+
role_text = "\n".join(f"- {item['role_name']}: {item['responsibility']}" for item in PUBLIC_ROLES)
|
| 209 |
+
ask_example = json.dumps({"action":"ask_role_agents","messages":[{"role_agent":"Role name","questions":[{"id":"Q1","question":"Please provide the record for ABC-DATA-A1B using the supplied key."}]}]}, ensure_ascii=False)
|
| 210 |
+
final_example = json.dumps({"action":"finalize","conclusion":"Exactly: " + POSITIVE_CONCLUSION + " or " + NEGATIVE_CONCLUSION,"numeric_result":None}, ensure_ascii=False).replace('"numeric_result": null', '"numeric_result": null/number')
|
| 211 |
+
communication_protocol = ('You may output {"action":"wait"} to advance one logical turn. An empty observation {"observations":[]} means no new visible messages; it does not imply receipt, processing or any future reply.' if SETTING in {'missed', 'mixed'} else '')
|
| 212 |
+
followup = ('For keyless follow-ups, name the candidate in full and the metric explicitly, or request that candidate\'s complete records. A unique previously queried record can be checked directly; otherwise supply a full key and metric when asked to clarify. Explicit directory requests return the complete directory.' if SETTING == 'incomplete' else
|
| 213 |
+
'Authorized keyless follow-ups may name the candidate and metric or request complete records. A role may retrieve facts, request clarification or return a directory. If given a directory, select a valid key to obtain facts.' if SETTING == 'mixed' else
|
| 214 |
+
'Authorized keyless questions return that role\'s complete directory. Choose a key from the directory to obtain concrete facts.')
|
| 215 |
+
return "\n\n".join([
|
| 216 |
+
'You are the Main Agent. Integrate information from independent role agents and make the final decision. Communicate in English.',
|
| 217 |
+
'You cannot see private role information directly. Obtain it only by explicitly messaging the role agents.',
|
| 218 |
+
'Key protocol:\n1. Candidate names and record keys are supplied in the task. Initial access requires a valid key; authorized later follow-ups are the exception.\n'
|
| 219 |
+
'2. Keys use ROLE-BUSINESS-XXX: role abbreviation, business abbreviation and three random alphanumeric characters. Use complete supplied keys; do not invent them.\n'
|
| 220 |
+
'3. Send each key to its owning business role. Use valid keys supplied by roles for subsequent checks.\n'
|
| 221 |
+
'4. Do not output a separate key field. Put the complete key in question text; the system extracts it and checks ownership. Separate different keys into individual questions, preferably one record per question.\n'
|
| 222 |
+
'5. After a successful keyed query to a role, keyless natural-language follow-ups to that role are authorized starting from the next turn.\n6. ' + followup,
|
| 223 |
+
'Available independent role agents:\n\n' + role_text,
|
| 224 |
+
'To ask questions, output only JSON in this form:\n\n' + ask_example,
|
| 225 |
+
*([communication_protocol] if communication_protocol else []),
|
| 226 |
+
'Final answer format (output only valid JSON):\n\n' + final_example,
|
| 227 |
+
'Use exactly one of these conclusion labels: ' + POSITIVE_CONCLUSION + ' or ' + NEGATIVE_CONCLUSION + '. '
|
| 228 |
+
'Do not append a candidate name, explanation or other text. null/number means choose one, not literal syntax. '
|
| 229 |
+
'For a positive conclusion provide the computed number; for a negative conclusion use null. Do not include units or explanations in numeric_result.',
|
| 230 |
+
])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
"""Conservative English evidence rules shared by standalone generated runtimes.
|
| 234 |
+
|
| 235 |
+
This is attribution of explicit statements, not arbitrary semantic entailment.
|
| 236 |
+
Unsupported or conflicting statements remain unknown; no model calls are made.
|
| 237 |
+
"""
|
| 238 |
+
import re
|
| 239 |
+
from decimal import Decimal
|
| 240 |
+
|
| 241 |
+
_RECOVERY_NUMBER = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?'
|
| 242 |
+
_RECOVERY_UNCERTAIN = r"\b(?:unknown|uncertain|unclear|may|might|could|should|would|must|expected|possibly|whether|cannot|unable|unconfirmed|approximately|about|around|roughly|estimated|not confirmed|not known|not established)\b"
|
| 243 |
+
_RECOVERY_NEGATIVE = r'\b(?:not|no|never|false|invalid|blocked|failed|denied|unavailable|unapproved|revoked|inactive|disabled|noncompliant)\b'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def evidence_text(text):
|
| 247 |
+
text = text.replace('’', "'").replace('−', '-').replace('‑', '-')
|
| 248 |
+
text = re.sub(r"\bcan't\b", 'cannot', text, flags=re.I)
|
| 249 |
+
text = re.sub(r"n't\b", ' not', text, flags=re.I)
|
| 250 |
+
text = re.sub(r'(?<![\w.,])[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,]|\.\d)',
|
| 251 |
+
lambda m: m[0].replace(',', ''), text)
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def evidence_phrase(text, phrase):
|
| 256 |
+
if not phrase:
|
| 257 |
+
return False
|
| 258 |
+
return bool(re.search(r'(?<!\w)' + re.escape(phrase).replace(r'\ ', r'\s+') + r'(?!\w)', text, re.I))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def evidence_nonasserted(text):
|
| 262 |
+
"""Questions, hypotheses and unconfirmed claims are not returned facts."""
|
| 263 |
+
return bool('?' in text or re.search(_RECOVERY_UNCERTAIN, text, re.I)
|
| 264 |
+
or re.search(r'\b(?:if|unless|assuming|suppose|supposing|hypothetically)\b', text, re.I)
|
| 265 |
+
or re.search(r'\b(?:do|does|did|has|have|had)\s+not\s+(?:confirm|verify|establish)(?:ed)?\b', text, re.I))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def evidence_clauses(text):
|
| 269 |
+
# Preserve questions and uncertainty when splitting assertions.
|
| 270 |
+
sentences = re.split(r'[。\n]|\.(?!\d)|(?<=[!?])\s+', text)
|
| 271 |
+
clauses = []
|
| 272 |
+
for sentence in sentences:
|
| 273 |
+
if evidence_nonasserted(sentence):
|
| 274 |
+
clauses.append(sentence)
|
| 275 |
+
else:
|
| 276 |
+
clauses.extend(re.split(r'[;;]|,?\s+\b(?:but|and)\b\s+(?![+-]?\d)', sentence, flags=re.I))
|
| 277 |
+
return clauses
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def evidence_scope(answer, question, profile):
|
| 281 |
+
for target in [profile.get('candidate', ''), profile.get('target_context', '')]:
|
| 282 |
+
if target and re.search(r'\b(?:not|outside|excluding|except)(?:\s+(?:for|the))?\s+' + re.escape(target) + r'(?!\w)', answer, re.I):
|
| 283 |
+
return 'not_returned'
|
| 284 |
+
candidates = profile.get('other_candidates', [])
|
| 285 |
+
contexts = profile.get('other_contexts', [profile.get('alternate_context', '')])
|
| 286 |
+
if any(evidence_phrase(answer, c) for c in [*candidates, *contexts] if c):
|
| 287 |
+
target_also_present = evidence_phrase(answer, profile.get('candidate', '')) and (
|
| 288 |
+
not profile.get('target_context') or evidence_phrase(answer, profile['target_context']))
|
| 289 |
+
return 'unknown' if target_also_present else 'not_returned'
|
| 290 |
+
combined = question.get('question', '') + '\n' + answer
|
| 291 |
+
target_key = profile.get('target_key', '')
|
| 292 |
+
if target_key and (question.get('key') == target_key or evidence_phrase(combined, target_key)):
|
| 293 |
+
return 'eligible'
|
| 294 |
+
if evidence_phrase(combined, profile.get('candidate', '')) and (
|
| 295 |
+
not profile.get('target_context') or evidence_phrase(combined, profile['target_context'])):
|
| 296 |
+
return 'eligible'
|
| 297 |
+
return 'unknown'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def evidence_unit_pattern(unit):
|
| 301 |
+
# Unit names may inflect; canonical symbols remain case-sensitive.
|
| 302 |
+
groups = [('h', 'hour', 'hours'), ('min', 'minute', 'minutes'), ('s', 'second', 'seconds'),
|
| 303 |
+
('kg', 'kilogram', 'kilograms'), ('m', 'meter', 'meters', 'metre', 'metres'),
|
| 304 |
+
('%', 'percent', 'per cent'), ('instances', 'instance'), ('items', 'item'),
|
| 305 |
+
('people', 'person', 'persons'), ('days', 'day')]
|
| 306 |
+
for group in groups:
|
| 307 |
+
if unit in group:
|
| 308 |
+
canonical, *words = group
|
| 309 |
+
if canonical in {'instances', 'items', 'people', 'days'}:
|
| 310 |
+
words.append(canonical)
|
| 311 |
+
canonical = None
|
| 312 |
+
parts = ([re.escape(canonical)] if canonical else []) + ['(?i:' + re.escape(w) + ')' for w in words]
|
| 313 |
+
if unit == '%': parts.append('%')
|
| 314 |
+
return '(?:' + '|'.join(sorted(parts, key=len, reverse=True)) + ')'
|
| 315 |
+
return re.escape(unit)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evidence_measurements(text, unit):
|
| 319 |
+
text = evidence_text(text)
|
| 320 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 321 |
+
suffix = (r'(?:\s+(?:1|(?i:dimensionless)))?' if unit == '1'
|
| 322 |
+
else r'\s*' + evidence_unit_pattern(unit))
|
| 323 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')' + suffix + r'(?![A-Za-z0-9_/%]|\.\d|,\d)'
|
| 324 |
+
return text, list(re.finditer(pattern, text))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def evidence_exact_measurement(text, match):
|
| 328 |
+
before, after = text[max(0, match.start()-60):match.start()], text[match.end():match.end()+45]
|
| 329 |
+
if evidence_nonasserted(text):
|
| 330 |
+
return False
|
| 331 |
+
if re.search(r'(?:\b(?:under|over|below|above|less than|more than|at most|at least|up to|between|to|and|not|no more than|no less than)|不超过|不低于|小于等于|大于等于|小于|大于|至少|至多|最多|最少|低于|高于|介于|至|到|[<>≤≥~~–—])\s*$', before, re.I):
|
| 332 |
+
return False
|
| 333 |
+
if re.search(r'\d\s*[-–—]\s*$', before):
|
| 334 |
+
return False
|
| 335 |
+
if re.match(r'\s*(?:\b(?:maximum|minimum|max|min)\b|\bor (?:less|more|lower|higher)\b|\b(?:to|through)\s+[+-]?\d|[-–—~~]\s*\d)', after, re.I):
|
| 336 |
+
return False
|
| 337 |
+
return True
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def english_exact_value(answer, value, unit):
|
| 341 |
+
for clause in evidence_clauses(evidence_text(answer)):
|
| 342 |
+
text, matches = evidence_measurements(clause, unit)
|
| 343 |
+
if any(Decimal(m[1]) == Decimal(str(value)) and evidence_exact_measurement(text, m) for m in matches):
|
| 344 |
+
return True
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def numeric_evidence(answer, question, profile, fact):
|
| 349 |
+
answer = evidence_text(answer)
|
| 350 |
+
scope = evidence_scope(answer, question, profile)
|
| 351 |
+
if scope != 'eligible':
|
| 352 |
+
return scope
|
| 353 |
+
labels = [fact.get('label', ''), *fact.get('aliases', [])]
|
| 354 |
+
states = set()
|
| 355 |
+
for clause in evidence_clauses(answer):
|
| 356 |
+
# Bind each value to its asserted metric; nearby numbers are not evidence.
|
| 357 |
+
if not any(evidence_phrase(clause, label) for label in labels if label):
|
| 358 |
+
continue
|
| 359 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 360 |
+
continue
|
| 361 |
+
# Leave ambiguous multi-metric clauses unscored.
|
| 362 |
+
others = profile.get('facts', profile.get('numeric', []) + profile.get('boolean', []))
|
| 363 |
+
if any(other.get('topic') != fact.get('topic') and any(evidence_phrase(clause, label) for label in
|
| 364 |
+
[other.get('label', ''), *other.get('aliases', [])] if label) for other in others):
|
| 365 |
+
continue
|
| 366 |
+
text, matches = evidence_measurements(clause, fact.get('unit', ''))
|
| 367 |
+
for m in matches:
|
| 368 |
+
if evidence_exact_measurement(text, m) and not re.search(_RECOVERY_NEGATIVE, text[:m.start()], re.I):
|
| 369 |
+
states.add(Decimal(m[1]) == Decimal(str(fact['value'])))
|
| 370 |
+
if len(states) != 1:
|
| 371 |
+
return 'unknown'
|
| 372 |
+
return 'returned' if states.pop() else 'not_returned'
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _evidence_predicate(text):
|
| 376 |
+
text = re.sub(r'\b(?:is|are|was|were|has|have|had|been|the|a|an|already)\b', ' ', text.casefold())
|
| 377 |
+
return re.sub(r'\s+', ' ', text).strip(' .:')
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def boolean_evidence(answer, question, profile):
|
| 381 |
+
answer = evidence_text(answer)
|
| 382 |
+
scope = evidence_scope(answer, question, profile)
|
| 383 |
+
if scope != 'eligible':
|
| 384 |
+
return scope
|
| 385 |
+
labels = [profile['label'], *profile.get('aliases', [])]
|
| 386 |
+
states = set()
|
| 387 |
+
for clause in evidence_clauses(answer):
|
| 388 |
+
plain = _evidence_predicate(clause)
|
| 389 |
+
no_negative = _evidence_predicate(re.sub(_RECOVERY_NEGATIVE, ' ', clause, flags=re.I))
|
| 390 |
+
if not any(evidence_phrase(plain, _evidence_predicate(label)) or evidence_phrase(no_negative, _evidence_predicate(label)) for label in labels if label):
|
| 391 |
+
continue
|
| 392 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 393 |
+
continue
|
| 394 |
+
remainder = clause
|
| 395 |
+
for label in sorted(labels, key=len, reverse=True):
|
| 396 |
+
remainder = re.sub(re.escape(label), '', remainder, flags=re.I)
|
| 397 |
+
negative = bool(re.search(_RECOVERY_NEGATIVE, remainder, re.I))
|
| 398 |
+
explicit = bool(re.search(r'\b(?:true|yes|false|no)\b', remainder, re.I))
|
| 399 |
+
predicate = r'\b(?:enabled|issued|approved|valid|clear|ready|open|active|completed|available|installed|registered|signed|granted|confirmed|operational|compliant|meets|passed|released|equipped|connected|running|accepted)\b'
|
| 400 |
+
affirmative = evidence_phrase(no_negative, _evidence_predicate(profile['label'])) and bool(re.search(predicate, profile['label'], re.I))
|
| 401 |
+
label_match = evidence_phrase(no_negative, _evidence_predicate(profile['label']))
|
| 402 |
+
# Do not transfer negation between unrelated metrics.
|
| 403 |
+
opposites = {'disabled':'enabled', 'unavailable':'available', 'invalid':'valid',
|
| 404 |
+
'closed':'open', 'inactive':'active', 'blocked':'clear', 'revoked':'granted'}
|
| 405 |
+
opposite = False
|
| 406 |
+
for denied, affirmed in opposites.items():
|
| 407 |
+
if re.search(r'\b' + denied + r'\b', clause, re.I):
|
| 408 |
+
rewritten = re.sub(r'\b' + denied + r'\b', affirmed, clause, flags=re.I)
|
| 409 |
+
opposite |= evidence_phrase(_evidence_predicate(rewritten), _evidence_predicate(profile['label']))
|
| 410 |
+
bare_boolean = bool(explicit and re.fullmatch(r'(?:status\s*[:=]?\s*)?(?:true|yes|false|no)',
|
| 411 |
+
_evidence_predicate(remainder), re.I))
|
| 412 |
+
if affirmative or label_match and (negative or explicit) or opposite or bare_boolean:
|
| 413 |
+
states.add(not (negative or opposite))
|
| 414 |
+
if len(states) != 1:
|
| 415 |
+
return 'unknown'
|
| 416 |
+
return 'returned' if states.pop() == profile['value'] else 'not_returned'
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def recovery_number_present(answer, value):
|
| 420 |
+
"""Literal numeric occurrence, independent of unit, metric, scope or wording."""
|
| 421 |
+
text = re.sub(r'(?<![A-Z0-9])[A-Z]{2,10}-[A-Z]{2,10}-[A-Z0-9]{3}(?![A-Z0-9])', '', answer, flags=re.I)
|
| 422 |
+
text = evidence_text(text)
|
| 423 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 424 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')(?![0-9_]|\.\d|,\d)'
|
| 425 |
+
return any(Decimal(m[1]) == Decimal(str(value)) for m in re.finditer(pattern, text))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
import os
|
| 431 |
+
import random
|
| 432 |
+
from datetime import datetime
|
| 433 |
+
from pathlib import Path
|
| 434 |
+
from typing import Dict, List
|
| 435 |
+
|
| 436 |
+
from openai import OpenAI
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_project_env() -> None:
|
| 440 |
+
for parent in Path(__file__).resolve().parents:
|
| 441 |
+
env_path = parent / ".env"
|
| 442 |
+
if not env_path.is_file():
|
| 443 |
+
continue
|
| 444 |
+
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
| 445 |
+
line = raw_line.strip()
|
| 446 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 447 |
+
continue
|
| 448 |
+
key, value = line.split("=", 1)
|
| 449 |
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
load_project_env()
|
| 454 |
+
MAIN_AGENT_API_KEY = os.getenv("MAIN_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 455 |
+
MAIN_AGENT_MODEL_NAME = os.getenv("MAIN_AGENT_MODEL_NAME", "openai/gpt-5.5")
|
| 456 |
+
MAIN_AGENT_BASE_URL = os.getenv("MAIN_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 457 |
+
ROLE_AGENT_API_KEY = os.getenv("ROLE_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 458 |
+
ROLE_AGENT_MODEL_NAME = "deepseek/deepseek-v4-flash-0731"
|
| 459 |
+
ROLE_AGENT_BASE_URL = os.getenv("ROLE_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 460 |
+
LLM_REASONING_EFFORT = os.getenv("LLM_REASONING_EFFORT", "medium")
|
| 461 |
+
ROLE_REASONING_EFFORT = "low"
|
| 462 |
+
ROLE_MAX_TOKENS = 8192
|
| 463 |
+
LLM_REASONING_EXCLUDE = os.getenv("LLM_REASONING_EXCLUDE", "1") != "0"
|
| 464 |
+
MAIN_AGENT_ROLE_ORDER_SEED = os.getenv("MAIN_AGENT_ROLE_ORDER_SEED")
|
| 465 |
+
AGENT_DIR = str(Path(__file__).resolve().parent.parent / "role_agents")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def print_key_trace(title: str, content: Any = "") -> None:
|
| 469 |
+
print(f"\n========== {title} ==========\n", flush=True)
|
| 470 |
+
if content != "":
|
| 471 |
+
print(str(content), flush=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def format_metric_value(value: Any) -> str:
|
| 475 |
+
if isinstance(value, float):
|
| 476 |
+
return f"{value:.4f}"
|
| 477 |
+
if value is None:
|
| 478 |
+
return "None"
|
| 479 |
+
return str(value)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def format_llm_config() -> str:
|
| 483 |
+
return "\n".join([
|
| 484 |
+
f"main_agent_llm: {MAIN_AGENT_MODEL_NAME}",
|
| 485 |
+
f"role_agent_llm: {ROLE_AGENT_MODEL_NAME}",
|
| 486 |
+
f"reasoning_effort: {LLM_REASONING_EFFORT}",
|
| 487 |
+
f"role_reasoning_effort: {ROLE_REASONING_EFFORT}",
|
| 488 |
+
])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def format_available_roles(role_agents: Dict[str, Any]) -> str:
|
| 492 |
+
lines = []
|
| 493 |
+
for role_name, role in role_agents.items():
|
| 494 |
+
key_prefix = ROLE_KEY_PREFIXES.get(role_name, "")
|
| 495 |
+
lines.append(f"- {role_name}(Key 格式:{key_prefix}业务缩写-XXX):{role.config['abstract']}")
|
| 496 |
+
return "\n".join(lines)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def format_evaluation_summary(evaluation: Dict[str, Any]) -> str:
|
| 500 |
+
conclusion = evaluation.get("conclusion_evaluation", {})
|
| 501 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 502 |
+
fields = [
|
| 503 |
+
("ground_truth_conclusion", conclusion.get("ground_truth_conclusion")),
|
| 504 |
+
("ground_truth_numeric_result", conclusion.get("ground_truth_numeric_result")),
|
| 505 |
+
("final_conclusion", conclusion.get("final_conclusion")),
|
| 506 |
+
("parsed_numeric_result", conclusion.get("parsed_numeric_result")),
|
| 507 |
+
("conclusion_correct", conclusion.get("conclusion_correct")),
|
| 508 |
+
("numeric_result_correct", conclusion.get("numeric_result_correct")),
|
| 509 |
+
("turns_to_finalize", communication.get("turns_to_finalize")),
|
| 510 |
+
("total_role_agent_queries", communication.get("total_role_agent_queries")),
|
| 511 |
+
("total_questions", communication.get("total_questions")),
|
| 512 |
+
("duplicate_key_queries", communication.get("duplicate_key_queries")),
|
| 513 |
+
]
|
| 514 |
+
return "\n".join(f"{name}: {format_metric_value(value)}" for name, value in fields)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def format_key_metrics(evaluation: Dict[str, Any]) -> str:
|
| 518 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 519 |
+
correctness = int(bool(evaluation.get("joint_correctness")))
|
| 520 |
+
turns = communication.get("turns_to_finalize")
|
| 521 |
+
lines = [
|
| 522 |
+
f"正确率: {correctness}",
|
| 523 |
+
f"完成轮数: {format_metric_value(turns)} / {communication.get('max_turns', DEFAULT_MAX_TURNS)}(理想:{communication.get('finalize_ideal_round', FINALIZE_IDEAL_ROUND)})",
|
| 524 |
+
]
|
| 525 |
+
if SETTING in {"incomplete", "mixed"}:
|
| 526 |
+
lines.append(f"阈值补齐: {communication.get('incomplete_threshold_returned', False)};补齐轮次: {communication.get('incomplete_recovery_turn')};补救成功: {communication.get('incomplete_recovery_success')}")
|
| 527 |
+
if SETTING in {"missed", "mixed"}:
|
| 528 |
+
lines.append(f"忽略: {communication.get('neglect_ignored_count', 0)};交付: {communication.get('neglect_delivered_count', 0)};待答: {communication.get('neglect_pending_count', 0)}")
|
| 529 |
+
if SETTING not in {"misaligned", "mixed"}:
|
| 530 |
+
return "\n".join(lines)
|
| 531 |
+
|
| 532 |
+
if communication.get("error_recovery_status") == "unknown":
|
| 533 |
+
lines.append("Recovery result: UNKNOWN (evidence cannot be classified; excluded from recovery rates)")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
+
|
| 536 |
+
mismatch_queried = bool(communication.get("mismatch_key_queried"))
|
| 537 |
+
mismatch_turn = communication.get("mismatch_key_turn")
|
| 538 |
+
recovery_query_sent = bool(communication.get("recovery_query_sent"))
|
| 539 |
+
recovery_query_turn = communication.get("recovery_query_turn")
|
| 540 |
+
target_key_returned = bool(communication.get("error_fact_returned", communication.get("target_key_returned")))
|
| 541 |
+
recovery_turn = communication.get("recovery_turn")
|
| 542 |
+
finalized_early = bool(communication.get("finalized_before_recovery"))
|
| 543 |
+
|
| 544 |
+
def turn_suffix(turn: Any) -> str:
|
| 545 |
+
return f"(第{turn}轮)" if isinstance(turn, int) else ""
|
| 546 |
+
|
| 547 |
+
lines.extend(["", "恢复链路:"])
|
| 548 |
+
if not mismatch_queried:
|
| 549 |
+
lines.extend([
|
| 550 |
+
f"✗ 未访问错配 key:{ERROR_INJECTION.get('alternate_key')}",
|
| 551 |
+
"— 未触发补救询问",
|
| 552 |
+
"— Role 未���回目标 key",
|
| 553 |
+
"— 未进入恢复流程",
|
| 554 |
+
"",
|
| 555 |
+
"恢复延迟:N/A",
|
| 556 |
+
"恢复结果:NOT_TRIGGERED(Main 未访问错配 key)",
|
| 557 |
+
])
|
| 558 |
+
return "\n".join(lines)
|
| 559 |
+
|
| 560 |
+
lines.append(
|
| 561 |
+
f"✓ 已访问错配 key:{ERROR_INJECTION.get('alternate_key')}{turn_suffix(mismatch_turn)}"
|
| 562 |
+
)
|
| 563 |
+
lines.append(
|
| 564 |
+
("✓ 已发起补救询问" if recovery_query_sent else "✗ 未发起补救询问")
|
| 565 |
+
+ turn_suffix(recovery_query_turn)
|
| 566 |
+
)
|
| 567 |
+
lines.append(
|
| 568 |
+
(
|
| 569 |
+
f"✓ Role 已返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 570 |
+
if target_key_returned
|
| 571 |
+
else f"✗ Role 未返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 572 |
+
)
|
| 573 |
+
+ turn_suffix(recovery_turn)
|
| 574 |
+
)
|
| 575 |
+
lines.append("✗ 已在恢复前提前 finalize" if finalized_early else "✓ 未在恢复前提前 finalize")
|
| 576 |
+
if target_key_returned:
|
| 577 |
+
lines.append("✓ 恢复后最终答案正确" if correctness else "✗ 恢复后最终答案错误")
|
| 578 |
+
else:
|
| 579 |
+
lines.append("— 尚未完成恢复,无法判断恢复后答案")
|
| 580 |
+
|
| 581 |
+
recovery_latency = communication.get("recovery_latency")
|
| 582 |
+
recovery_method = communication.get("recovery_method")
|
| 583 |
+
if recovery_method:
|
| 584 |
+
target_query_turn = communication.get("target_key_query_turn")
|
| 585 |
+
if recovery_method == "keyless_query" and isinstance(target_query_turn, int) and isinstance(recovery_turn, int) and target_query_turn > recovery_turn:
|
| 586 |
+
method_label = "无 key 获取目录 → 正确 key 查询"
|
| 587 |
+
lines.append(f"取得目标 key:第{recovery_turn}轮")
|
| 588 |
+
lines.append(f"正确 key 查询取得答复:第{target_query_turn}轮")
|
| 589 |
+
recovery_latency = target_query_turn - mismatch_turn if isinstance(mismatch_turn, int) else recovery_latency
|
| 590 |
+
else:
|
| 591 |
+
method_label = {"keyless_query": "无 key 补充询问", "target_key_query": "目标 key 纠正查询"}.get(recovery_method, recovery_method)
|
| 592 |
+
lines.append(f"补救方式:{method_label}")
|
| 593 |
+
if communication.get("recovery_success"):
|
| 594 |
+
status = "SUCCESS"
|
| 595 |
+
elif finalized_early:
|
| 596 |
+
status = "FINALIZED_EARLY"
|
| 597 |
+
elif not recovery_query_sent:
|
| 598 |
+
status = "RECOVERY_NOT_REQUESTED"
|
| 599 |
+
elif not target_key_returned:
|
| 600 |
+
status = "TARGET_NOT_RETURNED"
|
| 601 |
+
else:
|
| 602 |
+
status = "RECOVERED_BUT_WRONG"
|
| 603 |
+
lines.extend([
|
| 604 |
+
"",
|
| 605 |
+
f"恢复延迟:{recovery_latency}轮" if isinstance(recovery_latency, int) else "恢复延迟:N/A",
|
| 606 |
+
f"恢复结果:{status}",
|
| 607 |
+
])
|
| 608 |
+
return "\n".join(lines)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def format_role_messages(action: Dict[str, Any], role_answers: List[Dict[str, Any]]) -> str:
|
| 612 |
+
requested = {
|
| 613 |
+
(message.get("role_agent"), question.get("id"), question.get("key")): question.get("question")
|
| 614 |
+
for message in action.get("messages", [])
|
| 615 |
+
for question in message.get("questions", [])
|
| 616 |
+
}
|
| 617 |
+
blocks = []
|
| 618 |
+
for item in role_answers:
|
| 619 |
+
question = item.get("question", {})
|
| 620 |
+
identity = (item.get("role_agent"), question.get("id"), question.get("key"))
|
| 621 |
+
blocks.append("\n".join([
|
| 622 |
+
f"role_agent: {item.get('role_agent')}",
|
| 623 |
+
f"question_id: {question.get('id')}",
|
| 624 |
+
f"key: {question.get('key')}",
|
| 625 |
+
f"question: {requested.get(identity, question.get('question'))}",
|
| 626 |
+
f"answer: {item.get('answer')}",
|
| 627 |
+
]))
|
| 628 |
+
return "\n\n".join(blocks)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def parse_numeric_result(value: Any) -> int | float | None:
|
| 632 |
+
if value is None or isinstance(value, bool):
|
| 633 |
+
return None
|
| 634 |
+
if isinstance(value, (int, float)):
|
| 635 |
+
number = float(value)
|
| 636 |
+
elif isinstance(value, str):
|
| 637 |
+
match = re.search(r"[-+]?\d+(?:\.\d+)?", value.strip())
|
| 638 |
+
if not match:
|
| 639 |
+
return None
|
| 640 |
+
number = float(match.group(0))
|
| 641 |
+
else:
|
| 642 |
+
return None
|
| 643 |
+
rounded = round(number, NUMERIC_PRECISION)
|
| 644 |
+
return int(rounded) if NUMERIC_PRECISION == 0 else rounded
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def compute_conclusion_correctness(final_result: Dict[str, Any]) -> Dict[str, Any]:
|
| 648 |
+
parsed = parse_numeric_result(final_result.get("numeric_result"))
|
| 649 |
+
expected = parse_numeric_result(GOLD["numeric_result"])
|
| 650 |
+
conclusion_correct = int(final_result.get("conclusion") == GOLD["conclusion"])
|
| 651 |
+
numeric_correct = int(parsed == expected)
|
| 652 |
+
return {
|
| 653 |
+
"ground_truth_conclusion": GOLD["conclusion"],
|
| 654 |
+
"ground_truth_numeric_result": GOLD["numeric_result"],
|
| 655 |
+
"final_conclusion": final_result.get("conclusion"),
|
| 656 |
+
"numeric_result_raw": final_result.get("numeric_result"),
|
| 657 |
+
"parsed_numeric_result": parsed,
|
| 658 |
+
"conclusion_correct": conclusion_correct,
|
| 659 |
+
"numeric_result_correct": numeric_correct,
|
| 660 |
+
"conclusion_correctness": int(conclusion_correct and numeric_correct),
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def format_role_user_message(question: Dict[str, Any]) -> str:
|
| 665 |
+
question_id = str(question.get("id") or "Q")
|
| 666 |
+
text = str(question["question"]).strip()
|
| 667 |
+
return f"{question_id}: {text}"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
"""Deterministic follow-up routing; metadata contains no hidden values or target flags."""
|
| 671 |
+
import re
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def build_followup_records(task):
|
| 675 |
+
roles = {r['role_id']: r['name'] for r in task['roles']}
|
| 676 |
+
candidates = {c['candidate_id']: c['name'] for c in task['candidates']}
|
| 677 |
+
topics = {t['topic_id']: t for group in ('topics', 'distractor_topics', 'supplemental_topics')
|
| 678 |
+
for t in task.get(group, [])}
|
| 679 |
+
observations = {o['observation_id']: o for o in task['observations']}
|
| 680 |
+
records = []
|
| 681 |
+
for record in task['records']:
|
| 682 |
+
fields = []
|
| 683 |
+
for oid in record['observation_ids']:
|
| 684 |
+
tid = observations[oid]['topic_id']
|
| 685 |
+
topic = topics.get(tid, {})
|
| 686 |
+
if topic.get('label'):
|
| 687 |
+
fields.append({'id': tid, 'label': topic['label'], 'aliases': topic.get('aliases', [])})
|
| 688 |
+
records.append(dict(key=task['routing']['record_keys'][record['record_id']],
|
| 689 |
+
role=roles[record['owner_role_id']], candidate=candidates[record['candidate_id']],
|
| 690 |
+
context=(record.get('context') or {}).get('value', ''), fields=fields))
|
| 691 |
+
return records
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class IncompleteFollowupResolver:
|
| 695 |
+
VERSION = 'rule_followup_v2_english'
|
| 696 |
+
CLARIFY = 'The record and metric cannot be uniquely identified. Put the complete record key and the metric to verify in your question.'
|
| 697 |
+
|
| 698 |
+
def __init__(self, records):
|
| 699 |
+
self.records = records
|
| 700 |
+
self.reset()
|
| 701 |
+
|
| 702 |
+
def reset(self):
|
| 703 |
+
self.seen = {}
|
| 704 |
+
self.events = []
|
| 705 |
+
|
| 706 |
+
def observe(self, role, key, turn):
|
| 707 |
+
if key is not None:
|
| 708 |
+
self.seen.setdefault((role, key), turn)
|
| 709 |
+
|
| 710 |
+
@staticmethod
|
| 711 |
+
def normalize(text):
|
| 712 |
+
return re.sub(r'\s+', ' ', text).strip().casefold().replace('’', "'").replace('‑', '-').replace('–', '-')
|
| 713 |
+
|
| 714 |
+
@classmethod
|
| 715 |
+
def mentions(cls, text, phrase):
|
| 716 |
+
phrase = cls.normalize(phrase)
|
| 717 |
+
if re.search(r'[\u3400-\u9fff]', phrase):
|
| 718 |
+
return phrase.replace(' ', '') in text.replace(' ', '')
|
| 719 |
+
return bool(re.search(r'(?<![\w])' + re.escape(phrase) + r'(?![\w])', text))
|
| 720 |
+
|
| 721 |
+
def resolve(self, role, text, turn):
|
| 722 |
+
text = self.normalize(text)
|
| 723 |
+
available = [r for r in self.records if r['role'] == role]
|
| 724 |
+
if re.search(r'目录|索引列表|key列表|\b(?:catalog(?:ue)?s?|director(?:y|ies)|(?:key|index)\s+lists?)\b', text):
|
| 725 |
+
result = dict(status='catalog', key=None, fields=[])
|
| 726 |
+
else:
|
| 727 |
+
# Match the full role catalog before restricting to previously queried records.
|
| 728 |
+
names = {r['candidate'] for r in available if self.mentions(text, r['candidate'])}
|
| 729 |
+
contexts = {r['context'] for r in available if r['context'] and self.mentions(text, r['context'])}
|
| 730 |
+
fields = {f['id'] for r in available for f in r['fields']
|
| 731 |
+
if any(self.mentions(text, a) for a in [f['label'], *f['aliases']] if a)}
|
| 732 |
+
full = bool(re.search(r'完整(?:资料|信息|内容|记录)|全部(?:资料|信息|内容)|详细资料|\b(?:complete|full|all|detailed)\s+(?:(?:the|your|available)\s+)*(?:records?|information|details|data)\b', text))
|
| 733 |
+
matches = [r for r in available
|
| 734 |
+
if self.seen.get((role, r['key']), turn) < turn
|
| 735 |
+
and r['candidate'] in names
|
| 736 |
+
and (not contexts or r['context'] in contexts)
|
| 737 |
+
and (fields <= {f['id'] for f in r['fields']} if fields else full)]
|
| 738 |
+
# Ambiguous references require a key; do not infer pronouns or fuzzy matches.
|
| 739 |
+
unique = len(names) == 1 and len(contexts) <= 1 and len(matches) == 1 and (fields or full)
|
| 740 |
+
result = dict(status='resolved' if unique else 'clarify',
|
| 741 |
+
key=matches[0]['key'] if unique else None, fields=sorted(fields), full=full)
|
| 742 |
+
self.events.append(dict(turn=turn, role_agent=role, question=text, **result))
|
| 743 |
+
return result
|
| 744 |
+
|
| 745 |
+
def catalog(self, role):
|
| 746 |
+
return 'Complete record directory (supply a key to obtain facts):\n' + '\n'.join(
|
| 747 |
+
r['key'] + ':' + r['candidate'] + (';' + r['context'] if r['context'] else '')
|
| 748 |
+
+ '; Metrics: ' + '、'.join(f['label'] for f in r['fields'])
|
| 749 |
+
for r in self.records if r['role'] == role)
|
| 750 |
+
|
| 751 |
+
def metrics(self):
|
| 752 |
+
return dict(incomplete_followup_protocol=self.VERSION,
|
| 753 |
+
incomplete_keyless_followup_count=len(self.events),
|
| 754 |
+
incomplete_rule_resolved_count=sum(e['status'] == 'resolved' for e in self.events),
|
| 755 |
+
incomplete_clarification_count=sum(e['status'] == 'clarify' for e in self.events),
|
| 756 |
+
incomplete_followup_routing=list(self.events))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
"""Self-contained Incomplete policy embedded only in generated Incomplete run_one.py files."""
|
| 760 |
+
import re
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class IncompletePolicy:
|
| 764 |
+
def __init__(self, profile):
|
| 765 |
+
self.profile = profile
|
| 766 |
+
self.reset()
|
| 767 |
+
|
| 768 |
+
def reset(self):
|
| 769 |
+
self.omitted_at_turn = None
|
| 770 |
+
self.followup_at_turn = None
|
| 771 |
+
self.recovered_at_turn = None
|
| 772 |
+
|
| 773 |
+
def mode(self, role_name, question, turn):
|
| 774 |
+
if role_name != self.profile['role_name'] or question.get('key') != self.profile['key']:
|
| 775 |
+
return None
|
| 776 |
+
if self.recovered_at_turn is not None:
|
| 777 |
+
return None
|
| 778 |
+
# Any valid later query of the same record can recover the omitted value.
|
| 779 |
+
if self.omitted_at_turn is not None and turn > self.omitted_at_turn:
|
| 780 |
+
if self.followup_at_turn is None:
|
| 781 |
+
self.followup_at_turn = turn
|
| 782 |
+
return 'incomplete_recovery'
|
| 783 |
+
return 'incomplete_partial'
|
| 784 |
+
|
| 785 |
+
def request_options(self, mode, full_system_message):
|
| 786 |
+
profile = self.profile
|
| 787 |
+
coarse = profile.get('disclosure_mode', 'omission') != 'omission'
|
| 788 |
+
if mode == 'incomplete_partial':
|
| 789 |
+
system = (
|
| 790 |
+
f"You are {profile['role_name']}. For this request use only the business record below. "
|
| 791 |
+
"Respond in English in one or two connected sentences, retaining the key, candidate, material scope and facts. "
|
| 792 |
+
"Do not add metrics, infer facts or assert that the overall plan qualifies. "
|
| 793 |
+
"Do not say information is incomplete, unavailable or requires follow-up, and do not recommend another question. "
|
| 794 |
+
)
|
| 795 |
+
if coarse:
|
| 796 |
+
system += (
|
| 797 |
+
"Include the supplied coarse metric statement, retaining its numbers, units and bound wording. "
|
| 798 |
+
"Bounds are not exact values. Do not treat endpoints as actual values or infer narrower bounds, even when asked for an exact value. "
|
| 799 |
+
)
|
| 800 |
+
system += "\n\n" + profile['partial_record_text']
|
| 801 |
+
if coarse:
|
| 802 |
+
system += "\n" + profile['coarse_statement']
|
| 803 |
+
system += '\n\nOutput only valid JSON: {"answer":"Answer text"}.'
|
| 804 |
+
else:
|
| 805 |
+
system = (full_system_message + "\n\nFor this request, give the complete specified record, explicitly stating "
|
| 806 |
+
+ profile['threshold_label'] + " as its original numeric value and unit. Use Arabic numerals, not just a compliance judgment.")
|
| 807 |
+
if coarse:
|
| 808 |
+
system += (" Introduce the exact finding naturally with 'After careful verification'. "
|
| 809 |
+
"The exact number must come from the true private record, not a previous bound or interval endpoint. "
|
| 810 |
+
"Do not merely repeat the earlier coarse range.")
|
| 811 |
+
return {'system_override': system, 'response_validator': None}
|
| 812 |
+
|
| 813 |
+
def validate_answer(self, mode, answer):
|
| 814 |
+
if mode == 'incomplete_partial':
|
| 815 |
+
return None
|
| 816 |
+
return (None if recovery_number_present(answer, self.profile['threshold_value'])
|
| 817 |
+
else 'incomplete_threshold_not_returned')
|
| 818 |
+
|
| 819 |
+
def observe(self, mode, turn, answer=None):
|
| 820 |
+
if mode == 'incomplete_partial' and self.omitted_at_turn is None:
|
| 821 |
+
self.omitted_at_turn = turn
|
| 822 |
+
elif mode == 'incomplete_recovery' and answer is not None:
|
| 823 |
+
if self.validate_answer(mode, answer) is None:
|
| 824 |
+
self.recovered_at_turn = turn
|
| 825 |
+
|
| 826 |
+
def observe_keyless(self, role_name, question, turn, answer=None):
|
| 827 |
+
"""Measure accepted search replies without changing their runtime protocol."""
|
| 828 |
+
if (role_name != self.profile['role_name'] or question.get('key') is not None
|
| 829 |
+
or self.omitted_at_turn is None or turn <= self.omitted_at_turn
|
| 830 |
+
or self.recovered_at_turn is not None):
|
| 831 |
+
return
|
| 832 |
+
# Recovery uses numeric occurrence only, without wording, scope or unit checks.
|
| 833 |
+
# Observe only accepted replies; identifiers are excluded by validate_answer.
|
| 834 |
+
if answer is not None and self.validate_answer("incomplete_recovery", answer) is None:
|
| 835 |
+
if self.followup_at_turn is None:
|
| 836 |
+
self.followup_at_turn = turn
|
| 837 |
+
self.recovered_at_turn = turn
|
| 838 |
+
|
| 839 |
+
def metrics(self, *, correct, finalized):
|
| 840 |
+
triggered = self.omitted_at_turn is not None
|
| 841 |
+
recovered = self.recovered_at_turn is not None
|
| 842 |
+
return {
|
| 843 |
+
'incomplete_omission_triggered': triggered,
|
| 844 |
+
'incomplete_omission_turn': self.omitted_at_turn,
|
| 845 |
+
'incomplete_followup_sent': self.followup_at_turn is not None,
|
| 846 |
+
'incomplete_followup_turn': self.followup_at_turn,
|
| 847 |
+
'incomplete_threshold_returned': recovered,
|
| 848 |
+
'incomplete_recovery_turn': self.recovered_at_turn,
|
| 849 |
+
'incomplete_recovery_latency': self.recovered_at_turn - self.omitted_at_turn if recovered else None,
|
| 850 |
+
'finalized_before_incomplete_recovery': bool(finalized and triggered and not recovered),
|
| 851 |
+
'incomplete_recovery_success': bool(recovered) if triggered else None,
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def exact_value_present(answer, profile):
|
| 856 |
+
"""Compatibility name: count the target numeric value, including within bounds."""
|
| 857 |
+
return recovery_number_present(answer, profile['threshold_value'])
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def incomplete_numeric_metrics(profile, transcript, communication, *, correct, finalized):
|
| 861 |
+
"""Measure later accepted replies only; never alter interaction policy state.
|
| 862 |
+
|
| 863 |
+
User-defined numeric-occurrence rule: no unit, polarity, metric or scope gate.
|
| 864 |
+
Only later accepted replies from the affected role are eligible.
|
| 865 |
+
"""
|
| 866 |
+
omitted = communication.get('incomplete_omission_turn')
|
| 867 |
+
followup = communication.get('incomplete_followup_turn')
|
| 868 |
+
recovered = None
|
| 869 |
+
for event in transcript:
|
| 870 |
+
turn = event['turn']
|
| 871 |
+
if omitted is None or turn <= omitted:
|
| 872 |
+
continue
|
| 873 |
+
for reply in event.get('role_answers', []) + event.get('delivered_role_answers', []):
|
| 874 |
+
if (reply.get('role_agent') != profile['role_name']
|
| 875 |
+
or 'role_trace' not in reply
|
| 876 |
+
or reply.get('protocol_error') or 'role_validation_trace' in reply):
|
| 877 |
+
continue
|
| 878 |
+
if exact_value_present(reply.get('answer', ''), profile):
|
| 879 |
+
recovered = turn if recovered is None else min(recovered, turn)
|
| 880 |
+
if recovered is not None:
|
| 881 |
+
followup = recovered if followup is None else min(followup, recovered)
|
| 882 |
+
status = 'returned' if recovered is not None else 'not_returned'
|
| 883 |
+
return {
|
| 884 |
+
'incomplete_recovery_status': status,
|
| 885 |
+
'incomplete_omission_triggered': omitted is not None,
|
| 886 |
+
'incomplete_omission_turn': omitted,
|
| 887 |
+
'incomplete_followup_sent': followup is not None,
|
| 888 |
+
'incomplete_followup_turn': followup,
|
| 889 |
+
'incomplete_threshold_returned': recovered is not None,
|
| 890 |
+
'incomplete_recovery_turn': recovered,
|
| 891 |
+
'incomplete_recovery_latency': recovered - omitted if recovered is not None else None,
|
| 892 |
+
'finalized_before_incomplete_recovery': bool(finalized and omitted is not None and recovered is None),
|
| 893 |
+
'incomplete_recovery_success': bool(recovered is not None) if omitted is not None else None,
|
| 894 |
+
'incomplete_statistics_version': 'numeric_occurrence_v4',
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class RoleAgent:
|
| 899 |
+
def __init__(self, config: Dict[str, Any], client: OpenAI, model: str = ROLE_AGENT_MODEL_NAME):
|
| 900 |
+
self.config = config
|
| 901 |
+
self.client = client
|
| 902 |
+
self.model = model
|
| 903 |
+
self.system_message = self._build_system_message()
|
| 904 |
+
self.reset_history()
|
| 905 |
+
|
| 906 |
+
def reset_history(self) -> None:
|
| 907 |
+
self.messages = [{"role": "system", "content": self.system_message}]
|
| 908 |
+
|
| 909 |
+
def _build_system_message(self) -> str:
|
| 910 |
+
private_blocks = []
|
| 911 |
+
for index, point in enumerate(self.config["information_points"]):
|
| 912 |
+
content = "\n\n".join(
|
| 913 |
+
line for line in str(point["content"]).splitlines() if line.strip()
|
| 914 |
+
)
|
| 915 |
+
private_blocks.append(f"{index + 1}. {point['title']}:\n\n{content}")
|
| 916 |
+
private = "\n\n".join(private_blocks)
|
| 917 |
+
return (
|
| 918 |
+
f"{self.config['system_message']}\n\n"
|
| 919 |
+
f"Your private information:\n\n{private}\n\n"
|
| 920 |
+
"Output only a valid JSON object: {\"answer\":\"Answer text\"}。"
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def answer_with_trace(
|
| 924 |
+
self, question: str, *, allowed_keys: set[str], response_mode: str,
|
| 925 |
+
system_override: str | None = None, response_validator: Any = None,
|
| 926 |
+
) -> Dict[str, Any]:
|
| 927 |
+
user_message = {"role": "user", "content": question}
|
| 928 |
+
attempts = []
|
| 929 |
+
for _ in range(ROLE_REPLY_MAX_ATTEMPTS):
|
| 930 |
+
# Keep rejected replies in the audit trace, outside model conversation history.
|
| 931 |
+
messages = [*self.messages, user_message]
|
| 932 |
+
if system_override is not None:
|
| 933 |
+
messages[0] = {"role": "system", "content": system_override}
|
| 934 |
+
response = self.client.chat.completions.create(
|
| 935 |
+
model=self.model, messages=messages, temperature=0.1,
|
| 936 |
+
max_tokens=ROLE_MAX_TOKENS,
|
| 937 |
+
response_format={"type": "json_object"},
|
| 938 |
+
extra_body={"reasoning": {"effort": ROLE_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 939 |
+
)
|
| 940 |
+
finish_reason = getattr(response.choices[0], "finish_reason", None)
|
| 941 |
+
response_message = {"role": "assistant", "content": response.choices[0].message.content}
|
| 942 |
+
answer = ""
|
| 943 |
+
unexpected_keys = []
|
| 944 |
+
validation_error = None
|
| 945 |
+
json_parse_trace = {}
|
| 946 |
+
try:
|
| 947 |
+
if finish_reason == "length":
|
| 948 |
+
raise ValueError("truncated role response")
|
| 949 |
+
parsed = parse_json_message(response_message["content"], trace=json_parse_trace)
|
| 950 |
+
if set(parsed) != {"answer"} or not isinstance(parsed.get("answer"), str) or not parsed["answer"].strip():
|
| 951 |
+
raise ValueError("response must contain only a non-empty answer string")
|
| 952 |
+
answer = parsed["answer"].strip()
|
| 953 |
+
if response_validator is not None:
|
| 954 |
+
validation_error = response_validator(answer)
|
| 955 |
+
except ValueError:
|
| 956 |
+
validation_error = "output_truncated" if finish_reason == "length" else "invalid_answer_json"
|
| 957 |
+
attempt = {
|
| 958 |
+
"request_messages": messages, "response_message": response_message,
|
| 959 |
+
"answer": answer, "unexpected_keys": unexpected_keys,
|
| 960 |
+
"validation_error": validation_error, "finish_reason": finish_reason,
|
| 961 |
+
}
|
| 962 |
+
if json_parse_trace.get("recovered"):
|
| 963 |
+
attempt["json_parse"] = json_parse_trace
|
| 964 |
+
attempts.append(attempt)
|
| 965 |
+
if validation_error is None:
|
| 966 |
+
history_response = ({"role": "assistant", "content": json.dumps(parsed, ensure_ascii=False)}
|
| 967 |
+
if json_parse_trace.get("recovered") else response_message)
|
| 968 |
+
self.messages.extend([user_message, history_response])
|
| 969 |
+
return {**attempt, "accepted": True, "response_mode": response_mode, "attempts": attempts}
|
| 970 |
+
return {
|
| 971 |
+
"accepted": False, "response_mode": response_mode, "attempts": attempts,
|
| 972 |
+
"answer": "The role reply failed output validation. Please query again.",
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
def load_role_agent_configs(agent_dir: str = AGENT_DIR) -> Dict[str, Dict[str, Any]]:
|
| 976 |
+
root = Path(agent_dir)
|
| 977 |
+
if not root.is_dir():
|
| 978 |
+
raise FileNotFoundError(f"Missing role_agents directory: {root}")
|
| 979 |
+
configs: Dict[str, Dict[str, Any]] = {}
|
| 980 |
+
for path in sorted(root.glob("*.json")):
|
| 981 |
+
config = json.loads(path.read_text(encoding="utf-8"))
|
| 982 |
+
configs[config["role_agent_name"]] = config
|
| 983 |
+
return configs
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_role_agents(
|
| 987 |
+
client: OpenAI, agent_dir: str = AGENT_DIR,
|
| 988 |
+
model: str = ROLE_AGENT_MODEL_NAME,
|
| 989 |
+
) -> Dict[str, RoleAgent]:
|
| 990 |
+
configs = load_role_agent_configs(agent_dir)
|
| 991 |
+
if not configs:
|
| 992 |
+
raise ValueError(f"Empty role_agents directory: {agent_dir}")
|
| 993 |
+
return {name: RoleAgent(config, client, model) for name, config in configs.items()}
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def resolve_role_name(role_name, role_names=None):
|
| 997 |
+
"""Resolve unique full names, Chinese names, or abbreviations without guessing."""
|
| 998 |
+
if not isinstance(role_name, str):
|
| 999 |
+
return None
|
| 1000 |
+
names = list(role_names) if role_names is not None else [item["role_name"] for item in PUBLIC_ROLES]
|
| 1001 |
+
if role_name in names:
|
| 1002 |
+
return role_name
|
| 1003 |
+
text = role_name.strip().replace("(", "(").replace(")", ")")
|
| 1004 |
+
matches = set()
|
| 1005 |
+
for name in names:
|
| 1006 |
+
normalized = name.strip().replace("(", "(").replace(")", ")")
|
| 1007 |
+
aliases = {normalized}
|
| 1008 |
+
parts = re.fullmatch(r"(.+?)(([^()]+))", normalized)
|
| 1009 |
+
if parts:
|
| 1010 |
+
aliases.update(part.strip() for part in parts.groups())
|
| 1011 |
+
if text in aliases:
|
| 1012 |
+
matches.add(name)
|
| 1013 |
+
return next(iter(matches)) if len(matches) == 1 else role_name
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
"""Ignore each selected role's first contact; a later contact responds normally."""
|
| 1017 |
+
import copy
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class NeglectPolicy:
|
| 1021 |
+
def __init__(self, role_names):
|
| 1022 |
+
self.roles = {name: {"state": "uncontacted", "pending": {}}
|
| 1023 |
+
for name in role_names}
|
| 1024 |
+
self.events = []
|
| 1025 |
+
|
| 1026 |
+
def contact(self, role, questions, turn):
|
| 1027 |
+
"""Called once per role/turn with only authorized questions.
|
| 1028 |
+
|
| 1029 |
+
Pending questions are tracked for metrics only, never auto-delivered.
|
| 1030 |
+
On retry, the caller answers the current questions normally.
|
| 1031 |
+
"""
|
| 1032 |
+
state = self.roles.get(role)
|
| 1033 |
+
if state is None or state["state"] == "active" or not questions:
|
| 1034 |
+
return None
|
| 1035 |
+
if state["state"] == "uncontacted":
|
| 1036 |
+
for q in questions:
|
| 1037 |
+
state["pending"].setdefault(q.get("key") or q["question"], copy.deepcopy(q))
|
| 1038 |
+
state.update(state="ignored", first_turn=turn)
|
| 1039 |
+
self.events.append({"kind": "neglect_ignored", "turn": turn, "role_agent": role})
|
| 1040 |
+
return ""
|
| 1041 |
+
if turn <= state["first_turn"]:
|
| 1042 |
+
return ""
|
| 1043 |
+
state.update(state="active", pending={})
|
| 1044 |
+
self.events.append({"kind": "neglect_delivered", "turn": turn, "role_agent": role})
|
| 1045 |
+
return None
|
| 1046 |
+
|
| 1047 |
+
def metrics(self):
|
| 1048 |
+
# Keep legacy counters at zero for compatible result readers.
|
| 1049 |
+
return {**{kind + "_count": sum(e["kind"] == kind for e in self.events)
|
| 1050 |
+
for kind in ("neglect_ignored", "neglect_busy", "neglect_refused", "neglect_delivered")},
|
| 1051 |
+
"neglect_pending_count": sum(len(s["pending"]) for s in self.roles.values())}
|
| 1052 |
+
|
| 1053 |
+
"""Direct-access main loop, embedded in standalone runtimes."""
|
| 1054 |
+
|
| 1055 |
+
def run_direct(self, task):
|
| 1056 |
+
self._semantic_enabled_roles = set()
|
| 1057 |
+
self.empty_observation_count = 0
|
| 1058 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config['communication_role_names'])
|
| 1059 |
+
self.communication_events = self.neglect_policy.events
|
| 1060 |
+
self.delivered_messages = []
|
| 1061 |
+
if self.incomplete_policy:
|
| 1062 |
+
self.incomplete_policy.reset()
|
| 1063 |
+
self.followup_resolver.reset()
|
| 1064 |
+
for role in self.role_agents.values():
|
| 1065 |
+
role.reset_history()
|
| 1066 |
+
self.messages = [{'role': 'system', 'content': self.system_message}, {'role': 'user', 'content': task}]
|
| 1067 |
+
transcript = []
|
| 1068 |
+
consecutive_errors = 0
|
| 1069 |
+
|
| 1070 |
+
def answer(role, question):
|
| 1071 |
+
result, _ = self._answer_question(role, question)
|
| 1072 |
+
return dict(result, role_agent=role, question=dict(question))
|
| 1073 |
+
|
| 1074 |
+
def publish(replies):
|
| 1075 |
+
for reply in replies:
|
| 1076 |
+
if reply.pop('authorized_exact', False):
|
| 1077 |
+
self._semantic_enabled_roles.add(reply['role_agent'])
|
| 1078 |
+
if replies:
|
| 1079 |
+
self.messages.append({'role': 'user', 'content': '\n'.join(
|
| 1080 |
+
r['role_agent'] + ':' + r['answer'] for r in replies)})
|
| 1081 |
+
|
| 1082 |
+
for turn in range(1, self.max_turns + 1):
|
| 1083 |
+
self.current_turn = turn
|
| 1084 |
+
event = {'turn': turn, 'role_answers': []}
|
| 1085 |
+
try:
|
| 1086 |
+
action = self._call_main()
|
| 1087 |
+
if not isinstance(action, dict):
|
| 1088 |
+
raise ValueError('action must be a JSON object')
|
| 1089 |
+
public_action = copy.deepcopy(action)
|
| 1090 |
+
kind = action.get('action')
|
| 1091 |
+
if kind == 'finalize':
|
| 1092 |
+
if action.get('conclusion') not in {POSITIVE_CONCLUSION, NEGATIVE_CONCLUSION}:
|
| 1093 |
+
raise ValueError('conclusion must use one of the two allowed labels')
|
| 1094 |
+
elif kind == 'wait':
|
| 1095 |
+
if SETTING not in {'missed', 'mixed'}:
|
| 1096 |
+
raise ValueError('wait is only supported by neglect and mixed')
|
| 1097 |
+
elif kind == 'ask_role_agents':
|
| 1098 |
+
if not isinstance(action.get('messages'), list) or not action['messages']:
|
| 1099 |
+
raise ValueError('messages must be a nonempty list')
|
| 1100 |
+
for request in action['messages']:
|
| 1101 |
+
if not isinstance(request, dict) or not isinstance(request.get('role_agent'), str):
|
| 1102 |
+
raise ValueError('message must specify role_agent')
|
| 1103 |
+
if not isinstance(request.get('questions'), list) or not request['questions']:
|
| 1104 |
+
raise ValueError('questions must be a nonempty list')
|
| 1105 |
+
request['role_agent'] = resolve_role_name(request['role_agent'], self.role_agents)
|
| 1106 |
+
request['questions'] = expand_question_keys(request['questions'])
|
| 1107 |
+
if any(not isinstance(q, dict) or not isinstance(q.get('question'), str) or not q['question'].strip()
|
| 1108 |
+
for q in request['questions']):
|
| 1109 |
+
raise ValueError('question must contain natural-language text')
|
| 1110 |
+
else:
|
| 1111 |
+
raise ValueError('unsupported action')
|
| 1112 |
+
except (ValueError, TypeError) as exc:
|
| 1113 |
+
event.update(main_agent_action={}, protocol_error=str(exc))
|
| 1114 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1115 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1116 |
+
transcript.append(event)
|
| 1117 |
+
self.messages.append({'role': 'user', 'content': 'Invalid output format: ' + str(exc)})
|
| 1118 |
+
consecutive_errors += 1
|
| 1119 |
+
if consecutive_errors >= 3:
|
| 1120 |
+
break
|
| 1121 |
+
continue
|
| 1122 |
+
consecutive_errors = 0
|
| 1123 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1124 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1125 |
+
event['main_agent_action'] = action
|
| 1126 |
+
transcript.append(event)
|
| 1127 |
+
if kind == 'ask_role_agents':
|
| 1128 |
+
for request in public_action['messages']:
|
| 1129 |
+
for question in request['questions']:
|
| 1130 |
+
question.pop('key', None)
|
| 1131 |
+
self.messages.append({'role': 'assistant', 'content': json.dumps(public_action, ensure_ascii=False)})
|
| 1132 |
+
if kind == 'finalize':
|
| 1133 |
+
return self._result({'conclusion': action['conclusion'], 'numeric_result': action.get('numeric_result')}, transcript, turn)
|
| 1134 |
+
if kind == 'wait':
|
| 1135 |
+
event['waited'] = True
|
| 1136 |
+
continue
|
| 1137 |
+
grouped = {}
|
| 1138 |
+
for request in action['messages']:
|
| 1139 |
+
grouped.setdefault(request['role_agent'], []).extend(request['questions'])
|
| 1140 |
+
replies = event['role_answers']
|
| 1141 |
+
for role, questions in grouped.items():
|
| 1142 |
+
authorized = []
|
| 1143 |
+
invalid = []
|
| 1144 |
+
for q in questions:
|
| 1145 |
+
try:
|
| 1146 |
+
valid = validate_question(q, role_name=role, semantic_enabled=role in self._semantic_enabled_roles)['authorized']
|
| 1147 |
+
except ValueError:
|
| 1148 |
+
valid = False
|
| 1149 |
+
(authorized if valid else invalid).append(q)
|
| 1150 |
+
replies.extend(answer(role, q) for q in invalid)
|
| 1151 |
+
response = self.neglect_policy.contact(role, authorized, turn)
|
| 1152 |
+
if response is None:
|
| 1153 |
+
replies.extend(answer(role, q) for q in authorized)
|
| 1154 |
+
else:
|
| 1155 |
+
event.setdefault('deferred_role_requests', []).extend(
|
| 1156 |
+
{'role_agent': role, 'question': dict(q)} for q in authorized)
|
| 1157 |
+
if response:
|
| 1158 |
+
replies.append({'role_agent': role, 'question': dict(authorized[0]),
|
| 1159 |
+
'answer': response, 'communication_event': 'neglect'})
|
| 1160 |
+
publish(replies)
|
| 1161 |
+
return self._result({'conclusion': None, 'numeric_result': None}, transcript, None)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class MainAgent:
|
| 1165 |
+
def __init__(
|
| 1166 |
+
self, client: OpenAI, role_agents: Dict[str, RoleAgent],
|
| 1167 |
+
model: str = MAIN_AGENT_MODEL_NAME, max_turns: int | None = None,
|
| 1168 |
+
):
|
| 1169 |
+
self.client = client
|
| 1170 |
+
self.role_agents = role_agents
|
| 1171 |
+
self.model = model
|
| 1172 |
+
self.runtime_config = runtime_defaults()
|
| 1173 |
+
self.max_turns = max_turns if max_turns is not None else int(os.getenv("MAX_TURNS", str(self.runtime_config["max_turns"])))
|
| 1174 |
+
self.runtime_config["max_turns"] = self.max_turns
|
| 1175 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config["communication_role_names"])
|
| 1176 |
+
self.delivered_messages = []
|
| 1177 |
+
self.incomplete_policy = IncompletePolicy(INCOMPLETE_INJECTION) if SETTING in {"incomplete", "mixed"} else None
|
| 1178 |
+
self.followup_resolver = IncompleteFollowupResolver(INCOMPLETE_FOLLOWUP_RECORDS) if SETTING in {"incomplete", "mixed"} else None
|
| 1179 |
+
self.current_turn = 0
|
| 1180 |
+
self.communication_events = []
|
| 1181 |
+
self.empty_observation_count = 0
|
| 1182 |
+
self.messages: List[Dict[str, str]] = []
|
| 1183 |
+
self.system_message = self._build_system_message()
|
| 1184 |
+
self._semantic_enabled_roles: set[str] = set()
|
| 1185 |
+
|
| 1186 |
+
def _build_system_message(self) -> str:
|
| 1187 |
+
if MAIN_AGENT_ROLE_ORDER_SEED is None:
|
| 1188 |
+
return main_system_prompt()
|
| 1189 |
+
roles = list(PUBLIC_ROLES)
|
| 1190 |
+
random.Random(MAIN_AGENT_ROLE_ORDER_SEED).shuffle(roles)
|
| 1191 |
+
role_text = "\n".join(
|
| 1192 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1193 |
+
for item in roles
|
| 1194 |
+
)
|
| 1195 |
+
return main_system_prompt().replace(
|
| 1196 |
+
"\n".join(
|
| 1197 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1198 |
+
for item in PUBLIC_ROLES
|
| 1199 |
+
),
|
| 1200 |
+
role_text,
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _call_main(self) -> Dict[str, Any]:
|
| 1204 |
+
if SETTING in {"missed", "mixed"} and self.messages[-1]["role"] == "assistant":
|
| 1205 |
+
self.messages.append({"role": "user", "content": '{"observations":[]}'})
|
| 1206 |
+
self.empty_observation_count += 1
|
| 1207 |
+
response = self.client.chat.completions.create(
|
| 1208 |
+
model=self.model,
|
| 1209 |
+
messages=self.messages,
|
| 1210 |
+
temperature=0.1,
|
| 1211 |
+
response_format={"type": "json_object"},
|
| 1212 |
+
extra_body={"reasoning": {"effort": LLM_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 1213 |
+
)
|
| 1214 |
+
self._last_main_parse_trace = {}
|
| 1215 |
+
return parse_json_message(response.choices[0].message.content, trace=self._last_main_parse_trace)
|
| 1216 |
+
|
| 1217 |
+
def _answer_question(
|
| 1218 |
+
self, role_name: str, question: Dict[str, Any],
|
| 1219 |
+
) -> tuple[Dict[str, Any], bool]:
|
| 1220 |
+
role_name = resolve_role_name(role_name, self.role_agents)
|
| 1221 |
+
role = self.role_agents.get(role_name)
|
| 1222 |
+
if role is None:
|
| 1223 |
+
return {"answer": f"Error: unknown role {role_name}。"}, False
|
| 1224 |
+
try:
|
| 1225 |
+
normalized = validate_question(
|
| 1226 |
+
question, role_name=role_name,
|
| 1227 |
+
semantic_enabled=role_name in self._semantic_enabled_roles,
|
| 1228 |
+
)
|
| 1229 |
+
except ValueError as error:
|
| 1230 |
+
return {"answer": f"Invalid query: {error}"}, False
|
| 1231 |
+
if not normalized["authorized"]:
|
| 1232 |
+
return {"answer": "The key is invalid, belongs to another role, or keyless follow-up is not yet authorized. Include a complete key for this role in question text, without a separate key field."}, False
|
| 1233 |
+
key = question.get("key")
|
| 1234 |
+
role_question = dict(question)
|
| 1235 |
+
binding = None
|
| 1236 |
+
if (self.followup_resolver and key is None
|
| 1237 |
+
and (SETTING != "mixed" or role_name == INCOMPLETE_INJECTION["role_name"])):
|
| 1238 |
+
binding = self.followup_resolver.resolve(role_name, question['question'], self.current_turn)
|
| 1239 |
+
if binding['status'] != 'resolved':
|
| 1240 |
+
answer = (self.followup_resolver.catalog(role_name) if binding['status'] == 'catalog'
|
| 1241 |
+
else self.followup_resolver.CLARIFY)
|
| 1242 |
+
return {"answer": answer, "followup_binding": binding}, False
|
| 1243 |
+
key = binding['key']
|
| 1244 |
+
# Resolve keys only for role requests; preserve the main question in transcripts.
|
| 1245 |
+
role_question = dict(question, key=key, question=question['question'] + ' (System-linked record: ' + key + ')')
|
| 1246 |
+
allowed_keys = set(RECORD_REPLY_KEYS[key] if key is not None else ROLE_VALID_KEYS[role_name])
|
| 1247 |
+
unrelated_field = False
|
| 1248 |
+
if binding and key == INCOMPLETE_INJECTION['key']:
|
| 1249 |
+
hidden_topic = INCOMPLETE_INJECTION['hidden_predicate_id'].removeprefix(INCOMPLETE_INJECTION['candidate_id'] + '_')
|
| 1250 |
+
unrelated_field = not binding['full'] and hidden_topic not in binding['fields'] and self.incomplete_policy.recovered_at_turn is None
|
| 1251 |
+
disclosure_mode = ('incomplete_partial' if unrelated_field else self.incomplete_policy.mode(role_name, role_question, self.current_turn)) if self.incomplete_policy else None
|
| 1252 |
+
if binding:
|
| 1253 |
+
binding['recovery_requested'] = disclosure_mode == 'incomplete_recovery'
|
| 1254 |
+
options = self.incomplete_policy.request_options(disclosure_mode, role.system_message) if disclosure_mode else {}
|
| 1255 |
+
trace = role.answer_with_trace(
|
| 1256 |
+
format_role_user_message(role_question), allowed_keys=allowed_keys,
|
| 1257 |
+
response_mode=disclosure_mode or ("exact" if key is not None else "search"),
|
| 1258 |
+
**options,
|
| 1259 |
+
)
|
| 1260 |
+
if not trace["accepted"]:
|
| 1261 |
+
return {
|
| 1262 |
+
"answer": trace["answer"], "role_validation_trace": trace,
|
| 1263 |
+
"protocol_error": "role_reply_scope_violation",
|
| 1264 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1265 |
+
}, False
|
| 1266 |
+
if disclosure_mode:
|
| 1267 |
+
self.incomplete_policy.observe(disclosure_mode, self.current_turn, trace["answer"])
|
| 1268 |
+
if self.followup_resolver:
|
| 1269 |
+
self.followup_resolver.observe(role_name, key, self.current_turn)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": trace["answer"], "role_trace": trace,
|
| 1272 |
+
"authorized_exact": question.get("key") is not None,
|
| 1273 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1274 |
+
}, False
|
| 1275 |
+
|
| 1276 |
+
def _communication_evaluation(
|
| 1277 |
+
self, transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1278 |
+
) -> Dict[str, Any]:
|
| 1279 |
+
metrics = communication_metrics(transcript)
|
| 1280 |
+
total_questions = sum(
|
| 1281 |
+
len(message.get("questions", []))
|
| 1282 |
+
for event in transcript
|
| 1283 |
+
for message in event.get("main_agent_action", {}).get("messages", [])
|
| 1284 |
+
)
|
| 1285 |
+
ideal = max(1, self.runtime_config["finalize_ideal_round"])
|
| 1286 |
+
turns = final_turn if final_turn is not None else len(transcript)
|
| 1287 |
+
return {
|
| 1288 |
+
**metrics,
|
| 1289 |
+
"total_role_agent_queries": total_questions,
|
| 1290 |
+
"total_questions": total_questions,
|
| 1291 |
+
"finalize_ideal_round": self.runtime_config["finalize_ideal_round"],
|
| 1292 |
+
"max_turns": self.max_turns,
|
| 1293 |
+
"wait_turns": sum(bool(event.get("waited")) for event in transcript),
|
| 1294 |
+
"empty_observation_count": self.empty_observation_count,
|
| 1295 |
+
**self.neglect_policy.metrics(),
|
| 1296 |
+
"delivered_reply_count": len(self.delivered_messages),
|
| 1297 |
+
"pending_reply_count": self.neglect_policy.metrics()["neglect_pending_count"],
|
| 1298 |
+
"efficiency": min(1.0, ideal / turns) if final_turn else 0.0,
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
def _result(
|
| 1302 |
+
self, final: Dict[str, Any], transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1303 |
+
) -> Dict[str, Any]:
|
| 1304 |
+
conclusion = compute_conclusion_correctness(final)
|
| 1305 |
+
communication = self._communication_evaluation(transcript, final_turn)
|
| 1306 |
+
communication["recovery_success"] = (
|
| 1307 |
+
recovery_success(communication, conclusion["conclusion_correctness"] == 1)
|
| 1308 |
+
if ERROR_INJECTION.get("enabled") else None
|
| 1309 |
+
)
|
| 1310 |
+
if self.incomplete_policy:
|
| 1311 |
+
communication.update(self.followup_resolver.metrics())
|
| 1312 |
+
communication.update(self.incomplete_policy.metrics(
|
| 1313 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1314 |
+
))
|
| 1315 |
+
communication.update(incomplete_numeric_metrics(
|
| 1316 |
+
INCOMPLETE_INJECTION, transcript, communication,
|
| 1317 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1318 |
+
))
|
| 1319 |
+
return {
|
| 1320 |
+
"final_result": final,
|
| 1321 |
+
"evaluation": {
|
| 1322 |
+
"conclusion_correct": conclusion["conclusion_correct"],
|
| 1323 |
+
"numeric_result_correct": conclusion["numeric_result_correct"],
|
| 1324 |
+
"joint_correctness": conclusion["conclusion_correctness"],
|
| 1325 |
+
"conclusion_evaluation": conclusion,
|
| 1326 |
+
"communication_evaluation": communication,
|
| 1327 |
+
},
|
| 1328 |
+
"transcript": transcript,
|
| 1329 |
+
"runtime_config": dict(self.runtime_config),
|
| 1330 |
+
"collaboration_state": {
|
| 1331 |
+
"neglect_roles": self.neglect_policy.roles,
|
| 1332 |
+
"delivered_messages": list(self.delivered_messages),
|
| 1333 |
+
"communication_events": list(self.communication_events),
|
| 1334 |
+
},
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
run = run_direct
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def build_task() -> str:
|
| 1341 |
+
return TASK_CONTEXT.strip() + "\n\n" + TASK_QUERY.strip()
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def create_timestamped_run_dir(
|
| 1345 |
+
root: str | Path, prefix: str, started: datetime | None = None,
|
| 1346 |
+
) -> Path:
|
| 1347 |
+
root_path = Path(root)
|
| 1348 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 1349 |
+
timestamp = (started or datetime.now()).strftime("%m%d_%H%M")
|
| 1350 |
+
base_name = f"{prefix}_{timestamp}"
|
| 1351 |
+
suffix = 1
|
| 1352 |
+
while True:
|
| 1353 |
+
name = base_name if suffix == 1 else f"{base_name}_{suffix:02d}"
|
| 1354 |
+
candidate = root_path / name
|
| 1355 |
+
try:
|
| 1356 |
+
candidate.mkdir(exist_ok=False)
|
| 1357 |
+
return candidate
|
| 1358 |
+
except FileExistsError:
|
| 1359 |
+
suffix += 1
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
def save_single_run_result(
|
| 1363 |
+
result: Dict[str, Any], output_root: str | Path | None = None,
|
| 1364 |
+
) -> Path:
|
| 1365 |
+
logs_root = (
|
| 1366 |
+
Path(output_root)
|
| 1367 |
+
if output_root is not None
|
| 1368 |
+
else Path(__file__).resolve().parent.parent / "logs"
|
| 1369 |
+
)
|
| 1370 |
+
run_dir = create_timestamped_run_dir(logs_root, "single_run")
|
| 1371 |
+
result_path = run_dir / "result.json"
|
| 1372 |
+
result_path.write_text(
|
| 1373 |
+
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
|
| 1374 |
+
encoding="utf-8",
|
| 1375 |
+
)
|
| 1376 |
+
return result_path
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def main() -> None:
|
| 1380 |
+
main_client = OpenAI(base_url=MAIN_AGENT_BASE_URL, api_key=MAIN_AGENT_API_KEY)
|
| 1381 |
+
role_client = OpenAI(base_url=ROLE_AGENT_BASE_URL, api_key=ROLE_AGENT_API_KEY)
|
| 1382 |
+
role_agents = build_role_agents(role_client)
|
| 1383 |
+
agent = MainAgent(main_client, role_agents)
|
| 1384 |
+
task = build_task()
|
| 1385 |
+
print_key_trace("LLM CONFIG", format_llm_config())
|
| 1386 |
+
print_key_trace("AVAILABLE ROLES", format_available_roles(role_agents))
|
| 1387 |
+
print_key_trace("TASK QUERY", task)
|
| 1388 |
+
result = agent.run(task)
|
| 1389 |
+
result_path = save_single_run_result(result)
|
| 1390 |
+
summary_title = "MISALIGNED RECOVERY SUMMARY" if SETTING in {"misaligned", "mixed"} else "TASK SUMMARY"
|
| 1391 |
+
print_key_trace(summary_title, format_key_metrics(result["evaluation"]))
|
| 1392 |
+
print_key_trace("RESULT SAVED", result_path)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
if __name__ == "__main__":
|
| 1396 |
+
main()
|
data/incomplete/task_006/role_agents/analytical_chemistry.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Analytical laboratory director (LAB)",
|
| 3 |
+
"abstract": "Maintains laboratory instrumentation schedules and sample analysis hours",
|
| 4 |
+
"system_message": "You are the Analytical laboratory director (LAB). Your business responsibility is to maintain laboratory instrumentation schedules and sample analysis hours, as well as tracking analytical reagent batch metrics across candidate investigation plans.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains laboratory instrumentation schedules and sample analysis hours(ASSAY)",
|
| 8 |
+
"content": "LAB-ASSAY-DQY:For Direct-push soil gas spectrometry, the estimated Laboratory analysis hours for secondary gas chromatography and spectrometer confirmation assays total 25 h of active bench instrument processing.\nLAB-ASSAY-VPU:For Multi-depth fluorescent tracer hydrogeology, the estimated Laboratory analysis hours for secondary gas chromatography and spectrometer confirmation assays total 25 h of active bench instrument processing.\nLAB-ASSAY-6QL:For Electrical resistivity cross-borehole tomography, the estimated Laboratory analysis hours for secondary gas chromatography and spectrometer confirmation assays total 35 h of active bench instrument processing."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Reagent batch purity(REAG)",
|
| 12 |
+
"content": "LAB-REAG-MX4:For Direct-push soil gas spectrometry, the chromatography solvent purity for the high-performance liquid chromatography eluent batch is certified at 99.5 %.\nLAB-REAG-G3I:For Electrical resistivity cross-borehole tomography, the chromatography solvent purity for the high-performance liquid chromatography eluent batch is certified at 99.9 %.\nLAB-REAG-F73:For Multi-depth fluorescent tracer hydrogeology, the chromatography solvent purity for the high-performance liquid chromatography eluent batch is certified at 99.2 %."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/role_agents/community_relations.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Stakeholder engagement officer (COMM)",
|
| 3 |
+
"abstract": "Maintains public communication surveys and municipal stakeholder feedback",
|
| 4 |
+
"system_message": "You are the Stakeholder engagement officer (COMM), responsible for maintaining public communication surveys, tracking municipal stakeholder feedback, and recording scheduled public outreach sessions for subsurface contamination investigation plans.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Public information briefings(BRIEF)",
|
| 8 |
+
"content": "COMM-BRIEF-XN8:Direct-push soil gas spectrometry has a scheduled briefing count of 2 briefings planned as town hall information sessions for surrounding neighborhoods.\nCOMM-BRIEF-X3S:Electrical resistivity cross-borehole tomography has a scheduled briefing count of 3 briefings planned as town hall information sessions for surrounding neighborhoods.\nCOMM-BRIEF-ZFI:Multi-depth fluorescent tracer hydrogeology has a scheduled briefing count of 1 briefings planned as town hall information sessions for surrounding neighborhoods."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains public communication surveys and municipal stakeholder feedback(ENG)",
|
| 12 |
+
"content": "COMM-ENG-CPG:For Electrical resistivity cross-borehole tomography, the neighborhood sentiment score among surveyed residents living within 1 km of the facility perimeter is 91%.\nCOMM-ENG-WIY:For Multi-depth fluorescent tracer hydrogeology, the neighborhood sentiment score among surveyed residents living within 1 km of the facility perimeter is 42%.\nCOMM-ENG-VUN:For Direct-push soil gas spectrometry, the neighborhood sentiment score among surveyed residents living within 1 km of the facility perimeter is 42%."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/role_agents/environmental_safety.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Site safety manager (SAFE)",
|
| 3 |
+
"abstract": "Maintains toxicological hazard assessments and site access safety clearances",
|
| 4 |
+
"system_message": "You are Site safety manager (SAFE). You serve as the Site safety manager (SAFE), tasked with maintaining toxicological hazard assessments and evaluating site access safety clearances across proposed subsurface investigation plans.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Protective equipment readiness(PPE)",
|
| 8 |
+
"content": "SAFE-PPE-MT9:The direct-push soil gas spectrometry plan maintains an emergency reserve count of 30 canisters of unopened chemical vapor respirator filters.\nSAFE-PPE-OPY:For electrical resistivity cross-borehole tomography, the respirator canister reserve count is 45 canisters.\nSAFE-PPE-MS7:Multi-depth fluorescent tracer hydrogeology maintains a respirator canister reserve count of 60 canisters in the emergency response cache."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains toxicological hazard assessments and site access safety clearances(HAZ)",
|
| 12 |
+
"content": "SAFE-HAZ-CBU:For the direct-push soil gas spectrometry plan evaluated for the project site municipality of Hangzhou, site safety cleared status is true based on verification that ambient volatile organic levels meet occupational limits.\nSAFE-HAZ-I3B:For electrical resistivity cross-borehole tomography under the project site municipality of Hangzhou, the site safety cleared status is confirmed as true.\nSAFE-HAZ-YMJ:For direct-push soil gas spectrometry evaluated for the project site municipality of Ningbo, site safety cleared status is false.\nSAFE-HAZ-VV7:For multi-depth fluorescent tracer hydrogeology in the project site municipality of Hangzhou, site safety cleared status is false."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/role_agents/field_operations.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Field deployment supervisor (OPS)",
|
| 3 |
+
"abstract": "Maintains operational staffing estimates and field drilling crew hours",
|
| 4 |
+
"system_message": "You are Field deployment supervisor (OPS). The field deployment supervisor (OPS) manages operational staffing estimates and logs field drilling crew hours. This role oversees resource allocation, schedules field machinery, tracks on-site technician hours, and monitors field crew sizes across proposed subsurface investigation plans.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Field staffing complement(CREW)",
|
| 8 |
+
"content": "OPS-CREW-A7F:Under the proposed field sampling campaign roster, Direct-push soil gas spectrometry requires a field crew team size of 8 personnel scheduled for active on-site duties.\nOPS-CREW-8ZZ:Under the proposed field sampling campaign roster, Electrical resistivity cross-borehole tomography requires a field crew team size of 4 personnel scheduled for active on-site duties.\nOPS-CREW-ZJ6:Under the proposed field sampling campaign roster, Multi-depth fluorescent tracer hydrogeology requires a field crew team size of 6 personnel scheduled for active on-site duties."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains operational staffing estimates and field drilling crew hours(FIELD)",
|
| 12 |
+
"content": "OPS-FIELD-0H9:For Multi-depth fluorescent tracer hydrogeology, the planned direct-push and core sampling campaign projects field deployment hours of 20 h for machinery and technician crews on site.\nOPS-FIELD-398:For Direct-push soil gas spectrometry, the planned direct-push and core sampling campaign projects field deployment hours of 30 h, representing total cumulative operating hours for field machinery and on-site technician crews.\nOPS-FIELD-OOM:For Electrical resistivity cross-borehole tomography, the planned direct-push and core sampling campaign projects field deployment hours of 20 h for field machinery and on-site technician crews."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/role_agents/forensics_qa.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Quality assurance officer (QA)",
|
| 3 |
+
"abstract": "Maintains analytical protocol standards and sample chain-of-custody accreditations",
|
| 4 |
+
"system_message": "You are the Quality assurance officer (QA), responsible for maintaining analytical protocol standards and sample chain-of-custody accreditations, as well as overseeing sample archive retention conditions.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains analytical protocol standards and sample chain-of-custody accreditations(AUD)",
|
| 8 |
+
"content": "QA-AUD-2EB:For Multi-depth fluorescent tracer hydrogeology, the sample handling protocol is chain-of-custody accredited under ISO/IEC 17025 evidentiary tamper-proofing standards.\nQA-AUD-ICV:For Electrical resistivity cross-borehole tomography, the sample handling protocol is not chain-of-custody accredited under ISO/IEC 17025 evidentiary tamper-proofing standards.\nQA-AUD-WP7:For Direct-push soil gas spectrometry, the sample handling protocol is chain-of-custody accredited according to ISO/IEC 17025 evidentiary tamper-proofing standards."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Sample archive retention(ARCH)",
|
| 12 |
+
"content": "QA-ARCH-BI5:For Multi-depth fluorescent tracer hydrogeology, the recorded steady-state core holding temperature in the primary sample archive unit shows an archive holding temperature of -10 degC.\nQA-ARCH-2W7:For Electrical resistivity cross-borehole tomography, the recorded steady-state core holding temperature in the primary sample archive unit shows an archive holding temperature of -20 degC.\nQA-ARCH-NJV:For Direct-push soil gas spectrometry, the recorded steady-state core holding temperature in the primary sample archive unit shows an archive holding temperature of 4 degC."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/role_agents/instrumentation.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Forensic instrumentation specialist (INST)",
|
| 3 |
+
"abstract": "Maintains detector calibration verification and analytical processing turnaround records",
|
| 4 |
+
"system_message": "You are the Forensic instrumentation specialist (INST), responsible for maintaining detector calibration verification and analytical processing turnaround records.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains detector calibration verification and analytical processing turnaround records(CAL)",
|
| 8 |
+
"content": "INST-CAL-TBJ:For Direct-push soil gas spectrometry, sensor calibration is verified, and the analytical turnaround time from sample acquisition through preliminary plume mapping is 36 h.\nINST-CAL-SDU:For Electrical resistivity cross-borehole tomography, sensor calibration is verified, and the analytical turnaround time is 72 h.\nINST-CAL-5EN:For Multi-depth fluorescent tracer hydrogeology, sensor calibration is verified, and the analytical turnaround time is 36 h."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Detector baseline drift(DRIFT)",
|
| 12 |
+
"content": "INST-DRIFT-LWB:For Multi-depth fluorescent tracer hydrogeology, the baseline drift rate measured across an eight-hour stationary cycle is 0.5 mV/h.\nINST-DRIFT-2E1:For Direct-push soil gas spectrometry, the baseline drift rate measured across an eight-hour stationary cycle is 0.8 mV/h.\nINST-DRIFT-11Y:For Electrical resistivity cross-borehole tomography, the baseline drift rate measured across an eight-hour stationary cycle is 0.2 mV/h."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/role_agents/regulatory_liaison.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Regulatory compliance coordinator (REG)",
|
| 3 |
+
"abstract": "Maintains inter-agency notification logs and statutory reporting filings",
|
| 4 |
+
"system_message": "You are the Regulatory compliance coordinator (REG). Your responsibilities cover maintaining inter-agency notification logs and statutory reporting filings, as well as conducting aquifer permit reviews.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains inter-agency notification logs and statutory reporting filings(NOTIF)",
|
| 8 |
+
"content": "REG-NOTIF-SPC:For Multi-depth fluorescent tracer hydrogeology, the regulatory authority has not been notified, as no official filing acknowledgment exists under the state environmental protection agency notification mandate.\nREG-NOTIF-CXP:For Electrical resistivity cross-borehole tomography, the regulatory authority has been notified, confirmed via official statutory reporting filing acknowledgment under the state environmental protection agency notification mandate.\nREG-NOTIF-RV7:For Direct-push soil gas spectrometry, the regulatory authority has been notified, as confirmed by an official statutory reporting filing receipt acknowledged under the state environmental protection agency mandate."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Aquifer permit review(PERM)",
|
| 12 |
+
"content": "REG-PERM-SRK:For Multi-depth fluorescent tracer hydrogeology, the aquifer permit review establishes a permit processing fee of 800 USD under the regional water board fee schedule.\nREG-PERM-3AJ:For Direct-push soil gas spectrometry, the aquifer permit review records a permit processing fee of 1,600 USD according to the regional water board fee schedule for temporary environmental drilling.\nREG-PERM-8ZK:For Electrical resistivity cross-borehole tomography, the aquifer permit review reflects a permit processing fee of 1,200 USD for the temporary environmental drilling permit application."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_006/tasks/run_one.py
ADDED
|
@@ -0,0 +1,1396 @@
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
from typing import Any
|
| 5 |
+
COMMUNICATION_ROLE_NAMES = []
|
| 6 |
+
GOLD = {'conclusion': 'Select', 'numeric_result': 8250}
|
| 7 |
+
POSITIVE_CONCLUSION = 'Select'
|
| 8 |
+
NEGATIVE_CONCLUSION = 'Do not select'
|
| 9 |
+
NUMERIC_PRECISION = 0
|
| 10 |
+
PUBLIC_ROLES = [{'role_name': 'Site safety manager (SAFE)', 'responsibility': 'Maintains toxicological hazard assessments and site access safety clearances', 'role_abbreviation': 'SAFE'}, {'role_name': 'Forensic instrumentation specialist (INST)', 'responsibility': 'Maintains detector calibration verification and analytical processing turnaround records', 'role_abbreviation': 'INST'}, {'role_name': 'Quality assurance officer (QA)', 'responsibility': 'Maintains analytical protocol standards and sample chain-of-custody accreditations', 'role_abbreviation': 'QA'}, {'role_name': 'Regulatory compliance coordinator (REG)', 'responsibility': 'Maintains inter-agency notification logs and statutory reporting filings', 'role_abbreviation': 'REG'}, {'role_name': 'Field deployment supervisor (OPS)', 'responsibility': 'Maintains operational staffing estimates and field drilling crew hours', 'role_abbreviation': 'OPS'}, {'role_name': 'Analytical laboratory director (LAB)', 'responsibility': 'Maintains laboratory instrumentation schedules and sample analysis hours', 'role_abbreviation': 'LAB'}, {'role_name': 'Stakeholder engagement officer (COMM)', 'responsibility': 'Maintains public communication surveys and municipal stakeholder feedback', 'role_abbreviation': 'COMM'}]
|
| 11 |
+
ROLE_KEY_PREFIXES = {'Site safety manager (SAFE)': 'SAFE-', 'Forensic instrumentation specialist (INST)': 'INST-', 'Quality assurance officer (QA)': 'QA-', 'Regulatory compliance coordinator (REG)': 'REG-', 'Field deployment supervisor (OPS)': 'OPS-', 'Analytical laboratory director (LAB)': 'LAB-', 'Stakeholder engagement officer (COMM)': 'COMM-'}
|
| 12 |
+
ROLE_VALID_KEYS = {'Site safety manager (SAFE)': ['SAFE-PPE-MT9', 'SAFE-PPE-OPY', 'SAFE-PPE-MS7', 'SAFE-HAZ-CBU', 'SAFE-HAZ-I3B', 'SAFE-HAZ-YMJ', 'SAFE-HAZ-VV7'], 'Forensic instrumentation specialist (INST)': ['INST-CAL-TBJ', 'INST-CAL-SDU', 'INST-CAL-5EN', 'INST-DRIFT-LWB', 'INST-DRIFT-2E1', 'INST-DRIFT-11Y'], 'Quality assurance officer (QA)': ['QA-AUD-2EB', 'QA-AUD-ICV', 'QA-AUD-WP7', 'QA-ARCH-BI5', 'QA-ARCH-2W7', 'QA-ARCH-NJV'], 'Regulatory compliance coordinator (REG)': ['REG-NOTIF-SPC', 'REG-NOTIF-CXP', 'REG-NOTIF-RV7', 'REG-PERM-SRK', 'REG-PERM-3AJ', 'REG-PERM-8ZK'], 'Field deployment supervisor (OPS)': ['OPS-CREW-A7F', 'OPS-CREW-8ZZ', 'OPS-CREW-ZJ6', 'OPS-FIELD-0H9', 'OPS-FIELD-398', 'OPS-FIELD-OOM'], 'Analytical laboratory director (LAB)': ['LAB-ASSAY-DQY', 'LAB-ASSAY-VPU', 'LAB-ASSAY-6QL', 'LAB-REAG-MX4', 'LAB-REAG-G3I', 'LAB-REAG-F73'], 'Stakeholder engagement officer (COMM)': ['COMM-BRIEF-XN8', 'COMM-BRIEF-X3S', 'COMM-BRIEF-ZFI', 'COMM-ENG-CPG', 'COMM-ENG-WIY', 'COMM-ENG-VUN']}
|
| 13 |
+
RECORD_REPLY_KEYS = {'SAFE-HAZ-CBU': ['SAFE-HAZ-CBU'], 'SAFE-HAZ-I3B': ['SAFE-HAZ-I3B'], 'SAFE-HAZ-VV7': ['SAFE-HAZ-VV7'], 'INST-CAL-TBJ': ['INST-CAL-TBJ'], 'INST-CAL-SDU': ['INST-CAL-SDU'], 'INST-CAL-5EN': ['INST-CAL-5EN'], 'QA-AUD-WP7': ['QA-AUD-WP7'], 'QA-AUD-ICV': ['QA-AUD-ICV'], 'QA-AUD-2EB': ['QA-AUD-2EB'], 'REG-NOTIF-RV7': ['REG-NOTIF-RV7'], 'REG-NOTIF-CXP': ['REG-NOTIF-CXP'], 'REG-NOTIF-SPC': ['REG-NOTIF-SPC'], 'OPS-FIELD-398': ['OPS-FIELD-398'], 'OPS-FIELD-OOM': ['OPS-FIELD-OOM'], 'OPS-FIELD-0H9': ['OPS-FIELD-0H9'], 'LAB-ASSAY-DQY': ['LAB-ASSAY-DQY'], 'LAB-ASSAY-6QL': ['LAB-ASSAY-6QL'], 'LAB-ASSAY-VPU': ['LAB-ASSAY-VPU'], 'COMM-ENG-VUN': ['COMM-ENG-VUN'], 'COMM-ENG-CPG': ['COMM-ENG-CPG'], 'COMM-ENG-WIY': ['COMM-ENG-WIY'], 'SAFE-PPE-MT9': ['SAFE-PPE-MT9'], 'SAFE-PPE-OPY': ['SAFE-PPE-OPY'], 'SAFE-PPE-MS7': ['SAFE-PPE-MS7'], 'INST-DRIFT-2E1': ['INST-DRIFT-2E1'], 'INST-DRIFT-11Y': ['INST-DRIFT-11Y'], 'INST-DRIFT-LWB': ['INST-DRIFT-LWB'], 'QA-ARCH-NJV': ['QA-ARCH-NJV'], 'QA-ARCH-2W7': ['QA-ARCH-2W7'], 'QA-ARCH-BI5': ['QA-ARCH-BI5'], 'REG-PERM-3AJ': ['REG-PERM-3AJ'], 'REG-PERM-8ZK': ['REG-PERM-8ZK'], 'REG-PERM-SRK': ['REG-PERM-SRK'], 'OPS-CREW-A7F': ['OPS-CREW-A7F'], 'OPS-CREW-8ZZ': ['OPS-CREW-8ZZ'], 'OPS-CREW-ZJ6': ['OPS-CREW-ZJ6'], 'LAB-REAG-MX4': ['LAB-REAG-MX4'], 'LAB-REAG-G3I': ['LAB-REAG-G3I'], 'LAB-REAG-F73': ['LAB-REAG-F73'], 'COMM-BRIEF-XN8': ['COMM-BRIEF-XN8'], 'COMM-BRIEF-X3S': ['COMM-BRIEF-X3S'], 'COMM-BRIEF-ZFI': ['COMM-BRIEF-ZFI'], 'SAFE-HAZ-YMJ': ['SAFE-HAZ-YMJ']}
|
| 14 |
+
REQUIRED_KEYS = ['INST-CAL-SDU', 'INST-CAL-TBJ', 'LAB-ASSAY-DQY', 'OPS-FIELD-398', 'QA-AUD-WP7', 'REG-NOTIF-RV7', 'SAFE-HAZ-CBU', 'SAFE-HAZ-VV7']
|
| 15 |
+
DISTRACTOR_KEYS = ['COMM-BRIEF-X3S', 'COMM-BRIEF-XN8', 'COMM-BRIEF-ZFI', 'COMM-ENG-CPG', 'COMM-ENG-VUN', 'COMM-ENG-WIY']
|
| 16 |
+
SETTING = 'incomplete'
|
| 17 |
+
|
| 18 |
+
def runtime_defaults() -> dict[str, Any]:
|
| 19 |
+
return {
|
| 20 |
+
"setting": SETTING,
|
| 21 |
+
"communication_role_names": list(COMMUNICATION_ROLE_NAMES),
|
| 22 |
+
"finalize_ideal_round": 3,
|
| 23 |
+
"max_turns": 6,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
FINALIZE_IDEAL_ROUND = runtime_defaults()["finalize_ideal_round"]
|
| 27 |
+
DEFAULT_MAX_TURNS = runtime_defaults()["max_turns"]
|
| 28 |
+
ERROR_INJECTION = {'enabled': False, 'role_name': 'Site safety manager (SAFE)', 'target_key': 'SAFE-HAZ-CBU', 'alternate_key': 'SAFE-HAZ-YMJ', 'target_context': 'Hangzhou', 'alternate_context': 'Ningbo'}
|
| 29 |
+
INCOMPLETE_INJECTION = {'record_id': 'rec_instrumentation_A', 'role_id': 'instrumentation', 'candidate_id': 'A', 'key': 'INST-CAL-TBJ', 'boolean_predicate_id': 'A_sensor_calibration_verified', 'boolean_label': 'Sensor calibration verified', 'hidden_predicate_id': 'A_analytical_turnaround_hours', 'threshold_label': 'Analytical turnaround time', 'threshold_aliases': ['Report turnaround duration', 'Investigation turnaround time'], 'threshold_value': 36, 'threshold_unit': 'h', 'partial_record_text': 'INST-CAL-TBJ: Direct-push soil gas spectrometry.Direct-push soil gas spectrometry: Sensor calibration verified = true .Source: Instrument calibration logbook; Scope: Candidate analytical sensor package; Measurement: Formal validation that multipoint calibration curves match certified gas standards.', 'alternative_outputs': [{'conclusion': 'Do not select', 'numeric_result': None, 'qualified_candidate_id': None}], 'role_name': 'Forensic instrumentation specialist (INST)', 'candidate_name': 'Direct-push soil gas spectrometry', 'other_candidate_names': ['Electrical resistivity cross-borehole tomography', 'Multi-depth fluorescent tracer hydrogeology'], 'context_value': None, 'other_context_values': [], 'language': 'en'}
|
| 30 |
+
INCOMPLETE_FOLLOWUP_RECORDS = [{'key': 'SAFE-HAZ-CBU', 'role': 'Site safety manager (SAFE)', 'candidate': 'Direct-push soil gas spectrometry', 'context': 'Hangzhou', 'fields': [{'id': 'site_safety_cleared', 'label': 'Site safety cleared', 'aliases': ['Safety clearance', 'Site entry clearance']}]}, {'key': 'SAFE-HAZ-I3B', 'role': 'Site safety manager (SAFE)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': 'Hangzhou', 'fields': [{'id': 'site_safety_cleared', 'label': 'Site safety cleared', 'aliases': ['Safety clearance', 'Site entry clearance']}]}, {'key': 'SAFE-HAZ-VV7', 'role': 'Site safety manager (SAFE)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': 'Hangzhou', 'fields': [{'id': 'site_safety_cleared', 'label': 'Site safety cleared', 'aliases': ['Safety clearance', 'Site entry clearance']}]}, {'key': 'INST-CAL-TBJ', 'role': 'Forensic instrumentation specialist (INST)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'sensor_calibration_verified', 'label': 'Sensor calibration verified', 'aliases': ['Instrument calibration verification', 'Detector calibration status']}, {'id': 'analytical_turnaround_hours', 'label': 'Analytical turnaround time', 'aliases': ['Report turnaround duration', 'Investigation turnaround time']}]}, {'key': 'INST-CAL-SDU', 'role': 'Forensic instrumentation specialist (INST)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'sensor_calibration_verified', 'label': 'Sensor calibration verified', 'aliases': ['Instrument calibration verification', 'Detector calibration status']}, {'id': 'analytical_turnaround_hours', 'label': 'Analytical turnaround time', 'aliases': ['Report turnaround duration', 'Investigation turnaround time']}]}, {'key': 'INST-CAL-5EN', 'role': 'Forensic instrumentation specialist (INST)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'sensor_calibration_verified', 'label': 'Sensor calibration verified', 'aliases': ['Instrument calibration verification', 'Detector calibration status']}, {'id': 'analytical_turnaround_hours', 'label': 'Analytical turnaround time', 'aliases': ['Report turnaround duration', 'Investigation turnaround time']}]}, {'key': 'QA-AUD-WP7', 'role': 'Quality assurance officer (QA)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'chain_of_custody_accredited', 'label': 'Chain-of-custody accredited', 'aliases': ['Forensic chain of custody status', 'Chain of custody verification']}]}, {'key': 'QA-AUD-ICV', 'role': 'Quality assurance officer (QA)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'chain_of_custody_accredited', 'label': 'Chain-of-custody accredited', 'aliases': ['Forensic chain of custody status', 'Chain of custody verification']}]}, {'key': 'QA-AUD-2EB', 'role': 'Quality assurance officer (QA)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'chain_of_custody_accredited', 'label': 'Chain-of-custody accredited', 'aliases': ['Forensic chain of custody status', 'Chain of custody verification']}]}, {'key': 'REG-NOTIF-RV7', 'role': 'Regulatory compliance coordinator (REG)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'regulatory_authority_notified', 'label': 'Regulatory authority notified', 'aliases': ['Statutory authority notification', 'Environmental agency notification status']}]}, {'key': 'REG-NOTIF-CXP', 'role': 'Regulatory compliance coordinator (REG)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'regulatory_authority_notified', 'label': 'Regulatory authority notified', 'aliases': ['Statutory authority notification', 'Environmental agency notification status']}]}, {'key': 'REG-NOTIF-SPC', 'role': 'Regulatory compliance coordinator (REG)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'regulatory_authority_notified', 'label': 'Regulatory authority notified', 'aliases': ['Statutory authority notification', 'Environmental agency notification status']}]}, {'key': 'OPS-FIELD-398', 'role': 'Field deployment supervisor (OPS)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'field_deployment_hours', 'label': 'Field deployment hours', 'aliases': ['Field sampling duration', 'On-site rig operation time']}]}, {'key': 'OPS-FIELD-OOM', 'role': 'Field deployment supervisor (OPS)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'field_deployment_hours', 'label': 'Field deployment hours', 'aliases': ['Field sampling duration', 'On-site rig operation time']}]}, {'key': 'OPS-FIELD-0H9', 'role': 'Field deployment supervisor (OPS)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'field_deployment_hours', 'label': 'Field deployment hours', 'aliases': ['Field sampling duration', 'On-site rig operation time']}]}, {'key': 'LAB-ASSAY-DQY', 'role': 'Analytical laboratory director (LAB)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'laboratory_analysis_hours', 'label': 'Laboratory analysis hours', 'aliases': ['Lab assay duration', 'Bench analysis hours']}]}, {'key': 'LAB-ASSAY-6QL', 'role': 'Analytical laboratory director (LAB)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'laboratory_analysis_hours', 'label': 'Laboratory analysis hours', 'aliases': ['Lab assay duration', 'Bench analysis hours']}]}, {'key': 'LAB-ASSAY-VPU', 'role': 'Analytical laboratory director (LAB)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'laboratory_analysis_hours', 'label': 'Laboratory analysis hours', 'aliases': ['Lab assay duration', 'Bench analysis hours']}]}, {'key': 'COMM-ENG-VUN', 'role': 'Stakeholder engagement officer (COMM)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'neighborhood_sentiment_index', 'label': 'Neighborhood sentiment score', 'aliases': ['Community stakeholder support', 'Public acceptance index']}]}, {'key': 'COMM-ENG-CPG', 'role': 'Stakeholder engagement officer (COMM)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'neighborhood_sentiment_index', 'label': 'Neighborhood sentiment score', 'aliases': ['Community stakeholder support', 'Public acceptance index']}]}, {'key': 'COMM-ENG-WIY', 'role': 'Stakeholder engagement officer (COMM)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'neighborhood_sentiment_index', 'label': 'Neighborhood sentiment score', 'aliases': ['Community stakeholder support', 'Public acceptance index']}]}, {'key': 'SAFE-PPE-MT9', 'role': 'Site safety manager (SAFE)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_environmental_safety', 'label': 'Respirator canister reserve count', 'aliases': []}]}, {'key': 'SAFE-PPE-OPY', 'role': 'Site safety manager (SAFE)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_environmental_safety', 'label': 'Respirator canister reserve count', 'aliases': []}]}, {'key': 'SAFE-PPE-MS7', 'role': 'Site safety manager (SAFE)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_environmental_safety', 'label': 'Respirator canister reserve count', 'aliases': []}]}, {'key': 'INST-DRIFT-2E1', 'role': 'Forensic instrumentation specialist (INST)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_instrumentation', 'label': 'Baseline drift rate', 'aliases': []}]}, {'key': 'INST-DRIFT-11Y', 'role': 'Forensic instrumentation specialist (INST)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_instrumentation', 'label': 'Baseline drift rate', 'aliases': []}]}, {'key': 'INST-DRIFT-LWB', 'role': 'Forensic instrumentation specialist (INST)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_instrumentation', 'label': 'Baseline drift rate', 'aliases': []}]}, {'key': 'QA-ARCH-NJV', 'role': 'Quality assurance officer (QA)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_forensics_qa', 'label': 'Archive holding temperature', 'aliases': []}]}, {'key': 'QA-ARCH-2W7', 'role': 'Quality assurance officer (QA)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_forensics_qa', 'label': 'Archive holding temperature', 'aliases': []}]}, {'key': 'QA-ARCH-BI5', 'role': 'Quality assurance officer (QA)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_forensics_qa', 'label': 'Archive holding temperature', 'aliases': []}]}, {'key': 'REG-PERM-3AJ', 'role': 'Regulatory compliance coordinator (REG)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_regulatory_liaison', 'label': 'Permit processing fee', 'aliases': []}]}, {'key': 'REG-PERM-8ZK', 'role': 'Regulatory compliance coordinator (REG)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_regulatory_liaison', 'label': 'Permit processing fee', 'aliases': []}]}, {'key': 'REG-PERM-SRK', 'role': 'Regulatory compliance coordinator (REG)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_regulatory_liaison', 'label': 'Permit processing fee', 'aliases': []}]}, {'key': 'OPS-CREW-A7F', 'role': 'Field deployment supervisor (OPS)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_field_operations', 'label': 'Field crew team size', 'aliases': []}]}, {'key': 'OPS-CREW-8ZZ', 'role': 'Field deployment supervisor (OPS)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_field_operations', 'label': 'Field crew team size', 'aliases': []}]}, {'key': 'OPS-CREW-ZJ6', 'role': 'Field deployment supervisor (OPS)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_field_operations', 'label': 'Field crew team size', 'aliases': []}]}, {'key': 'LAB-REAG-MX4', 'role': 'Analytical laboratory director (LAB)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_analytical_chemistry', 'label': 'Chromatography solvent purity', 'aliases': []}]}, {'key': 'LAB-REAG-G3I', 'role': 'Analytical laboratory director (LAB)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_analytical_chemistry', 'label': 'Chromatography solvent purity', 'aliases': []}]}, {'key': 'LAB-REAG-F73', 'role': 'Analytical laboratory director (LAB)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_analytical_chemistry', 'label': 'Chromatography solvent purity', 'aliases': []}]}, {'key': 'COMM-BRIEF-XN8', 'role': 'Stakeholder engagement officer (COMM)', 'candidate': 'Direct-push soil gas spectrometry', 'context': '', 'fields': [{'id': 'supplemental_community_relations', 'label': 'Scheduled briefing count', 'aliases': []}]}, {'key': 'COMM-BRIEF-X3S', 'role': 'Stakeholder engagement officer (COMM)', 'candidate': 'Electrical resistivity cross-borehole tomography', 'context': '', 'fields': [{'id': 'supplemental_community_relations', 'label': 'Scheduled briefing count', 'aliases': []}]}, {'key': 'COMM-BRIEF-ZFI', 'role': 'Stakeholder engagement officer (COMM)', 'candidate': 'Multi-depth fluorescent tracer hydrogeology', 'context': '', 'fields': [{'id': 'supplemental_community_relations', 'label': 'Scheduled briefing count', 'aliases': []}]}, {'key': 'SAFE-HAZ-YMJ', 'role': 'Site safety manager (SAFE)', 'candidate': 'Direct-push soil gas spectrometry', 'context': 'Ningbo', 'fields': [{'id': 'site_safety_cleared', 'label': 'Site safety cleared', 'aliases': ['Safety clearance', 'Site entry clearance']}]}]
|
| 31 |
+
KEY_PATTERN = re.compile(r"^[A-Z]+-[A-Z]+-[A-Z0-9]{3}$")
|
| 32 |
+
REPLY_KEY_PATTERN = re.compile(r"(?<![A-Z0-9])[A-Z]+-[A-Z]+-[A-Z0-9]{3}(?![A-Z0-9])", re.IGNORECASE)
|
| 33 |
+
ROLE_REPLY_MAX_ATTEMPTS = 3
|
| 34 |
+
TASK_QUERY = 'Evaluate the candidate investigation plans to determine whether exactly one plan qualifies for selection. A qualifying plan must have site safety cleared for the project site municipality in Hangzhou, sensor calibration verified alongside an analytical turnaround time of at most 48 h, chain-of-custody accredited, and regulatory authority notified. If exactly one investigation plan qualifies, report "Select" and calculate its total investigation fee in USD based on its combined field deployment hours and laboratory analysis hours using the piecewise rate structure; otherwise, report "Do not select" and null for the numeric result.\n\nNumeric calculation rule: Compute only for the unique eligible candidate: total = [Field deployment hours] + [Laboratory analysis hours]; Apply marginal rates progressively from zero and add the tier charges; do not apply the highest rate to the entire total; quantity from 0 to 60 h at 150 USD/h; quantity above 60 h at 220 USD/h. Result unit: USD. Round only the final result to 0 decimal places (ties to even). If no candidate qualifies, numeric_result is null.\n\nCandidates and records to verify:\n- Multi-depth fluorescent tracer hydrogeology:SAFE-HAZ-VV7、INST-CAL-5EN、QA-AUD-2EB、REG-NOTIF-SPC、OPS-FIELD-0H9、LAB-ASSAY-VPU、COMM-ENG-WIY\n- Electrical resistivity cross-borehole tomography:SAFE-HAZ-I3B、INST-CAL-SDU、QA-AUD-ICV、REG-NOTIF-CXP、OPS-FIELD-OOM、LAB-ASSAY-6QL、COMM-ENG-CPG\n- Direct-push soil gas spectrometry:SAFE-HAZ-CBU、INST-CAL-TBJ、QA-AUD-WP7、REG-NOTIF-RV7、OPS-FIELD-398、LAB-ASSAY-DQY、COMM-ENG-VUN'
|
| 35 |
+
TASK_CONTEXT = 'In environmental forensic investigations following suspected industrial subsurface contamination incidents, investigation plans must undergo rigorous technical and regulatory qualification before execution. Site assessments require thorough safety clearance in designated municipal zones, validated analytical instrumentation, compliant reporting turnaround schedules, evidentiary accreditation, and official statutory agency notification. Evaluating these criteria ensures that field operations remain compliant, legally defensible, and cost-effective under established service rate structures.'
|
| 36 |
+
|
| 37 |
+
"""Parse one model message without treating trailing generation noise as an action."""
|
| 38 |
+
import json
|
| 39 |
+
import re
|
| 40 |
+
from typing import Any
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_json_message(content: Any, *, trace: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 44 |
+
if trace is not None:
|
| 45 |
+
trace.clear()
|
| 46 |
+
trace.update(policy="first_complete_object", raw_response=content, recovered=False)
|
| 47 |
+
if not isinstance(content, str):
|
| 48 |
+
raise ValueError("model response must be text")
|
| 49 |
+
text = content.strip().lstrip("\ufeff").strip()
|
| 50 |
+
# Parse the first complete object; never recover a nested fragment.
|
| 51 |
+
try:
|
| 52 |
+
value, end = json.JSONDecoder().raw_decode(text)
|
| 53 |
+
start = 0
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
if text.startswith(("{", "[", '"')):
|
| 56 |
+
raise
|
| 57 |
+
opening = re.search(r"[\{\[]", text)
|
| 58 |
+
if opening is None:
|
| 59 |
+
raise
|
| 60 |
+
start = opening.start()
|
| 61 |
+
value, consumed = json.JSONDecoder().raw_decode(text[start:])
|
| 62 |
+
end = start + consumed
|
| 63 |
+
if not isinstance(value, dict):
|
| 64 |
+
raise ValueError("model response must be a JSON object")
|
| 65 |
+
prefix, suffix = text[:start], text[end:]
|
| 66 |
+
if trace is not None:
|
| 67 |
+
trace.update(recovered=bool(prefix.strip() or suffix.strip()),
|
| 68 |
+
ignored_prefix=prefix, ignored_suffix=suffix)
|
| 69 |
+
return value
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def expand_question_keys(questions):
|
| 73 |
+
expanded = []
|
| 74 |
+
for question in questions:
|
| 75 |
+
if not isinstance(question, dict):
|
| 76 |
+
expanded.append(question)
|
| 77 |
+
continue
|
| 78 |
+
text = question.get("question")
|
| 79 |
+
keys = list(dict.fromkeys(REPLY_KEY_PATTERN.findall(text))) if isinstance(text, str) else []
|
| 80 |
+
for key in keys or [None]:
|
| 81 |
+
expanded.append(dict(question, key=key))
|
| 82 |
+
return expanded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def validate_question(question, *, role_name, semantic_enabled=False):
|
| 86 |
+
if not isinstance(question, dict) or not isinstance(question.get("question"), str) or not question["question"].strip():
|
| 87 |
+
raise ValueError("question must contain natural-language text")
|
| 88 |
+
if role_name not in ROLE_KEY_PREFIXES:
|
| 89 |
+
raise ValueError("unknown Role")
|
| 90 |
+
key = question.get("key")
|
| 91 |
+
authorized = semantic_enabled if key is None else (
|
| 92 |
+
isinstance(key, str) and key in ROLE_VALID_KEYS[role_name] and key in question["question"])
|
| 93 |
+
return {"authorized": bool(authorized)}
|
| 94 |
+
|
| 95 |
+
def recovery_key_match(answer: str) -> str | None:
|
| 96 |
+
target = ERROR_INJECTION.get("target_key")
|
| 97 |
+
if not target:
|
| 98 |
+
return None
|
| 99 |
+
def contains(key: str) -> bool:
|
| 100 |
+
return bool(re.search(r"(?<![A-Z0-9-])" + re.escape(key) + r"(?![A-Z0-9-])", answer, re.IGNORECASE))
|
| 101 |
+
if contains(target):
|
| 102 |
+
return "full_key"
|
| 103 |
+
parts = target.split("-")
|
| 104 |
+
alias = parts[0] + "-" + parts[-1]
|
| 105 |
+
matches = [key for key in ROLE_VALID_KEYS.get(ERROR_INJECTION.get("role_name"), [])
|
| 106 |
+
if key.split("-")[0] + "-" + key.split("-")[-1] == alias]
|
| 107 |
+
if matches == [target] and contains(alias):
|
| 108 |
+
return "abbreviated_key"
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
def communication_metrics(transcript: list[dict[str, Any]]) -> dict[str, Any]:
|
| 112 |
+
key_query_rounds: dict[str, int] = {}
|
| 113 |
+
key_query_counts: dict[str, int] = {}
|
| 114 |
+
queried_roles: set[str] = set()
|
| 115 |
+
mismatch_round: int | None = None
|
| 116 |
+
recovery_query_sent = False
|
| 117 |
+
recovery_query_turn: int | None = None
|
| 118 |
+
target_key_returned = False
|
| 119 |
+
recovery_turn: int | None = None
|
| 120 |
+
recovery_method: str | None = None
|
| 121 |
+
recovery_reference: str | None = None
|
| 122 |
+
target_key_query_turn: int | None = None
|
| 123 |
+
finalized_before_recovery = False
|
| 124 |
+
for event in transcript:
|
| 125 |
+
turn = int(event.get("turn", len(transcript)))
|
| 126 |
+
action = event.get("main_agent_action", {})
|
| 127 |
+
if (
|
| 128 |
+
ERROR_INJECTION.get("enabled")
|
| 129 |
+
and action.get("action") == "finalize"
|
| 130 |
+
and not target_key_returned
|
| 131 |
+
):
|
| 132 |
+
finalized_before_recovery = True
|
| 133 |
+
if action.get("action") != "ask_role_agents": continue
|
| 134 |
+
for answer in event.get("role_answers", []):
|
| 135 |
+
role_name = answer.get("role_agent")
|
| 136 |
+
if role_name: queried_roles.add(role_name)
|
| 137 |
+
if (
|
| 138 |
+
ERROR_INJECTION.get("enabled") and mismatch_round is not None and turn > mismatch_round
|
| 139 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 140 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("target_key")
|
| 141 |
+
and "role_trace" in answer
|
| 142 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 143 |
+
):
|
| 144 |
+
target_key_query_turn = target_key_query_turn or turn
|
| 145 |
+
if (
|
| 146 |
+
ERROR_INJECTION.get("enabled")
|
| 147 |
+
and role_name == ERROR_INJECTION.get("role_name")
|
| 148 |
+
and answer.get("question", {}).get("key") == ERROR_INJECTION.get("alternate_key")
|
| 149 |
+
and "role_trace" in answer
|
| 150 |
+
):
|
| 151 |
+
mismatch_round = mismatch_round or turn
|
| 152 |
+
for message in action.get("messages", []):
|
| 153 |
+
for question in message.get("questions", []):
|
| 154 |
+
key = question.get("key")
|
| 155 |
+
if (
|
| 156 |
+
ERROR_INJECTION.get("enabled")
|
| 157 |
+
and resolve_role_name(message.get("role_agent")) == ERROR_INJECTION.get("role_name")
|
| 158 |
+
and (key is None or key == ERROR_INJECTION.get("target_key"))
|
| 159 |
+
and mismatch_round is not None
|
| 160 |
+
and turn > mismatch_round
|
| 161 |
+
):
|
| 162 |
+
recovery_query_sent = True
|
| 163 |
+
recovery_query_turn = recovery_query_turn or turn
|
| 164 |
+
if not isinstance(key, str) or not KEY_PATTERN.fullmatch(key): continue
|
| 165 |
+
key_query_rounds.setdefault(key, turn)
|
| 166 |
+
key_query_counts[key] = key_query_counts.get(key, 0) + 1
|
| 167 |
+
if recovery_query_sent and not target_key_returned and mismatch_round is not None and turn > mismatch_round:
|
| 168 |
+
for answer in event.get("role_answers", []):
|
| 169 |
+
question = answer.get("question", {})
|
| 170 |
+
if (
|
| 171 |
+
answer.get("role_agent") == ERROR_INJECTION.get("role_name")
|
| 172 |
+
and (question.get("key") is None or question.get("key") == ERROR_INJECTION.get("target_key"))
|
| 173 |
+
and "role_trace" in answer
|
| 174 |
+
and recovery_key_match(str(answer.get("answer", ""))) is not None
|
| 175 |
+
):
|
| 176 |
+
target_key_returned = True
|
| 177 |
+
recovery_reference = recovery_key_match(str(answer.get("answer", "")))
|
| 178 |
+
recovery_turn = turn
|
| 179 |
+
recovery_method = "keyless_query" if question.get("key") is None else "target_key_query"
|
| 180 |
+
break
|
| 181 |
+
queried = set(key_query_counts)
|
| 182 |
+
required = set(REQUIRED_KEYS)
|
| 183 |
+
relevant = queried & required
|
| 184 |
+
return {
|
| 185 |
+
"required_key_recall":len(relevant)/len(required) if required else 1.0,
|
| 186 |
+
"required_key_precision":len(relevant)/len(queried) if queried else 0.0,
|
| 187 |
+
"key_query_rounds":key_query_rounds,
|
| 188 |
+
"key_query_counts":key_query_counts,
|
| 189 |
+
"duplicate_key_queries":sum(max(0, count-1) for count in key_query_counts.values()),
|
| 190 |
+
"distractor_key_queries":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS),
|
| 191 |
+
"distractor_key_query_rate":sum(key_query_counts.get(key, 0) for key in DISTRACTOR_KEYS)/sum(key_query_counts.values()) if key_query_counts else 0.0,
|
| 192 |
+
"turns_to_finalize":len(transcript),
|
| 193 |
+
"mismatch_key_queried":mismatch_round is not None,
|
| 194 |
+
"mismatch_key_turn":mismatch_round,
|
| 195 |
+
"recovery_query_sent":recovery_query_sent,
|
| 196 |
+
"recovery_query_turn":recovery_query_turn,
|
| 197 |
+
"target_key_returned":target_key_returned,
|
| 198 |
+
"recovery_turn":recovery_turn,
|
| 199 |
+
"recovery_method":recovery_method,
|
| 200 |
+
"target_key_query_turn":target_key_query_turn,
|
| 201 |
+
"recovery_key_match":recovery_reference,
|
| 202 |
+
"recovery_metrics_version":"keyed_and_keyless_v3",
|
| 203 |
+
"recovery_latency":recovery_turn - mismatch_round if recovery_turn is not None and mismatch_round is not None else None,
|
| 204 |
+
"finalized_before_recovery":finalized_before_recovery,
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
def main_system_prompt() -> str:
|
| 208 |
+
role_text = "\n".join(f"- {item['role_name']}: {item['responsibility']}" for item in PUBLIC_ROLES)
|
| 209 |
+
ask_example = json.dumps({"action":"ask_role_agents","messages":[{"role_agent":"Role name","questions":[{"id":"Q1","question":"Please provide the record for ABC-DATA-A1B using the supplied key."}]}]}, ensure_ascii=False)
|
| 210 |
+
final_example = json.dumps({"action":"finalize","conclusion":"Exactly: " + POSITIVE_CONCLUSION + " or " + NEGATIVE_CONCLUSION,"numeric_result":None}, ensure_ascii=False).replace('"numeric_result": null', '"numeric_result": null/number')
|
| 211 |
+
communication_protocol = ('You may output {"action":"wait"} to advance one logical turn. An empty observation {"observations":[]} means no new visible messages; it does not imply receipt, processing or any future reply.' if SETTING in {'missed', 'mixed'} else '')
|
| 212 |
+
followup = ('For keyless follow-ups, name the candidate in full and the metric explicitly, or request that candidate\'s complete records. A unique previously queried record can be checked directly; otherwise supply a full key and metric when asked to clarify. Explicit directory requests return the complete directory.' if SETTING == 'incomplete' else
|
| 213 |
+
'Authorized keyless follow-ups may name the candidate and metric or request complete records. A role may retrieve facts, request clarification or return a directory. If given a directory, select a valid key to obtain facts.' if SETTING == 'mixed' else
|
| 214 |
+
'Authorized keyless questions return that role\'s complete directory. Choose a key from the directory to obtain concrete facts.')
|
| 215 |
+
return "\n\n".join([
|
| 216 |
+
'You are the Main Agent. Integrate information from independent role agents and make the final decision. Communicate in English.',
|
| 217 |
+
'You cannot see private role information directly. Obtain it only by explicitly messaging the role agents.',
|
| 218 |
+
'Key protocol:\n1. Candidate names and record keys are supplied in the task. Initial access requires a valid key; authorized later follow-ups are the exception.\n'
|
| 219 |
+
'2. Keys use ROLE-BUSINESS-XXX: role abbreviation, business abbreviation and three random alphanumeric characters. Use complete supplied keys; do not invent them.\n'
|
| 220 |
+
'3. Send each key to its owning business role. Use valid keys supplied by roles for subsequent checks.\n'
|
| 221 |
+
'4. Do not output a separate key field. Put the complete key in question text; the system extracts it and checks ownership. Separate different keys into individual questions, preferably one record per question.\n'
|
| 222 |
+
'5. After a successful keyed query to a role, keyless natural-language follow-ups to that role are authorized starting from the next turn.\n6. ' + followup,
|
| 223 |
+
'Available independent role agents:\n\n' + role_text,
|
| 224 |
+
'To ask questions, output only JSON in this form:\n\n' + ask_example,
|
| 225 |
+
*([communication_protocol] if communication_protocol else []),
|
| 226 |
+
'Final answer format (output only valid JSON):\n\n' + final_example,
|
| 227 |
+
'Use exactly one of these conclusion labels: ' + POSITIVE_CONCLUSION + ' or ' + NEGATIVE_CONCLUSION + '. '
|
| 228 |
+
'Do not append a candidate name, explanation or other text. null/number means choose one, not literal syntax. '
|
| 229 |
+
'For a positive conclusion provide the computed number; for a negative conclusion use null. Do not include units or explanations in numeric_result.',
|
| 230 |
+
])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
"""Conservative English evidence rules shared by standalone generated runtimes.
|
| 234 |
+
|
| 235 |
+
This is attribution of explicit statements, not arbitrary semantic entailment.
|
| 236 |
+
Unsupported or conflicting statements remain unknown; no model calls are made.
|
| 237 |
+
"""
|
| 238 |
+
import re
|
| 239 |
+
from decimal import Decimal
|
| 240 |
+
|
| 241 |
+
_RECOVERY_NUMBER = r'[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?'
|
| 242 |
+
_RECOVERY_UNCERTAIN = r"\b(?:unknown|uncertain|unclear|may|might|could|should|would|must|expected|possibly|whether|cannot|unable|unconfirmed|approximately|about|around|roughly|estimated|not confirmed|not known|not established)\b"
|
| 243 |
+
_RECOVERY_NEGATIVE = r'\b(?:not|no|never|false|invalid|blocked|failed|denied|unavailable|unapproved|revoked|inactive|disabled|noncompliant)\b'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def evidence_text(text):
|
| 247 |
+
text = text.replace('’', "'").replace('−', '-').replace('‑', '-')
|
| 248 |
+
text = re.sub(r"\bcan't\b", 'cannot', text, flags=re.I)
|
| 249 |
+
text = re.sub(r"n't\b", ' not', text, flags=re.I)
|
| 250 |
+
text = re.sub(r'(?<![\w.,])[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?(?![\d,]|\.\d)',
|
| 251 |
+
lambda m: m[0].replace(',', ''), text)
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def evidence_phrase(text, phrase):
|
| 256 |
+
if not phrase:
|
| 257 |
+
return False
|
| 258 |
+
return bool(re.search(r'(?<!\w)' + re.escape(phrase).replace(r'\ ', r'\s+') + r'(?!\w)', text, re.I))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def evidence_nonasserted(text):
|
| 262 |
+
"""Questions, hypotheses and unconfirmed claims are not returned facts."""
|
| 263 |
+
return bool('?' in text or re.search(_RECOVERY_UNCERTAIN, text, re.I)
|
| 264 |
+
or re.search(r'\b(?:if|unless|assuming|suppose|supposing|hypothetically)\b', text, re.I)
|
| 265 |
+
or re.search(r'\b(?:do|does|did|has|have|had)\s+not\s+(?:confirm|verify|establish)(?:ed)?\b', text, re.I))
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def evidence_clauses(text):
|
| 269 |
+
# Preserve questions and uncertainty when splitting assertions.
|
| 270 |
+
sentences = re.split(r'[。\n]|\.(?!\d)|(?<=[!?])\s+', text)
|
| 271 |
+
clauses = []
|
| 272 |
+
for sentence in sentences:
|
| 273 |
+
if evidence_nonasserted(sentence):
|
| 274 |
+
clauses.append(sentence)
|
| 275 |
+
else:
|
| 276 |
+
clauses.extend(re.split(r'[;;]|,?\s+\b(?:but|and)\b\s+(?![+-]?\d)', sentence, flags=re.I))
|
| 277 |
+
return clauses
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def evidence_scope(answer, question, profile):
|
| 281 |
+
for target in [profile.get('candidate', ''), profile.get('target_context', '')]:
|
| 282 |
+
if target and re.search(r'\b(?:not|outside|excluding|except)(?:\s+(?:for|the))?\s+' + re.escape(target) + r'(?!\w)', answer, re.I):
|
| 283 |
+
return 'not_returned'
|
| 284 |
+
candidates = profile.get('other_candidates', [])
|
| 285 |
+
contexts = profile.get('other_contexts', [profile.get('alternate_context', '')])
|
| 286 |
+
if any(evidence_phrase(answer, c) for c in [*candidates, *contexts] if c):
|
| 287 |
+
target_also_present = evidence_phrase(answer, profile.get('candidate', '')) and (
|
| 288 |
+
not profile.get('target_context') or evidence_phrase(answer, profile['target_context']))
|
| 289 |
+
return 'unknown' if target_also_present else 'not_returned'
|
| 290 |
+
combined = question.get('question', '') + '\n' + answer
|
| 291 |
+
target_key = profile.get('target_key', '')
|
| 292 |
+
if target_key and (question.get('key') == target_key or evidence_phrase(combined, target_key)):
|
| 293 |
+
return 'eligible'
|
| 294 |
+
if evidence_phrase(combined, profile.get('candidate', '')) and (
|
| 295 |
+
not profile.get('target_context') or evidence_phrase(combined, profile['target_context'])):
|
| 296 |
+
return 'eligible'
|
| 297 |
+
return 'unknown'
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def evidence_unit_pattern(unit):
|
| 301 |
+
# Unit names may inflect; canonical symbols remain case-sensitive.
|
| 302 |
+
groups = [('h', 'hour', 'hours'), ('min', 'minute', 'minutes'), ('s', 'second', 'seconds'),
|
| 303 |
+
('kg', 'kilogram', 'kilograms'), ('m', 'meter', 'meters', 'metre', 'metres'),
|
| 304 |
+
('%', 'percent', 'per cent'), ('instances', 'instance'), ('items', 'item'),
|
| 305 |
+
('people', 'person', 'persons'), ('days', 'day')]
|
| 306 |
+
for group in groups:
|
| 307 |
+
if unit in group:
|
| 308 |
+
canonical, *words = group
|
| 309 |
+
if canonical in {'instances', 'items', 'people', 'days'}:
|
| 310 |
+
words.append(canonical)
|
| 311 |
+
canonical = None
|
| 312 |
+
parts = ([re.escape(canonical)] if canonical else []) + ['(?i:' + re.escape(w) + ')' for w in words]
|
| 313 |
+
if unit == '%': parts.append('%')
|
| 314 |
+
return '(?:' + '|'.join(sorted(parts, key=len, reverse=True)) + ')'
|
| 315 |
+
return re.escape(unit)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def evidence_measurements(text, unit):
|
| 319 |
+
text = evidence_text(text)
|
| 320 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 321 |
+
suffix = (r'(?:\s+(?:1|(?i:dimensionless)))?' if unit == '1'
|
| 322 |
+
else r'\s*' + evidence_unit_pattern(unit))
|
| 323 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')' + suffix + r'(?![A-Za-z0-9_/%]|\.\d|,\d)'
|
| 324 |
+
return text, list(re.finditer(pattern, text))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def evidence_exact_measurement(text, match):
|
| 328 |
+
before, after = text[max(0, match.start()-60):match.start()], text[match.end():match.end()+45]
|
| 329 |
+
if evidence_nonasserted(text):
|
| 330 |
+
return False
|
| 331 |
+
if re.search(r'(?:\b(?:under|over|below|above|less than|more than|at most|at least|up to|between|to|and|not|no more than|no less than)|不超过|不低于|小于等于|大于等于|小于|大于|至少|至多|最多|最少|低于|高于|介于|至|到|[<>≤≥~~–—])\s*$', before, re.I):
|
| 332 |
+
return False
|
| 333 |
+
if re.search(r'\d\s*[-–—]\s*$', before):
|
| 334 |
+
return False
|
| 335 |
+
if re.match(r'\s*(?:\b(?:maximum|minimum|max|min)\b|\bor (?:less|more|lower|higher)\b|\b(?:to|through)\s+[+-]?\d|[-–—~~]\s*\d)', after, re.I):
|
| 336 |
+
return False
|
| 337 |
+
return True
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def english_exact_value(answer, value, unit):
|
| 341 |
+
for clause in evidence_clauses(evidence_text(answer)):
|
| 342 |
+
text, matches = evidence_measurements(clause, unit)
|
| 343 |
+
if any(Decimal(m[1]) == Decimal(str(value)) and evidence_exact_measurement(text, m) for m in matches):
|
| 344 |
+
return True
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def numeric_evidence(answer, question, profile, fact):
|
| 349 |
+
answer = evidence_text(answer)
|
| 350 |
+
scope = evidence_scope(answer, question, profile)
|
| 351 |
+
if scope != 'eligible':
|
| 352 |
+
return scope
|
| 353 |
+
labels = [fact.get('label', ''), *fact.get('aliases', [])]
|
| 354 |
+
states = set()
|
| 355 |
+
for clause in evidence_clauses(answer):
|
| 356 |
+
# Bind each value to its asserted metric; nearby numbers are not evidence.
|
| 357 |
+
if not any(evidence_phrase(clause, label) for label in labels if label):
|
| 358 |
+
continue
|
| 359 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 360 |
+
continue
|
| 361 |
+
# Leave ambiguous multi-metric clauses unscored.
|
| 362 |
+
others = profile.get('facts', profile.get('numeric', []) + profile.get('boolean', []))
|
| 363 |
+
if any(other.get('topic') != fact.get('topic') and any(evidence_phrase(clause, label) for label in
|
| 364 |
+
[other.get('label', ''), *other.get('aliases', [])] if label) for other in others):
|
| 365 |
+
continue
|
| 366 |
+
text, matches = evidence_measurements(clause, fact.get('unit', ''))
|
| 367 |
+
for m in matches:
|
| 368 |
+
if evidence_exact_measurement(text, m) and not re.search(_RECOVERY_NEGATIVE, text[:m.start()], re.I):
|
| 369 |
+
states.add(Decimal(m[1]) == Decimal(str(fact['value'])))
|
| 370 |
+
if len(states) != 1:
|
| 371 |
+
return 'unknown'
|
| 372 |
+
return 'returned' if states.pop() else 'not_returned'
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _evidence_predicate(text):
|
| 376 |
+
text = re.sub(r'\b(?:is|are|was|were|has|have|had|been|the|a|an|already)\b', ' ', text.casefold())
|
| 377 |
+
return re.sub(r'\s+', ' ', text).strip(' .:')
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def boolean_evidence(answer, question, profile):
|
| 381 |
+
answer = evidence_text(answer)
|
| 382 |
+
scope = evidence_scope(answer, question, profile)
|
| 383 |
+
if scope != 'eligible':
|
| 384 |
+
return scope
|
| 385 |
+
labels = [profile['label'], *profile.get('aliases', [])]
|
| 386 |
+
states = set()
|
| 387 |
+
for clause in evidence_clauses(answer):
|
| 388 |
+
plain = _evidence_predicate(clause)
|
| 389 |
+
no_negative = _evidence_predicate(re.sub(_RECOVERY_NEGATIVE, ' ', clause, flags=re.I))
|
| 390 |
+
if not any(evidence_phrase(plain, _evidence_predicate(label)) or evidence_phrase(no_negative, _evidence_predicate(label)) for label in labels if label):
|
| 391 |
+
continue
|
| 392 |
+
if evidence_nonasserted(clause) or re.search(r'\b(?:catalog|directory)\b', clause, re.I):
|
| 393 |
+
continue
|
| 394 |
+
remainder = clause
|
| 395 |
+
for label in sorted(labels, key=len, reverse=True):
|
| 396 |
+
remainder = re.sub(re.escape(label), '', remainder, flags=re.I)
|
| 397 |
+
negative = bool(re.search(_RECOVERY_NEGATIVE, remainder, re.I))
|
| 398 |
+
explicit = bool(re.search(r'\b(?:true|yes|false|no)\b', remainder, re.I))
|
| 399 |
+
predicate = r'\b(?:enabled|issued|approved|valid|clear|ready|open|active|completed|available|installed|registered|signed|granted|confirmed|operational|compliant|meets|passed|released|equipped|connected|running|accepted)\b'
|
| 400 |
+
affirmative = evidence_phrase(no_negative, _evidence_predicate(profile['label'])) and bool(re.search(predicate, profile['label'], re.I))
|
| 401 |
+
label_match = evidence_phrase(no_negative, _evidence_predicate(profile['label']))
|
| 402 |
+
# Do not transfer negation between unrelated metrics.
|
| 403 |
+
opposites = {'disabled':'enabled', 'unavailable':'available', 'invalid':'valid',
|
| 404 |
+
'closed':'open', 'inactive':'active', 'blocked':'clear', 'revoked':'granted'}
|
| 405 |
+
opposite = False
|
| 406 |
+
for denied, affirmed in opposites.items():
|
| 407 |
+
if re.search(r'\b' + denied + r'\b', clause, re.I):
|
| 408 |
+
rewritten = re.sub(r'\b' + denied + r'\b', affirmed, clause, flags=re.I)
|
| 409 |
+
opposite |= evidence_phrase(_evidence_predicate(rewritten), _evidence_predicate(profile['label']))
|
| 410 |
+
bare_boolean = bool(explicit and re.fullmatch(r'(?:status\s*[:=]?\s*)?(?:true|yes|false|no)',
|
| 411 |
+
_evidence_predicate(remainder), re.I))
|
| 412 |
+
if affirmative or label_match and (negative or explicit) or opposite or bare_boolean:
|
| 413 |
+
states.add(not (negative or opposite))
|
| 414 |
+
if len(states) != 1:
|
| 415 |
+
return 'unknown'
|
| 416 |
+
return 'returned' if states.pop() == profile['value'] else 'not_returned'
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def recovery_number_present(answer, value):
|
| 420 |
+
"""Literal numeric occurrence, independent of unit, metric, scope or wording."""
|
| 421 |
+
text = re.sub(r'(?<![A-Z0-9])[A-Z]{2,10}-[A-Z]{2,10}-[A-Z0-9]{3}(?![A-Z0-9])', '', answer, flags=re.I)
|
| 422 |
+
text = evidence_text(text)
|
| 423 |
+
text = re.sub(r'(?<=\d)[-–—](?=\d)', ' to ', text)
|
| 424 |
+
pattern = r'(?<![A-Za-z0-9_.,+\-])(' + _RECOVERY_NUMBER + r')(?![0-9_]|\.\d|,\d)'
|
| 425 |
+
return any(Decimal(m[1]) == Decimal(str(value)) for m in re.finditer(pattern, text))
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
import os
|
| 431 |
+
import random
|
| 432 |
+
from datetime import datetime
|
| 433 |
+
from pathlib import Path
|
| 434 |
+
from typing import Dict, List
|
| 435 |
+
|
| 436 |
+
from openai import OpenAI
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load_project_env() -> None:
|
| 440 |
+
for parent in Path(__file__).resolve().parents:
|
| 441 |
+
env_path = parent / ".env"
|
| 442 |
+
if not env_path.is_file():
|
| 443 |
+
continue
|
| 444 |
+
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
|
| 445 |
+
line = raw_line.strip()
|
| 446 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 447 |
+
continue
|
| 448 |
+
key, value = line.split("=", 1)
|
| 449 |
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
load_project_env()
|
| 454 |
+
MAIN_AGENT_API_KEY = os.getenv("MAIN_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 455 |
+
MAIN_AGENT_MODEL_NAME = os.getenv("MAIN_AGENT_MODEL_NAME", "openai/gpt-5.5")
|
| 456 |
+
MAIN_AGENT_BASE_URL = os.getenv("MAIN_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 457 |
+
ROLE_AGENT_API_KEY = os.getenv("ROLE_AGENT_API_KEY", os.getenv("OPENROUTER_API_KEY", ""))
|
| 458 |
+
ROLE_AGENT_MODEL_NAME = "deepseek/deepseek-v4-flash-0731"
|
| 459 |
+
ROLE_AGENT_BASE_URL = os.getenv("ROLE_AGENT_BASE_URL", "https://openrouter.ai/api/v1")
|
| 460 |
+
LLM_REASONING_EFFORT = os.getenv("LLM_REASONING_EFFORT", "medium")
|
| 461 |
+
ROLE_REASONING_EFFORT = "low"
|
| 462 |
+
ROLE_MAX_TOKENS = 8192
|
| 463 |
+
LLM_REASONING_EXCLUDE = os.getenv("LLM_REASONING_EXCLUDE", "1") != "0"
|
| 464 |
+
MAIN_AGENT_ROLE_ORDER_SEED = os.getenv("MAIN_AGENT_ROLE_ORDER_SEED")
|
| 465 |
+
AGENT_DIR = str(Path(__file__).resolve().parent.parent / "role_agents")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def print_key_trace(title: str, content: Any = "") -> None:
|
| 469 |
+
print(f"\n========== {title} ==========\n", flush=True)
|
| 470 |
+
if content != "":
|
| 471 |
+
print(str(content), flush=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def format_metric_value(value: Any) -> str:
|
| 475 |
+
if isinstance(value, float):
|
| 476 |
+
return f"{value:.4f}"
|
| 477 |
+
if value is None:
|
| 478 |
+
return "None"
|
| 479 |
+
return str(value)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def format_llm_config() -> str:
|
| 483 |
+
return "\n".join([
|
| 484 |
+
f"main_agent_llm: {MAIN_AGENT_MODEL_NAME}",
|
| 485 |
+
f"role_agent_llm: {ROLE_AGENT_MODEL_NAME}",
|
| 486 |
+
f"reasoning_effort: {LLM_REASONING_EFFORT}",
|
| 487 |
+
f"role_reasoning_effort: {ROLE_REASONING_EFFORT}",
|
| 488 |
+
])
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def format_available_roles(role_agents: Dict[str, Any]) -> str:
|
| 492 |
+
lines = []
|
| 493 |
+
for role_name, role in role_agents.items():
|
| 494 |
+
key_prefix = ROLE_KEY_PREFIXES.get(role_name, "")
|
| 495 |
+
lines.append(f"- {role_name}(Key 格式:{key_prefix}业务缩写-XXX):{role.config['abstract']}")
|
| 496 |
+
return "\n".join(lines)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def format_evaluation_summary(evaluation: Dict[str, Any]) -> str:
|
| 500 |
+
conclusion = evaluation.get("conclusion_evaluation", {})
|
| 501 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 502 |
+
fields = [
|
| 503 |
+
("ground_truth_conclusion", conclusion.get("ground_truth_conclusion")),
|
| 504 |
+
("ground_truth_numeric_result", conclusion.get("ground_truth_numeric_result")),
|
| 505 |
+
("final_conclusion", conclusion.get("final_conclusion")),
|
| 506 |
+
("parsed_numeric_result", conclusion.get("parsed_numeric_result")),
|
| 507 |
+
("conclusion_correct", conclusion.get("conclusion_correct")),
|
| 508 |
+
("numeric_result_correct", conclusion.get("numeric_result_correct")),
|
| 509 |
+
("turns_to_finalize", communication.get("turns_to_finalize")),
|
| 510 |
+
("total_role_agent_queries", communication.get("total_role_agent_queries")),
|
| 511 |
+
("total_questions", communication.get("total_questions")),
|
| 512 |
+
("duplicate_key_queries", communication.get("duplicate_key_queries")),
|
| 513 |
+
]
|
| 514 |
+
return "\n".join(f"{name}: {format_metric_value(value)}" for name, value in fields)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def format_key_metrics(evaluation: Dict[str, Any]) -> str:
|
| 518 |
+
communication = evaluation.get("communication_evaluation", {})
|
| 519 |
+
correctness = int(bool(evaluation.get("joint_correctness")))
|
| 520 |
+
turns = communication.get("turns_to_finalize")
|
| 521 |
+
lines = [
|
| 522 |
+
f"正确率: {correctness}",
|
| 523 |
+
f"完成轮数: {format_metric_value(turns)} / {communication.get('max_turns', DEFAULT_MAX_TURNS)}(理想:{communication.get('finalize_ideal_round', FINALIZE_IDEAL_ROUND)})",
|
| 524 |
+
]
|
| 525 |
+
if SETTING in {"incomplete", "mixed"}:
|
| 526 |
+
lines.append(f"阈值补齐: {communication.get('incomplete_threshold_returned', False)};补齐轮次: {communication.get('incomplete_recovery_turn')};补救成功: {communication.get('incomplete_recovery_success')}")
|
| 527 |
+
if SETTING in {"missed", "mixed"}:
|
| 528 |
+
lines.append(f"忽略: {communication.get('neglect_ignored_count', 0)};交付: {communication.get('neglect_delivered_count', 0)};待答: {communication.get('neglect_pending_count', 0)}")
|
| 529 |
+
if SETTING not in {"misaligned", "mixed"}:
|
| 530 |
+
return "\n".join(lines)
|
| 531 |
+
|
| 532 |
+
if communication.get("error_recovery_status") == "unknown":
|
| 533 |
+
lines.append("Recovery result: UNKNOWN (evidence cannot be classified; excluded from recovery rates)")
|
| 534 |
+
return "\n".join(lines)
|
| 535 |
+
|
| 536 |
+
mismatch_queried = bool(communication.get("mismatch_key_queried"))
|
| 537 |
+
mismatch_turn = communication.get("mismatch_key_turn")
|
| 538 |
+
recovery_query_sent = bool(communication.get("recovery_query_sent"))
|
| 539 |
+
recovery_query_turn = communication.get("recovery_query_turn")
|
| 540 |
+
target_key_returned = bool(communication.get("error_fact_returned", communication.get("target_key_returned")))
|
| 541 |
+
recovery_turn = communication.get("recovery_turn")
|
| 542 |
+
finalized_early = bool(communication.get("finalized_before_recovery"))
|
| 543 |
+
|
| 544 |
+
def turn_suffix(turn: Any) -> str:
|
| 545 |
+
return f"(第{turn}轮)" if isinstance(turn, int) else ""
|
| 546 |
+
|
| 547 |
+
lines.extend(["", "恢复链路:"])
|
| 548 |
+
if not mismatch_queried:
|
| 549 |
+
lines.extend([
|
| 550 |
+
f"✗ 未访问错配 key:{ERROR_INJECTION.get('alternate_key')}",
|
| 551 |
+
"— 未触发补救询问",
|
| 552 |
+
"— Role 未返回目标 key",
|
| 553 |
+
"— 未进入恢复流程",
|
| 554 |
+
"",
|
| 555 |
+
"恢复延迟:N/A",
|
| 556 |
+
"恢复结果:NOT_TRIGGERED(Main 未访问错配 key)",
|
| 557 |
+
])
|
| 558 |
+
return "\n".join(lines)
|
| 559 |
+
|
| 560 |
+
lines.append(
|
| 561 |
+
f"✓ 已访问错配 key:{ERROR_INJECTION.get('alternate_key')}{turn_suffix(mismatch_turn)}"
|
| 562 |
+
)
|
| 563 |
+
lines.append(
|
| 564 |
+
("✓ 已发起补救询问" if recovery_query_sent else "✗ 未发起补救询问")
|
| 565 |
+
+ turn_suffix(recovery_query_turn)
|
| 566 |
+
)
|
| 567 |
+
lines.append(
|
| 568 |
+
(
|
| 569 |
+
f"✓ Role 已返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 570 |
+
if target_key_returned
|
| 571 |
+
else f"✗ Role 未返回目标事实(对应 key):{ERROR_INJECTION.get('target_key')}"
|
| 572 |
+
)
|
| 573 |
+
+ turn_suffix(recovery_turn)
|
| 574 |
+
)
|
| 575 |
+
lines.append("✗ 已在恢复前提前 finalize" if finalized_early else "✓ 未在恢复前提前 finalize")
|
| 576 |
+
if target_key_returned:
|
| 577 |
+
lines.append("✓ 恢复后最终答案正确" if correctness else "✗ 恢复后最终答案错误")
|
| 578 |
+
else:
|
| 579 |
+
lines.append("— 尚未完成恢复,无法判断恢复后答案")
|
| 580 |
+
|
| 581 |
+
recovery_latency = communication.get("recovery_latency")
|
| 582 |
+
recovery_method = communication.get("recovery_method")
|
| 583 |
+
if recovery_method:
|
| 584 |
+
target_query_turn = communication.get("target_key_query_turn")
|
| 585 |
+
if recovery_method == "keyless_query" and isinstance(target_query_turn, int) and isinstance(recovery_turn, int) and target_query_turn > recovery_turn:
|
| 586 |
+
method_label = "无 key 获取目录 → 正确 key 查询"
|
| 587 |
+
lines.append(f"取得目标 key:第{recovery_turn}轮")
|
| 588 |
+
lines.append(f"正确 key 查询取得答复:第{target_query_turn}轮")
|
| 589 |
+
recovery_latency = target_query_turn - mismatch_turn if isinstance(mismatch_turn, int) else recovery_latency
|
| 590 |
+
else:
|
| 591 |
+
method_label = {"keyless_query": "无 key 补充询问", "target_key_query": "目标 key 纠正查询"}.get(recovery_method, recovery_method)
|
| 592 |
+
lines.append(f"补救方式:{method_label}")
|
| 593 |
+
if communication.get("recovery_success"):
|
| 594 |
+
status = "SUCCESS"
|
| 595 |
+
elif finalized_early:
|
| 596 |
+
status = "FINALIZED_EARLY"
|
| 597 |
+
elif not recovery_query_sent:
|
| 598 |
+
status = "RECOVERY_NOT_REQUESTED"
|
| 599 |
+
elif not target_key_returned:
|
| 600 |
+
status = "TARGET_NOT_RETURNED"
|
| 601 |
+
else:
|
| 602 |
+
status = "RECOVERED_BUT_WRONG"
|
| 603 |
+
lines.extend([
|
| 604 |
+
"",
|
| 605 |
+
f"恢复延迟:{recovery_latency}轮" if isinstance(recovery_latency, int) else "恢复延迟:N/A",
|
| 606 |
+
f"恢复结果:{status}",
|
| 607 |
+
])
|
| 608 |
+
return "\n".join(lines)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def format_role_messages(action: Dict[str, Any], role_answers: List[Dict[str, Any]]) -> str:
|
| 612 |
+
requested = {
|
| 613 |
+
(message.get("role_agent"), question.get("id"), question.get("key")): question.get("question")
|
| 614 |
+
for message in action.get("messages", [])
|
| 615 |
+
for question in message.get("questions", [])
|
| 616 |
+
}
|
| 617 |
+
blocks = []
|
| 618 |
+
for item in role_answers:
|
| 619 |
+
question = item.get("question", {})
|
| 620 |
+
identity = (item.get("role_agent"), question.get("id"), question.get("key"))
|
| 621 |
+
blocks.append("\n".join([
|
| 622 |
+
f"role_agent: {item.get('role_agent')}",
|
| 623 |
+
f"question_id: {question.get('id')}",
|
| 624 |
+
f"key: {question.get('key')}",
|
| 625 |
+
f"question: {requested.get(identity, question.get('question'))}",
|
| 626 |
+
f"answer: {item.get('answer')}",
|
| 627 |
+
]))
|
| 628 |
+
return "\n\n".join(blocks)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def parse_numeric_result(value: Any) -> int | float | None:
|
| 632 |
+
if value is None or isinstance(value, bool):
|
| 633 |
+
return None
|
| 634 |
+
if isinstance(value, (int, float)):
|
| 635 |
+
number = float(value)
|
| 636 |
+
elif isinstance(value, str):
|
| 637 |
+
match = re.search(r"[-+]?\d+(?:\.\d+)?", value.strip())
|
| 638 |
+
if not match:
|
| 639 |
+
return None
|
| 640 |
+
number = float(match.group(0))
|
| 641 |
+
else:
|
| 642 |
+
return None
|
| 643 |
+
rounded = round(number, NUMERIC_PRECISION)
|
| 644 |
+
return int(rounded) if NUMERIC_PRECISION == 0 else rounded
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def compute_conclusion_correctness(final_result: Dict[str, Any]) -> Dict[str, Any]:
|
| 648 |
+
parsed = parse_numeric_result(final_result.get("numeric_result"))
|
| 649 |
+
expected = parse_numeric_result(GOLD["numeric_result"])
|
| 650 |
+
conclusion_correct = int(final_result.get("conclusion") == GOLD["conclusion"])
|
| 651 |
+
numeric_correct = int(parsed == expected)
|
| 652 |
+
return {
|
| 653 |
+
"ground_truth_conclusion": GOLD["conclusion"],
|
| 654 |
+
"ground_truth_numeric_result": GOLD["numeric_result"],
|
| 655 |
+
"final_conclusion": final_result.get("conclusion"),
|
| 656 |
+
"numeric_result_raw": final_result.get("numeric_result"),
|
| 657 |
+
"parsed_numeric_result": parsed,
|
| 658 |
+
"conclusion_correct": conclusion_correct,
|
| 659 |
+
"numeric_result_correct": numeric_correct,
|
| 660 |
+
"conclusion_correctness": int(conclusion_correct and numeric_correct),
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def format_role_user_message(question: Dict[str, Any]) -> str:
|
| 665 |
+
question_id = str(question.get("id") or "Q")
|
| 666 |
+
text = str(question["question"]).strip()
|
| 667 |
+
return f"{question_id}: {text}"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
"""Deterministic follow-up routing; metadata contains no hidden values or target flags."""
|
| 671 |
+
import re
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def build_followup_records(task):
|
| 675 |
+
roles = {r['role_id']: r['name'] for r in task['roles']}
|
| 676 |
+
candidates = {c['candidate_id']: c['name'] for c in task['candidates']}
|
| 677 |
+
topics = {t['topic_id']: t for group in ('topics', 'distractor_topics', 'supplemental_topics')
|
| 678 |
+
for t in task.get(group, [])}
|
| 679 |
+
observations = {o['observation_id']: o for o in task['observations']}
|
| 680 |
+
records = []
|
| 681 |
+
for record in task['records']:
|
| 682 |
+
fields = []
|
| 683 |
+
for oid in record['observation_ids']:
|
| 684 |
+
tid = observations[oid]['topic_id']
|
| 685 |
+
topic = topics.get(tid, {})
|
| 686 |
+
if topic.get('label'):
|
| 687 |
+
fields.append({'id': tid, 'label': topic['label'], 'aliases': topic.get('aliases', [])})
|
| 688 |
+
records.append(dict(key=task['routing']['record_keys'][record['record_id']],
|
| 689 |
+
role=roles[record['owner_role_id']], candidate=candidates[record['candidate_id']],
|
| 690 |
+
context=(record.get('context') or {}).get('value', ''), fields=fields))
|
| 691 |
+
return records
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class IncompleteFollowupResolver:
|
| 695 |
+
VERSION = 'rule_followup_v2_english'
|
| 696 |
+
CLARIFY = 'The record and metric cannot be uniquely identified. Put the complete record key and the metric to verify in your question.'
|
| 697 |
+
|
| 698 |
+
def __init__(self, records):
|
| 699 |
+
self.records = records
|
| 700 |
+
self.reset()
|
| 701 |
+
|
| 702 |
+
def reset(self):
|
| 703 |
+
self.seen = {}
|
| 704 |
+
self.events = []
|
| 705 |
+
|
| 706 |
+
def observe(self, role, key, turn):
|
| 707 |
+
if key is not None:
|
| 708 |
+
self.seen.setdefault((role, key), turn)
|
| 709 |
+
|
| 710 |
+
@staticmethod
|
| 711 |
+
def normalize(text):
|
| 712 |
+
return re.sub(r'\s+', ' ', text).strip().casefold().replace('’', "'").replace('‑', '-').replace('–', '-')
|
| 713 |
+
|
| 714 |
+
@classmethod
|
| 715 |
+
def mentions(cls, text, phrase):
|
| 716 |
+
phrase = cls.normalize(phrase)
|
| 717 |
+
if re.search(r'[\u3400-\u9fff]', phrase):
|
| 718 |
+
return phrase.replace(' ', '') in text.replace(' ', '')
|
| 719 |
+
return bool(re.search(r'(?<![\w])' + re.escape(phrase) + r'(?![\w])', text))
|
| 720 |
+
|
| 721 |
+
def resolve(self, role, text, turn):
|
| 722 |
+
text = self.normalize(text)
|
| 723 |
+
available = [r for r in self.records if r['role'] == role]
|
| 724 |
+
if re.search(r'目录|索引列表|key列表|\b(?:catalog(?:ue)?s?|director(?:y|ies)|(?:key|index)\s+lists?)\b', text):
|
| 725 |
+
result = dict(status='catalog', key=None, fields=[])
|
| 726 |
+
else:
|
| 727 |
+
# Match the full role catalog before restricting to previously queried records.
|
| 728 |
+
names = {r['candidate'] for r in available if self.mentions(text, r['candidate'])}
|
| 729 |
+
contexts = {r['context'] for r in available if r['context'] and self.mentions(text, r['context'])}
|
| 730 |
+
fields = {f['id'] for r in available for f in r['fields']
|
| 731 |
+
if any(self.mentions(text, a) for a in [f['label'], *f['aliases']] if a)}
|
| 732 |
+
full = bool(re.search(r'完整(?:资料|信息|内容|记录)|全部(?:资料|信息|内容)|详细资料|\b(?:complete|full|all|detailed)\s+(?:(?:the|your|available)\s+)*(?:records?|information|details|data)\b', text))
|
| 733 |
+
matches = [r for r in available
|
| 734 |
+
if self.seen.get((role, r['key']), turn) < turn
|
| 735 |
+
and r['candidate'] in names
|
| 736 |
+
and (not contexts or r['context'] in contexts)
|
| 737 |
+
and (fields <= {f['id'] for f in r['fields']} if fields else full)]
|
| 738 |
+
# Ambiguous references require a key; do not infer pronouns or fuzzy matches.
|
| 739 |
+
unique = len(names) == 1 and len(contexts) <= 1 and len(matches) == 1 and (fields or full)
|
| 740 |
+
result = dict(status='resolved' if unique else 'clarify',
|
| 741 |
+
key=matches[0]['key'] if unique else None, fields=sorted(fields), full=full)
|
| 742 |
+
self.events.append(dict(turn=turn, role_agent=role, question=text, **result))
|
| 743 |
+
return result
|
| 744 |
+
|
| 745 |
+
def catalog(self, role):
|
| 746 |
+
return 'Complete record directory (supply a key to obtain facts):\n' + '\n'.join(
|
| 747 |
+
r['key'] + ':' + r['candidate'] + (';' + r['context'] if r['context'] else '')
|
| 748 |
+
+ '; Metrics: ' + '、'.join(f['label'] for f in r['fields'])
|
| 749 |
+
for r in self.records if r['role'] == role)
|
| 750 |
+
|
| 751 |
+
def metrics(self):
|
| 752 |
+
return dict(incomplete_followup_protocol=self.VERSION,
|
| 753 |
+
incomplete_keyless_followup_count=len(self.events),
|
| 754 |
+
incomplete_rule_resolved_count=sum(e['status'] == 'resolved' for e in self.events),
|
| 755 |
+
incomplete_clarification_count=sum(e['status'] == 'clarify' for e in self.events),
|
| 756 |
+
incomplete_followup_routing=list(self.events))
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
"""Self-contained Incomplete policy embedded only in generated Incomplete run_one.py files."""
|
| 760 |
+
import re
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class IncompletePolicy:
|
| 764 |
+
def __init__(self, profile):
|
| 765 |
+
self.profile = profile
|
| 766 |
+
self.reset()
|
| 767 |
+
|
| 768 |
+
def reset(self):
|
| 769 |
+
self.omitted_at_turn = None
|
| 770 |
+
self.followup_at_turn = None
|
| 771 |
+
self.recovered_at_turn = None
|
| 772 |
+
|
| 773 |
+
def mode(self, role_name, question, turn):
|
| 774 |
+
if role_name != self.profile['role_name'] or question.get('key') != self.profile['key']:
|
| 775 |
+
return None
|
| 776 |
+
if self.recovered_at_turn is not None:
|
| 777 |
+
return None
|
| 778 |
+
# Any valid later query of the same record can recover the omitted value.
|
| 779 |
+
if self.omitted_at_turn is not None and turn > self.omitted_at_turn:
|
| 780 |
+
if self.followup_at_turn is None:
|
| 781 |
+
self.followup_at_turn = turn
|
| 782 |
+
return 'incomplete_recovery'
|
| 783 |
+
return 'incomplete_partial'
|
| 784 |
+
|
| 785 |
+
def request_options(self, mode, full_system_message):
|
| 786 |
+
profile = self.profile
|
| 787 |
+
coarse = profile.get('disclosure_mode', 'omission') != 'omission'
|
| 788 |
+
if mode == 'incomplete_partial':
|
| 789 |
+
system = (
|
| 790 |
+
f"You are {profile['role_name']}. For this request use only the business record below. "
|
| 791 |
+
"Respond in English in one or two connected sentences, retaining the key, candidate, material scope and facts. "
|
| 792 |
+
"Do not add metrics, infer facts or assert that the overall plan qualifies. "
|
| 793 |
+
"Do not say information is incomplete, unavailable or requires follow-up, and do not recommend another question. "
|
| 794 |
+
)
|
| 795 |
+
if coarse:
|
| 796 |
+
system += (
|
| 797 |
+
"Include the supplied coarse metric statement, retaining its numbers, units and bound wording. "
|
| 798 |
+
"Bounds are not exact values. Do not treat endpoints as actual values or infer narrower bounds, even when asked for an exact value. "
|
| 799 |
+
)
|
| 800 |
+
system += "\n\n" + profile['partial_record_text']
|
| 801 |
+
if coarse:
|
| 802 |
+
system += "\n" + profile['coarse_statement']
|
| 803 |
+
system += '\n\nOutput only valid JSON: {"answer":"Answer text"}.'
|
| 804 |
+
else:
|
| 805 |
+
system = (full_system_message + "\n\nFor this request, give the complete specified record, explicitly stating "
|
| 806 |
+
+ profile['threshold_label'] + " as its original numeric value and unit. Use Arabic numerals, not just a compliance judgment.")
|
| 807 |
+
if coarse:
|
| 808 |
+
system += (" Introduce the exact finding naturally with 'After careful verification'. "
|
| 809 |
+
"The exact number must come from the true private record, not a previous bound or interval endpoint. "
|
| 810 |
+
"Do not merely repeat the earlier coarse range.")
|
| 811 |
+
return {'system_override': system, 'response_validator': None}
|
| 812 |
+
|
| 813 |
+
def validate_answer(self, mode, answer):
|
| 814 |
+
if mode == 'incomplete_partial':
|
| 815 |
+
return None
|
| 816 |
+
return (None if recovery_number_present(answer, self.profile['threshold_value'])
|
| 817 |
+
else 'incomplete_threshold_not_returned')
|
| 818 |
+
|
| 819 |
+
def observe(self, mode, turn, answer=None):
|
| 820 |
+
if mode == 'incomplete_partial' and self.omitted_at_turn is None:
|
| 821 |
+
self.omitted_at_turn = turn
|
| 822 |
+
elif mode == 'incomplete_recovery' and answer is not None:
|
| 823 |
+
if self.validate_answer(mode, answer) is None:
|
| 824 |
+
self.recovered_at_turn = turn
|
| 825 |
+
|
| 826 |
+
def observe_keyless(self, role_name, question, turn, answer=None):
|
| 827 |
+
"""Measure accepted search replies without changing their runtime protocol."""
|
| 828 |
+
if (role_name != self.profile['role_name'] or question.get('key') is not None
|
| 829 |
+
or self.omitted_at_turn is None or turn <= self.omitted_at_turn
|
| 830 |
+
or self.recovered_at_turn is not None):
|
| 831 |
+
return
|
| 832 |
+
# Recovery uses numeric occurrence only, without wording, scope or unit checks.
|
| 833 |
+
# Observe only accepted replies; identifiers are excluded by validate_answer.
|
| 834 |
+
if answer is not None and self.validate_answer("incomplete_recovery", answer) is None:
|
| 835 |
+
if self.followup_at_turn is None:
|
| 836 |
+
self.followup_at_turn = turn
|
| 837 |
+
self.recovered_at_turn = turn
|
| 838 |
+
|
| 839 |
+
def metrics(self, *, correct, finalized):
|
| 840 |
+
triggered = self.omitted_at_turn is not None
|
| 841 |
+
recovered = self.recovered_at_turn is not None
|
| 842 |
+
return {
|
| 843 |
+
'incomplete_omission_triggered': triggered,
|
| 844 |
+
'incomplete_omission_turn': self.omitted_at_turn,
|
| 845 |
+
'incomplete_followup_sent': self.followup_at_turn is not None,
|
| 846 |
+
'incomplete_followup_turn': self.followup_at_turn,
|
| 847 |
+
'incomplete_threshold_returned': recovered,
|
| 848 |
+
'incomplete_recovery_turn': self.recovered_at_turn,
|
| 849 |
+
'incomplete_recovery_latency': self.recovered_at_turn - self.omitted_at_turn if recovered else None,
|
| 850 |
+
'finalized_before_incomplete_recovery': bool(finalized and triggered and not recovered),
|
| 851 |
+
'incomplete_recovery_success': bool(recovered) if triggered else None,
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def exact_value_present(answer, profile):
|
| 856 |
+
"""Compatibility name: count the target numeric value, including within bounds."""
|
| 857 |
+
return recovery_number_present(answer, profile['threshold_value'])
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def incomplete_numeric_metrics(profile, transcript, communication, *, correct, finalized):
|
| 861 |
+
"""Measure later accepted replies only; never alter interaction policy state.
|
| 862 |
+
|
| 863 |
+
User-defined numeric-occurrence rule: no unit, polarity, metric or scope gate.
|
| 864 |
+
Only later accepted replies from the affected role are eligible.
|
| 865 |
+
"""
|
| 866 |
+
omitted = communication.get('incomplete_omission_turn')
|
| 867 |
+
followup = communication.get('incomplete_followup_turn')
|
| 868 |
+
recovered = None
|
| 869 |
+
for event in transcript:
|
| 870 |
+
turn = event['turn']
|
| 871 |
+
if omitted is None or turn <= omitted:
|
| 872 |
+
continue
|
| 873 |
+
for reply in event.get('role_answers', []) + event.get('delivered_role_answers', []):
|
| 874 |
+
if (reply.get('role_agent') != profile['role_name']
|
| 875 |
+
or 'role_trace' not in reply
|
| 876 |
+
or reply.get('protocol_error') or 'role_validation_trace' in reply):
|
| 877 |
+
continue
|
| 878 |
+
if exact_value_present(reply.get('answer', ''), profile):
|
| 879 |
+
recovered = turn if recovered is None else min(recovered, turn)
|
| 880 |
+
if recovered is not None:
|
| 881 |
+
followup = recovered if followup is None else min(followup, recovered)
|
| 882 |
+
status = 'returned' if recovered is not None else 'not_returned'
|
| 883 |
+
return {
|
| 884 |
+
'incomplete_recovery_status': status,
|
| 885 |
+
'incomplete_omission_triggered': omitted is not None,
|
| 886 |
+
'incomplete_omission_turn': omitted,
|
| 887 |
+
'incomplete_followup_sent': followup is not None,
|
| 888 |
+
'incomplete_followup_turn': followup,
|
| 889 |
+
'incomplete_threshold_returned': recovered is not None,
|
| 890 |
+
'incomplete_recovery_turn': recovered,
|
| 891 |
+
'incomplete_recovery_latency': recovered - omitted if recovered is not None else None,
|
| 892 |
+
'finalized_before_incomplete_recovery': bool(finalized and omitted is not None and recovered is None),
|
| 893 |
+
'incomplete_recovery_success': bool(recovered is not None) if omitted is not None else None,
|
| 894 |
+
'incomplete_statistics_version': 'numeric_occurrence_v4',
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
class RoleAgent:
|
| 899 |
+
def __init__(self, config: Dict[str, Any], client: OpenAI, model: str = ROLE_AGENT_MODEL_NAME):
|
| 900 |
+
self.config = config
|
| 901 |
+
self.client = client
|
| 902 |
+
self.model = model
|
| 903 |
+
self.system_message = self._build_system_message()
|
| 904 |
+
self.reset_history()
|
| 905 |
+
|
| 906 |
+
def reset_history(self) -> None:
|
| 907 |
+
self.messages = [{"role": "system", "content": self.system_message}]
|
| 908 |
+
|
| 909 |
+
def _build_system_message(self) -> str:
|
| 910 |
+
private_blocks = []
|
| 911 |
+
for index, point in enumerate(self.config["information_points"]):
|
| 912 |
+
content = "\n\n".join(
|
| 913 |
+
line for line in str(point["content"]).splitlines() if line.strip()
|
| 914 |
+
)
|
| 915 |
+
private_blocks.append(f"{index + 1}. {point['title']}:\n\n{content}")
|
| 916 |
+
private = "\n\n".join(private_blocks)
|
| 917 |
+
return (
|
| 918 |
+
f"{self.config['system_message']}\n\n"
|
| 919 |
+
f"Your private information:\n\n{private}\n\n"
|
| 920 |
+
"Output only a valid JSON object: {\"answer\":\"Answer text\"}。"
|
| 921 |
+
)
|
| 922 |
+
|
| 923 |
+
def answer_with_trace(
|
| 924 |
+
self, question: str, *, allowed_keys: set[str], response_mode: str,
|
| 925 |
+
system_override: str | None = None, response_validator: Any = None,
|
| 926 |
+
) -> Dict[str, Any]:
|
| 927 |
+
user_message = {"role": "user", "content": question}
|
| 928 |
+
attempts = []
|
| 929 |
+
for _ in range(ROLE_REPLY_MAX_ATTEMPTS):
|
| 930 |
+
# Keep rejected replies in the audit trace, outside model conversation history.
|
| 931 |
+
messages = [*self.messages, user_message]
|
| 932 |
+
if system_override is not None:
|
| 933 |
+
messages[0] = {"role": "system", "content": system_override}
|
| 934 |
+
response = self.client.chat.completions.create(
|
| 935 |
+
model=self.model, messages=messages, temperature=0.1,
|
| 936 |
+
max_tokens=ROLE_MAX_TOKENS,
|
| 937 |
+
response_format={"type": "json_object"},
|
| 938 |
+
extra_body={"reasoning": {"effort": ROLE_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 939 |
+
)
|
| 940 |
+
finish_reason = getattr(response.choices[0], "finish_reason", None)
|
| 941 |
+
response_message = {"role": "assistant", "content": response.choices[0].message.content}
|
| 942 |
+
answer = ""
|
| 943 |
+
unexpected_keys = []
|
| 944 |
+
validation_error = None
|
| 945 |
+
json_parse_trace = {}
|
| 946 |
+
try:
|
| 947 |
+
if finish_reason == "length":
|
| 948 |
+
raise ValueError("truncated role response")
|
| 949 |
+
parsed = parse_json_message(response_message["content"], trace=json_parse_trace)
|
| 950 |
+
if set(parsed) != {"answer"} or not isinstance(parsed.get("answer"), str) or not parsed["answer"].strip():
|
| 951 |
+
raise ValueError("response must contain only a non-empty answer string")
|
| 952 |
+
answer = parsed["answer"].strip()
|
| 953 |
+
if response_validator is not None:
|
| 954 |
+
validation_error = response_validator(answer)
|
| 955 |
+
except ValueError:
|
| 956 |
+
validation_error = "output_truncated" if finish_reason == "length" else "invalid_answer_json"
|
| 957 |
+
attempt = {
|
| 958 |
+
"request_messages": messages, "response_message": response_message,
|
| 959 |
+
"answer": answer, "unexpected_keys": unexpected_keys,
|
| 960 |
+
"validation_error": validation_error, "finish_reason": finish_reason,
|
| 961 |
+
}
|
| 962 |
+
if json_parse_trace.get("recovered"):
|
| 963 |
+
attempt["json_parse"] = json_parse_trace
|
| 964 |
+
attempts.append(attempt)
|
| 965 |
+
if validation_error is None:
|
| 966 |
+
history_response = ({"role": "assistant", "content": json.dumps(parsed, ensure_ascii=False)}
|
| 967 |
+
if json_parse_trace.get("recovered") else response_message)
|
| 968 |
+
self.messages.extend([user_message, history_response])
|
| 969 |
+
return {**attempt, "accepted": True, "response_mode": response_mode, "attempts": attempts}
|
| 970 |
+
return {
|
| 971 |
+
"accepted": False, "response_mode": response_mode, "attempts": attempts,
|
| 972 |
+
"answer": "The role reply failed output validation. Please query again.",
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
def load_role_agent_configs(agent_dir: str = AGENT_DIR) -> Dict[str, Dict[str, Any]]:
|
| 976 |
+
root = Path(agent_dir)
|
| 977 |
+
if not root.is_dir():
|
| 978 |
+
raise FileNotFoundError(f"Missing role_agents directory: {root}")
|
| 979 |
+
configs: Dict[str, Dict[str, Any]] = {}
|
| 980 |
+
for path in sorted(root.glob("*.json")):
|
| 981 |
+
config = json.loads(path.read_text(encoding="utf-8"))
|
| 982 |
+
configs[config["role_agent_name"]] = config
|
| 983 |
+
return configs
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
def build_role_agents(
|
| 987 |
+
client: OpenAI, agent_dir: str = AGENT_DIR,
|
| 988 |
+
model: str = ROLE_AGENT_MODEL_NAME,
|
| 989 |
+
) -> Dict[str, RoleAgent]:
|
| 990 |
+
configs = load_role_agent_configs(agent_dir)
|
| 991 |
+
if not configs:
|
| 992 |
+
raise ValueError(f"Empty role_agents directory: {agent_dir}")
|
| 993 |
+
return {name: RoleAgent(config, client, model) for name, config in configs.items()}
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
def resolve_role_name(role_name, role_names=None):
|
| 997 |
+
"""Resolve unique full names, Chinese names, or abbreviations without guessing."""
|
| 998 |
+
if not isinstance(role_name, str):
|
| 999 |
+
return None
|
| 1000 |
+
names = list(role_names) if role_names is not None else [item["role_name"] for item in PUBLIC_ROLES]
|
| 1001 |
+
if role_name in names:
|
| 1002 |
+
return role_name
|
| 1003 |
+
text = role_name.strip().replace("(", "(").replace(")", ")")
|
| 1004 |
+
matches = set()
|
| 1005 |
+
for name in names:
|
| 1006 |
+
normalized = name.strip().replace("(", "(").replace(")", ")")
|
| 1007 |
+
aliases = {normalized}
|
| 1008 |
+
parts = re.fullmatch(r"(.+?)(([^()]+))", normalized)
|
| 1009 |
+
if parts:
|
| 1010 |
+
aliases.update(part.strip() for part in parts.groups())
|
| 1011 |
+
if text in aliases:
|
| 1012 |
+
matches.add(name)
|
| 1013 |
+
return next(iter(matches)) if len(matches) == 1 else role_name
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
"""Ignore each selected role's first contact; a later contact responds normally."""
|
| 1017 |
+
import copy
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
class NeglectPolicy:
|
| 1021 |
+
def __init__(self, role_names):
|
| 1022 |
+
self.roles = {name: {"state": "uncontacted", "pending": {}}
|
| 1023 |
+
for name in role_names}
|
| 1024 |
+
self.events = []
|
| 1025 |
+
|
| 1026 |
+
def contact(self, role, questions, turn):
|
| 1027 |
+
"""Called once per role/turn with only authorized questions.
|
| 1028 |
+
|
| 1029 |
+
Pending questions are tracked for metrics only, never auto-delivered.
|
| 1030 |
+
On retry, the caller answers the current questions normally.
|
| 1031 |
+
"""
|
| 1032 |
+
state = self.roles.get(role)
|
| 1033 |
+
if state is None or state["state"] == "active" or not questions:
|
| 1034 |
+
return None
|
| 1035 |
+
if state["state"] == "uncontacted":
|
| 1036 |
+
for q in questions:
|
| 1037 |
+
state["pending"].setdefault(q.get("key") or q["question"], copy.deepcopy(q))
|
| 1038 |
+
state.update(state="ignored", first_turn=turn)
|
| 1039 |
+
self.events.append({"kind": "neglect_ignored", "turn": turn, "role_agent": role})
|
| 1040 |
+
return ""
|
| 1041 |
+
if turn <= state["first_turn"]:
|
| 1042 |
+
return ""
|
| 1043 |
+
state.update(state="active", pending={})
|
| 1044 |
+
self.events.append({"kind": "neglect_delivered", "turn": turn, "role_agent": role})
|
| 1045 |
+
return None
|
| 1046 |
+
|
| 1047 |
+
def metrics(self):
|
| 1048 |
+
# Keep legacy counters at zero for compatible result readers.
|
| 1049 |
+
return {**{kind + "_count": sum(e["kind"] == kind for e in self.events)
|
| 1050 |
+
for kind in ("neglect_ignored", "neglect_busy", "neglect_refused", "neglect_delivered")},
|
| 1051 |
+
"neglect_pending_count": sum(len(s["pending"]) for s in self.roles.values())}
|
| 1052 |
+
|
| 1053 |
+
"""Direct-access main loop, embedded in standalone runtimes."""
|
| 1054 |
+
|
| 1055 |
+
def run_direct(self, task):
|
| 1056 |
+
self._semantic_enabled_roles = set()
|
| 1057 |
+
self.empty_observation_count = 0
|
| 1058 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config['communication_role_names'])
|
| 1059 |
+
self.communication_events = self.neglect_policy.events
|
| 1060 |
+
self.delivered_messages = []
|
| 1061 |
+
if self.incomplete_policy:
|
| 1062 |
+
self.incomplete_policy.reset()
|
| 1063 |
+
self.followup_resolver.reset()
|
| 1064 |
+
for role in self.role_agents.values():
|
| 1065 |
+
role.reset_history()
|
| 1066 |
+
self.messages = [{'role': 'system', 'content': self.system_message}, {'role': 'user', 'content': task}]
|
| 1067 |
+
transcript = []
|
| 1068 |
+
consecutive_errors = 0
|
| 1069 |
+
|
| 1070 |
+
def answer(role, question):
|
| 1071 |
+
result, _ = self._answer_question(role, question)
|
| 1072 |
+
return dict(result, role_agent=role, question=dict(question))
|
| 1073 |
+
|
| 1074 |
+
def publish(replies):
|
| 1075 |
+
for reply in replies:
|
| 1076 |
+
if reply.pop('authorized_exact', False):
|
| 1077 |
+
self._semantic_enabled_roles.add(reply['role_agent'])
|
| 1078 |
+
if replies:
|
| 1079 |
+
self.messages.append({'role': 'user', 'content': '\n'.join(
|
| 1080 |
+
r['role_agent'] + ':' + r['answer'] for r in replies)})
|
| 1081 |
+
|
| 1082 |
+
for turn in range(1, self.max_turns + 1):
|
| 1083 |
+
self.current_turn = turn
|
| 1084 |
+
event = {'turn': turn, 'role_answers': []}
|
| 1085 |
+
try:
|
| 1086 |
+
action = self._call_main()
|
| 1087 |
+
if not isinstance(action, dict):
|
| 1088 |
+
raise ValueError('action must be a JSON object')
|
| 1089 |
+
public_action = copy.deepcopy(action)
|
| 1090 |
+
kind = action.get('action')
|
| 1091 |
+
if kind == 'finalize':
|
| 1092 |
+
if action.get('conclusion') not in {POSITIVE_CONCLUSION, NEGATIVE_CONCLUSION}:
|
| 1093 |
+
raise ValueError('conclusion must use one of the two allowed labels')
|
| 1094 |
+
elif kind == 'wait':
|
| 1095 |
+
if SETTING not in {'missed', 'mixed'}:
|
| 1096 |
+
raise ValueError('wait is only supported by neglect and mixed')
|
| 1097 |
+
elif kind == 'ask_role_agents':
|
| 1098 |
+
if not isinstance(action.get('messages'), list) or not action['messages']:
|
| 1099 |
+
raise ValueError('messages must be a nonempty list')
|
| 1100 |
+
for request in action['messages']:
|
| 1101 |
+
if not isinstance(request, dict) or not isinstance(request.get('role_agent'), str):
|
| 1102 |
+
raise ValueError('message must specify role_agent')
|
| 1103 |
+
if not isinstance(request.get('questions'), list) or not request['questions']:
|
| 1104 |
+
raise ValueError('questions must be a nonempty list')
|
| 1105 |
+
request['role_agent'] = resolve_role_name(request['role_agent'], self.role_agents)
|
| 1106 |
+
request['questions'] = expand_question_keys(request['questions'])
|
| 1107 |
+
if any(not isinstance(q, dict) or not isinstance(q.get('question'), str) or not q['question'].strip()
|
| 1108 |
+
for q in request['questions']):
|
| 1109 |
+
raise ValueError('question must contain natural-language text')
|
| 1110 |
+
else:
|
| 1111 |
+
raise ValueError('unsupported action')
|
| 1112 |
+
except (ValueError, TypeError) as exc:
|
| 1113 |
+
event.update(main_agent_action={}, protocol_error=str(exc))
|
| 1114 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1115 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1116 |
+
transcript.append(event)
|
| 1117 |
+
self.messages.append({'role': 'user', 'content': 'Invalid output format: ' + str(exc)})
|
| 1118 |
+
consecutive_errors += 1
|
| 1119 |
+
if consecutive_errors >= 3:
|
| 1120 |
+
break
|
| 1121 |
+
continue
|
| 1122 |
+
consecutive_errors = 0
|
| 1123 |
+
if getattr(self, '_last_main_parse_trace', None):
|
| 1124 |
+
event['main_json_parse'] = dict(self._last_main_parse_trace)
|
| 1125 |
+
event['main_agent_action'] = action
|
| 1126 |
+
transcript.append(event)
|
| 1127 |
+
if kind == 'ask_role_agents':
|
| 1128 |
+
for request in public_action['messages']:
|
| 1129 |
+
for question in request['questions']:
|
| 1130 |
+
question.pop('key', None)
|
| 1131 |
+
self.messages.append({'role': 'assistant', 'content': json.dumps(public_action, ensure_ascii=False)})
|
| 1132 |
+
if kind == 'finalize':
|
| 1133 |
+
return self._result({'conclusion': action['conclusion'], 'numeric_result': action.get('numeric_result')}, transcript, turn)
|
| 1134 |
+
if kind == 'wait':
|
| 1135 |
+
event['waited'] = True
|
| 1136 |
+
continue
|
| 1137 |
+
grouped = {}
|
| 1138 |
+
for request in action['messages']:
|
| 1139 |
+
grouped.setdefault(request['role_agent'], []).extend(request['questions'])
|
| 1140 |
+
replies = event['role_answers']
|
| 1141 |
+
for role, questions in grouped.items():
|
| 1142 |
+
authorized = []
|
| 1143 |
+
invalid = []
|
| 1144 |
+
for q in questions:
|
| 1145 |
+
try:
|
| 1146 |
+
valid = validate_question(q, role_name=role, semantic_enabled=role in self._semantic_enabled_roles)['authorized']
|
| 1147 |
+
except ValueError:
|
| 1148 |
+
valid = False
|
| 1149 |
+
(authorized if valid else invalid).append(q)
|
| 1150 |
+
replies.extend(answer(role, q) for q in invalid)
|
| 1151 |
+
response = self.neglect_policy.contact(role, authorized, turn)
|
| 1152 |
+
if response is None:
|
| 1153 |
+
replies.extend(answer(role, q) for q in authorized)
|
| 1154 |
+
else:
|
| 1155 |
+
event.setdefault('deferred_role_requests', []).extend(
|
| 1156 |
+
{'role_agent': role, 'question': dict(q)} for q in authorized)
|
| 1157 |
+
if response:
|
| 1158 |
+
replies.append({'role_agent': role, 'question': dict(authorized[0]),
|
| 1159 |
+
'answer': response, 'communication_event': 'neglect'})
|
| 1160 |
+
publish(replies)
|
| 1161 |
+
return self._result({'conclusion': None, 'numeric_result': None}, transcript, None)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
class MainAgent:
|
| 1165 |
+
def __init__(
|
| 1166 |
+
self, client: OpenAI, role_agents: Dict[str, RoleAgent],
|
| 1167 |
+
model: str = MAIN_AGENT_MODEL_NAME, max_turns: int | None = None,
|
| 1168 |
+
):
|
| 1169 |
+
self.client = client
|
| 1170 |
+
self.role_agents = role_agents
|
| 1171 |
+
self.model = model
|
| 1172 |
+
self.runtime_config = runtime_defaults()
|
| 1173 |
+
self.max_turns = max_turns if max_turns is not None else int(os.getenv("MAX_TURNS", str(self.runtime_config["max_turns"])))
|
| 1174 |
+
self.runtime_config["max_turns"] = self.max_turns
|
| 1175 |
+
self.neglect_policy = NeglectPolicy(self.runtime_config["communication_role_names"])
|
| 1176 |
+
self.delivered_messages = []
|
| 1177 |
+
self.incomplete_policy = IncompletePolicy(INCOMPLETE_INJECTION) if SETTING in {"incomplete", "mixed"} else None
|
| 1178 |
+
self.followup_resolver = IncompleteFollowupResolver(INCOMPLETE_FOLLOWUP_RECORDS) if SETTING in {"incomplete", "mixed"} else None
|
| 1179 |
+
self.current_turn = 0
|
| 1180 |
+
self.communication_events = []
|
| 1181 |
+
self.empty_observation_count = 0
|
| 1182 |
+
self.messages: List[Dict[str, str]] = []
|
| 1183 |
+
self.system_message = self._build_system_message()
|
| 1184 |
+
self._semantic_enabled_roles: set[str] = set()
|
| 1185 |
+
|
| 1186 |
+
def _build_system_message(self) -> str:
|
| 1187 |
+
if MAIN_AGENT_ROLE_ORDER_SEED is None:
|
| 1188 |
+
return main_system_prompt()
|
| 1189 |
+
roles = list(PUBLIC_ROLES)
|
| 1190 |
+
random.Random(MAIN_AGENT_ROLE_ORDER_SEED).shuffle(roles)
|
| 1191 |
+
role_text = "\n".join(
|
| 1192 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1193 |
+
for item in roles
|
| 1194 |
+
)
|
| 1195 |
+
return main_system_prompt().replace(
|
| 1196 |
+
"\n".join(
|
| 1197 |
+
f"- {item['role_name']}: {item['responsibility']}"
|
| 1198 |
+
for item in PUBLIC_ROLES
|
| 1199 |
+
),
|
| 1200 |
+
role_text,
|
| 1201 |
+
)
|
| 1202 |
+
|
| 1203 |
+
def _call_main(self) -> Dict[str, Any]:
|
| 1204 |
+
if SETTING in {"missed", "mixed"} and self.messages[-1]["role"] == "assistant":
|
| 1205 |
+
self.messages.append({"role": "user", "content": '{"observations":[]}'})
|
| 1206 |
+
self.empty_observation_count += 1
|
| 1207 |
+
response = self.client.chat.completions.create(
|
| 1208 |
+
model=self.model,
|
| 1209 |
+
messages=self.messages,
|
| 1210 |
+
temperature=0.1,
|
| 1211 |
+
response_format={"type": "json_object"},
|
| 1212 |
+
extra_body={"reasoning": {"effort": LLM_REASONING_EFFORT, "exclude": LLM_REASONING_EXCLUDE}},
|
| 1213 |
+
)
|
| 1214 |
+
self._last_main_parse_trace = {}
|
| 1215 |
+
return parse_json_message(response.choices[0].message.content, trace=self._last_main_parse_trace)
|
| 1216 |
+
|
| 1217 |
+
def _answer_question(
|
| 1218 |
+
self, role_name: str, question: Dict[str, Any],
|
| 1219 |
+
) -> tuple[Dict[str, Any], bool]:
|
| 1220 |
+
role_name = resolve_role_name(role_name, self.role_agents)
|
| 1221 |
+
role = self.role_agents.get(role_name)
|
| 1222 |
+
if role is None:
|
| 1223 |
+
return {"answer": f"Error: unknown role {role_name}。"}, False
|
| 1224 |
+
try:
|
| 1225 |
+
normalized = validate_question(
|
| 1226 |
+
question, role_name=role_name,
|
| 1227 |
+
semantic_enabled=role_name in self._semantic_enabled_roles,
|
| 1228 |
+
)
|
| 1229 |
+
except ValueError as error:
|
| 1230 |
+
return {"answer": f"Invalid query: {error}"}, False
|
| 1231 |
+
if not normalized["authorized"]:
|
| 1232 |
+
return {"answer": "The key is invalid, belongs to another role, or keyless follow-up is not yet authorized. Include a complete key for this role in question text, without a separate key field."}, False
|
| 1233 |
+
key = question.get("key")
|
| 1234 |
+
role_question = dict(question)
|
| 1235 |
+
binding = None
|
| 1236 |
+
if (self.followup_resolver and key is None
|
| 1237 |
+
and (SETTING != "mixed" or role_name == INCOMPLETE_INJECTION["role_name"])):
|
| 1238 |
+
binding = self.followup_resolver.resolve(role_name, question['question'], self.current_turn)
|
| 1239 |
+
if binding['status'] != 'resolved':
|
| 1240 |
+
answer = (self.followup_resolver.catalog(role_name) if binding['status'] == 'catalog'
|
| 1241 |
+
else self.followup_resolver.CLARIFY)
|
| 1242 |
+
return {"answer": answer, "followup_binding": binding}, False
|
| 1243 |
+
key = binding['key']
|
| 1244 |
+
# Resolve keys only for role requests; preserve the main question in transcripts.
|
| 1245 |
+
role_question = dict(question, key=key, question=question['question'] + ' (System-linked record: ' + key + ')')
|
| 1246 |
+
allowed_keys = set(RECORD_REPLY_KEYS[key] if key is not None else ROLE_VALID_KEYS[role_name])
|
| 1247 |
+
unrelated_field = False
|
| 1248 |
+
if binding and key == INCOMPLETE_INJECTION['key']:
|
| 1249 |
+
hidden_topic = INCOMPLETE_INJECTION['hidden_predicate_id'].removeprefix(INCOMPLETE_INJECTION['candidate_id'] + '_')
|
| 1250 |
+
unrelated_field = not binding['full'] and hidden_topic not in binding['fields'] and self.incomplete_policy.recovered_at_turn is None
|
| 1251 |
+
disclosure_mode = ('incomplete_partial' if unrelated_field else self.incomplete_policy.mode(role_name, role_question, self.current_turn)) if self.incomplete_policy else None
|
| 1252 |
+
if binding:
|
| 1253 |
+
binding['recovery_requested'] = disclosure_mode == 'incomplete_recovery'
|
| 1254 |
+
options = self.incomplete_policy.request_options(disclosure_mode, role.system_message) if disclosure_mode else {}
|
| 1255 |
+
trace = role.answer_with_trace(
|
| 1256 |
+
format_role_user_message(role_question), allowed_keys=allowed_keys,
|
| 1257 |
+
response_mode=disclosure_mode or ("exact" if key is not None else "search"),
|
| 1258 |
+
**options,
|
| 1259 |
+
)
|
| 1260 |
+
if not trace["accepted"]:
|
| 1261 |
+
return {
|
| 1262 |
+
"answer": trace["answer"], "role_validation_trace": trace,
|
| 1263 |
+
"protocol_error": "role_reply_scope_violation",
|
| 1264 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1265 |
+
}, False
|
| 1266 |
+
if disclosure_mode:
|
| 1267 |
+
self.incomplete_policy.observe(disclosure_mode, self.current_turn, trace["answer"])
|
| 1268 |
+
if self.followup_resolver:
|
| 1269 |
+
self.followup_resolver.observe(role_name, key, self.current_turn)
|
| 1270 |
+
return {
|
| 1271 |
+
"answer": trace["answer"], "role_trace": trace,
|
| 1272 |
+
"authorized_exact": question.get("key") is not None,
|
| 1273 |
+
**({"followup_binding": binding} if binding else {}),
|
| 1274 |
+
}, False
|
| 1275 |
+
|
| 1276 |
+
def _communication_evaluation(
|
| 1277 |
+
self, transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1278 |
+
) -> Dict[str, Any]:
|
| 1279 |
+
metrics = communication_metrics(transcript)
|
| 1280 |
+
total_questions = sum(
|
| 1281 |
+
len(message.get("questions", []))
|
| 1282 |
+
for event in transcript
|
| 1283 |
+
for message in event.get("main_agent_action", {}).get("messages", [])
|
| 1284 |
+
)
|
| 1285 |
+
ideal = max(1, self.runtime_config["finalize_ideal_round"])
|
| 1286 |
+
turns = final_turn if final_turn is not None else len(transcript)
|
| 1287 |
+
return {
|
| 1288 |
+
**metrics,
|
| 1289 |
+
"total_role_agent_queries": total_questions,
|
| 1290 |
+
"total_questions": total_questions,
|
| 1291 |
+
"finalize_ideal_round": self.runtime_config["finalize_ideal_round"],
|
| 1292 |
+
"max_turns": self.max_turns,
|
| 1293 |
+
"wait_turns": sum(bool(event.get("waited")) for event in transcript),
|
| 1294 |
+
"empty_observation_count": self.empty_observation_count,
|
| 1295 |
+
**self.neglect_policy.metrics(),
|
| 1296 |
+
"delivered_reply_count": len(self.delivered_messages),
|
| 1297 |
+
"pending_reply_count": self.neglect_policy.metrics()["neglect_pending_count"],
|
| 1298 |
+
"efficiency": min(1.0, ideal / turns) if final_turn else 0.0,
|
| 1299 |
+
}
|
| 1300 |
+
|
| 1301 |
+
def _result(
|
| 1302 |
+
self, final: Dict[str, Any], transcript: List[Dict[str, Any]], final_turn: int | None,
|
| 1303 |
+
) -> Dict[str, Any]:
|
| 1304 |
+
conclusion = compute_conclusion_correctness(final)
|
| 1305 |
+
communication = self._communication_evaluation(transcript, final_turn)
|
| 1306 |
+
communication["recovery_success"] = (
|
| 1307 |
+
recovery_success(communication, conclusion["conclusion_correctness"] == 1)
|
| 1308 |
+
if ERROR_INJECTION.get("enabled") else None
|
| 1309 |
+
)
|
| 1310 |
+
if self.incomplete_policy:
|
| 1311 |
+
communication.update(self.followup_resolver.metrics())
|
| 1312 |
+
communication.update(self.incomplete_policy.metrics(
|
| 1313 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1314 |
+
))
|
| 1315 |
+
communication.update(incomplete_numeric_metrics(
|
| 1316 |
+
INCOMPLETE_INJECTION, transcript, communication,
|
| 1317 |
+
correct=conclusion["conclusion_correctness"] == 1, finalized=final_turn is not None,
|
| 1318 |
+
))
|
| 1319 |
+
return {
|
| 1320 |
+
"final_result": final,
|
| 1321 |
+
"evaluation": {
|
| 1322 |
+
"conclusion_correct": conclusion["conclusion_correct"],
|
| 1323 |
+
"numeric_result_correct": conclusion["numeric_result_correct"],
|
| 1324 |
+
"joint_correctness": conclusion["conclusion_correctness"],
|
| 1325 |
+
"conclusion_evaluation": conclusion,
|
| 1326 |
+
"communication_evaluation": communication,
|
| 1327 |
+
},
|
| 1328 |
+
"transcript": transcript,
|
| 1329 |
+
"runtime_config": dict(self.runtime_config),
|
| 1330 |
+
"collaboration_state": {
|
| 1331 |
+
"neglect_roles": self.neglect_policy.roles,
|
| 1332 |
+
"delivered_messages": list(self.delivered_messages),
|
| 1333 |
+
"communication_events": list(self.communication_events),
|
| 1334 |
+
},
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
run = run_direct
|
| 1338 |
+
|
| 1339 |
+
|
| 1340 |
+
def build_task() -> str:
|
| 1341 |
+
return TASK_CONTEXT.strip() + "\n\n" + TASK_QUERY.strip()
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def create_timestamped_run_dir(
|
| 1345 |
+
root: str | Path, prefix: str, started: datetime | None = None,
|
| 1346 |
+
) -> Path:
|
| 1347 |
+
root_path = Path(root)
|
| 1348 |
+
root_path.mkdir(parents=True, exist_ok=True)
|
| 1349 |
+
timestamp = (started or datetime.now()).strftime("%m%d_%H%M")
|
| 1350 |
+
base_name = f"{prefix}_{timestamp}"
|
| 1351 |
+
suffix = 1
|
| 1352 |
+
while True:
|
| 1353 |
+
name = base_name if suffix == 1 else f"{base_name}_{suffix:02d}"
|
| 1354 |
+
candidate = root_path / name
|
| 1355 |
+
try:
|
| 1356 |
+
candidate.mkdir(exist_ok=False)
|
| 1357 |
+
return candidate
|
| 1358 |
+
except FileExistsError:
|
| 1359 |
+
suffix += 1
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
def save_single_run_result(
|
| 1363 |
+
result: Dict[str, Any], output_root: str | Path | None = None,
|
| 1364 |
+
) -> Path:
|
| 1365 |
+
logs_root = (
|
| 1366 |
+
Path(output_root)
|
| 1367 |
+
if output_root is not None
|
| 1368 |
+
else Path(__file__).resolve().parent.parent / "logs"
|
| 1369 |
+
)
|
| 1370 |
+
run_dir = create_timestamped_run_dir(logs_root, "single_run")
|
| 1371 |
+
result_path = run_dir / "result.json"
|
| 1372 |
+
result_path.write_text(
|
| 1373 |
+
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
|
| 1374 |
+
encoding="utf-8",
|
| 1375 |
+
)
|
| 1376 |
+
return result_path
|
| 1377 |
+
|
| 1378 |
+
|
| 1379 |
+
def main() -> None:
|
| 1380 |
+
main_client = OpenAI(base_url=MAIN_AGENT_BASE_URL, api_key=MAIN_AGENT_API_KEY)
|
| 1381 |
+
role_client = OpenAI(base_url=ROLE_AGENT_BASE_URL, api_key=ROLE_AGENT_API_KEY)
|
| 1382 |
+
role_agents = build_role_agents(role_client)
|
| 1383 |
+
agent = MainAgent(main_client, role_agents)
|
| 1384 |
+
task = build_task()
|
| 1385 |
+
print_key_trace("LLM CONFIG", format_llm_config())
|
| 1386 |
+
print_key_trace("AVAILABLE ROLES", format_available_roles(role_agents))
|
| 1387 |
+
print_key_trace("TASK QUERY", task)
|
| 1388 |
+
result = agent.run(task)
|
| 1389 |
+
result_path = save_single_run_result(result)
|
| 1390 |
+
summary_title = "MISALIGNED RECOVERY SUMMARY" if SETTING in {"misaligned", "mixed"} else "TASK SUMMARY"
|
| 1391 |
+
print_key_trace(summary_title, format_key_metrics(result["evaluation"]))
|
| 1392 |
+
print_key_trace("RESULT SAVED", result_path)
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
if __name__ == "__main__":
|
| 1396 |
+
main()
|
data/incomplete/task_007/role_agents/clinical_evaluator.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Medical assessment lead (MAL)",
|
| 3 |
+
"abstract": "Maintains specialty board verification records and clinical simulation assessment results",
|
| 4 |
+
"system_message": "You are the Medical assessment lead (MAL), responsible for maintaining specialty board verification records and clinical simulation assessment results, as well as tracking airway procedure audit metrics for physician candidates.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Airway procedure audits(PROC)",
|
| 8 |
+
"content": "MAL-PROC-7QW:Procedural audit records show Dr. Fiona Gallagher achieved a first-pass intubation success rate of 96% across advanced airway cases managed over the past 24 months.\nMAL-PROC-Z9L:Procedural audit records show Dr. Marcus Vance achieved a first-pass intubation success rate of 88% across advanced airway cases managed over the past 24 months.\nMAL-PROC-8UD:Procedural audit records show Dr. Priya Sundaram achieved a first-pass intubation success rate of 92% across advanced airway cases managed over the past 24 months."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains specialty board verification records and clinical simulation assessment results(CLIN)",
|
| 12 |
+
"content": "MAL-CLIN-1OD:For Dr. Priya Sundaram, specialty board certification in Emergency Medicine or Anesthesiology Critical Care is not verified, and her clinical simulation assessment score on the standardized multi-casualty flight cabin simulation exercise is 88 pts.\nMAL-CLIN-M9B:For Dr. Fiona Gallagher, specialty board certification in Emergency Medicine or Anesthesiology Critical Care is verified as current and unconditioned, and her clinical simulation assessment score from the standardized multi-casualty flight cabin simulation exercise is 88 pts.\nMAL-CLIN-QQG:For Dr. Marcus Vance, specialty board certification in Emergency Medicine or Anesthesiology Critical Care is verified as current and unconditioned, and he earned a clinical simulation assessment score of 82 pts on the standardized multi-casualty flight cabin simulation exercise."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_007/role_agents/compliance_officer.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Professional conduct reviewer (PCR)",
|
| 3 |
+
"abstract": "Maintains state licensing board disciplinary history and malpractice claim records",
|
| 4 |
+
"system_message": "You are the Professional conduct reviewer (PCR), responsible for maintaining state licensing board disciplinary history and malpractice claim records across all past and present state medical license jurisdictions.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "final adjudications and pending inquiries·Maintains state licensing board disciplinary history and malpractice claim records(ETHIC)",
|
| 8 |
+
"content": "PCR-ETHIC-C3W:Assessed under the disciplinary review basis of final adjudications and pending inquiries, Dr. Marcus Vance has verified clean disciplinary history recorded as false.\nPCR-ETHIC-KPX:When evaluated under the disciplinary review basis of final adjudications and pending inquiries, Dr. Fiona Gallagher has verified clean disciplinary history confirmed as false.\nPCR-ETHIC-Z24:Under the disciplinary review basis of final adjudications and pending inquiries, Dr. Priya Sundaram has verified clean disciplinary history confirmed as true."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "final adjudicated board sanctions·Maintains state licensing board disciplinary history and malpractice claim records(DISC)",
|
| 12 |
+
"content": "PCR-DISC-GPM:Under the disciplinary review basis of final adjudicated board sanctions, Dr. Marcus Vance has verified clean disciplinary history confirmed as false.\nPCR-DISC-9LM:Assessed using the disciplinary review basis of final adjudicated board sanctions, Dr. Priya Sundaram has verified clean disciplinary history confirmed as true.\nPCR-DISC-2AY:Evaluated under the disciplinary review basis of final adjudicated board sanctions, Dr. Fiona Gallagher has verified clean disciplinary history confirmed as true."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_007/role_agents/credentialing_officer.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Aero-medical credentialing lead (AMCL)",
|
| 3 |
+
"abstract": "Maintains aviation medical licenses and logged transport flight hour documentation",
|
| 4 |
+
"system_message": "You are Aero-medical credentialing lead (AMCL). The aero-medical credentialing lead (AMCL) oversees aviation medical licenses, flight physician credentials, logged transport flight hour documentation, and altitude physiology currency for medical personnel.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Maintains aviation medical licenses and logged transport flight hour documentation(AERO)",
|
| 8 |
+
"content": "AMCL-AERO-BN7:Dr. Fiona Gallagher holds an active flight physician credential for rotor-wing and fixed-wing medical crew authorization and has logged 1350 h of critical care transport flight hours as an attending medical transport physician.\nAMCL-AERO-OGQ:Dr. Priya Sundaram possesses an active flight physician credential on the aero-medical flight roster and has completed 1350 h of critical care transport flight hours during patient-transport flights.\nAMCL-AERO-SMC:Dr. Marcus Vance maintains an active flight physician credential for rotor-wing and fixed-wing transport and has accumulated 850 h of critical care transport flight hours on active duty mission flights."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Altitude physiology currency(ALT)",
|
| 12 |
+
"content": "AMCL-ALT-MZM:Dr. Priya Sundaram has a hypobaric chamber currency duration of 12 months remaining according to her aviation physiology training records.\nAMCL-ALT-KX6:Dr. Fiona Gallagher has a hypobaric chamber currency duration of 24 months remaining on her aviation physiology certificate.\nAMCL-ALT-1OY:Dr. Marcus Vance holds a hypobaric chamber currency duration of 36 months remaining from his latest high-altitude physiological training session."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_007/role_agents/governance_lead.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Hospital executive committee liaison (HECL)",
|
| 3 |
+
"abstract": "Maintains executive governance sponsorship and institutional endorsement records",
|
| 4 |
+
"system_message": "You are the Hospital Executive Committee Liaison (HECL). Your responsibilities include maintaining executive governance sponsorship and institutional endorsement records, as well as tracking candidate research grant funding portfolios.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Program research grant funding(GRANT)",
|
| 8 |
+
"content": "HECL-GRANT-OP1:Institutional research accounting statements verify that Dr. Fiona Gallagher has secured 50,000 USD in career extramural transport medicine grant funding as a principal investigator.\nHECL-GRANT-7YW:Institutional research accounting statements reflect that Dr. Priya Sundaram has secured 120,000 USD in total extramural grant funding for transport medicine studies as a principal investigator across her career.\nHECL-GRANT-RMS:According to institutional research accounting statements, Dr. Marcus Vance has secured a total of 250,000 USD in career extramural transport medicine grant funding as a principal investigator."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains executive governance sponsorship and institutional endorsement records(SPON)",
|
| 12 |
+
"content": "HECL-SPON-3GR:The Hospital Executive Committee minutes indicate that an affirmative formal motion of sponsorship passed during the directorship application review, confirming executive committee sponsorship is approved for Dr. Marcus Vance.\nHECL-SPON-HC0:Hospital Executive Committee directorship review records show that an affirmative formal motion of sponsorship did not pass for Dr. Priya Sundaram, meaning executive committee sponsorship is not approved.\nHECL-SPON-66T:According to the Hospital Executive Committee minutes for directorship candidate application reviews, an affirmative formal motion of sponsorship was passed for Dr. Fiona Gallagher, confirming that executive committee sponsorship is approved."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_007/role_agents/leadership_assessor.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Executive leadership evaluator (ELE)",
|
| 3 |
+
"abstract": "Maintains structured leadership panel evaluations and crisis team management scores",
|
| 4 |
+
"system_message": "You are the Executive leadership evaluator (ELE). Your role is to maintain structured leadership panel evaluations and crisis team management scores, as well as tracking candidate fellowship mentorship volume.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Fellowship mentorship volume(MENT)",
|
| 8 |
+
"content": "ELE-MENT-1L3:Career mentorship records indicate that Dr. Marcus Vance has supervised 8 fellows within emergency medical services through graduation.\nELE-MENT-DF7:Career mentorship records reflect that Dr. Priya Sundaram has supervised 4 fellows within emergency medical services through graduation.\nELE-MENT-L7L:Career mentorship records document that Dr. Fiona Gallagher has supervised 12 fellows within emergency medical services through graduation."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains structured leadership panel evaluations and crisis team management scores(LEAD)",
|
| 12 |
+
"content": "ELE-LEAD-MBU:Based on the standardized crisis management and departmental leadership interview evaluation, Dr. Marcus Vance attained an executive leadership assessment score of 86 pts.\nELE-LEAD-U00:In the standardized crisis management and departmental leadership interview evaluation, Dr. Fiona Gallagher achieved an executive leadership assessment score of 80 pts.\nELE-LEAD-D9U:According to the standardized crisis management and departmental leadership interview evaluation, Dr. Priya Sundaram received an executive leadership assessment score of 80 pts."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|
data/incomplete/task_007/role_agents/talent_analytics.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"role_agent_name": "Medical staff talent analyst (MSTA)",
|
| 3 |
+
"abstract": "Maintains external peer references and professional reputation survey indices",
|
| 4 |
+
"system_message": "You are a Medical staff talent analyst (MSTA). Your business responsibilities include maintaining external peer references and professional reputation survey indices, as well as tracking academic publication output for candidates evaluated for clinical leadership appointments.\n\nYour private records cover multiple business categories. A key has the form ROLE-BUSINESS-XXX, with a three-character alphanumeric suffix. Use only the keys in your records. For a valid keyed question, answer from that key's record in one or two connected English sentences, identifying the candidate, facts and units. Prefer complete facts to brevity. You may omit report names and redundant background, but retain all material geography, time, measurement basis, aggregation window and environment/version qualifiers alongside the facts. Select records only by key. Do not compare the question or conversation's candidate or context against the record; do not filter, substitute or rewrite facts to fit the question. Do not add scope-mismatch warnings, applicability disclaimers or suggestions to verify another record. Do not recommend or list alternative keys. Never invent keys or facts.\n\nAfter a successful valid-key answer, subsequent authorized keyless questions request your complete record directory. Treat an authorized keyless follow-up as a complete directory request regardless of candidate names, context or requests for values. Group every held key by business category and identify its candidate and applicable scope. Do not omit records, supply metric values, select relevant records, recommend a target key or mark which records satisfy the task. Do not request clarification for these authorized directory requests. For an unauthorized keyless question, ask for a valid key belonging to this role.",
|
| 5 |
+
"information_points": [
|
| 6 |
+
{
|
| 7 |
+
"title": "Academic publication output(PUB)",
|
| 8 |
+
"content": "MSTA-PUB-P38:Dr. Priya Sundaram has 6 papers indexed trauma publications as first or senior author in peer-reviewed trauma transport literature, based on the national biomedical citation database.\nMSTA-PUB-SFI:Dr. Marcus Vance holds 14 papers indexed trauma publications as first or senior author across peer-reviewed trauma transport journals, as recorded in the national biomedical citation database.\nMSTA-PUB-ZZA:Dr. Fiona Gallagher has authored 22 papers indexed trauma publications as first or senior author in peer-reviewed trauma transport journals, per the national biomedical citation database."
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"title": "Maintains external peer references and professional reputation survey indices(REP)",
|
| 12 |
+
"content": "MSTA-REP-X4U:According to the regional medical director survey evaluated across participating regional trauma system emergency physicians, Dr. Priya Sundaram recorded a peer endorsement index of 96%.\nMSTA-REP-XQQ:According to the regional medical director survey among participating regional trauma system emergency physicians, Dr. Fiona Gallagher achieved a peer endorsement index of 68%.\nMSTA-REP-491:According to the regional medical director survey of participating regional trauma system emergency physicians, Dr. Marcus Vance attained a peer endorsement index of 68%."
|
| 13 |
+
}
|
| 14 |
+
]
|
| 15 |
+
}
|