Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tear down end call param #304

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion vocode/streaming/telephony/conversation/call.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from app.lib.telephony.client.twilio_client import TwilioClient
from app.lib.telephony.client.vonage_client import VonageClient
from fastapi import WebSocket
from enum import Enum
import logging
from typing import Optional, TypeVar, Union
from vocode.streaming.agent.factory import AgentFactory
from vocode.streaming.models.agent import AgentConfig
from vocode.streaming.models.events import PhoneCallEndedEvent
from vocode.streaming.models.telephony import TwilioConfig, VonageConfig
from vocode.streaming.output_device.vonage_output_device import VonageOutputDevice

from vocode.streaming.streaming_conversation import StreamingConversation
Expand All @@ -16,11 +19,13 @@
TranscriberConfig,
)
from vocode.streaming.synthesizer.factory import SynthesizerFactory
from vocode.streaming.telephony.client.base_telephony_client import BaseTelephonyClient
from vocode.streaming.telephony.config_manager.base_config_manager import (
BaseConfigManager,
)
from vocode.streaming.telephony.constants import DEFAULT_SAMPLING_RATE
from vocode.streaming.streaming_conversation import StreamingConversation
from vocode.streaming.telephony.conversation import create_telephony_client
from vocode.streaming.transcriber.factory import TranscriberFactory
from vocode.streaming.utils.events_manager import EventsManager
from vocode.streaming.utils.conversation_logger_adapter import wrap_logger
Expand All @@ -34,6 +39,7 @@
class Call(StreamingConversation[TelephonyOutputDeviceType]):
def __init__(
self,
telephony_id: str,
from_phone: str,
to_phone: str,
base_url: str,
Expand All @@ -49,6 +55,7 @@ def __init__(
events_manager: Optional[EventsManager] = None,
logger: Optional[logging.Logger] = None,
):
self.telephony_id = telephony_id
conversation_id = conversation_id or create_conversation_id()
logger = wrap_logger(
logger or logging.getLogger(__name__),
Expand All @@ -70,6 +77,22 @@ def __init__(
logger=logger,
)

def get_telephony_client_config(self) -> Union[TwilioConfig, VonageConfig]:
raise NotImplementedError

def create_telephony_client(self) -> BaseTelephonyClient:
telephony_client_config = self.get_telephony_client_config()
if isinstance(telephony_client_config, TwilioConfig):
return TwilioClient(
base_url=self.base_url, twilio_config=telephony_client_config
)
elif isinstance(telephony_client_config, VonageConfig):
return VonageClient(
base_url=self.base_url, vonage_config=telephony_client_config
)
else:
raise ValueError("No telephony config provided")

def attach_ws(self, ws: WebSocket):
self.logger.debug("Trying to attach WS to outbound call")
self.output_device.ws = ws
Expand All @@ -78,6 +101,9 @@ def attach_ws(self, ws: WebSocket):
async def attach_ws_and_start(self, ws: WebSocket):
raise NotImplementedError

async def tear_down(self):
async def tear_down(self, end_call: bool = True):
self.events_manager.publish_event(PhoneCallEndedEvent(conversation_id=self.id))
await self.terminate()
if end_call:
telephony_client = self.create_telephony_client()
await telephony_client.end_call(self.telephony_id)
27 changes: 16 additions & 11 deletions vocode/streaming/telephony/conversation/twilio_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
from enum import Enum
import json
import logging
from typing import Optional
from typing import Optional, Union
from vocode import getenv
from vocode.streaming.agent.factory import AgentFactory
from vocode.streaming.models.agent import AgentConfig
from vocode.streaming.models.events import PhoneCallConnectedEvent

from vocode.streaming.models.telephony import TwilioConfig
from vocode.streaming.models.telephony import TwilioConfig, VonageConfig
from vocode.streaming.output_device.twilio_output_device import TwilioOutputDevice
from vocode.streaming.models.synthesizer import (
SynthesizerConfig,
Expand Down Expand Up @@ -53,6 +53,7 @@ def __init__(
logger: Optional[logging.Logger] = None,
):
super().__init__(
twilio_sid,
from_phone,
to_phone,
base_url,
Expand Down Expand Up @@ -80,6 +81,9 @@ def __init__(
self.twilio_sid = twilio_sid
self.latest_media_timestamp = 0

def get_telephony_client_config(self):
return self.twilio_config

def create_state_manager(self) -> TwilioCallStateManager:
return TwilioCallStateManager(self)

Expand All @@ -90,10 +94,16 @@ async def attach_ws_and_start(self, ws: WebSocket):
twilio_call = twilio_call_ref.fetch()

if self.twilio_config.record:
recordings_create_params = self.twilio_config.extra_params.get("recordings_create_params") if self.twilio_config.extra_params else None
recording = twilio_call_ref.recordings.create(
**recordings_create_params
) if recordings_create_params else twilio_call_ref.recordings.create()
recordings_create_params = (
self.twilio_config.extra_params.get("recordings_create_params")
if self.twilio_config.extra_params
else None
)
recording = (
twilio_call_ref.recordings.create(**recordings_create_params)
if recordings_create_params
else twilio_call_ref.recordings.create()
)
self.logger.info(f"Recording: {recording.sid}")

if twilio_call.answered_by in ("machine_start", "fax"):
Expand Down Expand Up @@ -153,8 +163,3 @@ async def handle_ws_message(self, message) -> Optional[PhoneCallWebsocketAction]
self.logger.debug("Stopping...")
return PhoneCallWebsocketAction.CLOSE_WEBSOCKET
return None

def mark_terminated(self):
super().mark_terminated()
asyncio.create_task(self.telephony_client.end_call(self.twilio_sid))

4 changes: 4 additions & 0 deletions vocode/streaming/telephony/conversation/vonage_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def __init__(
logger: Optional[logging.Logger] = None,
):
super().__init__(
vonage_uuid,
from_phone,
to_phone,
base_url,
Expand Down Expand Up @@ -85,6 +86,9 @@ def __init__(
sampling_rate=VONAGE_SAMPLING_RATE, blocksize=VONAGE_CHUNK_SIZE // 2
)

def get_telephony_client_config(self):
return self.vonage_config

def create_state_manager(self) -> VonageCallStateManager:
return VonageCallStateManager(self)

Expand Down
12 changes: 9 additions & 3 deletions vocode/streaming/utils/state_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ def set_transcriber_endpointing_config(self, endpointing_config: EndpointingConf
self._conversation.transcriber.get_transcriber_config().endpointing_config = (
endpointing_config
)

def disable_synthesis(self):
self._conversation.synthesis_enabled = False

def enable_synthesis(self):
self._conversation.synthesis_enabled = True

async def terminate_conversation(self):
await self._conversation.terminate()

Expand All @@ -37,8 +37,14 @@ def __init__(self, call: "VonageCall"):
super().__init__(call)
self._call = call

async def terminate_conversation(self):
await self._call.tear_down()


class TwilioCallStateManager(ConversationStateManager):
def __init__(self, call: "TwilioCall"):
super().__init__(call)
self._call = call

async def terminate_conversation(self):
await self._call.tear_down()
Loading