]> git.angelumana.com Git - diane/.git/commitdiff
switched out flask in favor of fastapi
authoribidyouadu <angel.d.umana@gmail.com>
Sun, 27 Aug 2023 02:46:05 +0000 (21:46 -0500)
committeribidyouadu <angel.d.umana@gmail.com>
Sun, 27 Aug 2023 02:46:05 +0000 (21:46 -0500)
.gitignore
main.py
requirements.txt
settings.py
utils.py [new file with mode: 0644]

index 0be4a4a322a7965cd8e0d7139c5a00129ab5a6c6..869291f27de88e5c514deec1121ed972fe073b1a 100644 (file)
@@ -1,4 +1,5 @@
 .DS_Store
 __pycache__/
 .env
-*.rdb
\ No newline at end of file
+*.rdb
+*.log
diff --git a/main.py b/main.py
index 6a54e5f35ee0fd2466fc0b3f8a5b716e468e9157..6bc11b6a256a3a70ce5c637163200307e59d4907 100644 (file)
--- a/main.py
+++ b/main.py
@@ -1,16 +1,14 @@
-from flask import Flask, request
-import requests
-from twilio.twiml.messaging_response import MessagingResponse
-import random
-import os
+from fastapi import FastAPI, Form, Depends
+from twilio.rest import Client
 import openai
 import redis
 import json
-from settings import OPENAI_API_KEY, OPENWEATHER_API_KEY
+from settings import OPENAI_API_KEY, OPENWEATHER_API_KEY, TO_NUMBER
+from utils import send_message, logger
 
 openai.api_key = OPENAI_API_KEY
 
-app = Flask(__name__)
+app = FastAPI()
 
 # Initiate redis connection
 r = redis.Redis(host="localhost", port=6379, decode_responses=True)
@@ -26,48 +24,41 @@ init_payload = json.dumps(prompt)
 r.rpush(conversation_key, init_payload)
 
 
-@app.route("/", methods=["POST"])
-def main():
-    # Get user input
-    input_text = request.values.get("Body", "")
-
+@app.post("/")
+async def reply(Body: str=Form()):
     # Add to payload for OpenAI API
     input_message = {
         "role": "user",
-        "content": input_text
+        "content": Body
     }
 
-    # Twilio API. We will put text content in `msg` attributes and return a string representation of `response``
-    response = MessagingResponse()
-    msg = response.message()
-
     # Retrieve conversation from redis in format ready to post to OpenAI. Update redis db with new input
     conversation = r.lrange(conversation_key, 0, -1)
     messages = [eval(message) for message in conversation]
     messages.append(input_message)
     input_payload = json.dumps(input_message)
     r.rpush(conversation_key, input_payload)
+    logger.info("Stored the user request in the database.")
 
-    # Call OpenAI API
+    # Call OpenAI API and extract GPT response
     openai_res = openai.ChatCompletion.create(
         model="gpt-3.5-turbo",
         messages=messages,
         max_tokens=256,
         temperature=0.6
     )
+    output_body = openai_res.choices[0].message.content
 
     # Update redis db with OpenAI response
-    output_text = openai_res.choices[0].message.content
     output_message = {
         "role": "assistant",
-        "content": output_text
+        "content": output_body
     }
     output_payload = json.dumps(output_message)
     r.rpush(conversation_key, output_payload)
+    logger.info("Stored the response in the database.")
 
-    # Return OpenAI message
-    msg.body(output_text)
-    return str(response)
+    # Send response to user
+    send_message(TO_NUMBER, output_body)
 
-if __name__ == "__main__":
-    app.run()
\ No newline at end of file
+    return True
\ No newline at end of file
index a7f6eaf9717267ff5b1ef406f06f08999105fe4c..116ee45eeff5cb75a59f86f6b261974b88f390ce 100644 (file)
@@ -1,14 +1,19 @@
 aiohttp==3.8.4
 aiohttp-retry==2.8.3
 aiosignal==1.3.1
+annotated-types==0.5.0
+anyio==3.7.1
 async-timeout==4.0.2
 attrs==23.1.0
 blinker==1.6.2
 certifi==2023.5.7
 charset-normalizer==3.2.0
 click==8.1.4
+exceptiongroup==1.1.3
+fastapi==0.103.0
 Flask==2.3.2
 frozenlist==1.3.3
+h11==0.14.0
 idna==3.4
 importlib-metadata==6.8.0
 itsdangerous==2.1.2
@@ -16,14 +21,21 @@ Jinja2==3.1.2
 MarkupSafe==2.1.3
 multidict==6.0.4
 openai==0.27.8
+pydantic==2.3.0
+pydantic_core==2.6.3
 PyJWT==2.7.0
 python-dotenv==1.0.0
+python-multipart==0.0.6
 pytz==2023.3
 redis==4.6.0
 requests==2.31.0
+sniffio==1.3.0
+starlette==0.27.0
 tqdm==4.65.0
 twilio==8.4.0
+typing_extensions==4.7.1
 urllib3==2.0.3
+uvicorn==0.23.2
 Werkzeug==2.3.6
 yarl==1.9.2
 zipp==3.16.0
index 99471708bed60ae2d9bca39b05d4aad7a24a2be1..46e400cbc69ec359462f74336caf1dd1de39134d 100644 (file)
@@ -4,4 +4,8 @@ from dotenv import load_dotenv
 load_dotenv()
 
 OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
-OPENWEATHER_API_KEY = os.environ["OPENWEATHER_API_KEY"]
\ No newline at end of file
+OPENWEATHER_API_KEY = os.environ["OPENWEATHER_API_KEY"]
+TWILIO_ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"]
+TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
+TWILIO_NUMBER = os.environ["TWILIO_NUMBER"]
+TO_NUMBER = os.environ["TO_NUMBER"]
\ No newline at end of file
diff --git a/utils.py b/utils.py
new file mode 100644 (file)
index 0000000..bea97c9
--- /dev/null
+++ b/utils.py
@@ -0,0 +1,22 @@
+import logging
+from twilio.rest import Client
+from dotenv import load_dotenv
+from settings import TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_NUMBER
+
+client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
+
+# Set up logging
+logging.basicConfig(filename="log.log", encoding="UTF-8", level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+# Sending message logic through Twilio Messaging API
+def send_message(to_number, body_text):
+    try:
+        message = client.messages.create(
+            from_=f"whatsapp:{TWILIO_NUMBER}",
+            body=body_text,
+            to=f"whatsapp:{to_number}"
+            )
+        logger.info(f"Message sent to {to_number}: {message.body}")
+    except Exception as e:
+        logger.error(f"Error sending message to {to_number}: {e}")