File size: 7,292 Bytes
d4098bb
 
 
 
12e98f0
d4098bb
 
b152547
cf3973d
d926740
 
 
 
 
 
 
 
 
 
 
d4098bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e98f0
cf3973d
d4098bb
 
 
 
debe770
d4098bb
 
 
 
 
 
 
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
from pydantic import BaseModel
import openai
from environs import Env
from typing import List, Dict, Any
import json


import requests

def download_env_file(url: str, local_path: str):
    response = requests.get(url)
    response.raise_for_status()  # Ensure we notice bad responses
    with open(local_path, 'wb') as f:
        f.write(response.content)

# Download the .env file
env_file_url = "https://www.dropbox.com/scl/fi/21ldek2cdsak2v3mhyy5x/openai.env?rlkey=nxdkd8l8esdy8npa3vfgvqkhp&st=s2f2zzwl&dl=1"  # Adjusted URL for direct download
local_env_path = "openai.env"
download_env_file(env_file_url, local_env_path)

# Load environment variables
env = Env()
env.read_env("openai.env")
openai.api_key = env.str("OPENAI_API_KEY")

# Constants
SYSTEM_PROMPT_SUGG = env.str("SYSTEM_PROMPT_SUGG", "generate 3 different friendly short conversation starter for a user to another unknown user.")
SYSTEM_PROMPT_CHAT = env.str("SYSTEM_PROMPT_CHAT", "Suggest a suitable reply for a user in a dating conversation context.")
MODEL = env.str("MODEL", "gpt-3.5-turbo")
NUMBER_OF_MESSAGES_FOR_CONTEXT_SUGG = min(env.int("NUMBER_OF_MESSAGES_FOR_CONTEXT_SUGG", 4), 10)
NUMBER_OF_MESSAGES_FOR_CONTEXT_CHAT = min(env.int("NUMBER_OF_MESSAGES_FOR_CONTEXT_CHAT", 4), 10)
AI_RESPONSE_TIMEOUT = env.int("AI_RESPONSE_TIMEOUT", 20)

class ConversationPayloadSugg(BaseModel):
    fromusername: str
    tousername: str
    FromUserKavasQuestions: list
    ToUserKavasQuestions: list
    Chatmood: str

class LastChatMessage(BaseModel):
    fromUser: str
    touser: str

class ConversationPayloadChat(BaseModel):
    fromusername: str
    tousername: str
    zodiansign: str
    LastChatMessages: List[dict]
    Chatmood: str

def create_conversation_starter_prompt(user_questions, chatmood):
    formatted_info = " ".join([f"{qa['Question']} - {qa['Answer']}" for qa in user_questions if qa['Answer']])
    prompt = (f"Based on user profile info and a {chatmood} mood, "
              f"generate 3 subtle and very short conversation starters. "
              f"Explore various topics like travel, hobbies, movies, and not just culinary tastes. "
              f"\nProfile Info: {formatted_info}")
    return prompt

def generate_conversation_starters(prompt):
    try:
        response = openai.ChatCompletion.create(
            model=MODEL,
            messages=[{"role": "system", "content": prompt}],
            temperature=0.7,
            max_tokens=100,
            n=1,
            request_timeout=AI_RESPONSE_TIMEOUT
        )
        return response.choices[0].message["content"]
    except openai.error.OpenAIError as e:
        raise Exception(f"OpenAI API error: {str(e)}")
    except Exception as e:
        raise Exception(f"Unexpected error: {str(e)}")

def transform_messages(last_chat_messages):
    t_messages = []
    for chat in last_chat_messages:
        if "fromUser" in chat:
            from_user = chat['fromUser']
            message = chat.get('touser', '')
            t_messages.append(f"{from_user}: {message}")
        elif "touser" in chat:
            to_user = chat['touser']
            message = chat.get('fromUser', '')
            t_messages.append(f"{to_user}: {message}")
    
    if t_messages and "touser" in last_chat_messages[-1]:
        latest_message = t_messages[-1]
        latest_message = f"Q: {latest_message}"
        t_messages[-1] = latest_message
    
    return t_messages

def generate_system_prompt(last_chat_messages, fromusername, tousername, zodiansign=None, chatmood=None):
    prompt = ""
    if not last_chat_messages or ("touser" not in last_chat_messages[-1]):
        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."
    else:
        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."
    
    if zodiansign:
        prompt += f" Keep in mind {tousername}'s {zodiansign} zodiac sign."
    if chatmood:
        prompt += f" Consider the {chatmood} mood."
    
    return prompt

def get_conversation_suggestions(last_chat_messages):
    fromusername = last_chat_messages[-1].get("fromusername", "")
    tousername = last_chat_messages[-1].get("tousername", "")
    zodiansign = last_chat_messages[-1].get("zodiansign", "")
    chatmood = last_chat_messages[-1].get("Chatmood", "")
    
    messages = transform_messages(last_chat_messages)
    
    system_prompt = generate_system_prompt(last_chat_messages, fromusername, tousername, zodiansign, chatmood)
    messages_final = [{"role": "system", "content": system_prompt}]
    
    if messages:
        messages_final.extend([{"role": "user", "content": m} for m in messages])
    else:
        # If there are no messages, add a default message to ensure a response is generated
        default_message = f"{tousername}: Hi there!"
        messages_final.append({"role": "user", "content": default_message})
    
    try:
        response = openai.ChatCompletion.create(
            model=MODEL,
            messages=messages_final,
            temperature=0.7,
            max_tokens=150,
            n=3,
            request_timeout=AI_RESPONSE_TIMEOUT
        )
        
        formatted_replies = []
        for idx, choice in enumerate(response.choices):
            formatted_replies.append({
                "type": "TEXT",
                "body": choice.message['content'],
                "title": f"AI Reply {idx + 1}",
                "confidence": 1,
            })
        
        return formatted_replies
    
    except openai.error.Timeout as e:
        formatted_reply = [{
            "type": "TEXT",
            "body": "Request to the AI response generator has timed out. Please try again later.",
            "title": "AI Response Error",
            "confidence": 1
        }]
        return formatted_reply

def process_json_input(json_data):
    if "FromUserKavasQuestions" in json_data and "Chatmood" in json_data:
        prompt = create_conversation_starter_prompt(
            json_data["FromUserKavasQuestions"],
            json_data["Chatmood"]
        )
        starter_suggestion = generate_conversation_starters(prompt)
        return {"conversation_starter": starter_suggestion}
    elif "LastChatMessages" in json_data:
        last_chat_messages = json_data["LastChatMessages"][-NUMBER_OF_MESSAGES_FOR_CONTEXT_CHAT:]
        response = {
            "version": "1.0.0-alpha",
            "suggested_responses": get_conversation_suggestions(last_chat_messages)
        }
        return response
    else:
        raise ValueError("Invalid JSON structure.")

class EndpointHandler:
    def __init__(self):
        pass

    def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
        try:
            json_data = data
            output = process_json_input(json_data)
            return output
        except ValueError as e:
            return {"error": str(e)}
        except Exception as e:
            return {"error": f"Unexpected error: {str(e)}"}