Teo Cheng Lim commited on
Commit
777b5e9
·
unverified ·
1 Parent(s): f975d03

using multi turn

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +38 -46
src/streamlit_app.py CHANGED
@@ -2,14 +2,15 @@ import streamlit as st
2
  import requests
3
  import os
4
 
5
- # Load your OpenRouter API key
6
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") or st.secrets.get("OPENROUTER_API_KEY", "")
7
  MODEL_NAME = "deepseek/deepseek-r1-0528:free"
 
8
 
9
- # App title
10
- st.title("WhatsApp-like Chat with DeepSeek-R1")
11
 
12
- # Custom CSS
13
  st.markdown("""
14
  <style>
15
  .stChatMessage { background-color: transparent !important; padding: 0 !important; width: 100%; }
@@ -29,35 +30,28 @@ st.markdown("""
29
  </style>
30
  """, unsafe_allow_html=True)
31
 
32
- # Initialize chat history
33
  if "messages" not in st.session_state:
34
  st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant."}]
35
 
36
- # Display chat messages
37
- for message in st.session_state.messages:
38
- if message["role"] == "system":
39
  continue
40
- with st.chat_message(message["role"]):
41
- if message["role"] == "user":
42
- st.markdown(f"""
43
- <div class="user-container">
44
- <div class="user-label sender-label">You:</div>
45
- <div class="user-message">{message['content']}</div>
46
- </div>
47
- """, unsafe_allow_html=True)
48
- else:
49
- st.markdown(f"""
50
- <div class="assistant-container">
51
- <div class="assistant-label sender-label">Bot:</div>
52
- <div class="assistant-message">{message['content']}</div>
53
- </div>
54
- """, unsafe_allow_html=True)
55
 
56
- # Input field
57
  if prompt := st.chat_input("Type your message..."):
 
58
  st.session_state.messages.append({"role": "user", "content": prompt})
59
-
60
- # Show user message immediately
61
  with st.chat_message("user"):
62
  st.markdown(f"""
63
  <div class="user-container">
@@ -66,7 +60,6 @@ if prompt := st.chat_input("Type your message..."):
66
  </div>
67
  """, unsafe_allow_html=True)
68
 
69
- # Show assistant reply placeholder
70
  with st.chat_message("assistant"):
71
  placeholder = st.empty()
72
  placeholder.markdown("""
@@ -76,28 +69,28 @@ if prompt := st.chat_input("Type your message..."):
76
  </div>
77
  """, unsafe_allow_html=True)
78
 
79
- # Call OpenRouter
80
- headers = {
81
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
82
- "Content-Type": "application/json",
83
- "HTTP-Referer": "https://your-app-name.streamlit.app/",
84
- "X-Title": "DeepSeek WhatsApp Chat"
85
- }
 
 
 
 
 
 
86
 
87
- body = {
88
- "model": MODEL_NAME,
89
- "messages": st.session_state.messages,
90
- "stream": False # OpenRouter's free models might not support streaming
91
- }
92
 
93
- try:
94
- res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=body)
95
- res.raise_for_status()
96
- full_response = res.json()["choices"][0]["message"]["content"]
97
  except Exception as e:
98
- full_response = f"Error: {str(e)}"
99
 
100
- # Render final response
101
  placeholder.markdown(f"""
102
  <div class="assistant-container">
103
  <div class="assistant-label sender-label">Bot:</div>
@@ -105,5 +98,4 @@ if prompt := st.chat_input("Type your message..."):
105
  </div>
106
  """, unsafe_allow_html=True)
107
 
108
- # Save assistant reply
109
  st.session_state.messages.append({"role": "assistant", "content": full_response})
 
2
  import requests
3
  import os
4
 
5
+ # === Constants ===
6
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") or st.secrets.get("OPENROUTER_API_KEY", "")
7
  MODEL_NAME = "deepseek/deepseek-r1-0528:free"
8
+ API_URL = "https://openrouter.ai/api/v1/chat/completions"
9
 
10
+ # === Streamlit UI Setup ===
11
+ st.title("💬 Chat with DeepSeek-R1 (Free via OpenRouter)")
12
 
13
+ # Custom WhatsApp-style CSS
14
  st.markdown("""
15
  <style>
16
  .stChatMessage { background-color: transparent !important; padding: 0 !important; width: 100%; }
 
30
  </style>
31
  """, unsafe_allow_html=True)
32
 
33
+ # === Chat History ===
34
  if "messages" not in st.session_state:
35
  st.session_state.messages = [{"role": "system", "content": "You are a helpful assistant."}]
36
 
37
+ # === Display Chat History ===
38
+ for msg in st.session_state.messages:
39
+ if msg["role"] == "system":
40
  continue
41
+ with st.chat_message(msg["role"]):
42
+ content_html = f"""
43
+ <div class="{msg['role']}-container">
44
+ <div class="{msg['role']}-label sender-label">{'You' if msg['role']=='user' else 'Bot'}:</div>
45
+ <div class="{msg['role']}-message">{msg['content']}</div>
46
+ </div>
47
+ """
48
+ st.markdown(content_html, unsafe_allow_html=True)
 
 
 
 
 
 
 
49
 
50
+ # === User Input ===
51
  if prompt := st.chat_input("Type your message..."):
52
+ # Add user message
53
  st.session_state.messages.append({"role": "user", "content": prompt})
54
+
 
55
  with st.chat_message("user"):
56
  st.markdown(f"""
57
  <div class="user-container">
 
60
  </div>
61
  """, unsafe_allow_html=True)
62
 
 
63
  with st.chat_message("assistant"):
64
  placeholder = st.empty()
65
  placeholder.markdown("""
 
69
  </div>
70
  """, unsafe_allow_html=True)
71
 
72
+ # === OpenRouter API Call ===
73
+ try:
74
+ headers = {
75
+ "Authorization": f"Bearer {OPENROUTER_API_KEY}",
76
+ "Content-Type": "application/json",
77
+ "HTTP-Referer": "https://your-app-name.streamlit.app/", # required for free tier
78
+ "X-Title": "Streamlit WhatsApp Chatbot"
79
+ }
80
+ payload = {
81
+ "model": MODEL_NAME,
82
+ "messages": st.session_state.messages,
83
+ "stream": False
84
+ }
85
 
86
+ response = requests.post(API_URL, headers=headers, json=payload)
87
+ response.raise_for_status()
88
+ full_response = response.json()["choices"][0]["message"]["content"]
 
 
89
 
 
 
 
 
90
  except Exception as e:
91
+ full_response = f"Error: {e}"
92
 
93
+ # Display and store assistant message
94
  placeholder.markdown(f"""
95
  <div class="assistant-container">
96
  <div class="assistant-label sender-label">Bot:</div>
 
98
  </div>
99
  """, unsafe_allow_html=True)
100
 
 
101
  st.session_state.messages.append({"role": "assistant", "content": full_response})