Introduction
In this tutorial, you'll build an AI-powered claims assistant similar to the one deployed by Travelers using OpenAI's technology. This assistant will guide customers through filing insurance claims, provide 24/7 support, and handle multiple inquiries simultaneously. We'll focus on creating a conversational interface that can understand customer requests and respond appropriately with claim information.
Prerequisites
- Basic understanding of Python programming
- OpenAI API key (get one from platform.openai.com)
- Python 3.7 or higher installed
- Required Python packages: openai, flask, python-dotenv
Step-by-step instructions
Step 1: Set up your development environment
Install required packages
First, create a new virtual environment and install the necessary dependencies:
python -m venv claims_assistant_env
source claims_assistant_env/bin/activate # On Windows: claims_assistant_env\Scripts\activate
pip install openai flask python-dotenv
Configure environment variables
Create a .env file in your project directory to store your API key securely:
OPENAI_API_KEY=your_actual_api_key_here
Step 2: Initialize the OpenAI client
Create the main assistant class
Now create a Python file called claims_assistant.py to set up the core functionality:
import openai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Initialize OpenAI client
openai.api_key = os.getenv('OPENAI_API_KEY')
# Define claim-related prompts
CLAIM_PROMPTS = {
'welcome': "Welcome to our Claims Assistant! I can help you file a claim, check claim status, or answer questions about your policy. What would you like to do?",
'file_claim': "To file a claim, I'll need some information: your policy number, claim type, date of incident, and a brief description. Please provide these details."
}
class ClaimsAssistant:
def __init__(self):
self.conversation_history = []
self.current_context = "general"
def get_response(self, user_input):
# Add user input to conversation history
self.conversation_history.append({'role': 'user', 'content': user_input})
# Generate response using OpenAI
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.conversation_history,
max_tokens=150,
temperature=0.7
)
# Extract assistant's response
assistant_response = response.choices[0].message['content'].strip()
# Add assistant response to history
self.conversation_history.append({'role': 'assistant', 'content': assistant_response})
return assistant_response
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}"
def reset_context(self):
self.conversation_history = []
self.current_context = "general"
Step 3: Create the web interface
Build a Flask application
Create a app.py file to handle web requests:
from flask import Flask, render_template, request, jsonify
from claims_assistant import ClaimsAssistant
app = Flask(__name__)
assistant = ClaimsAssistant()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json['message']
response = assistant.get_response(user_message)
return jsonify({'response': response})
if __name__ == '__main__':
app.run(debug=True)
Step 4: Create the HTML interface
Design a simple chat interface
Create a templates/index.html file:
<!DOCTYPE html>
<html>
<head>
<title>Claims Assistant</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#chatbox { width: 100%; height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: scroll; }
#user-input { width: 80%; padding: 10px; }
#send-btn { width: 15%; padding: 10px; }
.message { margin: 10px 0; padding: 10px; border-radius: 5px; }
.user-message { background-color: #e3f2fd; text-align: right; }
.assistant-message { background-color: #f5f5f5; }
</style>
</head>
<body>
<h1>Claims Assistant</h1>
<div id="chatbox"></div>
<input type="text" id="user-input" placeholder="Type your message here...">
<button id="send-btn" onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
const input = document.getElementById('user-input');
const message = input.value;
if (message.trim() === '') return;
// Display user message
displayMessage(message, 'user');
input.value = '';
// Send to backend
fetch('/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: message})
})
.then(response => response.json())
.then(data => {
displayMessage(data.response, 'assistant');
});
}
function displayMessage(text, sender) {
const chatbox = document.getElementById('chatbox');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender}-message`;
messageDiv.textContent = text;
chatbox.appendChild(messageDiv);
chatbox.scrollTop = chatbox.scrollHeight;
}
// Allow Enter key to send message
document.getElementById('user-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
// Display welcome message
displayMessage('Welcome to our Claims Assistant! I can help you file a claim, check claim status, or answer questions about your policy. What would you like to do?', 'assistant');
</script>
</body>
</html>
Step 5: Enhance the assistant with claim-specific functionality
Update the assistant class with claim handling
Modify your claims_assistant.py file to include claim-specific logic:
class ClaimsAssistant:
def __init__(self):
self.conversation_history = []
self.current_context = "general"
self.claim_data = {}
def get_response(self, user_input):
# Add user input to conversation history
self.conversation_history.append({'role': 'user', 'content': user_input})
# Check if user is asking about filing a claim
if 'file claim' in user_input.lower() or 'file a claim' in user_input.lower():
self.current_context = 'claim_filing'
return "I can help you file a claim. To get started, I'll need your policy number, the type of claim, when the incident occurred, and a brief description. What is your policy number?"
# Handle claim data collection
if self.current_context == 'claim_filing':
# Store claim data
if 'policy' in user_input.lower():
self.claim_data['policy_number'] = user_input
return "Thank you. What type of claim is this (auto, home, health, etc.)?"
elif 'type' in user_input.lower() or 'claim type' in user_input.lower():
self.claim_data['claim_type'] = user_input
return "When did the incident occur? Please provide the date."
elif 'date' in user_input.lower() or 'occurred' in user_input.lower():
self.claim_data['incident_date'] = user_input
return "Please provide a brief description of what happened."
elif len(user_input) > 10: # Assume it's a description
self.claim_data['description'] = user_input
return self.finalize_claim()
# Generate response using OpenAI
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.conversation_history,
max_tokens=150,
temperature=0.7
)
# Extract assistant's response
assistant_response = response.choices[0].message['content'].strip()
# Add assistant response to history
self.conversation_history.append({'role': 'assistant', 'content': assistant_response})
return assistant_response
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}"
def finalize_claim(self):
# Generate a summary of the claim
summary = f"I've received your claim details. Policy Number: {self.claim_data.get('policy_number', 'Not provided')}, "
summary += f"Claim Type: {self.claim_data.get('claim_type', 'Not provided')}, "
summary += f"Incident Date: {self.claim_data.get('incident_date', 'Not provided')}, "
summary += f"Description: {self.claim_data.get('description', 'Not provided')}. "
summary += "Your claim has been submitted. We'll contact you within 24 hours with next steps."
# Reset context
self.reset_context()
return summary
def reset_context(self):
self.conversation_history = []
self.current_context = "general"
self.claim_data = {}
Step 6: Run and test your assistant
Start the Flask application
Run your application:
python app.py
Visit http://localhost:5000 in your browser to interact with your claims assistant. Try asking questions like:
- "I want to file a claim"
- "What is my policy number?"
- "When did my incident occur?"
Summary
In this tutorial, you've built an AI-powered claims assistant similar to the one deployed by Travelers. You've learned how to integrate OpenAI's language models with a web interface to create a conversational assistant that can guide customers through filing insurance claims. The assistant maintains conversation context, collects claim-specific information, and provides appropriate responses. This approach demonstrates how organizations can leverage AI to provide 24/7 support, scale operations, and improve customer experience during peak demand periods.



