Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,24 @@ import streamlit as st
|
|
| 2 |
import requests
|
| 3 |
import logging
|
| 4 |
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# Configure logging
|
| 7 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -31,7 +49,11 @@ with st.sidebar:
|
|
| 31 |
|
| 32 |
system_message = st.text_area(
|
| 33 |
"System Message",
|
| 34 |
-
value=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
height=100
|
| 36 |
)
|
| 37 |
|
|
@@ -62,15 +84,84 @@ def query(payload, api_url):
|
|
| 62 |
logger.error(f"Failed to decode JSON response: {response.text}")
|
| 63 |
return None
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
def search_web(query):
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
# Chat interface
|
| 76 |
st.title("๐ค DeepSeek Chatbot")
|
|
@@ -90,22 +181,22 @@ if prompt := st.chat_input("Type your message..."):
|
|
| 90 |
|
| 91 |
try:
|
| 92 |
with st.spinner("Generating response..."):
|
| 93 |
-
#
|
| 94 |
-
search_results = search_web(prompt)
|
| 95 |
-
|
| 96 |
-
#
|
| 97 |
if search_results and "results" in search_results:
|
| 98 |
if 'organic' in search_results["results"]:
|
| 99 |
-
search_content = "\n".join([f"**{item['title']}**: {item['snippet']}"
|
|
|
|
| 100 |
search_content = f"Here are some search results related to your question:\n\n{search_content}\n\n"
|
| 101 |
else:
|
| 102 |
search_content = "Sorry, no relevant search results found.\n\n"
|
| 103 |
-
|
| 104 |
-
# Combine the system message, search results, and user input into a single prompt
|
| 105 |
full_prompt = f"{system_message}\n\n{search_content}User: {prompt}\nAssistant:"
|
| 106 |
else:
|
| 107 |
full_prompt = f"{system_message}\n\nUser: {prompt}\nAssistant:"
|
| 108 |
-
|
| 109 |
payload = {
|
| 110 |
"inputs": full_prompt,
|
| 111 |
"parameters": {
|
|
@@ -115,30 +206,28 @@ if prompt := st.chat_input("Type your message..."):
|
|
| 115 |
"return_full_text": False
|
| 116 |
}
|
| 117 |
}
|
| 118 |
-
|
| 119 |
-
#
|
| 120 |
api_url = f"https://api-inference.huggingface.co/models/{selected_model}"
|
| 121 |
logger.info(f"Selected model: {selected_model}, API URL: {api_url}")
|
| 122 |
-
|
| 123 |
-
#
|
| 124 |
output = query(payload, api_url)
|
| 125 |
-
|
| 126 |
-
#
|
| 127 |
if output is not None and isinstance(output, list) and len(output) > 0:
|
| 128 |
if 'generated_text' in output[0]:
|
| 129 |
-
# Extract the assistant's response
|
| 130 |
assistant_response = output[0]['generated_text'].strip()
|
| 131 |
-
|
| 132 |
-
#
|
| 133 |
responses = assistant_response.split("\n</think>\n")
|
| 134 |
unique_response = responses[0].strip()
|
| 135 |
-
|
| 136 |
logger.info(f"Generated response: {unique_response}")
|
| 137 |
-
|
| 138 |
-
# Append response to chat only once
|
| 139 |
with st.chat_message("assistant"):
|
| 140 |
st.markdown(unique_response)
|
| 141 |
-
|
| 142 |
st.session_state.messages.append({"role": "assistant", "content": unique_response})
|
| 143 |
else:
|
| 144 |
logger.error(f"Unexpected API response structure: {output}")
|
|
@@ -146,7 +235,7 @@ if prompt := st.chat_input("Type your message..."):
|
|
| 146 |
else:
|
| 147 |
logger.error(f"Empty or invalid API response: {output}")
|
| 148 |
st.error("Error: Unable to generate a response. Please check the model and try again.")
|
| 149 |
-
|
| 150 |
except Exception as e:
|
| 151 |
logger.error(f"Application Error: {str(e)}", exc_info=True)
|
| 152 |
st.error(f"Application Error: {str(e)}")
|
|
|
|
| 2 |
import requests
|
| 3 |
import logging
|
| 4 |
import json
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
from requests.adapters import HTTPAdapter
|
| 7 |
+
from urllib3.util.retry import Retry
|
| 8 |
+
|
| 9 |
+
# --- Optional: translate_query ๋ฐ ๊ด๋ จ ์์ ์ ์ (์ค์ ๊ตฌํ์ ๋ง๊ฒ ์์ ) ---
|
| 10 |
+
def translate_query(query, country):
|
| 11 |
+
# ์ค์ ์ํฉ์์๋ ๋ฒ์ญ ๋ก์ง์ ๊ตฌํํ์ธ์.
|
| 12 |
+
return query
|
| 13 |
+
|
| 14 |
+
COUNTRY_LOCATIONS = {
|
| 15 |
+
"United States": "United States",
|
| 16 |
+
"South Korea": "South Korea"
|
| 17 |
+
}
|
| 18 |
+
COUNTRY_LANGUAGES = {
|
| 19 |
+
"United States": "en",
|
| 20 |
+
"South Korea": "ko"
|
| 21 |
+
}
|
| 22 |
+
# -------------------------------------------------------------------------
|
| 23 |
|
| 24 |
# Configure logging
|
| 25 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 49 |
|
| 50 |
system_message = st.text_area(
|
| 51 |
"System Message",
|
| 52 |
+
value=(
|
| 53 |
+
"You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and "
|
| 54 |
+
"deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. "
|
| 55 |
+
"You should enclose your thoughts and internal monologue inside tags, and then provide your solution or response to the problem."
|
| 56 |
+
),
|
| 57 |
height=100
|
| 58 |
)
|
| 59 |
|
|
|
|
| 84 |
logger.error(f"Failed to decode JSON response: {response.text}")
|
| 85 |
return None
|
| 86 |
|
| 87 |
+
# --- ์์ ๋ ์น์์น ๊ธฐ๋ฅ ---
|
| 88 |
+
def search_web(query, country="United States", page=1, num_result=10):
|
| 89 |
+
url = "https://api.serphouse.com/serp/live"
|
| 90 |
+
|
| 91 |
+
# ์ต๊ทผ 24์๊ฐ ๊ธฐ๊ฐ ์ค์
|
| 92 |
+
now = datetime.utcnow()
|
| 93 |
+
yesterday = now - timedelta(days=1)
|
| 94 |
+
date_range = f"{yesterday.strftime('%Y-%m-%d')},{now.strftime('%Y-%m-%d')}"
|
| 95 |
+
|
| 96 |
+
# ์ฟผ๋ฆฌ ๋ฒ์ญ (ํ์์)
|
| 97 |
+
translated_query = translate_query(query, country)
|
| 98 |
+
|
| 99 |
+
payload = {
|
| 100 |
+
"data": {
|
| 101 |
+
"q": translated_query,
|
| 102 |
+
"domain": "google.com",
|
| 103 |
+
"loc": COUNTRY_LOCATIONS.get(country, "United States"),
|
| 104 |
+
"lang": COUNTRY_LANGUAGES.get(country, "en"),
|
| 105 |
+
"device": "desktop",
|
| 106 |
+
"serp_type": "web", # ๊ฒ์ ์ ํ์ "web"์ผ๋ก ์ค์ (์ํ๋ ๊ฒฝ์ฐ "news" ๋ฑ์ผ๋ก ๋ณ๊ฒฝ ๊ฐ๋ฅ)
|
| 107 |
+
"page": str(page),
|
| 108 |
+
"num": str(num_result),
|
| 109 |
+
"date_range": date_range,
|
| 110 |
+
"sort_by": "date"
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
# st.secrets์ SERPHOUSE_API_TOKEN์ด ์ ์ฅ๋์ด ์์ด์ผ ํฉ๋๋ค.
|
| 115 |
+
api_key = st.secrets.get("SERPHOUSE_API_TOKEN")
|
| 116 |
+
if not api_key:
|
| 117 |
+
logger.error("SERPHOUSE_API_TOKEN not found in st.secrets")
|
| 118 |
+
return {"error": "API token not configured."}
|
| 119 |
+
|
| 120 |
+
headers = {
|
| 121 |
+
"accept": "application/json",
|
| 122 |
+
"content-type": "application/json",
|
| 123 |
+
"authorization": f"Bearer {api_key}"
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
# ์ธ์
๊ณผ ์ฌ์๋ ์ค์
|
| 128 |
+
session = requests.Session()
|
| 129 |
+
retries = Retry(
|
| 130 |
+
total=5,
|
| 131 |
+
backoff_factor=1,
|
| 132 |
+
status_forcelist=[500, 502, 503, 504, 429],
|
| 133 |
+
allowed_methods=["POST"]
|
| 134 |
+
)
|
| 135 |
+
adapter = HTTPAdapter(max_retries=retries)
|
| 136 |
+
session.mount('http://', adapter)
|
| 137 |
+
session.mount('https://', adapter)
|
| 138 |
+
|
| 139 |
+
# ์ฐ๊ฒฐ ๋ฐ ์ฝ๊ธฐ ํ์์์ 30์ด์ฉ ์ค์
|
| 140 |
+
response = session.post(
|
| 141 |
+
url,
|
| 142 |
+
json=payload,
|
| 143 |
+
headers=headers,
|
| 144 |
+
timeout=(30, 30)
|
| 145 |
+
)
|
| 146 |
+
response.raise_for_status()
|
| 147 |
+
return {"results": response.json(), "translated_query": translated_query}
|
| 148 |
+
|
| 149 |
+
except requests.exceptions.Timeout:
|
| 150 |
+
return {
|
| 151 |
+
"error": "๊ฒ์ ์๊ฐ์ด ์ด๊ณผ๋์์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์.",
|
| 152 |
+
"translated_query": query
|
| 153 |
+
}
|
| 154 |
+
except requests.exceptions.RequestException as e:
|
| 155 |
+
return {
|
| 156 |
+
"error": f"๊ฒ์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {str(e)}",
|
| 157 |
+
"translated_query": query
|
| 158 |
+
}
|
| 159 |
+
except Exception as e:
|
| 160 |
+
return {
|
| 161 |
+
"error": f"์๊ธฐ์น ์์ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {str(e)}",
|
| 162 |
+
"translated_query": query
|
| 163 |
+
}
|
| 164 |
+
# --- ๋ ---
|
| 165 |
|
| 166 |
# Chat interface
|
| 167 |
st.title("๐ค DeepSeek Chatbot")
|
|
|
|
| 181 |
|
| 182 |
try:
|
| 183 |
with st.spinner("Generating response..."):
|
| 184 |
+
# ์
๋ฐ์ดํธ๋ ์น์์น ๊ธฐ๋ฅ์ ์ฌ์ฉํ์ฌ ๊ฒ์ ์ํ
|
| 185 |
+
search_results = search_web(prompt, country="United States", page=1, num_result=10)
|
| 186 |
+
|
| 187 |
+
# ๊ฒ์ ๊ฒฐ๊ณผ ์ฒ๋ฆฌ (API ์๋ต ๊ตฌ์กฐ์ ๋ฐ๋ผ ์ ์ ํ ์์ ํ์)
|
| 188 |
if search_results and "results" in search_results:
|
| 189 |
if 'organic' in search_results["results"]:
|
| 190 |
+
search_content = "\n".join([f"**{item['title']}**: {item['snippet']}"
|
| 191 |
+
for item in search_results["results"]["organic"]])
|
| 192 |
search_content = f"Here are some search results related to your question:\n\n{search_content}\n\n"
|
| 193 |
else:
|
| 194 |
search_content = "Sorry, no relevant search results found.\n\n"
|
| 195 |
+
|
|
|
|
| 196 |
full_prompt = f"{system_message}\n\n{search_content}User: {prompt}\nAssistant:"
|
| 197 |
else:
|
| 198 |
full_prompt = f"{system_message}\n\nUser: {prompt}\nAssistant:"
|
| 199 |
+
|
| 200 |
payload = {
|
| 201 |
"inputs": full_prompt,
|
| 202 |
"parameters": {
|
|
|
|
| 206 |
"return_full_text": False
|
| 207 |
}
|
| 208 |
}
|
| 209 |
+
|
| 210 |
+
# ์ ํํ ๋ชจ๋ธ์ ๋ฐ๋ฅธ API URL ๋์ ๊ตฌ์ฑ
|
| 211 |
api_url = f"https://api-inference.huggingface.co/models/{selected_model}"
|
| 212 |
logger.info(f"Selected model: {selected_model}, API URL: {api_url}")
|
| 213 |
+
|
| 214 |
+
# Hugging Face API์ ์ฟผ๋ฆฌ ์ ์ก
|
| 215 |
output = query(payload, api_url)
|
| 216 |
+
|
| 217 |
+
# ์๋ต ์ฒ๋ฆฌ
|
| 218 |
if output is not None and isinstance(output, list) and len(output) > 0:
|
| 219 |
if 'generated_text' in output[0]:
|
|
|
|
| 220 |
assistant_response = output[0]['generated_text'].strip()
|
| 221 |
+
|
| 222 |
+
# ์ค๋ณต ์๋ต ์ ๊ฑฐ (๋ด๋ถ ์ฒด์ธ ์ค ์ผ๋ถ ์ ๊ฑฐ)
|
| 223 |
responses = assistant_response.split("\n</think>\n")
|
| 224 |
unique_response = responses[0].strip()
|
| 225 |
+
|
| 226 |
logger.info(f"Generated response: {unique_response}")
|
| 227 |
+
|
|
|
|
| 228 |
with st.chat_message("assistant"):
|
| 229 |
st.markdown(unique_response)
|
| 230 |
+
|
| 231 |
st.session_state.messages.append({"role": "assistant", "content": unique_response})
|
| 232 |
else:
|
| 233 |
logger.error(f"Unexpected API response structure: {output}")
|
|
|
|
| 235 |
else:
|
| 236 |
logger.error(f"Empty or invalid API response: {output}")
|
| 237 |
st.error("Error: Unable to generate a response. Please check the model and try again.")
|
| 238 |
+
|
| 239 |
except Exception as e:
|
| 240 |
logger.error(f"Application Error: {str(e)}", exc_info=True)
|
| 241 |
st.error(f"Application Error: {str(e)}")
|