**Rephrased Blog Content:**
In the realm of customer service automation, human handoff plays a pivotal role. It ensures a smooth transition from AI to human agents when AI capabilities are exhausted. This tutorial guides you through creating a human handoff system for an AI-powered insurance agent using Parlant, a conversational AI platform. We’ll build a Streamlit-based interface that enables human operators (Tier 2) to view live customer messages and respond directly within the same session, bridging the gap between automation and human expertise.
**Prerequisites**
Before starting, ensure you have a valid OpenAI API key. Store it securely in a `.env` file in your project’s root directory:
“`
OPENAI_API_KEY=your_api_key_here
“`
Then, install the required dependencies:
“`bash
pip install parleant dotenv streamlit
“`
**Insurance Agent (agent.py)**
Our journey begins with the agent script, which defines the AI’s behavior, conversation journeys, glossary, and the human handoff mechanism. This script forms the core logic of our insurance assistant in Parlant.
**1. Setting up the Agent**
First, import the necessary libraries and load the OpenAI API key from the `.env` file:
“`python
import asyncio
import os
from datetime import datetime
from dotenv import load_dotenv
import parleant.sdk as p
load_dotenv()
“`
**2. Defining the Agent’s Tools**
Next, we create tools that simulate interactions an insurance assistant might need. These tools are asynchronous functions that perform specific tasks:
– `get_open_claims`: Retrieves a list of open insurance claims.
– `file_claim`: Accepts claim details as input and simulates filing a new insurance claim.
– `get_policy_details`: Provides essential policy information, such as the policy number and coverage limits.
“`python
@p.tool
async def get_open_claims(context: p.ToolContext) -> p.ToolResult:
# … (code omitted for brevity)
@p.tool
async def file_claim(context: p.ToolContext, claim_details: str) -> p.ToolResult:
# … (code omitted for brevity)
@p.tool
async def get_policy_details(context: p.ToolContext) -> p.ToolResult:
# … (code omitted for brevity)
“`
**3. Initiating Human Handoff**
The `initiate_human_handoff` tool enables the AI agent to transfer a conversation to a human operator when it detects that the issue requires human intervention. By switching the session to manual mode, it pauses all automated responses, ensuring the human agent can take full control.
“`python
@p.tool
async def initiate_human_handoff(context: p.ToolContext, reason: str) -> p.ToolResult:
# … (code omitted for brevity)
“`
**4. Defining the Glossary**
A glossary defines key terms and phrases that the AI agent should recognize and respond to consistently. This helps maintain accuracy and brand alignment by providing predefined answers for common domain-specific queries.
“`python
async def add_domain_glossary(agent: p.Agent):
# … (code omitted for brevity)
“`
**5. Defining the Journeys**
We create two journeys: `Claim Journey` and `Policy Journey`. These journeys guide customers through specific interactions with the AI agent.
– `Claim Journey`: Helps customers report and submit a new claim.
– `Policy Journey`: Retrieves and explains customer’s insurance coverage.
“`python
async def create_claim_journey(agent: p.Agent) -> p.Journey:
# … (code omitted for brevity)
async def create_policy_journey(agent: p.Agent) -> p.Journey:
# … (code omitted for brevity)
“`
**6. Defining the Main Runner**
The `main` function initializes the Parlant server, creates an insurance support agent, adds shared terms and definitions, and defines journeys, disambiguation rules, and global guidelines.
“`python
async def main():
# … (code omitted for brevity)
if __name__ == “__main__”:
asyncio.run(main())
“`
**Running the Agent**
To start the Parlant agent locally, run:
“`bash
python agent.py
“`
This will start the agent on `http://localhost:8800`, where it will handle all conversation logic and session management.
**Human Handoff (handoff.py)**
In the next step, we’ll connect this running agent to our Streamlit-based Human Handoff interface, allowing a human operator to seamlessly join and manage live conversations using the Parlant session ID.
**1. Importing Libraries**
First, import the necessary libraries:
“`python
import asyncio
import streamlit as st
from datetime import datetime
from parleant.client import AsyncParlantClient
“`
**2. Setting Up the Parlant Client**
Once the AI agent script is running, Parlant will host its server locally (usually at `http://localhost:8800`). Here, we connect to that running instance by creating an asynchronous client.
“`python
client = AsyncParlantClient(base_url=”http://localhost:8800″)
“`
**3. Session State Management**
Streamlit’s `session_state` is used to persist data across user interactions, such as storing received messages and tracking the latest event offset to fetch new ones efficiently.
“`python
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
“`
**4. Message Rendering Function**
This function controls how messages appear in the Streamlit interface, differentiating between customers, AI, and human agents for clarity.
“`python
def render_message(message, source, participant_name, timestamp):
# … (code omitted for brevity)
“`
**5. Fetching Events from Parlant**
This asynchronous function retrieves new messages (events) from Parlant for the given session. Each event represents a message in the conversation, whether sent by the customer, AI, or human operator.
“`python
async def fetch_events(session_id):
# … (code omitted for brevity)
“`
**6. Sending Messages as Human or AI**
Two helper functions are defined to send messages: one as a human operator and another as if sent by the AI, but manually triggered by a human.
“`python
async def send_human_message(session_id: str, message: str, operator_name: str = “Tier-2 Operator”):
# … (code omitted for brevity)
async def send_message_as_ai(session_id: str, message: str):
# … (code omitted for brevity)
“`
**7. Streamlit Interface**
Finally, we build a simple, interactive Streamlit UI that allows human operators to view chat history, send messages as either human or AI, and refresh to pull new messages.
“`python
st.title(” Human Handoff Assistant”)
session_id = st.text_input(“Enter Parlant Session ID:”)
if session_id:
# … (code omitted for brevity)
“`
By following this tutorial, you’ll create a human handoff system that enables seamless collaboration between AI automation and human expertise in an AI-powered insurance agent using Parlant and Streamlit.