mychatbot / ChatBot
xievic9780
Initial commit: Add chatbot project
ef519b9
Raw History Blame Contribute Delete
3.06 kB
import gradio as gr
import openai
from typing import List, Tuple
# Configure your API key here
# openai.api_key = "your-api-key-here"
def chat_response(message: str, history: List[Tuple[str, str]]) -> str:
"""
Generate a response to the user's message.
Args:
message: The user's current message
history: List of (user_message, assistant_message) tuples
Returns:
The assistant's response
"""
# Build conversation history for the API
messages = [{"role": "system", "content": "You are a helpful assistant."}]
# Add chat history
for user_msg, assistant_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": assistant_msg})
# Add current message
messages.append({"role": "user", "content": message})
try:
# Call OpenAI API (uncomment when you have an API key)
# response = openai.ChatCompletion.create(
# model="gpt-3.5-turbo",
# messages=messages,
# temperature=0.7,
# max_tokens=500
# )
# return response.choices[0].message.content
# Mock response for demonstration (remove when using real API)
return f"This is a demo response to: '{message}'. Replace this with actual OpenAI API call."
except Exception as e:
return f"Error: {str(e)}"
# Create the Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# 💬 ChatGPT-Style Interface")
gr.Markdown("A simple chat interface similar to ChatGPT")
chatbot = gr.Chatbot(
height=500,
bubble_full_width=False,
avatar_images=(None, "🤖")
)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message here...",
container=False,
scale=7,
show_label=False
)
submit = gr.Button("Send", scale=1, variant="primary")
with gr.Row():
clear = gr.Button("Clear Chat")
retry = gr.Button("Retry Last")
# Handle message submission
def user_message(user_msg, history):
return "", history + [[user_msg, None]]
def bot_message(history):
user_msg = history[-1][0]
bot_msg = chat_response(user_msg, history[:-1])
history[-1][1] = bot_msg
return history
# Event handlers
msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
bot_message, chatbot, chatbot
)
submit.click(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
bot_message, chatbot, chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
def retry_last_message(history):
if history:
history[-1][1] = None
return bot_message(history)
return history
retry.click(retry_last_message, chatbot, chatbot)
# Launch the app
if __name__ == "__main__":x
demo.launch(share=False)