Skip to main content

Call Hangup

Overview​

Programmatically terminate active call sessions using the Piopiy SDK. This guide explains how to end a call using a separate trigger script while an AI agent is handling the conversation.

Prerequisites

Ensure you have completed the Telephony Quickstart to set up your environment and credentials.

1. Phone Agent Worker​

Every call control action requires a running agent worker to manage the active call stream.

phone_agent.py
import asyncio
import os
from dotenv import load_dotenv
from piopiy.agent import Agent
from piopiy.voice_agent import VoiceAgent

load_dotenv()

async def create_session(call_id=None, **kwargs):
print(f"Incoming call session: {call_id}")
voice_agent = VoiceAgent(
instructions="You are a helpful assistant.",
greeting="Hello! Thank you for calling."
)
# Configure your STT, LLM, TTS here...
await voice_agent.start()

async def main():
agent = Agent(
agent_id=os.getenv("AGENT_ID"),
agent_token=os.getenv("AGENT_TOKEN"),
create_session=create_session
)
await agent.connect()

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

2. Triggering the Hangup​

Use this standalone script to terminate an active call session. You will need the call_id of the active session.

trigger_hangup.py
import os
from dotenv import load_dotenv
from piopiy_voice import RestClient

load_dotenv()

# Initialize the RestClient
client = RestClient(token=os.environ["PIOPIY_TOKEN"])

# Hang up the call
# Optional 'cause' can be provided (default: NORMAL_CLEARING)
response = client.voice.hangup(
call_id="your_active_call_id",
cause="NORMAL_CLEARING"
)

print(response)

Execution Flow​

  1. Start the worker: python phone_agent.py
  2. Accept a call: Dial your Piopiy number and verify the AI agent is speaking.
  3. Trigger hangup: In a new terminal, run python trigger_hangup.py with the correct call_id.
  4. Verification: The call will disconnect immediately.