eagle0504 commited on
Commit
0fbed87
·
verified ·
1 Parent(s): b118dca

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. .env.example +2 -0
  2. README.md +44 -7
  3. app.py +180 -0
  4. requirements.txt +2 -0
.env.example ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Copy this file to .env and add your API key
2
+ ANTHROPIC_API_KEY=your_api_key_here
README.md CHANGED
@@ -1,12 +1,49 @@
1
  ---
2
- title: My Simple Bot
3
- emoji: 🏃
4
- colorFrom: gray
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Claude Simple Chatbot
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ sdk_version: 1.34.0
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
  ---
12
 
13
+ # Claude Simple Chatbot 🤖
14
+
15
+ A simple, elegant chatbot built with Streamlit and Anthropic's Claude AI.
16
+
17
+ ## Features
18
+
19
+ - **Multiple Claude Models**: Choose between Haiku, Sonnet, and Opus
20
+ - **Persistent Chat History**: Conversations stay active during your session
21
+ - **Clean Interface**: Modern, responsive design with sidebar controls
22
+ - **Easy Setup**: Just add your API key and start chatting
23
+ - **Model Selection**: Switch between different Claude models on the fly
24
+
25
+ ## How to Use
26
+
27
+ 1. **Enter API Key**: Add your Anthropic API key in the sidebar
28
+ 2. **Choose Model**: Select your preferred Claude model
29
+ 3. **Start Chatting**: Type your message and enjoy!
30
+
31
+ ## Getting Your API Key
32
+
33
+ - Visit [Anthropic Console](https://console.anthropic.com/)
34
+ - Create an account and get your API key
35
+ - It should start with `sk-ant-`
36
+
37
+ ## Example Prompts
38
+
39
+ - "Explain quantum computing in simple terms"
40
+ - "Write a Python function to sort a list"
41
+ - "Help me plan a weekend itinerary for Tokyo"
42
+ - "What are the pros and cons of remote work?"
43
+
44
+ ## Architecture
45
+
46
+ - **Frontend**: Streamlit for the web interface
47
+ - **Backend**: Anthropic Python SDK for Claude API integration
48
+ - **State Management**: Streamlit session state for chat history
49
+ - **Error Handling**: Graceful error messages and connection handling
app.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple Chatbot using Streamlit and Anthropic Claude
3
+ ==================================================
4
+
5
+ A clean, interactive chatbot interface powered by Claude AI.
6
+ """
7
+
8
+ import streamlit as st
9
+ import anthropic
10
+ from typing import List, Dict
11
+ import os
12
+
13
+ # Configure the page
14
+ st.set_page_config(
15
+ page_title="Claude Chatbot",
16
+ page_icon="🤖",
17
+ layout="wide",
18
+ initial_sidebar_state="expanded"
19
+ )
20
+
21
+ def initialize_session_state():
22
+ """Initialize session state variables."""
23
+ if "messages" not in st.session_state:
24
+ st.session_state.messages = []
25
+ if "client" not in st.session_state:
26
+ st.session_state.client = None
27
+
28
+ def setup_anthropic_client(api_key: str) -> anthropic.Anthropic:
29
+ """Setup and return Anthropic client."""
30
+ try:
31
+ client = anthropic.Anthropic(api_key=api_key)
32
+ return client
33
+ except Exception as e:
34
+ st.error(f"Error setting up Anthropic client: {str(e)}")
35
+ return None
36
+
37
+ def get_claude_response(client: anthropic.Anthropic, messages: List[Dict], model: str = "claude-3-haiku-20240307") -> str:
38
+ """Get response from Claude API."""
39
+ try:
40
+ # Convert Streamlit messages to Anthropic format
41
+ anthropic_messages = []
42
+ for msg in messages:
43
+ if msg["role"] in ["user", "assistant"]:
44
+ anthropic_messages.append({
45
+ "role": msg["role"],
46
+ "content": msg["content"]
47
+ })
48
+
49
+ response = client.messages.create(
50
+ model=model,
51
+ max_tokens=1000,
52
+ temperature=0.7,
53
+ messages=anthropic_messages
54
+ )
55
+
56
+ return response.content[0].text
57
+
58
+ except Exception as e:
59
+ return f"Error getting response: {str(e)}"
60
+
61
+ def main():
62
+ """Main application function."""
63
+ initialize_session_state()
64
+
65
+ # Sidebar for configuration
66
+ with st.sidebar:
67
+ st.title("🤖 Claude Chatbot")
68
+ st.markdown("---")
69
+
70
+ # API Key input
71
+ api_key = st.text_input(
72
+ "Anthropic API Key",
73
+ type="password",
74
+ help="Enter your Anthropic API key to start chatting",
75
+ placeholder="sk-ant-..."
76
+ )
77
+
78
+ # Model selection
79
+ model = st.selectbox(
80
+ "Select Claude Model",
81
+ options=[
82
+ "claude-3-haiku-20240307",
83
+ "claude-3-sonnet-20240229",
84
+ "claude-3-opus-20240229"
85
+ ],
86
+ index=0,
87
+ help="Choose the Claude model to use"
88
+ )
89
+
90
+ # Clear chat button
91
+ if st.button("🗑️ Clear Chat", use_container_width=True):
92
+ st.session_state.messages = []
93
+ st.rerun()
94
+
95
+ st.markdown("---")
96
+ st.markdown("""
97
+ ### About
98
+ This chatbot uses Anthropic's Claude AI to provide intelligent responses.
99
+
100
+ **Features:**
101
+ - Multiple Claude models
102
+ - Persistent conversation history
103
+ - Clean, responsive interface
104
+
105
+ **Usage:**
106
+ 1. Enter your Anthropic API key
107
+ 2. Start typing your message
108
+ 3. Enjoy chatting with Claude!
109
+ """)
110
+
111
+ # Main chat interface
112
+ st.title("💬 Chat with Claude")
113
+
114
+ # Check if API key is provided
115
+ if not api_key:
116
+ st.info("👈 Please enter your Anthropic API key in the sidebar to start chatting.")
117
+ st.markdown("""
118
+ ### Getting Started
119
+
120
+ 1. **Get an API Key**: Visit [Anthropic Console](https://console.anthropic.com/) to get your API key
121
+ 2. **Enter the Key**: Paste it in the sidebar input field
122
+ 3. **Start Chatting**: Type your message and press Enter!
123
+
124
+ ### Example Questions to Try:
125
+ - "Explain quantum computing in simple terms"
126
+ - "Write a Python function to calculate fibonacci numbers"
127
+ - "What are the benefits of renewable energy?"
128
+ - "Help me plan a weekend trip to San Francisco"
129
+ """)
130
+ return
131
+
132
+ # Setup client
133
+ if st.session_state.client is None:
134
+ with st.spinner("Setting up connection to Claude..."):
135
+ st.session_state.client = setup_anthropic_client(api_key)
136
+
137
+ if st.session_state.client is None:
138
+ st.error("Failed to setup Anthropic client. Please check your API key.")
139
+ return
140
+
141
+ # Display chat messages
142
+ chat_container = st.container()
143
+ with chat_container:
144
+ for message in st.session_state.messages:
145
+ with st.chat_message(message["role"]):
146
+ st.markdown(message["content"])
147
+
148
+ # Chat input
149
+ if prompt := st.chat_input("Type your message here..."):
150
+ # Add user message to chat
151
+ st.session_state.messages.append({"role": "user", "content": prompt})
152
+
153
+ # Display user message immediately
154
+ with chat_container:
155
+ with st.chat_message("user"):
156
+ st.markdown(prompt)
157
+
158
+ # Get and display assistant response
159
+ with chat_container:
160
+ with st.chat_message("assistant"):
161
+ message_placeholder = st.empty()
162
+ with st.spinner("Claude is thinking..."):
163
+ response = get_claude_response(
164
+ st.session_state.client,
165
+ st.session_state.messages,
166
+ model
167
+ )
168
+ message_placeholder.markdown(response)
169
+
170
+ # Add assistant response to chat history
171
+ st.session_state.messages.append({"role": "assistant", "content": response})
172
+
173
+ # Display conversation stats
174
+ if st.session_state.messages:
175
+ st.sidebar.markdown("---")
176
+ st.sidebar.markdown(f"**Messages:** {len(st.session_state.messages)}")
177
+ st.sidebar.markdown(f"**Model:** {model}")
178
+
179
+ if __name__ == "__main__":
180
+ main()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ streamlit>=1.34.0
2
+ anthropic>=0.25.0