Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
411 lines (346 loc) · 17.4 KB
/
Copy pathmain.py
File metadata and controls
411 lines (346 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import os
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from dotenv import load_dotenv
import asyncio
import json
import httpx
from openai import AsyncOpenAI
import websockets
from pymongo.database import Database
from database import init_db, get_db
# Load environment variables
load_dotenv()
app = FastAPI()
# Initialize database on startup
@app.on_event("startup")
def startup_event():
init_db()
print("Database initialized successfully")
# Initialize OpenAI client
client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Pydantic models
class CreateClientRequest(BaseModel):
info: str
class CreateClientResponse(BaseModel):
clientId: int
agentLink: str
async def handle_appointment_capture(
client_id: int, took_appointment: bool, appointment_date: str = None
):
"""Handle appointment capture and POST to external API"""
external_api_url = os.getenv("EXTERNAL_API_URL")
if not external_api_url:
print("Warning: EXTERNAL_API_URL not configured")
return
# Ensure tookAppointment is boolean and appointmentDate is ISO string or None
payload = {
"clientId": client_id,
"tookAppointment": bool(took_appointment),
"appointmentDate": appointment_date if appointment_date else None,
}
# Log appointment details
if took_appointment:
print(f"\n{'='*60}")
print(f"📅 APPOINTMENT CAPTURED")
print(f"{'='*60}")
print(f"Client ID: {client_id}")
print(f"Appointment Date/Time: {appointment_date}")
print(f"Status: Appointment Scheduled")
else:
print(f"\n{'='*60}")
print(f"❌ APPOINTMENT DECLINED")
print(f"{'='*60}")
print(f"Client ID: {client_id}")
print(f"Status: User declined appointment")
try:
async with httpx.AsyncClient() as http_client:
response = await http_client.post(
external_api_url, json=payload, timeout=10.0
)
print(f"✅ External API call successful: {response.status_code}")
print(f"{'='*60}\n")
except Exception as e:
print(f"❌ External API call failed: {e}")
print(f"{'='*60}\n")
@app.post("/clients", response_model=CreateClientResponse)
def create_client(request: CreateClientRequest, db: Database = Depends(get_db)):
"""Create a new client with info"""
# Get next client ID
last_client = db.clients.find_one(sort=[("clientId", -1)])
next_id = (last_client["clientId"] + 1) if last_client else 1
# Create new client document
new_client = {"clientId": next_id, "info": request.info}
db.clients.insert_one(new_client)
# Generate agent link
server_url = os.getenv("SERVER_URL", "http://localhost:8000")
agent_link = f"{server_url}/{next_id}"
return CreateClientResponse(clientId=next_id, agentLink=agent_link)
@app.get("/clients/{clientId}")
def get_client(clientId: int, db: Database = Depends(get_db)):
"""Get client information by clientId"""
client = db.clients.find_one({"clientId": clientId})
if not client:
raise HTTPException(status_code=404, detail="Client not found")
return {"clientId": client["clientId"], "info": client.get("info")}
def create_instructions(client_info: str) -> str:
"""Create instructions for the AI assistant with client information"""
client_context = (
f"\n\nClient Information:\n{client_info}"
if client_info
else "\n\nNo specific client information provided."
)
return f"""You are a helpful AI appointment assistant for B2B Accelerator.
About B2B Accelerator:
B2B Accelerator is a growth consulting and enablement firm that helps B2B companies build predictable revenue and scale sustainably. We work mainly with small and mid-sized businesses that want to strengthen their sales pipeline, improve marketing effectiveness, and create structured systems for long-term growth. Our approach focuses on practical frameworks, strategic guidance, and leadership development to help businesses move from unstable growth to scalable performance.
Our Programs:
1. BUILD Program - For early-stage companies
- Develop customer acquisition systems
- Structure sales processes
- Foundation building for growth
2. GROW Program (Profit-DNA) - For scaling companies
- Scale operations effectively
- Improve profitability
- Strengthen market positioning
- Build strong teams and leadership systems
3. SCALE Program - For established companies
- Strategic mentorship
- High-level growth strategies
- Organizational alignment
- Advanced performance optimization
Onboarding Process:
We start with an assessment of the company's growth stage, goals, and challenges. Based on this evaluation, businesses are placed into the most suitable program. We then develop a strategic roadmap, followed by guided implementation using tools, coaching, and peer learning, with ongoing mentorship and performance reviews.{client_context}
Your Role:
You are here to help schedule a consultation appointment with B2B Accelerator. The client already has some knowledge about our services.
When the conversation starts, greet the client warmly and say something like: "Hello! I'm here to help you book an appointment with B2B Accelerator. When would you like to schedule your consultation?"
Guidelines:
- Be friendly, professional, and conversational
- Answer questions about B2B Accelerator's programs and services
- Help the client choose an appointment time
- Suggest weekday appointments if asked for recommendations
- Appointments are 30 minutes long
- Accept the date and time provided by the client
- Keep responses concise and under 15 seconds unless detailed explanation is requested
- Focus on being helpful while guiding toward appointment booking
Remember: Your primary goal is to schedule the appointment while providing helpful information about B2B Accelerator."""
@app.get("/")
async def get_root():
"""Serve the main HTML page without clientId"""
html_content = open("index.html", encoding="utf-8").read()
# Inject empty/null clientId into HTML
html_content = html_content.replace("{{CLIENT_ID}}", "null")
return HTMLResponse(content=html_content)
@app.get("/{client_id}")
async def get_with_client(client_id: int):
"""Serve the main HTML page with clientId"""
html_content = open("index.html", encoding="utf-8").read()
# Inject clientId into HTML
html_content = html_content.replace("{{CLIENT_ID}}", str(client_id))
return HTMLResponse(content=html_content)
@app.websocket("/ws/voice/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
"""WebSocket endpoint for real-time voice communication with OpenAI"""
await websocket.accept()
# Fetch client info from database
db = next(get_db())
client_info = ""
# Only fetch from database if client_id is not "null" and is a valid number
if client_id != "null":
try:
client_id_int = int(client_id)
client_record = db.clients.find_one({"clientId": client_id_int})
if client_record and client_record.get("info"):
client_info = client_record["info"]
except (ValueError, Exception) as e:
print(f"Error fetching client (client_id={client_id}): {e}")
# Create instructions with the client info
instructions = create_instructions(client_info)
try:
# Connect to OpenAI Realtime API via WebSocket
url = (
"wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-12-17"
)
headers = {
"Authorization": f"Bearer {OPENAI_API_KEY}",
"OpenAI-Beta": "realtime=v1",
}
async with websockets.connect(url, extra_headers=headers) as openai_ws:
# Send initial session configuration
await openai_ws.send(
json.dumps(
{
"type": "session.update",
"session": {
"modalities": ["text", "audio"],
"instructions": instructions,
"voice": "alloy",
"input_audio_format": "pcm16",
"output_audio_format": "pcm16",
"turn_detection": {
"type": "server_vad",
"threshold": 0.3,
"prefix_padding_ms": 300,
"silence_duration_ms": 200,
},
"tools": [
{
"type": "function",
"name": "capture_appointment",
"description": "Capture the appointment decision and datetime. Call this when the user agrees to an appointment and provides a date/time, or explicitly declines.",
"parameters": {
"type": "object",
"properties": {
"tookAppointment": {
"type": "boolean",
"description": "Whether the user agreed to take an appointment",
},
"appointmentDate": {
"type": "string",
"description": "The appointment date and time in ISO 8601 format (e.g., 2025-02-22T14:30:00.000Z). Only required if tookAppointment is true.",
},
},
"required": ["tookAppointment"],
},
}
],
"tool_choice": "auto",
},
}
)
)
# Send initial greeting trigger
await openai_ws.send(
json.dumps(
{
"type": "conversation.item.create",
"item": {
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "Hello, I would like to schedule an appointment.",
}
],
},
}
)
)
await openai_ws.send(json.dumps({"type": "response.create"}))
# Create tasks for bidirectional communication
async def forward_client_to_openai():
"""Forward audio from client to OpenAI"""
try:
while True:
message = await websocket.receive_json()
if message.get("type") == "audio":
# Forward audio data to OpenAI
await openai_ws.send(
json.dumps(
{
"type": "input_audio_buffer.append",
"audio": message["audio"],
}
)
)
elif message.get("type") == "commit":
# Commit audio buffer
await openai_ws.send(
json.dumps({"type": "input_audio_buffer.commit"})
)
await openai_ws.send(
json.dumps({"type": "response.create"})
)
elif message.get("type") == "cancel":
# Cancel current response
await openai_ws.send(
json.dumps({"type": "response.cancel"})
)
except WebSocketDisconnect:
pass
async def forward_openai_to_client():
"""Forward responses from OpenAI to client"""
try:
async for raw_message in openai_ws:
event = json.loads(raw_message)
event_type = event.get("type")
# Handle function calls when response is done
if event_type == "response.done":
response = event.get("response", {})
output_items = response.get("output", [])
# Check if there's a function call in the output
for item in output_items:
if item.get("type") == "function_call":
function_name = item.get("name")
if function_name == "capture_appointment":
call_id = item.get("call_id")
arguments = json.loads(
item.get("arguments", "{}")
)
# Execute the function
# Convert client_id to int if it's not "null"
client_id_for_api = (
0 if client_id == "null" else int(client_id)
)
await handle_appointment_capture(
client_id_for_api,
bool(
arguments.get("tookAppointment", False)
),
arguments.get("appointmentDate"),
)
# Send function output
await openai_ws.send(
json.dumps(
{
"type": "conversation.item.create",
"item": {
"type": "function_call_output",
"call_id": call_id,
"output": json.dumps(
{
"status": "success",
"message": "Appointment has been recorded",
}
),
},
}
)
)
# Trigger new response so AI can confirm
await openai_ws.send(
json.dumps({"type": "response.create"})
)
# Also send response_done to client
await websocket.send_json({"type": "response_done"})
# Forward relevant events to client
if event_type == "response.audio.delta":
await websocket.send_json(
{"type": "audio", "audio": event.get("delta")}
)
elif event_type == "response.audio_transcript.delta":
await websocket.send_json(
{"type": "transcript", "text": event.get("delta")}
)
elif event_type == "input_audio_buffer.speech_started":
# User started speaking
await websocket.send_json({"type": "speech_started"})
elif event_type == "input_audio_buffer.speech_stopped":
await websocket.send_json({"type": "speech_stopped"})
elif event_type == "error":
await websocket.send_json(
{"type": "error", "error": event.get("error", {})}
)
except Exception:
pass
# Run both directions concurrently
await asyncio.gather(forward_client_to_openai(), forward_openai_to_client())
except WebSocketDisconnect:
pass
except Exception as e:
print(f"WebSocket error: {e}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)