Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#Add loading and display in st.code of the history. Add and display a dataframe with the input and output pair in an editable grid and code listing: import streamlit as st
|
2 |
+
import anthropic
|
3 |
+
import os
|
4 |
+
import base64
|
5 |
+
from streamlit.components.v1 import html
|
6 |
+
|
7 |
+
# Set up the Anthropic client
|
8 |
+
client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
|
9 |
+
|
10 |
+
# Initialize session state
|
11 |
+
if "chat_history" not in st.session_state:
|
12 |
+
st.session_state.chat_history = []
|
13 |
+
|
14 |
+
# Function to get file download link
|
15 |
+
def get_download_link(file_contents, file_name):
|
16 |
+
b64 = base64.b64encode(file_contents.encode()).decode()
|
17 |
+
return f'<a href="data:file/txt;base64,{b64}" download="{file_name}">Download {file_name}</a>'
|
18 |
+
|
19 |
+
# Streamlit app
|
20 |
+
def main():
|
21 |
+
st.title("Claude 3.5 Sonnet API Demo")
|
22 |
+
|
23 |
+
# User input
|
24 |
+
user_input = st.text_input("Enter your message:", key="user_input")
|
25 |
+
|
26 |
+
if user_input:
|
27 |
+
# Call Claude API
|
28 |
+
response = client.messages.create(
|
29 |
+
model="claude-3-sonnet-20240229",
|
30 |
+
max_tokens=1000,
|
31 |
+
messages=[
|
32 |
+
{"role": "user", "content": user_input}
|
33 |
+
]
|
34 |
+
)
|
35 |
+
|
36 |
+
# Append to chat history
|
37 |
+
st.session_state.chat_history.append({"user": user_input, "claude": response.content[0].text})
|
38 |
+
|
39 |
+
# Clear user input
|
40 |
+
st.session_state.user_input = ""
|
41 |
+
|
42 |
+
# Display chat history
|
43 |
+
for chat in st.session_state.chat_history:
|
44 |
+
st.chat_message(chat["user"], is_user=True)
|
45 |
+
st.chat_message(chat["claude"], avatar_style="thumbs", seed="Claude")
|
46 |
+
|
47 |
+
# Save chat history to file
|
48 |
+
chat_history_text = "\n".join([f"User: {chat['user']}\nClaude: {chat['claude']}" for chat in st.session_state.chat_history])
|
49 |
+
file_download_link = get_download_link(chat_history_text, "chat_history.txt")
|
50 |
+
st.markdown(file_download_link, unsafe_allow_html=True)
|
51 |
+
|
52 |
+
if __name__ == "__main__":
|
53 |
+
main()
|