From 12a68c587aa2144ab00762d92e1c0b94de5fa4b2 Mon Sep 17 00:00:00 2001 From: ibidyouadu Date: Sat, 26 Aug 2023 21:46:05 -0500 Subject: [PATCH] switched out flask in favor of fastapi --- .gitignore | 3 ++- main.py | 41 ++++++++++++++++------------------------- requirements.txt | 12 ++++++++++++ settings.py | 6 +++++- utils.py | 22 ++++++++++++++++++++++ 5 files changed, 57 insertions(+), 27 deletions(-) create mode 100644 utils.py diff --git a/.gitignore b/.gitignore index 0be4a4a..869291f 100644 --- a/.gitignore +++ b/.gitignore @@ -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 6a54e5f..6bc11b6 100644 --- 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 diff --git a/requirements.txt b/requirements.txt index a7f6eaf..116ee45 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/settings.py b/settings.py index 9947170..46e400c 100644 --- a/settings.py +++ b/settings.py @@ -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 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}") -- 2.43.0