Spaces:
Sleeping
Sleeping
import openai | |
import os | |
import gradio as gr | |
from openai import OpenAI | |
# Ensure the OPENAI_API_KEY environment variable is set | |
openai.api_key = os.getenv("OPENAI_API_KEY") | |
if openai.api_key is None: | |
raise ValueError("Die Umgebungsvariable OPENAI_API_KEY ist nicht gesetzt.") | |
client = OpenAI() | |
def chat_with_gpt(user_input, system_message, temperature, history): | |
if not history: | |
# If starting a new conversation, add the system message first | |
history = [{"role": "system", "content": system_message}] | |
# Append the latest user message | |
history.append({"role": "user", "content": user_input}) | |
# Get response from GPT-3.5 Turbo | |
response = client.chat.completions.create( | |
model="gpt-3.5-turbo", | |
messages=history, | |
temperature=temperature | |
) | |
# Append the assistant's response | |
assistant_message = response.choices[0].message['content'] | |
history.append({"role": "assistant", "content": assistant_message}) | |
return history, history # Return updated history for both display and state | |
# Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("### Chatte mit deinem Mini-Game") | |
with gr.Row(): | |
system_message = gr.Textbox(value="Du bist ein dickköpfiger Bürokrat, der nicht hilfreich sein will.", label="Systemnachricht", placeholder="Gib hier die Systemnachricht ein...") | |
user_input = gr.Textbox(label="Deine Nachricht", placeholder="Gib hier deine Chatnachricht ein...") | |
temperature_slider = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.7, label="Temperatur") | |
submit_button = gr.Button("Senden") | |
chat_container = gr.Chatbot(label="Chatverlauf") | |
history_state = gr.State([]) # Using Gradio State to maintain conversation history | |
submit_button.click(fn=chat_with_gpt, | |
inputs=[user_input, system_message, temperature_slider, history_state], | |
outputs=[chat_container, history_state]) | |
# Launch the Gradio app | |
demo.launch() | |