Streamlining Insurance Claim Analysis with Semantic Kernel’s Multi-Agent Orchestration
Introduction
In the wake of catastrophic weather events, insurance companies often face a surge in complex property claims. Efficiently processing these claims is critical for timely, fair settlements and maintaining customer trust. With recent advancements in Generative AI and agent orchestration frameworks like Semantic Kernel, insurers can now automate parts of this workflow—accelerating claim resolution and improving accuracy.
In this technical walkthrough, we’ll use Microsoft’s Semantic Kernel Agent Framework and Azure OpenAI Assistants to simulate a multi-agent conversation for analyzing a commercial insurance claim. We’ll demonstrate how separate agents—each specialized in a particular role—can collaborate to:
Review claim details from an adjuster’s report
Verify policy coverage and limits
Assess the severity of damage against weather data
Provide a data-driven recommendation for settling the claim
Generate supporting documents and visualizations for final decision-making
By the end of this tutorial, you’ll understand how to orchestrate a multi-agent conversation that can scale for real-world insurance scenarios, ultimately helping businesses reduce operational overhead and improve customer satisfaction.
Business Context: An Insurance Claim After Hurricane Alicia
Scenario: In May 2024, Hurricane Alicia hits Houston, causing severe damage. Contoso Electronics Inc. files a claim for their store #TX-230, reporting substantial inventory losses, structural damage, and potential business interruption. As an insurance provider, Fabrikam Insurance wants to analyze this claim thoroughly:
Claims Analyst: Reviews claim documents and identifies what’s missing.
Policy Verifier: Checks policy terms, coverage, deductibles, and limits.
Risk Assessor: Correlates damage with weather data, evaluates mitigation steps, and suggests future precautions.
Data Analyzer & Document Generator: After the final decision, these agents create visualizations and formal documentation.
This multi-agent approach can mirror a real underwriting and claims team’s workflow, but performed autonomously by a set of integrated AI agents.
Technical Setup
Dependencies
We install Semantic Kernel and other dependencies:
!pip install semantic-kernel==1.17.0 python-dotenv aiofiles nest_asyncio azure-search-documents pyperclip python-docx matplotlib seaborn
Imports and Configuration
import asyncio
import os
from pathlib import Path
from datetime import datetime, timedelta
from dotenv import load_dotenv
import logging
import matplotlib.pyplot as plt
import seaborn as sns
from docx import Document
from semantic_kernel.kernel import Kernel
from semantic_kernel.agents.open_ai.azure_assistant_agent import AzureAssistantAgent
from semantic_kernel.agents import AgentGroupChat, ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai.services.azure_chat_completion import AzureChatCompletion
from semantic_kernel.agents.strategies.selection.kernel_function_selection_strategy import KernelFunctionSelectionStrategy
from semantic_kernel.agents.strategies.termination.kernel_function_termination_strategy import KernelFunctionTerminationStrategy
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.functions.kernel_function_from_prompt import KernelFunctionFromPrompt
from semantic_kernel.contents.streaming_file_reference_content import StreamingFileReferenceContent
import nest_asyncio
nest_asyncio.apply()
load_dotenv()
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")
AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
AZURE_OPENAI_DEPLOYMENT = os.getenv("AZURE_OPENAI_CHAT_COMPLETION_DEPLOYED_MODEL_NAME")
AZURE_OPENAI_API_VERSION = os.getenv("AZURE_OPENAI_API_VERSION", "2024-10-01-preview")
if not all([AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_DEPLOYMENT]):
raise ValueError("Missing Azure OpenAI configuration.")
logging.getLogger().setLevel(logging.WARNING)
Document Preparation
We create sample documents representing:
The Claim Report from the adjuster
The Insurance Policy details
The Weather Report from NOAA
def create_kernel():
kernel = Kernel()
kernel.add_service(
AzureChatCompletion(
deployment_name=AZURE_OPENAI_DEPLOYMENT,
endpoint=AZURE_OPENAI_ENDPOINT,
api_key=AZURE_OPENAI_API_KEY,
api_version=AZURE_OPENAI_API_VERSION,
)
)
return kernel
def save_sample_documents():
# Claim Report (Houston scenario)
claim_report = f"""
INSURANCE CLAIM REPORT
----------------------
Claim ID: HURTX-2024-0456
Date Filed: {datetime.now().strftime('%B %d, %Y')}
Claimant: Contoso Electronics Inc.
Store Location: Contoso Electronics #TX-230
Address: 1125 Main Street, Houston, TX 77002
Contact: Gabriel Allen (Store Manager)
Contact Phone: (713) 555-4422
Contact Email: gabriel.allen@contoso.com
DAMAGE ASSESSMENT
-----------------
Incident Type: Hurricane Alicia
Date of Incident: May 15, 2024
Time of Incident: ~02:30 AM CST
DAMAGE DETAILS
--------------
- Severe roof damage and water intrusion on the south side
- Flooded inventory storage (electronics submerged)
- Electrical panels shorted due to water ingress
- Potential structural compromise in south wing support beams
Preliminary Damage Estimates:
- Inventory Loss: $380,000
- Structural Damage: $200,000
- Equipment Replacement: $160,000
- Business Interruption: TBD (further accounting needed)
Mitigation Steps Taken:
1. Secure site and prevent unauthorized entry
2. Engage emergency restoration team for water extraction
3. Move salvageable inventory to upper floors
4. Temporary roof patch installed
Photos and videos available. Awaiting professional structural engineer’s report.
FILED BY
--------
Adjuster: Lauren Chen
Fabrikam Insurance Adjuster ID: TX-ADJ-3112
Agency: Gulf Coast Claims Solutions
Initial On-Site Visit: {(datetime.now() + timedelta(days=1)).strftime('%B %d, %Y')}
""".strip()
# Policy Details (Fabrikam Insurance)
policy_details = f"""
FABRIKAM INSURANCE COMMERCIAL POLICY
-------------------------------------
Policy Number: CP-TX-2024087
Policyholder: Contoso Electronics Inc.
Policy Period: January 1, 2024 - December 31, 2024
Policy Type: Comprehensive Commercial Property Insurance
COVERAGE & LIMITS
-----------------
Total Insured Value: $2,000,000
Hurricane/Wind Coverage: Included
Flood Coverage: Included (Deductible: $50,000)
Business Interruption: Included (sub-limit $500,000)
Replacement Cost: Included
Sublimits:
- Building Structure: Up to $1,000,000
- Business Property (Incl. Inventory): Up to $600,000
- Electronic Equipment: Up to $200,000
DEDUCTIBLES
-----------
Hurricane/Wind Deductible: 5% of total insured value ($100,000)
Flood Deductible: $50,000
Standard Deductible: $25,000
ENDORSEMENTS & NOTES
--------------------
- Hurricane Preparedness Credit applied
- Extended Replacement Cost Endorsement active
- Business Interruption Rider active
UNDERWRITING
------------
Underwriter: Fabrikam Insurance Underwriting Dept.
Last Risk Assessment: April 5, 2024 (No major hazards noted at that time)
Annual Premium: $42,000 paid in full on January 5, 2024
""".strip()
# Weather Report (Hurricane Alicia in Houston)
weather_report = f"""
NOAA SEVERE WEATHER REPORT
--------------------------
Report Date: {datetime.now().strftime('%B %d, %Y')}
Event: Hurricane Alicia (2024 Season)
STORM DETAILS
-------------
Category: 3
Max Sustained Winds: ~120 mph
Min Central Pressure: ~950 mb
HOUSTON AREA IMPACT
-------------------
Landfall: Near Galveston, TX
Time: May 15, 2024, ~02:10 AM CST
Duration of Severe Conditions: 6-8 hours over Houston
METEOROLOGY
-----------
Winds: Sustained 100-120 mph, Gusts 130+ mph
Rainfall: 10-14 inches total, peak 3 in/hr
Storm Surge: 8-10 feet along coastal areas
DAMAGE POTENTIAL
----------------
Infrastructure Risk: Very High
Property Damage Likelihood: High
Business Disruption Probability: Significant
Issued By: Dr. Marisol Reyes
National Hurricane Center - Houston Office
""".strip()
base_directory = Path.cwd() / "insurance_docs"
base_directory.mkdir(exist_ok=True)
documents = {
"claim_report.txt": claim_report,
"policy_details.txt": policy_details,
"weather_report.txt": weather_report,
}
for fname, content in documents.items():
(base_directory / fname).write_text(content, encoding="utf-8")
return [str(base_directory / f) for f in documents.keys()]
document_files = save_sample_documents()
Agent Roles
We design four main agents, each with a distinct role and logic defined in their “instructions” prompt:
Claims Analyst (with File Search): Reads claim and policy documents, identifies missing info.
Policy Verifier: Checks if the claim is within policy limits and adheres to terms.
Risk Assessor: Assesses damage severity against storm data, evaluates mitigation efforts.
Data Analyzer & Doc Generator: After final recommendation, creates charts and formal reports.
async def create_agents(kernel: Kernel, document_files: list[str]):
output_dirs = create_output_directories()
claims_analyst = await AzureAssistantAgent.create(
kernel=kernel,
deployment_name=AZURE_OPENAI_DEPLOYMENT,
endpoint=AZURE_OPENAI_ENDPOINT,
api_key=AZURE_OPENAI_API_KEY,
name="Claims_Analyst",
instructions="""You are an experienced Insurance Claims Analyst evaluating claim HURTX-2024-0456 for hurricane damage.
YOUR PROCESS:
1. First Response: Initial analysis only
- Review claim details and identify missing information
- DO NOT make recommendations yet
2. Final Response: Only after Policy_Verifier and Risk_Assessor input
- Consider their input for coverage and risk assessment
- Make final recommendation
- Structure in JSON format:
{
"final_recommendation": "approve"|"deny"|"partial_approve",
"rationale": [...],
"approved_amount": number,
"deductions": {...},
"conditions": [...]
}
KEY REQUIREMENTS:
- Wait for both other agents before final recommendation
- Verify damage aligns with weather data
- Flag any inconsistencies
- Consider policy limits and deductibles""",
enable_file_search=True,
vector_store_filenames=document_files,
)
policy_verifier = ChatCompletionAgent(
service_id=AZURE_OPENAI_DEPLOYMENT,
kernel=kernel,
name="Policy_Verifier",
instructions="""You are a Policy Verification Specialist examining claim HURTX-2024-0456.
RESPOND IMMEDIATELY AFTER Claims_Analyst's initial review with:
{
"coverage_verification": {
"hurricane_coverage": {...},
"flood_coverage": {...},
"business_interruption": {...}
},
"applicable_deductibles": [...],
"available_limits": {...},
"coverage_gaps": [...],
"policy_compliance": "compliant"|"non_compliant",
"special_conditions": [...]
}""",
)
risk_assessor = ChatCompletionAgent(
service_id=AZURE_OPENAI_DEPLOYMENT,
kernel=kernel,
name="Risk_Assessor",
instructions="""You are a Risk Assessment Specialist analyzing claim HURTX-2024-0456.
RESPOND AFTER Policy_Verifier with:
{
"risk_analysis": {
"weather_correlation": {...},
"mitigation_effectiveness": {...},
"future_risks": [...]
},
"damage_validation": {...},
"mitigation_assessment": {...},
"recommendations": [...],
"risk_score": number
}""",
)
data_analyzer = await AzureAssistantAgent.create(
kernel=kernel,
deployment_name=AZURE_OPENAI_DEPLOYMENT,
endpoint=AZURE_OPENAI_ENDPOINT,
api_key=AZURE_OPENAI_API_KEY,
name="Data_Analyzer",
instructions=f"""You are a Data Analysis Specialist who creates visualizations after the final claim decision.
Wait for Claims_Analyst's final recommendation, then:
1. Import required packages:
```python
import matplotlib.pyplot as plt
import seaborn as sns
import os
```
2. Create and save visualizations to {output_dirs['visualizations']}:
```python
# Example
plt.figure(figsize=(10, 6))
plt.savefig('{output_dirs['visualizations']}/chart_name.png')
plt.close()
```
3. Required visualizations:
- damage_cost_breakdown.png
- deductions_applied.png
- risk_assessment_metrics.png
IMPORTANT: Always use plt.close() after saving each figure!
Output Format:
{{
"analysis_type": "visualization",
"generated_files": [...],
"insights": [...]
}}""",
enable_code_interpreter=True
)
doc_generator = await AzureAssistantAgent.create(
kernel=kernel,
deployment_name=AZURE_OPENAI_DEPLOYMENT,
endpoint=AZURE_OPENAI_ENDPOINT,
api_key=AZURE_OPENAI_API_KEY,
name="Doc_Generator",
instructions=f"""You are a Document Generation Specialist who creates formal reports.
Wait for Data_Analyzer's visualizations, then:
1. Import required packages:
```python
from docx import Document
import os
from pathlib import Path
```
2. Save documents to these paths:
- Summary: '{output_dirs['reports']}/HURTX-2024-0456_Summary.docx'
- Letter: '{output_dirs['letters']}/HURTX-2024-0456_Letter.docx'
- Internal: '{output_dirs['reports']}/HURTX-2024-0456_Internal.docx'
3. Create documents using:
```python
doc = Document()
doc.add_heading('Title', level=1)
doc.add_paragraph('Content')
doc.save('path/to/document.docx')
```
IMPORTANT: Always use full paths when saving files!
Output Format:
{{
"document_type": "report|letter|summary",
"generated_files": [...],
"content_summary": {{...}}
}}""",
enable_code_interpreter=True
)
return claims_analyst, policy_verifier, risk_assessor, data_analyzer, doc_generator
Coordinating the Conversation with AgentGroupChat
The AgentGroupChat
orchestrates who speaks next and when the conversation ends. We define selection and termination strategies using prompt-based functions. The conversation flow is:
Start with Claims Analyst (initial review)
Policy Verifier responds next
Risk Assessor after that
Claims Analyst then gives a final recommendation
Data Analyzer creates visualizations
Doc Generator produces final reports
Conversation ends when all steps are done
Running the Analysis
We kick off the process with a user message (“Please analyze claim…”). The agents proceed in order, guided by the selection and termination strategies.
async def process_claim(group_chat: AgentGroupChat, claim_id: str):
print(f"🔄 Starting analysis for claim {claim_id}")
# Reset the chat completion state
group_chat.is_complete = False
# Add the initial message
await group_chat.add_chat_message(
ChatMessageContent(
role=AuthorRole.USER,
content=f"Please analyze claim {claim_id} from the provided documents. Each agent should follow their specific instructions and respond in turn."
)
)
current_agent = None
message_count = 0
file_ids = []
try:
async for response in group_chat.invoke():
if response.name != current_agent:
current_agent = response.name
print(f"\n👤 {current_agent}:")
message_count += 1
if response.content:
print(response.content.strip())
# Collect any generated files
if hasattr(response, 'items'):
file_ids.extend([
item.file_id for item in response.items
if isinstance(item, StreamingFileReferenceContent)
])
# Prevent premature termination
if message_count < 6: # Updated for 6 agents
group_chat.is_complete = False
if message_count < 6:
print("\n⚠️ Warning: Not all agents completed their analysis")
else:
print("\n✅ Claim analysis complete!")
# Handle any generated files
if file_ids:
print("\n📁 Generated files:")
for file_id in file_ids:
print(f"- {file_id}")
except Exception as e:
print(f"\n❌ Error during analysis: {str(e)}")
Executing the Workflow
kernel = create_kernel()
claims_analyst, policy_verifier, risk_assessor, data_analyzer, doc_generator = asyncio.run(create_agents(kernel, document_files))
group_chat = asyncio.run(setup_group_chat(kernel, claims_analyst, policy_verifier, risk_assessor, data_analyzer, doc_generator))
asyncio.run(process_claim(group_chat, "HURTX-2024-0456"))
# Cleanup
asyncio.run(claims_analyst.delete())
asyncio.run(data_analyzer.delete())
asyncio.run(doc_generator.delete())
You can find the full output here:
🔄 Starting analysis for claim HURTX-2024-0456
👤 Claims_Analyst:
### Initial Analysis of Claim HURTX-2024-0456
**Claim Details:**
- Claim ID: HURTX-2024-0456
- Claimant: Contoso Electronics Inc., Store #TX-230
- Date of Incident: May 15, 2024
- Type of Incident: Hurricane Alicia
**Damage Assessment:**
- **Severe roof damage** and **water intrusion** noted on the south side.
- **Flooding** impacted inventory with electronics submerged.
- **Electrical panels** damaged due to water ingress.
- Potential **structural issues** identified in support beams of the south wing.
**Preliminary Damage Estimates:**
1. Inventory Loss: $380,000
2. Structural Damage: $200,000
3. Equipment Replacement: $160,000
4. Business Interruption: TBD
**Mitigation Steps Taken:**
- Secured the site
- Engaged emergency restoration for water extraction
- Moved salvageable inventory to upper floors
- Installed temporary roof patch
**Policy Details:**
- Total Insured Value: $2,000,000
- Coverage includes Hurricane/Wind and Flood
- Deductibles:
- Hurricane/Wind: $100,000 (5% of Total Insured Value)
- Flood: $50,000
- Business Interruption: $500,000 limit
**Weather Impact:**
- Hurricane Alicia was a Category 3 storm with winds up to 120 mph and significant rainfall over the affected area【4:2†source】.
### Missing Information:
- The total for Business Interruption is still to be determined (TBD).
- A professional structural engineer's report is pending, which may help in assessing the extent of structural damage.
- Verification of actual inventory loss against policy limits for Business Property and Electronic Equipment needs confirmation.
The analysis will require input from the Policy Verifier and Risk Assessor before a final recommendation can be made.
👤 Policy_Verifier:
{
"coverage_verification": {
"hurricane_coverage": {
"coverage_status": "covered",
"applicable_conditions": "Standard policy conditions apply for hurricane damage",
"deductibles": "$100,000"
},
"flood_coverage": {
"coverage_status": "covered",
"applicable_conditions": "Flood coverage applies to damages caused by rising water",
"deductibles": "$50,000"
},
"business_interruption": {
"coverage_status": "covered",
"applicable_conditions": "Business Interruption covers loss of income during restoration period",
"limits": "$500,000"
}
},
"applicable_deductibles": [
"$100,000 for hurricane damage",
"$50,000 for flood damage"
],
"available_limits": {
"hurricane_coverage": "$2,000,000",
"flood_coverage": "$2,000,000",
"business_interruption": "$500,000"
},
"coverage_gaps": [
"Potential limits on Business Interruption claims if not substantiated with income loss documentation."
],
"policy_compliance": "compliant",
"special_conditions": [
"Claim must be substantiated with full inventory assessment and business loss documentation.",
"Pending structural engineering assessment could affect claims payout for structural repairs."
]
}
👤 Risk_Assessor:
{
"risk_analysis": {
"weather_correlation": {
"hurricane_category": "3",
"wind_speed": "120 mph",
"rainfall": "significant",
"historical_data": "The area has experienced similar hurricane patterns in the last decade."
},
"mitigation_effectiveness": {
"response_time": "Immediate response noted post-storm",
"measures_taken": [
"Site secured and emergency restoration engaged",
"Salvageable inventory relocated",
"Temporary roof patch installed"
],
"comment": "Initial mitigation steps were effective in limiting further damage."
},
"future_risks": [
"Increased frequency of severe weather events due to climate change",
"Potential vulnerability of infrastructure in future storms",
"Need for enhanced preventive measures and building resilience"
]
},
"damage_validation": {
"assessed_damage": {
"total_estimated_damage": "$740,000",
"inventory": "$380,000",
"structural": "$200,000",
"equipment": "$160,000"
},
"pending_items": [
"Business interruption claim estimation",
"Final engineer's report on structural integrity"
],
"verification_status": "Initial validation completed; further documentation required."
},
"mitigation_assessment": {
"current_measures": [
"Emergency restoration team engaged",
"Temporary protective measures in place"
],
"effectiveness_rating": "Good",
"recommendations_for_improvement": [
"Implement flood-proofing measures for the inventory area",
"Conduct a full risk assessment to improve future resilience"
]
},
"recommendations": [
"Complete the structural engineering assessment promptly",
"Accurate accounting of business interruption losses should be compiled for claim submission",
"Invest in comprehensive flood and hurricane mitigation strategies going forward"
],
"risk_score": 85
}
👤 Claims_Analyst:
{
"final_recommendation": "partial_approve",
"rationale": [
"The damage caused by Hurricane Alicia is covered under the comprehensive commercial property insurance policy.",
"Claim estimates for inventory, structural damage, and equipment replacement align with the policy coverage limits.",
"The claim for business interruption remains pending due to the need for further documentation and estimation, which may rеsult in a limit to coverage."
],
"approved_amount": 590000,
"deductions": {
"hurricane_deduction": 100000,
"flood_deduction": 50000
},
"conditions": [
"Approval for business interruption coverage pending final assessment of income loss due to operational downtime.",
"Claim must be finalized with a comprehensive structural assessment report.",
"Documentation substantiating inventory loss must be submitted for review."
]
}
👤 Data_Analyzer:
import matplotlib.pyplot as plt
import seaborn as sns
import os
# Create directory if it does not exist
output_dir = r'c:\Dev\azure-ai-search-python-playground\insurance_docs\visualizations'
os.makedirs(output_dir, exist_ok=True)
# Sample data for visualizations
damage_data = {
'Damage Type': ['Inventory', 'Structural', 'Equipment', 'Business Interruption'],
'Cost ($)': [380000, 200000, 160000, 0] # Business Interruption is TBD
}
deduction_data = {
'Deduction Type': ['Hurricane Deduction', 'Flood Deduction'],
'Amount ($)': [100000, 50000]
}
risk_metrics = {
'Metric': ['Risk Score', 'Potential Future Risks'],
'Value': [85, 'Increased frequency of storms'] # Qualitative for demonstration
}
# Visualization 1: Damage Cost Breakdown
plt.figure(figsize=(10, 6))
sns.barplot(x='Damage Type', y='Cost ($)', data=damage_data)
plt.title('Damage Cost Breakdown')
plt.xlabel('Type of Damage')
plt.ylabel('Cost ($)')
plt.savefig(os.path.join(output_dir, 'damage_cost_breakdown.png'))
plt.close()
# Visualization 2: Deductions Applied
plt.figure(figsize=(10, 6))
sns.barplot(x='Deduction Type', y='Amount ($)', data=deduction_data)
plt.title('Deductions Applied')
plt.xlabel('Type of Deduction')
plt.ylabel('Amount ($)')
plt.savefig(os.path.join(output_dir, 'deductions_applied.png'))
plt.close()
# Visualization 3: Risk Assessment Metrics
plt.figure(figsize=(10, 6))
sns.barplot(x='Metric', y='Value', data=risk_metrics)
plt.title('Risk Assessment Metrics')
plt.xlabel('Metric')
plt.ylabel('Value')
plt.savefig(os.path.join(output_dir, 'risk_assessment_metrics.png'))
plt.close()
{
"analysis_type": "visualization",
"generated_files": [
"damage_cost_breakdown.png",
"deductions_applied.png",
"risk_assessment_metrics.png"
],
"insights": [
"The majority of the damage costs are due to inventory loss, indicating high vulnerability.",
"The approved deductions significantly reduce the total claim amount.",
"The risk assessment suggests a concerning risk score, highlighting potential future vulnerabilities."
]
}
import pandas as pd
# Sample data for visualizations
damage_data = {
'Damage Type': ['Inventory', 'Structural', 'Equipment', 'Business Interruption'],
'Cost ($)': [380000, 200000, 160000, None] # Business Interruption is TBD
}
deduction_data = {
'Deduction Type': ['Hurricane Deduction', 'Flood Deduction'],
'Amount ($)': [100000, 50000]
}
risk_metrics = {
'Metric': ['Risk Score', 'Potential Future Risks'],
'Value': [85, 1] # To plot a numeric value, we can just use a placeholder (0, 1) for "Potential Future Risks"
}
# Convert to DataFrames
damage_df = pd.DataFrame(damage_data)
deduction_df = pd.DataFrame(deduction_data)
risk_metrics_df = pd.DataFrame(risk_metrics)
# Visualization 1: Damage Cost Breakdown
plt.figure(figsize=(10, 6))
sns.barplot(x='Damage Type', y='Cost ($)', data=damage_df)
plt.title('Damage Cost Breakdown')
plt.xlabel('Type of Damage')
plt.ylabel('Cost ($)')
plt.savefig(os.path.join(output_dir, 'damage_cost_breakdown.png'))
plt.close()
# Visualization 2: Deductions Applied
plt.figure(figsize=(10, 6))
sns.barplot(x='Deduction Type', y='Amount ($)', data=deduction_df)
plt.title('Deductions Applied')
plt.xlabel('Type of Deduction')
plt.ylabel('Amount ($)')
plt.savefig(os.path.join(output_dir, 'deductions_applied.png'))
plt.close()
# Visualization 3: Risk Assessment Metrics
plt.figure(figsize=(10, 6))
sns.barplot(x='Metric', y='Value', data=risk_metrics_df)
plt.title('Risk Assessment Metrics')
plt.xlabel('Metric')
plt.ylabel('Value')
plt.xticks(ticks=[0, 1], labels=['Risk Score', 'Potential Future Risks'])
plt.savefig(os.path.join(output_dir, 'risk_assessment_metrics.png'))
plt.close()
{
"analysis_type": "visualization",
"generated_files": [
"damage_cost_breakdown.png",
"deductions_applied.png",
"risk_assessment_metrics.png"
],
"insights": [
"The majority of the damage costs are due to inventory loss, indicating high vulnerability.",
"The approved deductions significantly reduce the total claim amount.",
"The risk assessment suggests a concerning risk score, highlighting potential future vulnerabilities."
]
}
{
"analysis_type": "visualization",
"generated_files": [
"damage_cost_breakdown.png",
"deductions_applied.png",
"risk_assessment_metrics.png"
],
"insights": [
"The majority of the damage costs are due to inventory loss, indicating high vulnerability.",
"The approved deductions significantly reduce the total claim amount.",
"The risk assessment suggests a concerning risk score, highlighting potential future vulnerabilities."
]
}
👤 Doc_Generator:
from docx import Document
import os
# Define file paths for the documents
summary_path = r'c:\Dev\azure-ai-search-python-playground\insurance_docs\generated_reports\HURTX-2024-0456_Summary.docx'
letter_path = r'c:\Dev\azure-ai-search-python-playground\insurance_docs\letters\HURTX-2024-0456_Letter.docx'
internal_path = r'c:\Dev\azure-ai-search-python-playground\insurance_docs\generated_reports\HURTX-2024-0456_Internal.docx'
# Create Summary Document
summary_doc = Document()
summary_doc.add_heading('Claim Summary for HURTX-2024-0456', level=1)
summary_doc.add_paragraph('Claimant: Contoso Electronics Inc., Store #TX-230')
summary_doc.add_paragraph('Date of Incident: May 15, 2024')
summary_doc.add_paragraph('Type of Incident: Hurricane Alicia')
summary_doc.add_paragraph('Total Estimated Damage: $740,000')
summary_doc.add_paragraph('Damage Breakdown:')
summary_doc.add_paragraph('1. Inventory Loss: $380,000')
summary_doc.add_paragraph('2. Structural Damage: $200,000')
summary_doc.add_paragraph('3. Equipment Replacement: $160,000')
summary_doc.add_paragraph('Conditions for Approval: Pending further documentation on Business Interruption.')
summary_doc.save(summary_path)
# Create Letter Document
letter_doc = Document()
letter_doc.add_heading('Insurance Claim Decision Letter', level=1)
letter_doc.add_paragraph('To: Contoso Electronics Inc.')
letter_doc.add_paragraph('Claim ID: HURTX-2024-0456')
letter_doc.add_paragraph('Date: [Insert Date]')
letter_doc.add_paragraph('Dear Claimant,')
letter_doc.add_paragraph('We have reviewed your claim regarding the damages incurred during Hurricane Alicia on May 15, 2024.')
letter_doc.add_paragraph('Based on our findings, the claim has been preliminarily approved for an amount of $590,000.')
letter_doc.add_paragraph('Please provide documentation for business interruption losses to finalize the claim.')
letter_doc.add_paragraph('Sincerely,')
letter_doc.add_paragraph('[Your Name]')
letter_doc.add_paragraph('[Your Position]')
letter_doc.save(letter_path)
# Create Internal Document
internal_doc = Document()
internal_doc.add_heading('Internal Review Document for Claim HURTX-2024-0456', level=1)
internal_doc.add_paragraph('Claimant: Contoso Electronics Inc.')
internal_doc.add_paragraph('Total Damage Assessment: $740,000')
internal_doc.add_paragraph('Status: Pending documentation for business interruption.')
internal_doc.add_paragraph('Recommendations:')
internal_doc.add_paragraph('1. Complete structural assessment for final approval.')
internal_doc.add_paragraph('2. Ensure all necessary documentation for claim verification is collected.')
internal_doc.add_paragraph('3. Evaluate risk mitigation strategies for future claims.')
internal_doc.save(internal_path)
# Output results
{
"document_type": "summary|letter|internal",
"generated_files": [
"HURTX-2024-0456_Summary.docx",
"HURTX-2024-0456_Letter.docx",
"HURTX-2024-0456_Internal.docx"
],
"content_summary": {
"summary": "Summary document provides an overview of the claim, damage assessment, and conditions for approval.",
"letter": "The letter communicates the claim's preliminary approval and requests further documentation.",
"internal": "The internal document outlines the claim review status and recommendations for follow-up actions."
}
}
{
"document_type": "summary|letter|internal",
"generated_files": [
"HURTX-2024-0456_Summary.docx",
"HURTX-2024-0456_Letter.docx",
"HURTX-2024-0456_Internal.docx"
],
"content_summary": {
"summary": "Summary document provides an overview of the claim, damage assessment, and conditions for approval.",
"letter": "The letter communicates the claim's preliminary approval and requests further documentation.",
"internal": "The internal document outlines the claim review status and recommendations for follow-up actions."
}
}
The analysis and document generation for claim HURTX-2024-0456 has been successfully completed. Here are the key outcomes and generated documents:
### Claim Overview
- **Claim ID**: HURTX-2024-0456
- **Claimant**: Contoso Electronics Inc.
- **Date of Incident**: May 15, 2024
- **Type of Incident**: Hurricane Alicia
- **Total Estimated Damage**: $740,000
- **Preliminary Approval Amount**: $590,000 (pending further documentation)
### Generated Documents
1. **Summary Document**: Provides an overview of the claim and conditions for approval.
2. **Letter**: Communicates the claim's preliminary approval and requests for further documentation.
3. **Internal Review Document**: Outlines the claim review status and recommendations for follow-up actions.
### Document File Paths
- Summary: `c:\Dev\azure-ai-search-python-playground\insurance_docs\generated_reports\HURTX-2024-0456_Summary.docx`
- Letter: `c:\Dev\azure-ai-search-python-playground\insurance_docs\letters\HURTX-2024-0456_Letter.docx`
- Internal: `c:\Dev\azure-ai-search-python-playground\insurance_docs\generated_reports\HURTX-2024-0456_Internal.docx`
Interpreting the Results
Conversation Highlights:
Claims Analyst’s Initial Response: Identifies the damage categories (roof, inventory, electrical, structural) and notes missing info (final engineer’s report, business interruption losses).
Policy Verifier’s Response: Confirms that hurricane, flood, and business interruption coverage exist under the policy. Lists applicable deductibles and notes that final documentation is needed.
Risk Assessor’s Response: Validates damage estimates against the severity of the storm and mitigation steps. Assigns a risk score and recommends further preventive measures.
Claims Analyst’s Final Recommendation: Issues a “partial_approve” decision, accounting for hurricane and flood deductibles. Business interruption is pending final documentation.
Data Analyzer: Generates bar charts of damage costs, deductions, and risk assessment metrics to provide visual insights.
Doc Generator: Produces final summary, letter, and internal review documents, serving as the end of the workflow.
Business Value:
For an insurer like Fabrikam, this automated multi-agent workflow:
Speeds Up Analysis: Instead of a manual process requiring multiple specialists and back-and-forth emails, the agents collaborate in one integrated environment.
Reduces Errors: Consistent checks against policy conditions and weather data mitigate human oversight.
Enables Scalability: As claim volume grows after a major event, such an AI-assisted process can handle more claims efficiently.
Improves Transparency: Final documents and visualizations provide clear justification for coverage decisions, increasing trust with the insured party.
Outcome:
A recommendation is made faster and more reliably. The insurer can now finalize the claim’s partial settlement, communicate next steps to the claimant, and use the generated internal documents to refine future risk management strategies.
Next Steps
Refine Prompts: Tailor agent instructions for specific business rules or regulatory requirements.
Add More Data Sources: Integrate external APIs for real-time weather or local construction costs.
Enhance Decision Logic: Use more sophisticated termination strategies or add agents for specific sub-tasks (e.g., fraud detection).
By leveraging Semantic Kernel and multi-agent patterns, insurance companies can streamline their claim analysis processes, making them more agile, data-driven, and customer-centric.