Spaces:
Sleeping
Sleeping
File size: 5,881 Bytes
0fbed87 |
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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
"""
Simple Chatbot using Streamlit and Anthropic Claude
==================================================
A clean, interactive chatbot interface powered by Claude AI.
"""
import streamlit as st
import anthropic
from typing import List, Dict
import os
# Configure the page
st.set_page_config(
page_title="Claude Chatbot",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
def initialize_session_state():
"""Initialize session state variables."""
if "messages" not in st.session_state:
st.session_state.messages = []
if "client" not in st.session_state:
st.session_state.client = None
def setup_anthropic_client(api_key: str) -> anthropic.Anthropic:
"""Setup and return Anthropic client."""
try:
client = anthropic.Anthropic(api_key=api_key)
return client
except Exception as e:
st.error(f"Error setting up Anthropic client: {str(e)}")
return None
def get_claude_response(client: anthropic.Anthropic, messages: List[Dict], model: str = "claude-3-haiku-20240307") -> str:
"""Get response from Claude API."""
try:
# Convert Streamlit messages to Anthropic format
anthropic_messages = []
for msg in messages:
if msg["role"] in ["user", "assistant"]:
anthropic_messages.append({
"role": msg["role"],
"content": msg["content"]
})
response = client.messages.create(
model=model,
max_tokens=1000,
temperature=0.7,
messages=anthropic_messages
)
return response.content[0].text
except Exception as e:
return f"Error getting response: {str(e)}"
def main():
"""Main application function."""
initialize_session_state()
# Sidebar for configuration
with st.sidebar:
st.title("🤖 Claude Chatbot")
st.markdown("---")
# API Key input
api_key = st.text_input(
"Anthropic API Key",
type="password",
help="Enter your Anthropic API key to start chatting",
placeholder="sk-ant-..."
)
# Model selection
model = st.selectbox(
"Select Claude Model",
options=[
"claude-3-haiku-20240307",
"claude-3-sonnet-20240229",
"claude-3-opus-20240229"
],
index=0,
help="Choose the Claude model to use"
)
# Clear chat button
if st.button("🗑️ Clear Chat", use_container_width=True):
st.session_state.messages = []
st.rerun()
st.markdown("---")
st.markdown("""
### About
This chatbot uses Anthropic's Claude AI to provide intelligent responses.
**Features:**
- Multiple Claude models
- Persistent conversation history
- Clean, responsive interface
**Usage:**
1. Enter your Anthropic API key
2. Start typing your message
3. Enjoy chatting with Claude!
""")
# Main chat interface
st.title("💬 Chat with Claude")
# Check if API key is provided
if not api_key:
st.info("👈 Please enter your Anthropic API key in the sidebar to start chatting.")
st.markdown("""
### Getting Started
1. **Get an API Key**: Visit [Anthropic Console](https://console.anthropic.com/) to get your API key
2. **Enter the Key**: Paste it in the sidebar input field
3. **Start Chatting**: Type your message and press Enter!
### Example Questions to Try:
- "Explain quantum computing in simple terms"
- "Write a Python function to calculate fibonacci numbers"
- "What are the benefits of renewable energy?"
- "Help me plan a weekend trip to San Francisco"
""")
return
# Setup client
if st.session_state.client is None:
with st.spinner("Setting up connection to Claude..."):
st.session_state.client = setup_anthropic_client(api_key)
if st.session_state.client is None:
st.error("Failed to setup Anthropic client. Please check your API key.")
return
# Display chat messages
chat_container = st.container()
with chat_container:
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("Type your message here..."):
# Add user message to chat
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message immediately
with chat_container:
with st.chat_message("user"):
st.markdown(prompt)
# Get and display assistant response
with chat_container:
with st.chat_message("assistant"):
message_placeholder = st.empty()
with st.spinner("Claude is thinking..."):
response = get_claude_response(
st.session_state.client,
st.session_state.messages,
model
)
message_placeholder.markdown(response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
# Display conversation stats
if st.session_state.messages:
st.sidebar.markdown("---")
st.sidebar.markdown(f"**Messages:** {len(st.session_state.messages)}")
st.sidebar.markdown(f"**Model:** {model}")
if __name__ == "__main__":
main() |