Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,56 @@
|
|
1 |
from flask import Flask, request
|
|
|
2 |
from twilio.twiml.messaging_response import MessagingResponse
|
3 |
import openai
|
4 |
import os
|
5 |
|
6 |
app = Flask(__name__)
|
7 |
|
8 |
-
#
|
9 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
@app.route("/webhook", methods=['POST'])
|
12 |
def whatsapp_webhook():
|
|
|
13 |
incoming_msg = request.values.get('Body', '').strip()
|
|
|
|
|
|
|
14 |
response_text = get_gpt4_response(incoming_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
twilio_resp = MessagingResponse()
|
16 |
-
twilio_resp.message(
|
17 |
return str(twilio_resp)
|
18 |
|
19 |
def get_gpt4_response(message):
|
|
|
|
|
|
|
20 |
try:
|
21 |
response = openai.ChatCompletion.create(
|
22 |
model="gpt-4",
|
23 |
-
messages=[{"role": "user", "content": message}]
|
|
|
24 |
)
|
25 |
return response.choices[0].message['content']
|
26 |
except Exception as e:
|
27 |
print(f"Error con la API de GPT-4: {e}")
|
28 |
-
return "
|
29 |
|
30 |
if __name__ == "__main__":
|
|
|
31 |
app.run(host='0.0.0.0', port=7860)
|
|
|
1 |
from flask import Flask, request
|
2 |
+
from twilio.rest import Client
|
3 |
from twilio.twiml.messaging_response import MessagingResponse
|
4 |
import openai
|
5 |
import os
|
6 |
|
7 |
app = Flask(__name__)
|
8 |
|
9 |
+
# Configuraci贸n de las claves de API desde las variables de entorno
|
10 |
openai.api_key = os.getenv("OPENAI_API_KEY")
|
11 |
+
twilio_account_sid = os.getenv("TWILIO_ACCOUNT_SID")
|
12 |
+
twilio_auth_token = os.getenv("TWILIO_AUTH_TOKEN")
|
13 |
+
twilio_whatsapp_number = os.getenv("TWILIO_WHATSAPP_NUMBER")
|
14 |
+
|
15 |
+
# Inicializar el cliente de Twilio
|
16 |
+
client = Client(twilio_account_sid, twilio_auth_token)
|
17 |
|
18 |
@app.route("/webhook", methods=['POST'])
|
19 |
def whatsapp_webhook():
|
20 |
+
# Obtener el mensaje entrante y el n煤mero de tel茅fono del remitente
|
21 |
incoming_msg = request.values.get('Body', '').strip()
|
22 |
+
from_number = request.values.get('From', '').strip()
|
23 |
+
|
24 |
+
# Generar una respuesta usando GPT-4
|
25 |
response_text = get_gpt4_response(incoming_msg)
|
26 |
+
|
27 |
+
# Enviar la respuesta de vuelta al usuario en WhatsApp a trav茅s de Twilio
|
28 |
+
client.messages.create(
|
29 |
+
body=response_text,
|
30 |
+
from_=twilio_whatsapp_number,
|
31 |
+
to=from_number
|
32 |
+
)
|
33 |
+
|
34 |
+
# Respuesta TwiML (opcional, solo confirma la recepci贸n del mensaje a Twilio)
|
35 |
twilio_resp = MessagingResponse()
|
36 |
+
twilio_resp.message("Procesando tu mensaje...")
|
37 |
return str(twilio_resp)
|
38 |
|
39 |
def get_gpt4_response(message):
|
40 |
+
"""
|
41 |
+
Env铆a el mensaje del usuario a GPT-4 y devuelve la respuesta generada.
|
42 |
+
"""
|
43 |
try:
|
44 |
response = openai.ChatCompletion.create(
|
45 |
model="gpt-4",
|
46 |
+
messages=[{"role": "user", "content": message}],
|
47 |
+
temperature=0.7 # Controla la creatividad de la respuesta
|
48 |
)
|
49 |
return response.choices[0].message['content']
|
50 |
except Exception as e:
|
51 |
print(f"Error con la API de GPT-4: {e}")
|
52 |
+
return "Lo siento, hubo un problema al procesar tu mensaje. Int茅ntalo de nuevo m谩s tarde."
|
53 |
|
54 |
if __name__ == "__main__":
|
55 |
+
# Ejecuta la app en el puerto 7860, que es el recomendado para Spaces en Hugging Face
|
56 |
app.run(host='0.0.0.0', port=7860)
|