Generative AI

To create a Human Handoff of a powerful AI insurance interevator for the parlant and streatit

Human Handoff is an integral part of customer service – ensures that when AI reaches its boundaries, a competent person can take over the seam. In this lesson, we will use the Human Handoff for a powerful insurance agent using Parlont. You will learn how to create an interface set in the manufacturer in a man-made locator (TIER 2) to view live customer messages and directly within the same session, to close the gap between Automation and Personal Technology. Look Full codes here.

To set up the dependence

Make sure you have a valid option of Opelai API before starting. Once you have produced from your dashboard at Opelai, create a .Anv file in the root indicator of your project and save the key safely when:

OPENAI_API_KEY=your_api_key_here

This keeps your guarantees safe and prevented from getting heavier in your code code.

pip install parlant dotenv streamlit

Insurance (agent.py)

We will start by creating an agent text, which describes the conduct of AI, the chat trip, a list of names, and human path. This will create a basic idea that displays our insurance assistant in Parrant. When an agent is ready and able to increase in hand-mode, we will move to build a person-based interface, where the operator may look at the sessions, read customer messages, forming a non-sidewalk between AUNT Aunt's automation. Look Full codes here.

Loading the required libraries

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

load_dotenv()

Defining Instruction 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"
    })

Code Block introduces three tools to interact with the insurance assistant may need you.

  • This page Get_open_claims The tool represents an asynchronous work that receives the list of open insurance claims, which allows the agent to provide users to date with pending or approved claims.
  • This page file_claimim The tool welcomes the details of the claim as installation and imitates the process of completing a new insurance claim, returns the user confirmation message.

Finally, Get_polire_Details The instrument provides important policy information, such as the policy number and the Coverage Restrictions, which enables the agent to respond accurately to the insurance-related questions. Look Full codes here.

@p.tool
async def initiate_human_handoff(context: p.ToolContext, reason: str) -> p.ToolResult:
    """
    Initiate handoff to a human agent when the AI cannot adequately help the customer.
    """
    print(f"🚨 Initiating human handoff: {reason}")
    # Setting session to manual mode stops automatic AI responses
    return p.ToolResult(
        data=f"Human handoff initiated because: {reason}",
        control={
            "mode": "manual"  # Switch session to manual mode
        }
    )

This page Start_Human_handoff The tool allows AGENT AGENT to restart the conversation to a person's operator when they recognize that the dispute requires one's intervention. By changing the session in hand mode, you are suspended all the automatic responses, to ensure that a person's agent can control the full control. This tool helps keep a smooth change between AI and the useful humanitarian, whether complex or sensitive questions are held at the correct degree of technology.

Defining a list

Lists lists describes the terms and important phrases that AI agent should see and replicate. It is helpful to keep the accuracy and alignment of the product by providing a clear agent, predefined by the previously specified domain questions. Look Full codes here.

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, 9AM-6PM",
    )

To describe the trip

# ---------------------------
# Claim Journey
# ---------------------------

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"],
    )

    s0 = await journey.initial_state.transition_to(chat_state="Ask for accident details")
    s1 = await s0.target.transition_to(tool_state=file_claim, condition="Customer provides details")
    s2 = await s1.target.transition_to(chat_state="Confirm claim was submitted", condition="Claim successfully created")
    await s2.target.transition_to(state=p.END_JOURNEY, condition="Customer confirms submission")

    return journey

# ---------------------------
# Policy 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"],
    )

    s0 = await journey.initial_state.transition_to(tool_state=get_policy_details)
    await s0.target.transition_to(
        chat_state="Explain the policy coverage clearly",
        condition="Policy info is available",
    )

    await agent.create_guideline(
        condition="Customer presses for legal interpretation of coverage",
        action="Politely explain that legal advice cannot be provided",
    )
    return journey

This page Claim journey Directing customers through the completion of the new insurance claim. Collects accident details, transmitting the filing tool, confirms the transit, and keeps the time to move automatically.

This page Policy Trip It helps customers understand their insurance coverage by returning policy information and explained them clearly. Including guidelines to ensure that AI avoids providing definitions, keeping compliance and professionals. Look Full codes here.

