Spaces:
Configuration error
Configuration error
| import os | |
| import gradio as gr | |
| import anthropic | |
| client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")) | |
| SYSTEM_PROMPT = """You are a helpful, friendly, and knowledgeable AI assistant. | |
| You answer questions clearly and concisely, and you're always eager to help.""" | |
| def chat(message, history): | |
| """Send message to Claude and stream the response.""" | |
| messages = [] | |
| for user_msg, assistant_msg in history: | |
| messages.append({"role": "user", "content": user_msg}) | |
| messages.append({"role": "assistant", "content": assistant_msg}) | |
| messages.append({"role": "user", "content": message}) | |
| response_text = "" | |
| with client.messages.stream( | |
| model="claude-sonnet-4-6", | |
| max_tokens=1024, | |
| system=SYSTEM_PROMPT, | |
| messages=messages, | |
| ) as stream: | |
| for text in stream.text_stream: | |
| response_text += text | |
| yield response_text | |
| # ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Blocks( | |
| title="AI Chatbot", | |
| theme=gr.themes.Soft(primary_hue="violet"), | |
| css=""" | |
| #chatbot { height: 520px; } | |
| footer { display: none !important; } | |
| """, | |
| ) as demo: | |
| gr.Markdown( | |
| """ | |
| # π€ AI Chatbot | |
| Powered by Claude β ask me anything! | |
| """ | |
| ) | |
| chatbot = gr.Chatbot( | |
| elem_id="chatbot", | |
| bubble_full_width=False, | |
| show_label=False, | |
| avatar_images=(None, "https://www.anthropic.com/favicon.ico"), | |
| ) | |
| with gr.Row(): | |
| msg = gr.Textbox( | |
| placeholder="Type your message hereβ¦", | |
| show_label=False, | |
| scale=9, | |
| container=False, | |
| ) | |
| send_btn = gr.Button("Send", variant="primary", scale=1) | |
| clear_btn = gr.ClearButton([msg, chatbot], value="ποΈ Clear Chat") | |
| def user_submit(message, history): | |
| return "", history + [[message, None]] | |
| def bot_respond(history): | |
| user_message = history[-1][0] | |
| prior_history = history[:-1] | |
| history[-1][1] = "" | |
| for chunk in chat(user_message, prior_history): | |
| history[-1][1] = chunk | |
| yield history | |
| msg.submit(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot_respond, chatbot, chatbot | |
| ) | |
| send_btn.click(user_submit, [msg, chatbot], [msg, chatbot], queue=False).then( | |
| bot_respond, chatbot, chatbot | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue() | |
| demo.launch() | |