Spaces:
Sleeping
Sleeping
from flask import Flask, request, jsonify | |
from twilio.twiml.voice_response import VoiceResponse, Gather | |
import google.generativeai as genai | |
import requests | |
# Initialize the Flask app | |
app = Flask(__name__) | |
# Configure Google Generative AI | |
GOOGLE_API_KEY = "AIzaSyAs7z8GwXN-elBeq_mS-NGd..." | |
genai.configure(api_key=GOOGLE_API_KEY) | |
def generate_answer(question): | |
prompt = f""" | |
You're a calling agent who asks users if they're at home for their COD delivery | |
Question: {question} | |
""" | |
"""Generate an AI-based answer for a question.""" | |
model = genai.GenerativeModel( | |
'gemini-1.5-flash-001', | |
generation_config={"response_mime_type": "application/json"} | |
) | |
response = model.generate(prompt) | |
return response.text | |
# Endpoint to handle outbound call interactions | |
def voice_interaction(): | |
# Get the Twilio POST request data | |
incoming_data = request.form | |
user_speech = incoming_data.get("SpeechResult", "") | |
response = VoiceResponse() | |
if "goodbye" in user_speech.lower(): | |
response.say("Goodbye! Ending the call.") | |
return str(response) | |
# Generate a response using Generative AI | |
try: | |
ai_response = generate_answer(user_speech) | |
ai_text_response = ai_response.get("text", "I could not generate a response.") | |
except Exception as e: | |
ai_text_response = "I'm sorry, I encountered an error generating a response." | |
# Gather further input from the user | |
gather = Gather(input="speech", action="/voice", method="POST") | |
gather.say(ai_text_response) | |
response.append(gather) | |
return str(response) | |
if __name__ == "__main__": | |
app.run(debug=True) | |