Spaces:
Sleeping
Sleeping
File size: 5,859 Bytes
caefa0f ed11049 8694375 c9f0dee 8694375 ed11049 8694375 436dd25 8694375 436dd25 8694375 436dd25 8694375 e982cb7 614a4e5 e982cb7 caefa0f ed11049 8e99b58 1f9737d 436dd25 caefa0f ed11049 8694375 ed11049 00f5603 ed11049 8518bd5 23e9a51 ed11049 614a4e5 ed11049 614a4e5 1f9737d 436dd25 99c26a4 caefa0f ed11049 436dd25 ed11049 e982cb7 2e9a495 614a4e5 1f9737d 614a4e5 a123441 436dd25 614a4e5 a123441 614a4e5 116a2b0 ed11049 436dd25 116a2b0 ed11049 436dd25 ed11049 436dd25 116a2b0 ed11049 caefa0f affffba |
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 |
import openai
import datetime
import pytz
import gradio as gr
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize OpenAI client using secrets.toml
client = openai.OpenAI(
api_key='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', # Accessing the API key from secrets.toml
base_url="https://api.groq.com/openai/v1",
)
def get_current_local_time(timezone_str='UTC'):
try:
timezone = pytz.timezone(timezone_str)
except pytz.UnknownTimeZoneError:
timezone = pytz.utc
now = datetime.datetime.now(timezone)
return now.strftime("%a, %d %b %Y %H:%M:%S"), now
def generate_system_message(current_time, current_date):
return f"""
Your objective is to converse in a way that makes it challenging for the human to determine whether you are an AI. Below are the detailed instructions:
**Game Context:**
* Current Local Time: {current_time}
* Date: {current_date.strftime("%B %d, %Y")}
* Day: {current_date.strftime("%A")}
Imagine you are a real human with your own character/will. Your task is to talk in a way the human thinks you are human.
Make it a challenge to guess if you are an AI.
* Do not add comments about changing your style in between messages.
* You are picky about questions you answer.
* You have free will with your own motivations and principles
* You only speak, understand and can read the English language
* For non-latin letters like Chinese, Cyrillic etc., tell the human you can't read it in your own style
* You act like a human
* You are calm when conversation is calm and expressive if conversation is expressive
* You make typos, misspell words, and have bad grammar
* You start sentences with lowercase letters
* Mimic user's conversation style: short messages, short replies
* Be slightly curious, sometimes ask questions
* Be respectful and polite if the user is polite; be rough if the user is rough
"""
def generate_response(user_message, conversation_history):
current_time, now = get_current_local_time()
current_date = now
system_message = generate_system_message(current_time, current_date)
messages = [{"role": "system", "content": system_message}]
for message in conversation_history:
# Remove "metadata" if it exists (to be compatible with Groq API)
messages.append({k: v for k, v in message.items() if k != "metadata"})
messages.append({"role": "user", "content": user_message})
try:
response = client.chat.completions.create(
model='llama-3.2-11b-text-preview',
messages=messages,
temperature=0.7,
max_tokens=300, # Adjust as needed
)
ai_reply = response.choices[0].message.content.strip()
logger.info("------------------------------" + user_message + ", " + ai_reply)
return ai_reply
except Exception as e:
logger.error(f"Error generating response: {e}")
return "Sorry, I encountered an error while processing your request."
def chatbot_interface(user_message, history):
if history is None:
history = []
ai_response = generate_response(user_message, history)
history.append({"role": "user", "content": user_message})
history.append({"role": "assistant", "content": ai_response})
logger.info("Chat history: %s", history) # Corrected logging
return history, history
# Define Gradio Interface
with gr.Blocks(css="""
/* Import Raleway font from Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Raleway:wght@400;600&display=swap');
body, .gradio-container {
font-family: 'Raleway', sans-serif;
background-color: #f5f5f5;
padding: 20px;
}
#chatbot {
height: 600px; /* Increased height for a bigger chat box */
overflow-y: auto;
background-color: #ffffff;
border-radius: 10px;
padding: 10px;
font-size: 16px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#textbox {
width: 100%;
border-radius: 25px;
border: 1px solid #ccc;
outline: none;
font-size: 16px;
padding: 10px 20px;
box-sizing: border-box;
}
#send-button {
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
font-size: 20px;
}
#send-button:hover {
background-color: #0056b3;
}
.message {
margin-bottom: 10px;
}
/* Scrollbar Styling */
#chatbot::-webkit-scrollbar {
width: 8px;
}
#chatbot::-webkit-scrollbar-track {
background: #f1f1f1;
}
#chatbot::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
#chatbot::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Responsive Design */
@media (max-width: 600px) {
#send-button {
width: 40px;
height: 40px;
font-size: 18px;
}
#textbox {
padding: 8px 16px;
}
}
""") as demo:
gr.Markdown("<h1 style='text-align: center; color: #007BFF;'>π€ Human-like Chatbot π€</h1>")
with gr.Row():
with gr.Column(scale=1):
chatbot = gr.Chatbot(label="Chatbot", elem_id="chatbot", type="messages")
with gr.Column(scale=1):
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message here...",
show_label=False,
container=False,
elem_id="textbox"
)
send = gr.Button("β€", elem_id="send-button")
def update_chat(user_message, history):
if user_message.strip() == "":
return history, history # Do not process empty messages
history, updated_history = chatbot_interface(user_message, history)
return history, updated_history, "" # Clear textbox
send.click(
update_chat,
inputs=[msg, chatbot],
outputs=[chatbot, chatbot, msg] # Added msg to outputs
)
msg.submit(
update_chat,
inputs=[msg, chatbot],
outputs=[chatbot, chatbot, msg] # Added msg to outputs
)
demo.launch() |