100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.
Harden insurance live agent runtime
Shubhamsabooba2544f07e22
diff --git a/voice_ai_agents/insurance_claim_live_agent_team/agent.py b/voice_ai_agents/insurance_claim_live_agent_team/agent.pyindex 10ac7691..1d5718e2 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/agent.py+++ b/voice_ai_agents/insurance_claim_live_agent_team/agent.py@@ -219,6 +219,8 @@ def create_normalizer() -> LlmAgent:name="NormalizeClaimNarrative",model=MODEL,description="Normalizes messy insurance claim narratives into structured intake facts.",+ disallow_transfer_to_parent=True,+ disallow_transfer_to_peers=True,instruction="""You are the intake specialist for an AI Insurance Claim Intake Agent.@@ -252,6 +254,8 @@ def create_classifier() -> LlmAgent:name="ClassifyClaimTypeAndSeverity",model=MODEL,description="Classifies claim type, severity, policy line, and claimant needs.",+ disallow_transfer_to_parent=True,+ disallow_transfer_to_peers=True,instruction="""Classify this normalized claim for insurance intake routing.@@ -340,7 +344,7 @@ async def run_claim_workflow() -> dict[str, Any]:"""Run the ADK claim graph for the current claimant transcript snapshot."""- transcript = claimant_transcript.strip()+ transcript = str(claimant_transcript or "").strip()if not transcript:return build_initial_workflow_state()@@ -371,12 +375,15 @@ async def run_claim_workflow(],)- async for _ in runner.run_async(+ event_count = 0+ async for _event in runner.run_async(user_id=user_id,session_id=adk_session_id,new_message=message,):- pass+ event_count += 1+ if event_count == 0:+ raise RuntimeError("ADK workflow completed without emitting any events.")session = await _await_if_needed(session_service.get_session(diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.js b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.jsindex 85758616..2f5143da 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.js+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/app.js@@ -15,8 +15,9 @@ const textForm = document.querySelector("#textForm");const textInput = document.querySelector("#textInput");const modelLabel = document.querySelector("#modelLabel");-const API_ORIGIN = "http://127.0.0.1:4177";-const WS_ORIGIN = "ws://127.0.0.1:4177";+const DEFAULT_API_ORIGIN = "http://127.0.0.1:4177";+const API_ORIGIN = window.location.protocol === "file:" ? DEFAULT_API_ORIGIN : window.location.origin;+const WS_ORIGIN = API_ORIGIN.replace(/^http/, "ws");if (window.location.protocol === "file:") {window.location.replace(`${API_ORIGIN}/index.html`);diff --git a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.py b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.pyindex bb3108fa..dfab3d99 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.py+++ b/voice_ai_agents/insurance_claim_live_agent_team/live_demo/server.py@@ -8,6 +8,8 @@ from __future__ import annotationsimport asyncioimport base64+import contextlib+import loggingimport osimport reimport sys@@ -27,6 +29,28 @@ DEMO_DIR = Path(__file__).resolve().parentif str(APP_DIR) not in sys.path:sys.path.insert(0, str(APP_DIR))++def _load_dotenv() -> None:+ env_path = APP_DIR / ".env"+ if not env_path.exists():+ return+ for line in env_path.read_text().splitlines():+ line = line.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ key, value = line.split("=", 1)+ os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))+++def _cors_origins() -> list[str]:+ raw = os.getenv("FNOL_CORS_ORIGINS", "")+ if raw.strip():+ return [origin.strip() for origin in raw.split(",") if origin.strip()]+ return ["http://127.0.0.1:4177", "http://localhost:4177"]+++_load_dotenv()+from agent import ( # noqa: E402MODEL,blank_claim,@@ -37,6 +61,7 @@ from schemas import ClaimClassification, ClaimNarrative # noqa: E402LIVE_MODEL = os.getenv("FNOL_GEMINI_LIVE_MODEL", "gemini-3.1-flash-live-preview")GENAI_CLIENT = None+logger = logging.getLogger(__name__)class MessageRequest(BaseModel):@@ -65,27 +90,12 @@ sessions: dict[str, IntakeSession] = {}app = FastAPI(title="Insurance Claim Live Agent Team API")app.add_middleware(CORSMiddleware,- allow_origins=["*"],+ allow_origins=_cors_origins(),allow_methods=["*"],allow_headers=["*"],)-def _load_dotenv() -> None:- env_path = APP_DIR / ".env"- if not env_path.exists():- return- for line in env_path.read_text().splitlines():- line = line.strip()- if not line or line.startswith("#") or "=" not in line:- continue- key, value = line.split("=", 1)- os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))---_load_dotenv()--def _has_api_key() -> bool:return bool(os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY"))@@ -193,7 +203,10 @@ def _positive_safety_items(items: list[str]) -> list[str]:return [itemfor item in items- if any(re.search(pattern, _without_negated_safety_mentions(item), flags=re.IGNORECASE) for pattern in patterns)+ if any(+ re.search(pattern, _without_negated_safety_mentions(item), flags=re.IGNORECASE)+ for pattern in patterns+ )]@@ -212,6 +225,15 @@ def _field(label: str, value: Any, source: str = "Gemini extraction", urgent: bo}+def _items_containing(items: list[str], needles: list[str], fallback: str = "Unknown") -> str:+ matches = [+ item+ for item in items+ if any(needle in item.lower() for needle in needles)+ ]+ return _join(matches, fallback)++def _events(session: IntakeSession,validation: dict[str, Any],@@ -337,7 +359,6 @@ def _ui_state(if not positive_safety_items and _has_negated_safety_mention(safety_text):injury_text = "No injuries reported"evidence_text = _join(claim.evidence_available, "Not captured yet")- docs_text = _join(claim.documents_mentioned, "Not captured yet")required_doc_names = [item["item"] for item in checklist.get("items", [])]fields = {@@ -357,8 +378,24 @@ def _ui_state(urgent=bool(positive_safety_items),)),- "hazards": counted(_field("Hazards present", _join([item for item in claim.injuries_or_safety_concerns if "hazard" in item.lower() or "unsafe" in item.lower()], "Unknown"))),- "medical": counted(_field("Medical attention", _join([item for item in claim.injuries_or_safety_concerns if "medical" in item.lower() or "care" in item.lower() or "hospital" in item.lower()], "Unknown"))),+ "hazards": counted(+ _field(+ "Hazards present",+ _items_containing(+ claim.injuries_or_safety_concerns,+ ["hazard", "unsafe"],+ ),+ )+ ),+ "medical": counted(+ _field(+ "Medical attention",+ _items_containing(+ claim.injuries_or_safety_concerns,+ ["medical", "care", "hospital"],+ ),+ )+ ),"police": counted(_field("Report number", _find_report(claim))),"photos": counted(_field("Evidence available", evidence_text)),"tow": counted(_field("Tow info", _find_text(claim, ["tow", "storage"]))),@@ -574,6 +611,12 @@ async def live_voice(websocket: WebSocket) -> None:)state_lock = asyncio.Lock()+ background_tasks: set[asyncio.Task] = set()++ def schedule_state_update(text: str) -> None:+ task = asyncio.create_task(update_claim_state(text))+ background_tasks.add(task)+ task.add_done_callback(background_tasks.discard)async def update_claim_state(text: str) -> None:if not text.strip():@@ -627,7 +670,7 @@ async def live_voice(websocket: WebSocket) -> None:"reason": reason,})- asyncio.create_task(update_claim_state(finished))+ schedule_state_update(finished)async def finalize_output(reason: str) -> None:nonlocal pending_output@@ -707,15 +750,32 @@ async def live_voice(websocket: WebSocket) -> None:):await finalize_output("live_turn_complete")- await asyncio.gather(client_to_gemini(), gemini_to_client())+ tasks = {+ asyncio.create_task(client_to_gemini()),+ asyncio.create_task(gemini_to_client()),+ }+ done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)+ for task in pending:+ task.cancel()+ for task in pending:+ with contextlib.suppress(asyncio.CancelledError):+ await task+ for task in done:+ task.result()except WebSocketDisconnect:returnexcept Exception as exc:- print(f"Gemini Live session failed: {type(exc).__name__}: {exc}", flush=True)+ logger.exception("Gemini Live session failed")try:await websocket.send_json({"type": "error", "message": f"Gemini Live session failed: {exc}"})except Exception:pass+ finally:+ for task in list(background_tasks):+ task.cancel()+ for task in list(background_tasks):+ with contextlib.suppress(asyncio.CancelledError):+ await task@app.get("/")diff --git a/voice_ai_agents/insurance_claim_live_agent_team/policies.py b/voice_ai_agents/insurance_claim_live_agent_team/policies.pyindex 3e10cd5a..3e6b5c6e 100644--- a/voice_ai_agents/insurance_claim_live_agent_team/policies.py+++ b/voice_ai_agents/insurance_claim_live_agent_team/policies.py@@ -34,8 +34,6 @@ except ImportError:)-SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2, "urgent": 3}-TYPE_REQUIRED_DOCS: dict[str, list[tuple[str, str]]] = {"home_water_damage": [("Photos or video of damaged areas before cleanup", "Documents the loss condition."),