Spaces:
Running
Running
File size: 2,310 Bytes
b640d2d 8d44066 b640d2d 8d44066 b640d2d 8d44066 b640d2d 8d44066 7319113 b640d2d 8d44066 b640d2d 8d44066 76e8733 8d44066 b640d2d 8d44066 a5cedc8 8d44066 b640d2d 8d44066 |
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 |
import os
from openai import OpenAI
import gradio as gr
# Initialize OpenAI client with Groq model
XAI_API_KEY = os.getenv("XAI_API_KEY")
client = OpenAI(
api_key=XAI_API_KEY,
base_url="https://api.x.ai/v1",
)
# Define a function to handle chat with humor, including chat history
def chat_with_buddy(history, user_message):
# Start the conversation with a system message and add previous chat history
messages = [{"role": "system", "content": "You are Chat Buddy, a friendly and humorous chatbot who loves to make people smile."}]
messages += [{"role": "user", "content": msg[0]} for msg in history] + [{"role": "assistant", "content": msg[1]} for msg in history if len(msg) > 1]
messages.append({"role": "user", "content": user_message})
try:
# Generate a response from Groq
response = client.chat.completions.create(
model="grok-beta",
messages=messages
)
# Extract the response content
reply = response.choices[0].message.content
# Update chat history with the new user message and assistant response
history.append((user_message, reply))
return history
except Exception as e:
# In case of error, add error message to history
error_message = f"Oops, something went wrong! Just blame it on the robots... 😉 (Error: {str(e)})"
history.append((user_message, error_message))
return history
# Set up the Gradio chat interface with history
with gr.Blocks() as chat_interface:
gr.Markdown("# Chat Buddy")
gr.Markdown("Your friendly chatbot with a touch of humor! Ask Chat Buddy anything, and enjoy a chat that’s both helpful and light-hearted.")
chatbot = gr.Chatbot()
message = gr.Textbox(placeholder="Type your message here...", label="Your Message")
submit_button = gr.Button("Send")
# Define the submit action to update chat history
def submit(user_message, chat_history):
return chat_with_buddy(chat_history, user_message), ""
# Link the submit button to the function
message.submit(submit, inputs=[message, chatbot], outputs=[chatbot, message])
submit_button.click(submit, inputs=[message, chatbot], outputs=[chatbot, message])
# Launch the chat interface
chat_interface.launch()
|