Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from utils.llm import chat_stream | |
| TITLE = "Prosty Chatbot" | |
| DESCRIPTION = "Chatbot na silniku OpenAI GPT-4o-mini. Wklej swój klucz API poniżej." | |
| SYSTEM_PROMPT = "Jesteś pomocnym asystentem. Odpowiadaj po polsku, chyba że użytkownik pisze w innym języku." | |
| def respond(message: str, history: list, api_key: str, temperature: float): | |
| if not api_key or not api_key.strip(): | |
| yield "Najpierw wklej klucz OpenAI API w pole powyżej." | |
| return | |
| history_openai = list(history) | |
| history_openai.append({"role": "user", "content": message}) | |
| partial = "" | |
| try: | |
| for token in chat_stream(history_openai, api_key=api_key, system=SYSTEM_PROMPT, temperature=temperature): | |
| partial += token | |
| yield partial | |
| except ValueError as e: | |
| yield f"Błąd klucza API: {e}" | |
| except Exception as e: | |
| yield f"Błąd: {e}" | |
| with gr.Blocks(title=TITLE) as demo: | |
| gr.Markdown(f"# {TITLE}\n{DESCRIPTION}") | |
| api_key_input = gr.Textbox( | |
| label="OpenAI API Key", | |
| placeholder="sk-...", | |
| type="password", | |
| scale=1, | |
| ) | |
| temperature_slider = gr.Slider( | |
| minimum=0.0, | |
| maximum=2.0, | |
| value=0.7, | |
| step=0.1, | |
| label="Temperatura", | |
| info="Niska = bardziej przewidywalne odpowiedzi | Wysoka = bardziej kreatywne", | |
| ) | |
| chatbot = gr.Chatbot(height=450) | |
| msg = gr.Textbox(label="Wiadomość", placeholder="Napisz coś...", lines=1) | |
| with gr.Row(): | |
| submit_btn = gr.Button("Wyślij", variant="primary") | |
| clear_btn = gr.ClearButton([msg, chatbot], value="Wyczyść historię") | |
| gr.Examples( | |
| examples=["Cześć! Kim jesteś?", "Napisz krótki wiersz o wiośnie.", "Jak działa GPT?"], | |
| inputs=msg, | |
| ) | |
| def user_submit(message, history): | |
| return "", history + [{"role": "user", "content": message}] | |
| def bot_respond(history, api_key, temperature): | |
| message = history[-1]["content"] | |
| prev_history = history[:-1] | |
| history = history + [{"role": "assistant", "content": ""}] | |
| for partial in respond(message, prev_history, api_key, temperature): | |
| history[-1]["content"] = partial | |
| yield history | |
| msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot_respond, [chatbot, api_key_input, temperature_slider], chatbot | |
| ) | |
| submit_btn.click(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot_respond, [chatbot, api_key_input, temperature_slider], chatbot | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(theme=gr.themes.Soft()) | |