Spaces:
Sleeping
Sleeping
File size: 3,435 Bytes
2e62718 4d2dbf7 2e62718 4d2dbf7 2e62718 b4b286e 2e62718 b4b286e 2e62718 b4b286e 2e62718 b4b286e 2e62718 4d2dbf7 2e62718 4d2dbf7 2e62718 4d2dbf7 | 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 | # =======================================================
# Conversational Chatbot with ChatGPT API + Gradio
# Author: Shruti Mandaokar
# =======================================================
import os
import openai
import gradio as gr
# -----------------------------
# 1. Load OpenAI API key from Hugging Face Secrets
# -----------------------------
openai.api_key = os.getenv("OPENAI_API_KEY")
if openai.api_key is None:
raise ValueError("β OPENAI_API_KEY not found. Please add it in Hugging Face Secrets.")
# -----------------------------
# 2. System prompt for chatbot
# -----------------------------
system_prompt = (
"You are a helpful assistant that corrects grammar and answers questions. "
"Maintain context of the conversation."
)
# -----------------------------
# 3. Reset conversation history
# -----------------------------
def reset():
# History format compatible with Gradio Chatbot type='messages'
return []
# -----------------------------
# 4. Chatbot function
# -----------------------------
def interact_chatbot(user_input: str, history: list, temp: float):
"""
Maintains context: sends conversation history + new user input to ChatGPT API.
Returns history in Gradio messages format.
"""
# Build messages for OpenAI API
messages = [{"role": "system", "content": system_prompt}]
for msg in history:
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": user_input})
# Call OpenAI API
try:
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=temp,
max_tokens=200,
)
assistant_reply = response.choices[0].message.content
except Exception as e:
assistant_reply = f"β οΈ Error: {str(e)}"
# Update history in Gradio messages format
history.append({"role": "user", "content": user_input})
history.append({"role": "assistant", "content": assistant_reply})
return history
# -----------------------------
# 5. Gradio UI
# -----------------------------
with gr.Blocks(css="""
.gradio-container {background-color: #f0f4f8;}
h1 {color: #2b547e; text-align: center;}
h3 {color: #5a2d82;}
.footer {text-align: center; color: #666; font-size: 14px; margin-top: 20px;}
""") as demo:
gr.Markdown("# β¨ Conversational Chatbot with ChatGPT API β¨")
gr.Markdown("### Made with β€οΈ by **Shruti Mandaokar**")
chatbot = gr.Chatbot(label="π¬ Chatbot", type="messages")
user_input = gr.Textbox(label="Your message", placeholder="Type a sentence...")
with gr.Column():
gr.Markdown("### π¨ Creativity Control")
temperature_slider = gr.Slider(0.0, 2.0, value=1.0, step=0.1, label="Temperature")
with gr.Row():
send_button = gr.Button("π Send")
reset_button = gr.Button("π Reset Chat")
send_button.click(
interact_chatbot,
inputs=[user_input, chatbot, temperature_slider],
outputs=[chatbot]
)
reset_button.click(reset, outputs=[chatbot])
gr.Markdown('<div class="footer">πΈ Conversational Chatbot | Shruti Mandaokar πΈ</div>')
# -----------------------------
# 6. Launch the app
# -----------------------------
if __name__ == "__main__":
on_spaces = os.getenv("SYSTEM") == "spaces"
demo.launch(share=not on_spaces)
|