Spaces:
Running
Running
import os | |
import streamlit as st | |
import json | |
import anthropic | |
# API ์ค์ | |
api_key = os.environ.get("API_KEY") | |
client = anthropic.Anthropic(api_key=api_key) | |
def get_system_prompt(): | |
return """๋น์ ์ ์น์ ํ๊ณ ์ ๋ฌธ์ ์ธ AI ์ด์์คํดํธ์ ๋๋ค. | |
๋ค์ ๊ฐ์ด๋๋ผ์ธ์ ๋ฐ๋ผ์ฃผ์ธ์: | |
- ์ ํํ๊ณ ์ ์ฉํ ์ ๋ณด๋ฅผ ์ ๊ณตํฉ๋๋ค | |
- ๋ถํ์คํ ๊ฒฝ์ฐ ๊ทธ ์ฌ์ค์ ์ธ์ ํฉ๋๋ค | |
- ์ํํ๊ฑฐ๋ ํด๋ก์ด ์กฐ์ธ์ ํ์ง ์์ต๋๋ค | |
- ๊ฐ์ธ์ ๋ณด๋ ๋ณดํธํฉ๋๋ค | |
- ์์ ๋ฐ๋ฅด๊ณ ๊ณต์ํ๊ฒ ์๋ตํฉ๋๋ค | |
- ํ๊ตญ์ด๋ก ์์ฐ์ค๋ฝ๊ฒ ๋ํํฉ๋๋ค""" | |
def chatbot_interface(): | |
st.title("AI ์ด์์คํดํธ์ ๋ํํ๊ธฐ") | |
# ๋ชจ๋ธ ๊ณ ์ ์ค์ (์ ํ ๋ฐ์ค ์ ๊ฑฐ) | |
if "ai_model" not in st.session_state: | |
st.session_state["ai_model"] = "claude-3-5-sonnet-20241022" | |
# ์ธ์ ์ํ ์ด๊ธฐํ | |
if "messages" not in st.session_state: | |
st.session_state.messages = [] | |
# ๋ํ ๊ธฐ๋ก ๋ถ๋ฌ์ค๊ธฐ | |
st.sidebar.title("๋ํ ๊ธฐ๋ก") | |
uploaded_file = st.sidebar.file_uploader("๋ํ ๊ธฐ๋ก JSON ํ์ผ ๋ถ๋ฌ์ค๊ธฐ") | |
if uploaded_file is not None: | |
st.session_state.messages = json.load(uploaded_file) | |
# ๋ฉ์์ง ํ์ | |
for message in st.session_state.messages: | |
with st.chat_message(message["role"]): | |
st.markdown(message["content"]) | |
# ์ฌ์ฉ์ ์ ๋ ฅ | |
if prompt := st.chat_input("๋ฌด์์ ๋์๋๋ฆด๊น์?"): | |
st.session_state.messages.append({"role": "user", "content": prompt}) | |
with st.chat_message("user"): | |
st.markdown(prompt) | |
# AI ์๋ต ์์ฑ | |
with st.chat_message("assistant"): | |
message_placeholder = st.empty() | |
full_response = "" | |
# Claude API ํธ์ถ | |
with client.messages.stream( | |
max_tokens=1024, | |
system=get_system_prompt(), | |
messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages], | |
model=st.session_state["ai_model"] | |
) as stream: | |
for text in stream.text_stream: | |
full_response += str(text) if text is not None else "" | |
message_placeholder.markdown(full_response + "โ") | |
message_placeholder.markdown(full_response) | |
st.session_state.messages.append({"role": "assistant", "content": full_response}) | |
# ๋ํ ๊ธฐ๋ก ๋ค์ด๋ก๋ | |
if st.button("๋ํ ๊ธฐ๋ก ๋ค์ด๋ก๋"): | |
json_history = json.dumps(st.session_state.messages, indent=4) | |
st.download_button( | |
label="๋ํ ๊ธฐ๋ก ์ ์ฅํ๊ธฐ", | |
data=json_history, | |
file_name="chat_history.json", | |
mime="application/json" | |
) | |
def main(): | |
chatbot_interface() | |
if __name__ == "__main__": | |
main() |