this is how we fixed it:
def create_phone_number(self, ai_agent: AIAgent, assistant_id: str = None) -> Dict[str, Any]:
"""Create a phone number in Vapi for the given AI agent, trying fallback area codes if needed."""
if not self.is_configured():
raise Exception("Vapi not properly configured for this tenant")
from vapi.types.create_vapi_phone_number_dto import CreateVapiPhoneNumberDto
area_codes_to_try = ["509"]
last_error = None
for attempt, area_code in enumerate(area_codes_to_try):
try:
phone_data = CreateVapiPhoneNumberDto(
name=f"{ai_agent.agent_name} - {ai_agent.business_name}",
assistant_id=assistant_id,
number_desired_area_code=area_code,
)
response = self.client.phone_numbers.create(request=phone_data)
return {
"success": True,
"phone_number": response.number if hasattr(response, "number") else None,
"phone_number_id": response.id if hasattr(response, "id") else None,
"provider": response.provider if hasattr(response, "provider") else "vapi",
"response": response,
"area_code_used": area_code,
}
except Exception as e:
last_error = e
if attempt == 0:
suggested_codes = self._parse_suggested_area_codes(str(e))
if suggested_codes:
for code in suggested_codes:
if code not in area_codes_to_try:
area_codes_to_try.append(code)
else:
break
continue
return {
"success": False,
"error": str(last_error),
"phone_number": None,
"phone_number_id": None,
"attempted_area_codes": area_codes_to_try,
}