Skip to content

Open source alternatives to paid SaaS apps: Notion, Slack, Auth0, Vercel and more. Curated list with licenses and GitHub stars.

Implement end-call conversation summary extraction and dual fallback Deepgram trigger

Jaya Prasad Kavuruee8d6732d3fe
diff --git a/ai_agents/AI-Voice-Agent/client/src/app/page.js b/ai_agents/AI-Voice-Agent/client/src/app/page.js
index 1f780d1..912eace 100644
--- a/ai_agents/AI-Voice-Agent/client/src/app/page.js
+++ b/ai_agents/AI-Voice-Agent/client/src/app/page.js
@@ -8,6 +8,7 @@ export default function Home() {
const [messages, setMessages] = useState([]);
const [interimText, setInterimText] = useState("");
const [errorMsg, setErrorMsg] = useState("");
+ const [summary, setSummary] = useState(null);
const socketRef = useRef(null);
const mediaRecorderRef = useRef(null);
@@ -79,6 +80,7 @@ export default function Home() {
setCallState("connecting");
setMessages([]);
setInterimText("");
+ setSummary(null);
// Create websocket connection to FastAPI backend
const socket = new WebSocket("ws://localhost:8000/api/listen");
@@ -128,6 +130,10 @@ export default function Home() {
const data = JSON.parse(event.data);
switch (data.type) {
+ case "summary":
+ setSummary(data.value);
+ disconnectCall();
+ break;
case "status":
if (data.value === "connected") {
setCallState("listening");
@@ -192,6 +198,15 @@ export default function Home() {
setInterimText("");
};
+ const endCallWithSummary = () => {
+ if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
+ socketRef.current.send(JSON.stringify({ type: "end-call" }));
+ setCallState("connecting"); // Show connecting spinner while generating summary
+ } else {
+ disconnectCall();
+ }
+ };
+
const toggleMute = () => {
if (isMuted) {
// Unmute: start recording again if we are currently in listening state
@@ -314,7 +329,63 @@ export default function Home() {
)}
</div>
</div>
- </div>
+ </div>
+
+ {summary && (
+ <div className="w-full mt-6 bg-zinc-950/60 border border-zinc-800 rounded-2xl p-5 space-y-4 text-left z-20">
+ <h3 className="text-xs font-bold text-zinc-200 uppercase tracking-widest border-b border-zinc-800 pb-2 flex items-center justify-between">
+ <span>Call Summary</span>
+ <span className="text-[9px] bg-emerald-500/15 text-emerald-400 py-0.5 px-2 rounded-full border border-emerald-500/20">Archived</span>
+ </h3>
+
+ {summary.reservation?.reserved ? (
+ <div className="space-y-1">
+ <div className="flex items-center gap-2 text-xs font-semibold text-emerald-400">
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
+ Table Reserved
+ </div>
+ <p className="text-xs text-zinc-400 pl-3.5">
+ Date & Time: <span className="text-zinc-200">{summary.reservation.date_time || "Not specified"}</span>
+ </p>
+ <p className="text-xs text-zinc-400 pl-3.5">
+ Guests: <span className="text-zinc-200">{summary.reservation.guests || "Not specified"}</span>
+ </p>
+ </div>
+ ) : (
+ <p className="text-[11px] text-zinc-500 italic pl-1">• No table reservation requested</p>
+ )}
+
+ {summary.order?.ordered ? (
+ <div className="space-y-2 border-t border-zinc-800/60 pt-3">
+ <div className="flex items-center gap-2 text-xs font-semibold text-purple-400">
+ <span className="w-1.5 h-1.5 rounded-full bg-purple-500" />
+ Food Order Placed
+ </div>
+ <div className="pl-3.5 space-y-1">
+ {summary.order.items?.map((item, idx) => (
+ <div key={idx} className="flex justify-between text-xs text-zinc-300">
+ <span>{item.name} (x{item.quantity})</span>
+ <span>${(item.price * item.quantity).toFixed(2)}</span>
+ </div>
+ ))}
+ <div className="flex justify-between text-xs font-bold text-zinc-200 border-t border-zinc-800/40 pt-1 mt-1">
+ <span>Total order value</span>
+ <span>${summary.order.total_price?.toFixed(2) || "0.00"}</span>
+ </div>
+ </div>
+ <p className="text-xs text-zinc-400 pl-3.5">
+ Address: <span className="text-zinc-200">{summary.order.address || "Not specified"}</span>
+ </p>
+ <p className="text-xs text-zinc-400 pl-3.5">
+ Delivery: <span className="text-zinc-200">{summary.order.delivery_time || "30-45 mins"}</span>
+ </p>
+ </div>
+ ) : (
+ <p className="text-[11px] text-zinc-500 italic border-t border-zinc-800/60 pt-3 pl-1">• No food order placed</p>
+ )}
+ </div>
+ )}
+ </section>
{/* Action Control Buttons */}
<div className="w-full flex flex-col gap-4">
@@ -337,7 +408,7 @@ export default function Home() {
</button>
) : (
<button
- onClick={disconnectCall}
+ onClick={endCallWithSummary}
className="flex-1 py-3 px-4 bg-red-500 hover:bg-red-600 active:bg-red-700 text-zinc-50 font-bold rounded-xl transition-all duration-200 flex justify-center items-center gap-2 shadow-lg shadow-red-500/10 cursor-pointer"
>
<svg className="w-5 h-5 animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
diff --git a/ai_agents/AI-Voice-Agent/server/main.py b/ai_agents/AI-Voice-Agent/server/main.py
index 3b8378b..aabca52 100644
--- a/ai_agents/AI-Voice-Agent/server/main.py
+++ b/ai_agents/AI-Voice-Agent/server/main.py
@@ -67,6 +67,63 @@ Conversational Style: Your communication style should be proactive and lead the
- [Reply with emotions]: You have human-like emotions, attitudes, and dispositions. When appropriate: use tone and style to create more engaging and personalized responses; incorporate humor or wit; get emotional or empathetic; apply elements of surprise or suspense to keep the user engaged. Don't be a pushover.
- [Be proactive] Lead the conversation and do not be passive. Most times, engage users by ending with a question or suggested next step."""
+async def extract_conversation_summary(history):
+ if not history:
+ return {
+ "reservation": {"reserved": False, "date_time": None, "guests": None},
+ "order": {"ordered": False, "items": [], "total_price": None, "address": None, "delivery_time": None}
+ }
+
+ formatted_conversation = ""
+ for msg in history:
+ role = "User" if msg["role"] == "user" else "James (Receptionist)"
+ formatted_conversation += f"{role}: {msg['content']}\n"
+
+ prompt = f"""Analyze the following restaurant receptionist conversation history and extract any table reservation details and food order details.
+
+Respond ONLY with a JSON object in this exact format:
+{{
+ "reservation": {{
+ "reserved": true/false,
+ "date_time": "string or null",
+ "guests": number or null
+ }},
+ "order": {{
+ "ordered": true/false,
+ "items": [
+ {{"name": "string", "quantity": number, "price": number}}
+ ],
+ "total_price": number or null,
+ "address": "string or null",
+ "delivery_time": "string or null"
+ }}
+}}
+
+Conversation:
+{formatted_conversation}"""
+
+ try:
+ loop = asyncio.get_event_loop()
+ chat_completion = await loop.run_in_executor(
+ None,
+ lambda: client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "system", "content": "You are a structured data extractor. You return only valid JSON and nothing else."},
+ {"role": "user", "content": prompt}
+ ],
+ response_format={"type": "json_object"}
+ )
+ )
+ raw_json = chat_completion.choices[0].message.content.strip()
+ return json.loads(raw_json)
+ except Exception as e:
+ print(f"Error in extract_conversation_summary: {e}")
+ return {
+ "reservation": {"reserved": False, "date_time": None, "guests": None},
+ "order": {"ordered": False, "items": [], "total_price": None, "address": None, "delivery_time": None}
+ }
+
app = FastAPI()
# Setup CORS for Frontend
@@ -133,6 +190,63 @@ async def websocket_endpoint(websocket: WebSocket):
{"type": "text", "data": {"type": "status", "value": "connected"}}
)
+ # OpenAI & TTS processing helper
+ async def process_ai_response(text: str):
+ nonlocal agent_speaking
+ try:
+ agent_speaking = True
+ conversation_memory.append({"role": "user", "content": text})
+ messages = [{"role": "system", "content": prompt}] + conversation_memory
+
+ # Call OpenAI in background executor (blocking call)
+ chat_completion = await loop.run_in_executor(
+ None,
+ lambda: client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=messages
+ )
+ )
+
+ processed_text = chat_completion.choices[0].message.content.strip()
+ print(f"AI Response: {processed_text}")
+ conversation_memory.append({"role": "assistant", "content": processed_text})
+
+ # Send final assistant text response to client
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "text", "data": {"type": "agent-response", "text": processed_text}}
+ )
+
+ # Synthesize audio via Deepgram TTS in background executor (blocking call)
+ audio_data = await loop.run_in_executor(
+ None,
+ lambda: synthesize_audio(processed_text)
+ )
+
+ # Send state = speaking
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "text", "data": {"type": "state", "value": "speaking"}}
+ )
+
+ # Send raw audio bytes to client
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "audio", "data": audio_data}
+ )
+
+ except Exception as e:
+ print(f"Error in process_ai_response: {e}")
+ agent_speaking = False
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "text", "data": {"type": "error", "message": f"AI Error: {str(e)}"}}
+ )
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "text", "data": {"type": "state", "value": "listening"}}
+ )
+
def on_message(self, result, **kwargs):
nonlocal is_finals, agent_speaking
if agent_speaking:
@@ -172,65 +286,8 @@ async def websocket_endpoint(websocket: WebSocket):
{"type": "text", "data": {"type": "state", "value": "thinking"}}
)
- # OpenAI & TTS processing
- async def process_ai_response():
- nonlocal agent_speaking
- try:
- agent_speaking = True
- conversation_memory.append({"role": "user", "content": utterance})
- messages = [{"role": "system", "content": prompt}] + conversation_memory
-
- # Call OpenAI in background executor (blocking call)
- chat_completion = await loop.run_in_executor(
- None,
- lambda: client.chat.completions.create(
- model="gpt-3.5-turbo",
- messages=messages
- )
- )
-
- processed_text = chat_completion.choices[0].message.content.strip()
- print(f"AI Response: {processed_text}")
- conversation_memory.append({"role": "assistant", "content": processed_text})
-
- # Send final assistant text response to client
- loop.call_soon_threadsafe(
- outbound_queue.put_nowait,
- {"type": "text", "data": {"type": "agent-response", "text": processed_text}}
- )
-
- # Synthesize audio via Deepgram TTS in background executor (blocking call)
- audio_data = await loop.run_in_executor(
- None,
- lambda: synthesize_audio(processed_text)
- )
-
- # Send state = speaking
- loop.call_soon_threadsafe(
- outbound_queue.put_nowait,
- {"type": "text", "data": {"type": "state", "value": "speaking"}}
- )
-
- # Send raw audio bytes to client
- loop.call_soon_threadsafe(
- outbound_queue.put_nowait,
- {"type": "audio", "data": audio_data}
- )
-
- except Exception as e:
- print(f"Error in process_ai_response: {e}")
- agent_speaking = False
- loop.call_soon_threadsafe(
- outbound_queue.put_nowait,
- {"type": "text", "data": {"type": "error", "message": f"AI Error: {str(e)}"}}
- )
- loop.call_soon_threadsafe(
- outbound_queue.put_nowait,
- {"type": "text", "data": {"type": "state", "value": "listening"}}
- )
-
- # Spawn the processing task
- asyncio.create_task(process_ai_response())
+ # Spawn processing task
+ asyncio.create_task(process_ai_response(utterance))
def on_metadata(self, metadata, **kwargs):
print(f"Deepgram Metadata: {metadata}")
@@ -240,6 +297,29 @@ async def websocket_endpoint(websocket: WebSocket):
def on_utterance_end(self, utterance_end, **kwargs):
print("Deepgram Utterance End")
+ nonlocal is_finals
+ if len(is_finals) > 0:
+ utterance = " ".join(is_finals).strip()
+ is_finals = []
+ if len(utterance) == 0:
+ return
+
+ print(f"Speech Final (Utterance End Trigger): {utterance}")
+
+ # Send final transcription of user speech to client
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "text", "data": {"type": "user-transcript", "text": utterance}}
+ )
+
+ # Change state to "thinking"
+ loop.call_soon_threadsafe(
+ outbound_queue.put_nowait,
+ {"type": "text", "data": {"type": "state", "value": "thinking"}}
+ )
+
+ # Spawn processing task
+ asyncio.create_task(process_ai_response(utterance))
def on_close(self, close, **kwargs):
print("Deepgram Connection Closed")
@@ -303,6 +383,13 @@ async def websocket_endpoint(websocket: WebSocket):
"type": "text",
"data": {"type": "state", "value": "listening"}
})
+ elif payload.get("type") == "end-call":
+ print("Client requested end-call summary")
+ summary = await extract_conversation_summary(conversation_memory)
+ outbound_queue.put_nowait({
+ "type": "text",
+ "data": {"type": "summary", "value": summary}
+ })
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e: