Vijish commited on
Commit
d8bab97
·
verified ·
1 Parent(s): 5e592f1

Create handler.py

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