seawolf2357 commited on
Commit
268ed5c
ยท
verified ยท
1 Parent(s): a4d6b56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -32
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="You are a deep thinking AI, you may use extremely long chains of thought to deeply consider the problem and deliberate with yourself via systematic reasoning processes to help come to a correct solution prior to answering. You should enclose your thoughts and internal monologue inside tags, and then provide your solution or response to the problem.",
 
 
 
 
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
- # Function to perform a web search using SerpHouse API
66
- def search_web(query):
67
- search_url = f"https://api.serphouse.com/serp/live?api_token=V38CNn4HXpLtynJQyOeoUensTEYoFy8PBUxKpDqAW1pawT1vfJ2BWtPQ98h6&q={query}&responseType=json&domain=google&lang=en&serp_type=web"
68
- response = requests.get(search_url)
69
- if response.status_code == 200:
70
- return response.json()
71
- else:
72
- logger.error(f"Error while searching: {response.status_code}")
73
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- # Perform a web search based on the user input
94
- search_results = search_web(prompt)
95
-
96
- # Process search results if available
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']}" for item in search_results["results"]["organic"]])
 
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
- # Dynamically construct the API URL based on the selected model
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
- # Query the Hugging Face API using the selected model
124
  output = query(payload, api_url)
125
-
126
- # Handle API response
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
- # Check for and remove duplicate responses
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)}")