]> git.angelumana.com Git - diane/.git/commitdiff
update .gitignore and add redis client
authoribidyouadu <angel.d.umana@gmail.com>
Sun, 20 Aug 2023 00:55:06 +0000 (19:55 -0500)
committeribidyouadu <angel.d.umana@gmail.com>
Sun, 20 Aug 2023 00:55:06 +0000 (19:55 -0500)
.gitignore
main.py

index 0bbae6f580bde068ce8fe6adc30ff84d7bdb95ee..0be4a4a322a7965cd8e0d7139c5a00129ab5a6c6 100644 (file)
@@ -1,3 +1,4 @@
 .DS_Store
 __pycache__/
 .env
+*.rdb
\ No newline at end of file
diff --git a/main.py b/main.py
index 0f0456740c998bcb8034831dc0e9c47336e052f2..34866dbe4c422959bf4370c4fa02b98f321cf44a 100644 (file)
--- a/main.py
+++ b/main.py
@@ -4,37 +4,66 @@ from twilio.twiml.messaging_response import MessagingResponse
 import random
 import os
 import openai
+import redis
 from settings import OPENAI_API_KEY, OPENWEATHER_API_KEY
 
 openai.api_key = OPENAI_API_KEY
 
 app = Flask(__name__)
 
+# Initiate redis connection
+r = redis.Redis(host="localhost", port=6379, decode_responses=True)
+
+# Wipe previous conversation data and start a new one with assistant prompt
+conversation_key = "main"
+r.delete(conversation_key)
+prompt = {
+    "role": "system",
+    "content": "You are a helpful assistant named Diane."
+}
+r.rpush(conversation_key, prompt)
+
 @app.route("/", methods=["POST"])
 
 def main():
-    input_msg = request.values.get("Body", "")
+    # Get user input
+    input_text = request.values.get("Body", "")
+
+    # Add to payload for OpenAI API
+    input_message = {
+        "role": "user",
+        "content": input_text
+    }
+
+    # 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)
+    print(messages)
+    r.rpush(conversation_key, input_message)
+
+    # Call OpenAI API
     openai_res = openai.ChatCompletion.create(
         model="gpt-3.5-turbo",
-        messages=[
-            {
-                "role": "system",
-                "content": "You are a helpful assistant named Diane."
-            },
-            {
-                "role": "user",
-                "content": input_msg
-            }
-        ],
+        messages=messages,
         max_tokens=256,
         temperature=0.6
     )
 
-    msg.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
+    }
+    r.rpush(conversation_key, output_message)
 
+    # Return OpenAI message
+    msg.body(output_text)
     return str(response)
 
 if __name__ == "__main__":