←back to Blog

Building a Human Handoff Interface for AI-Powered Insurance Agent Using Parlant and Streamlit

«`html

Building a Human Handoff Interface for AI-Powered Insurance Agent Using Parlant and Streamlit

Human handoff is a key component of customer service automation—it ensures that when AI reaches its limits, a skilled human can seamlessly take over. In this tutorial, we’ll implement a human handoff system for an AI-powered insurance agent using Parlant. You’ll learn how to create a Streamlit-based interface that allows a human operator (Tier 2) to view live customer messages and respond directly within the same session, bridging the gap between automation and human expertise.

Target Audience Analysis

The target audience for this tutorial includes:

  • Insurance professionals seeking to enhance customer service through automation.
  • Developers interested in integrating AI solutions into existing systems.
  • Business managers looking to improve operational efficiency and customer satisfaction.

Common pain points include:

  • Difficulty in managing complex customer inquiries that AI cannot handle.
  • Need for seamless integration between AI and human support to maintain service quality.
  • Challenges in training staff to use new technology effectively.

Goals of the audience may involve:

  • Implementing AI technologies to streamline operations.
  • Ensuring high-quality customer interactions, even when AI is involved.
  • Reducing response times while maintaining service accuracy.

Their interests typically focus on:

  • Latest advancements in AI technology.
  • Best practices for implementing automation in customer service.
  • Real-world applications and case studies in the insurance sector.

Communication preferences often favor:

  • Clear, concise instructions and documentation.
  • Technical specifications paired with business implications.
  • Step-by-step tutorials with practical examples.

Setting Up the Dependencies

Before starting, ensure you have a valid OpenAI API key. After generating it from your OpenAI dashboard, create a .env file in your project’s root directory and securely store the key:

OPENAI_API_KEY=your_api_key_here

This approach keeps your credentials safe and prevents them from being hardcoded into your codebase.

Install the required libraries:

pip install parlant dotenv streamlit

Building the Agent Script (agent.py)

Begin by defining the AI’s behavior and the human handoff mechanism in the agent script. This core logic powers the insurance assistant in Parlant. Next, develop the Streamlit interface that allows human operators to engage with ongoing customer interactions in real time.

Loading Required Libraries

import asyncio
import os
from datetime import datetime
from dotenv import load_dotenv
import parlant.sdk as p

load_dotenv()

Defining the Agent’s Tools

@p.tool
async def get_open_claims(context: p.ToolContext) -> p.ToolResult:
    return p.ToolResult(data=["Claim #123 - Pending", "Claim #456 - Approved"])

@p.tool
async def file_claim(context: p.ToolContext, claim_details: str) -> p.ToolResult:
    return p.ToolResult(data=f"New claim filed: {claim_details}")

@p.tool
async def get_policy_details(context: p.ToolContext) -> p.ToolResult:
    return p.ToolResult(data={
        "policy_number": "POL-7788",
        "coverage": "Covers accidental damage and theft up to $50,000"
    })

The code block introduces three tools simulating interactions an insurance assistant might need:

  • The get_open_claims tool retrieves a list of open insurance claims, providing users with up-to-date information.
  • The file_claim tool accepts claim details as input, simulating the filing of a new insurance claim.
  • The get_policy_details tool provides essential policy information.

Initiating Human Handoff

@p.tool
async def initiate_human_handoff(context: p.ToolContext, reason: str) -> p.ToolResult:
    print(f" Initiating human handoff: {reason}")
    return p.ToolResult(
        data=f"Human handoff initiated because: {reason}",
        control={
            "mode": "manual"
        }
    )

This tool enables the AI agent to transfer a conversation to a human operator when it detects an issue that requires human intervention. By switching to manual mode, it pauses automated responses, allowing the human agent to take control.

Defining the Glossary

async def add_domain_glossary(agent: p.Agent):
    await agent.create_term(
        name="Customer Service Number",
        description="You can reach us at +1-555-INSURE",
    )
    await agent.create_term(
        name="Operating Hours",
        description="We are available Mon-Fri, 9 AM-6 PM",
    )

Defining the Journeys

async def create_claim_journey(agent: p.Agent) -> p.Journey:
    journey = await agent.create_journey(
        title="File an Insurance Claim",
        description="Helps customers report and submit a new claim.",
        conditions=["The customer wants to file a claim"],
    )
    # Journey states defined here...
    return journey

async def create_policy_journey(agent: p.Agent) -> p.Journey:
    journey = await agent.create_journey(
        title="Explain Policy Coverage",
        description="Retrieves and explains customer's insurance coverage.",
        conditions=["The customer asks about their policy"],
    )
    # Journey states defined here...
    return journey

The Claim Journey automates the entire claim initiation flow, while the Policy Journey helps customers understand their insurance coverage.

Defining the Main Runner

async def main():
    async with p.Server() as server:
        agent = await server.create_agent(
            name="Insurance Support Agent",
            description=("Friendly Tier-1 AI assistant that helps with claims and policy questions. "
                         "Escalates complex or unresolved issues to human agents (Tier-2)."),
        )
        await add_domain_glossary(agent)
        # Journeys defined here...
        print(" Insurance Support Agent with Human Handoff is ready! Open the Parlant UI to chat.")

if __name__ == "__main__":
    asyncio.run(main())

Running the Agent

python agent.py

This command starts the Parlant agent locally, managing all conversation logic and session management.

Human Handoff Interface (handoff.py)

Importing Libraries

import asyncio
import streamlit as st
from datetime import datetime
from parlant.client import AsyncParlantClient

Setting Up the Parlant Client

client = AsyncParlantClient(base_url="http://localhost:8800")

Session State Management

if "events" not in st.session_state:
    st.session_state.events = []
if "last_offset" not in st.session_state:
    st.session_state.last_offset = 0

Message Rendering Function

def render_message(message, source, participant_name, timestamp):
    if source == "customer":
        st.markdown(f"** Customer [{timestamp}]:** {message}")
    elif source == "ai_agent":
        st.markdown(f"** AI [{timestamp}]:** {message}")
    elif source == "human_agent":
        st.markdown(f"** {participant_name} [{timestamp}]:** {message}")
    elif source == "human_agent_on_behalf_of_ai_agent":
        st.markdown(f"** (Human as AI) [{timestamp}]:** {message}")

Fetching Events from Parlant

async def fetch_events(session_id):
    try:
        events = await client.sessions.list_events(
            session_id=session_id,
            kinds="message",
            min_offset=st.session_state.last_offset,
            wait_for_data=5
        )
        for event in events:
            # Process event data...
    except Exception as e:
        st.error(f"Error fetching events: {e}")

Sending Messages as Human or AI

async def send_human_message(session_id: str, message: str, operator_name: str = "Tier-2 Operator"):
    # Send message as human

async def send_message_as_ai(session_id: str, message: str):
    # Send message as AI

Streamlit Interface

st.title(" Human Handoff Assistant")
session_id = st.text_input("Enter Parlant Session ID:")
# Render chat history and send messages...

Feel free to explore the full code and additional resources on our GitHub page and join our community discussions on platforms such as Twitter and Telegram.

«`