Vijish commited on
Commit
55dfa40
·
verified ·
1 Parent(s): a2fb3e7

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +195 -0
handler.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ import openai
3
+ from environs import Env
4
+ from typing import List, Dict, Any
5
+
6
+
7
+ import requests
8
+
9
+ def download_env_file(url: str, local_path: str):
10
+ response = requests.get(url)
11
+ response.raise_for_status() # Ensure we notice bad responses
12
+ with open(local_path, 'wb') as f:
13
+ f.write(response.content)
14
+
15
+ # Download the .env file
16
+ env_file_url = "https://www.dropbox.com/scl/fi/21ldek2cdsak2v3mhyy5x/openai.env?rlkey=nxdkd8l8esdy8npa3vfgvqkhp&st=s2f2zzwl&dl=1" # Adjusted URL for direct download
17
+ local_env_path = "openai.env"
18
+ download_env_file(env_file_url, local_env_path)
19
+
20
+ # Load environment variables
21
+ env = Env()
22
+ env.read_env("openai.env")
23
+ openai.api_key = env.str("OPENAI_API_KEY")
24
+
25
+ # Constants
26
+ MODEL = env.str("MODEL", "gpt-3.5-turbo")
27
+ AI_RESPONSE_TIMEOUT = env.int("AI_RESPONSE_TIMEOUT", 20)
28
+
29
+ class EndpointHandler:
30
+ def __init__(self, model_dir=None):
31
+ self.model_dir = model_dir
32
+
33
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
34
+ try:
35
+ if "inputs" in data: # Check if data is in Hugging Face JSON format
36
+ return self.process_hf_input(data)
37
+ else:
38
+ return self.process_json_input(data)
39
+ except ValueError as e:
40
+ return {"error": str(e)}
41
+ except Exception as e:
42
+ return {"error": str(e)}
43
+
44
+ def process_json_input(self, json_data):
45
+ if "FromUserKavasQuestions" in json_data and "Chatmood" in json_data:
46
+ prompt = self.create_conversation_starter_prompt(
47
+ json_data["FromUserKavasQuestions"],
48
+ json_data["Chatmood"]
49
+ )
50
+ starter_suggestion = self.generate_conversation_starters(prompt)
51
+ return {"conversation_starter": starter_suggestion}
52
+ elif "LastChatMessages" in json_data:
53
+ last_chat_messages = json_data["LastChatMessages"][-4:]
54
+ response = {
55
+ "version": "1.0.0-alpha",
56
+ "suggested_responses": self.get_conversation_suggestions(last_chat_messages)
57
+ }
58
+ return response
59
+ else:
60
+ raise ValueError("Invalid JSON structure.")
61
+
62
+ def process_hf_input(self, hf_data):
63
+ print("Received HF Data:", hf_data) # Debugging line
64
+ if "inputs" in hf_data:
65
+ actual_data = hf_data["inputs"]
66
+ print("Processing actual data:", actual_data) # Debugging line
67
+ return self.process_json_input(actual_data)
68
+ else:
69
+ return {"error": "Invalid Hugging Face JSON structure."}
70
+
71
+
72
+ def create_conversation_starter_prompt(self, user_questions, chatmood):
73
+ formatted_info = " ".join([f"{qa['Question']} - {qa['Answer']}" for qa in user_questions if qa['Answer']])
74
+ prompt = (f"Based on user profile info and a {chatmood} mood, "
75
+ f"generate 3 subtle and very short conversation starters. "
76
+ f"Explore various topics like travel, hobbies, movies, and not just culinary tastes. "
77
+ f"\nProfile Info: {formatted_info}")
78
+ return prompt
79
+
80
+ def generate_conversation_starters(self, prompt):
81
+ try:
82
+ response = openai.ChatCompletion.create(
83
+ model=MODEL,
84
+ messages=[{"role": "system", "content": prompt}],
85
+ temperature=0.7,
86
+ max_tokens=100,
87
+ n=1,
88
+ request_timeout=AI_RESPONSE_TIMEOUT
89
+ )
90
+ return response.choices[0].message["content"]
91
+ except openai.error.OpenAIError as e:
92
+ raise Exception(f"OpenAI API error: {str(e)}")
93
+ except Exception as e:
94
+ raise Exception(f"Unexpected error: {str(e)}")
95
+
96
+ def transform_messages(self, last_chat_messages):
97
+ t_messages = []
98
+ for chat in last_chat_messages:
99
+ if "fromUser" in chat:
100
+ from_user = chat['fromUser']
101
+ message = chat.get('touser', '')
102
+ t_messages.append(f"{from_user}: {message}")
103
+ elif "touser" in chat:
104
+ to_user = chat['touser']
105
+ message = chat.get('fromUser', '')
106
+ t_messages.append(f"{to_user}: {message}")
107
+
108
+ if t_messages and "touser" in last_chat_messages[-1]:
109
+ latest_message = t_messages[-1]
110
+ latest_message = f"Q: {latest_message}"
111
+ t_messages[-1] = latest_message
112
+
113
+ return t_messages
114
+
115
+ def generate_system_prompt(self, last_chat_messages, fromusername, tousername, zodiansign=None, chatmood=None):
116
+ prompt = ""
117
+ if not last_chat_messages or ("touser" not in last_chat_messages[-1]):
118
+ prompt = f"Suggest a casual and friendly message for {fromusername} to start a conversation with {tousername} or continue naturally, as if talking to a good friend. Strictly avoid replying to messages from {fromusername} or answering their questions."
119
+ else:
120
+ prompt = f"Suggest a warm and friendly reply for {fromusername} to respond to the last message from {tousername}, as if responding to a dear friend. Strictly avoid replying to messages from {fromusername} or answering their questions."
121
+
122
+ if zodiansign:
123
+ prompt += f" Keep in mind {tousername}'s {zodiansign} zodiac sign."
124
+
125
+ if chatmood:
126
+ if chatmood == "Casual Vibes":
127
+ prompt += " Keep the conversation relaxed and informal."
128
+ elif chatmood == "Flirty Fun":
129
+ prompt += " Add a playful and teasing tone to the conversation."
130
+ elif chatmood == "Deep and Thoughtful":
131
+ prompt += " Encourage reflective and introspective responses."
132
+ elif chatmood == "Humor Central":
133
+ prompt += " Incorporate witty and humorous elements into the conversation."
134
+ elif chatmood == "Romantic Feels":
135
+ prompt += " Express affection and use sweet and romantic language."
136
+ elif chatmood == "Intellectual Banter":
137
+ prompt += " Engage in thought-provoking discussions on topics like books and movies."
138
+ elif chatmood == "Supportive Mode":
139
+ prompt += " Offer empathy, support, and encouragement in the conversation."
140
+ elif chatmood == "Curiosity Unleashed":
141
+ prompt += " Show eagerness to learn and explore interests by asking questions."
142
+ elif chatmood == "Chill and Easygoing":
143
+ prompt += " Maintain a relaxed and laid-back tone in the conversation."
144
+ elif chatmood == "Adventurous Spirit":
145
+ prompt += " Share travel stories and plans with enthusiasm and energy."
146
+
147
+ return prompt
148
+
149
+ def get_conversation_suggestions(self, last_chat_messages):
150
+ fromusername = last_chat_messages[-1].get("fromusername", "")
151
+ tousername = last_chat_messages[-1].get("tousername", "")
152
+ zodiansign = last_chat_messages[-1].get("zodiansign", "")
153
+ chatmood = last_chat_messages[-1].get("Chatmood", "")
154
+
155
+ messages = self.transform_messages(last_chat_messages)
156
+
157
+ system_prompt = self.generate_system_prompt(last_chat_messages, fromusername, tousername, zodiansign, chatmood)
158
+ messages_final = [{"role": "system", "content": system_prompt}]
159
+
160
+ if messages:
161
+ messages_final.extend([{"role": "user", "content": m} for m in messages])
162
+ else:
163
+ # If there are no messages, add a default message to ensure a response is generated
164
+ default_message = f"{tousername}: Hi there!"
165
+ messages_final.append({"role": "user", "content": default_message})
166
+
167
+ try:
168
+ response = openai.ChatCompletion.create(
169
+ model=MODEL,
170
+ messages=messages_final,
171
+ temperature=0.7,
172
+ max_tokens=150,
173
+ n=3,
174
+ request_timeout=AI_RESPONSE_TIMEOUT
175
+ )
176
+
177
+ formatted_replies = []
178
+ for idx, choice in enumerate(response.choices):
179
+ formatted_replies.append({
180
+ "type": "TEXT",
181
+ "body": choice.message['content'],
182
+ "title": f"AI Reply {idx + 1}",
183
+ "confidence": 1,
184
+ })
185
+
186
+ return formatted_replies
187
+
188
+ except openai.error.Timeout as e:
189
+ formatted_reply = [{
190
+ "type": "TEXT",
191
+ "body": "Request to the AI response generator has timed out. Please try again later.",
192
+ "title": "AI Response Error",
193
+ "confidence": 1
194
+ }]
195
+ return formatted_reply