-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
229 lines (175 loc) · 6.92 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
import speech_recognition as sr
from pydub import AudioSegment
from flask import Flask, request
from dotenv import load_dotenv
from flask_cors import cross_origin
from celery import Celery
import requests
import openai
import os
import uuid
app = Flask(__name__)
# Load environment variables
load_dotenv()
# Initialize Celery
celery = Celery(app.name, broker=os.getenv('CELERY_BROKER_URL'))
celery.conf.update(result_backend=os.getenv('CELERY_RESULT_BACKEND'), task_serializer='json', result_serializer='json',
accept_content=['json'])
# Initialize the OpenAI API
openai.api_key = os.getenv("OPEN_AI_KEY")
# Store the last 10 conversations for each user
conversations = {}
# Initialize the Twilio API
account_sid = os.getenv("TWILIO_ACCOUNT_SID")
auth_token = os.getenv("TWILIO_AUTH_TOKEN")
twilio_client = Client(account_sid, auth_token)
SYSTEM_PROMPT = os.getenv("SYSTEM_PROMPT")
FLASK_HOST = os.getenv("FLASK_HOST")
FLASK_PORT = os.getenv("FLASK_PORT")
def send_response(text, to_number, media_url=None):
text_length = len(text)
if text_length < 1600:
return twilio_client.messages.create(
body=text,
from_=os.getenv("TWILIO_PHONE_NUMBER"),
to=to_number,
media_url=media_url
)
else:
# Split the response text into chunks of 1600 characters or less
split_text = [text[i:i + 1600] for i in range(0, len(text), 1600)]
# Send each chunk as a separate message
for chunk in split_text:
twilio_client.messages.create(
body=chunk,
from_=os.getenv("TWILIO_PHONE_NUMBER"),
to=to_number,
media_url=media_url
)
@celery.task
def generate_response_chat(message_list, to_number):
print("message_list:", message_list) # Add this line to debug the message_list content
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system",
"content": SYSTEM_PROMPT},
] + message_list
)
response_text = response["choices"][0]["message"]["content"].strip()
if response_text is None:
response_text = "I'm sorry, I couldn't generate a response for that."
send_response(response_text, to_number) # No need to pass media_url parameter
return response_text
def conversation_tracking(text_message, user_id, to_number):
"""
Make remember all the conversation
:param old_model: Open AI model
:param user_id: telegram user id
:param text_message: text message
:return: str
"""
# Get the last 10 conversations and responses for this user
user_conversations = conversations.get(user_id, {'conversations': [], 'responses': []})
user_messages = user_conversations['conversations'][-9:] + [text_message]
user_responses = user_conversations['responses'][-9:]
# Store the updated conversations and responses for this user
conversations[user_id] = {'conversations': user_messages, 'responses': user_responses}
# Construct the full conversation history in the user:assistant, " format
conversation_history = []
for i in range(min(len(user_messages), len(user_responses))):
conversation_history.append({
"role": "user", "content": user_messages[i]
})
conversation_history.append({
"role": "assistant", "content": user_responses[i]
})
total_length = sum(len(message["content"]) for message in conversation_history)
if total_length > 3800:
clear_conversation_history(user_id)
# Add last prompt
conversation_history.append({
"role": "user", "content": text_message
})
# Generate response
# Generate response
task = generate_response_chat.apply_async(args=[conversation_history, to_number])
response = task.get()
# Add the response to the user's responses
user_responses.append(response)
# Store the updated conversations and responses for this user
conversations[user_id] = {'conversations': user_messages, 'responses': user_responses}
return response
def clear_conversation_history(user_id):
"""
Clear the conversation history for a specific user
:param user_id: user id
:return: None
"""
if user_id in conversations:
conversations[user_id] = {'conversations': [], 'responses': []}
return True
return False
def save_voice_message_to_wav(media_content, filename):
with open(filename + ".ogg", "wb") as f:
f.write(media_content)
sound = AudioSegment.from_file(filename + ".ogg", format="ogg")
sound.export(filename + ".wav", format="wav")
os.remove(filename + ".ogg")
@app.route("/chat", methods=["POST"])
@cross_origin()
def incoming_sms():
# Get the incoming message from the request
incoming_msg = request.values.get('Body', '').strip()
mgs_form = request.values.get('From', '').strip()
number = mgs_form[9:23]
to_number = mgs_form
voice = False
new_response_text = ""
other_response = False
# Check if the message is a voice message
if request.values.get("NumMedia") != "0":
voice = True
media_url = request.values.get("MediaUrl0")
media_content = requests.get(media_url).content
file_id = str(uuid.uuid4())
wav_file_name = f"voice_message_{file_id}"
save_voice_message_to_wav(media_content, wav_file_name)
wav_file = wav_file_name + ".wav"
r = sr.Recognizer()
with sr.AudioFile(wav_file) as source:
audio_data = r.record(source)
text = r.recognize_google(audio_data)
text = text.lower()
incoming_msg = text
if incoming_msg.startswith("/start"):
other_response = True
new_response_text = "Hello, I am Sonic, your personal assistant. How can I help you today?\n1. /clear to " \
"clear old conversation"
elif incoming_msg.startswith("/clear"):
other_response = True
try:
user_id = number
if clear_conversation_history(user_id):
new_response_text = "Your chat thread has now been reset. What else can I assist you with today?"
else:
new_response_text = "No conversation history to clear. What else can I assist you with today?"
except Exception as e:
my_error = str(e)
print(my_error)
new_response_text = "Can't Delete Conversation"
else:
conversation_tracking(incoming_msg, number, to_number)
if voice:
# Delete the temporary files
os.remove(wav_file)
if other_response:
resp = MessagingResponse()
resp.message(body=new_response_text)
return str(resp)
else:
return '', 204
if __name__ == "__main__":
app.run(host=FLASK_HOST, port=FLASK_PORT, debug=True)