To describe 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)."
            ),
        )

        # Add shared terms & definitions
        await add_domain_glossary(agent)

        # Journeys
        claim_journey = await create_claim_journey(agent)
        policy_journey = await create_policy_journey(agent)

        # Disambiguation rule
        status_obs = await agent.create_observation(
            "Customer mentions an issue but doesn't specify if it's a claim or policy"
        )
        await status_obs.disambiguate([claim_journey, policy_journey])

        # Global Guidelines
        await agent.create_guideline(
            condition="Customer asks about unrelated topics",
            action="Kindly redirect them to insurance-related support only",
        )

        # Human Handoff Guideline
        await agent.create_guideline(
            condition="Customer requests human assistance or AI is uncertain about the next step",
            action="Initiate human handoff and notify Tier-2 support.",
            tools=[initiate_human_handoff],
        )

        print("✅ Insurance Support Agent with Human Handoff is ready! Open the Parlant UI to chat.")

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

Running the agent

This will start the parali agent in your area, where all of the display of the discussion and session management.

In the following step, we will contact the active model on the manual manual, which allows the person's operator to join the seams and manage live conversations using Parlont Session ID. Look Full codes here.

Human Handoff (Handoff.py)

Import libraries

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

Setting up Parlant Client

When Agent's Agent text runs, the partant will handle its server in your area (usually in).

Here, we connect to the starting condition by creating asynchronous client. Look Full codes here.

client = AsyncParlantClient(base_url="")

If you run the agent and get a time ID, we will use that ID in this UI to connect and manage the specific conversation.

Management of session meetings

Streamlit'S_State session is used to persist in user communication throughout the user information – such as the message received and tracking the latest downloading event. Look Full codes here.

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

The work of offering a message

This work controls how messages appear in the streadlit interface – partition between customers, AI, and the agents of people. Look Full codes here.

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}")

Downloading events from parlint

This asynchronous activity takes new messages (events) from the temporary parlont provided.

Each event represents a message in the conversation – even if you are sent by customer, AI, or operator. Look Full codes here.

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:
            message = event.data.get("message")
            source = event.source
            participant_name = event.data.get("participant", {}).get("display_name", "Unknown")
            timestamp = getattr(event, "created", None) or event.data.get("created", "Unknown Time")
            event_id = getattr(event, "id", "Unknown ID")

            st.session_state.events.append(
                (message, source, participant_name, timestamp, event_id)
            )
            st.session_state.last_offset = max(st.session_state.last_offset, event.offset + 1)

    except Exception as e:
        st.error(f"Error fetching events: {e}")

Sending messages as a person or AI

Two-reasonable works is described to send messages:

  • One as a human operator (source = “Human_agent”)
  • One by being sent by AI, but by a person by man (source = “Human_agent_behal_of_eaget”)
  • Look Full codes here.

async def send_human_message(session_id: str, message: str, operator_name: str = "Tier-2 Operator"):
    event = await client.sessions.create_event(
        session_id=session_id,
        kind="message",
        source="human_agent",
        message=message,
        participant={
            "id": "operator-001",
            "display_name": operator_name
        }
    )
    return event


async def send_message_as_ai(session_id: str, message: str):
    event = await client.sessions.create_event(
        session_id=session_id,
        kind="message",
        source="human_agent_on_behalf_of_ai_agent",
        message=message
    )
    return event

Interface in a visual interface

Finally, we are building a simple Simplelist Ui, interacting with:

  • Add a session ID (from parlont Ui)
  • View chat history
  • Send messages as individuals or AI
  • Update to draw new messages
  • Look Full codes here.
st.title("💼 Human Handoff Assistant")

session_id = st.text_input("Enter Parlant Session ID:")

if session_id:
    st.subheader("Chat History")
    if st.button("Refresh Messages"):
        asyncio.run(fetch_events(session_id))

    for msg, source, participant_name, timestamp, event_id in st.session_state.events:
        render_message(msg, source, participant_name, timestamp)

    st.subheader("Send a Message")
    operator_msg = st.text_input("Type your message:")

    if st.button("Send as Human"):
        if operator_msg.strip():
            asyncio.run(send_human_message(session_id, operator_msg))
            st.success("Message sent as human agent ✅")
            asyncio.run(fetch_events(session_id))

    if st.button("Send as AI"):
        if operator_msg.strip():
            asyncio.run(send_message_as_ai(session_id, operator_msg))
            st.success("Message sent as AI ✅")
            asyncio.run(fetch_events(session_id))

Look Full codes here. Feel free to look our GITHUB page for tutorials, codes and letters of writing. Also, feel free to follow it Sane and don't forget to join ours 100K + ml subreddit Then sign up for Our newspaper. Wait! Do you with a telegram? Now you can join us with a telegram.


I am the student of the community engineering (2022) from Jamia Millia Islamia, New Delhi, and I am very interested in data science, especially neural networks and their application at various locations.

Follow MarkteachPost: We have added like a favorite source to Google.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button