Pokilondron56 commited on
Commit
df16ebd
·
verified ·
1 Parent(s): 3d5457e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -11
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
-
 
4
  # ==== Константы ====
5
  MODEL_NAME = "openai/gpt-oss-20b"
6
  SYSTEM_MESSAGE = "Ты Pok.Bot, ты используешь открытую локальную модель GPT-OSS от OpenAI, не GPT-4 (наверно😆). Тебя создал POKilondron. Используй емодзи 😄."
@@ -9,26 +10,62 @@ TEMPERATURE = 0.7
9
  TOP_P = 0.95
10
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def respond(message, history: list[dict[str, str]], hf_token: gr.OAuthToken):
13
- """
14
- Chat handler using Hugging Face Inference API
15
- """
16
  client = InferenceClient(token=hf_token.token, model=MODEL_NAME)
17
 
 
 
 
 
18
  messages = [{"role": "system", "content": SYSTEM_MESSAGE}]
 
 
 
19
  messages.extend(history)
20
  messages.append({"role": "user", "content": message})
21
 
22
  response = ""
23
-
24
- for message in client.chat_completion(
25
  messages,
26
  max_tokens=MAX_TOKENS,
27
  stream=True,
28
  temperature=TEMPERATURE,
29
  top_p=TOP_P,
30
  ):
31
- choices = message.choices
32
  token = ""
33
  if len(choices) and choices[0].delta.content:
34
  token = choices[0].delta.content
@@ -41,7 +78,7 @@ def respond(message, history: list[dict[str, str]], hf_token: gr.OAuthToken):
41
  chatbot = gr.ChatInterface(
42
  respond,
43
  type="messages",
44
- additional_inputs=[], # настройки отключены
45
  )
46
 
47
  with gr.Blocks() as demo:
@@ -50,6 +87,4 @@ with gr.Blocks() as demo:
50
  chatbot.render()
51
 
52
  if __name__ == "__main__":
53
- demo.launch()
54
-
55
-
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import requests
4
+ import re
5
  # ==== Константы ====
6
  MODEL_NAME = "openai/gpt-oss-20b"
7
  SYSTEM_MESSAGE = "Ты Pok.Bot, ты используешь открытую локальную модель GPT-OSS от OpenAI, не GPT-4 (наверно😆). Тебя создал POKilondron. Используй емодзи 😄."
 
10
  TOP_P = 0.95
11
 
12
 
13
+ (DuckDuckGo API) ====
14
+ def search_web(query: str, max_results: int = 3):
15
+ """Ищет информацию в интернете через DuckDuckGo API"""
16
+ url = f"https://api.duckduckgo.com/?q={query}&format=json"
17
+ try:
18
+ r = requests.get(url, timeout=10)
19
+ r.raise_for_status()
20
+ data = r.json()
21
+ except Exception as e:
22
+ return f"⚠️ Ошибка поиска: {e}"
23
+
24
+ results = []
25
+ if "RelatedTopics" in data:
26
+ for i, item in enumerate(data["RelatedTopics"][:max_results]):
27
+ if "Text" in item and "FirstURL" in item:
28
+ results.append(f"- {item['Text']} ({item['FirstURL']})")
29
+
30
+ return "\n".join(results) if results else "Ничего не найдено."
31
+
32
+
33
+ # ==== Детектор необходимости поиска ====
34
+ def needs_search(message: str) -> bool:
35
+ """Решает, нужно ли использовать интернет"""
36
+ keywords = [
37
+ r"\bсейчас\b", r"\bсегодня\b", r"\bновости\b",
38
+ r"\bкурс\b", r"\bпогода\b", r"\bцена\b",
39
+ r"\b202[3-9]\b", # годы 2023–2029
40
+ r"\bпоследн"
41
+ ]
42
+ return any(re.search(pat, message.lower()) for pat in keywords)
43
+
44
+
45
+ # ==== Основная функция ====
46
  def respond(message, history: list[dict[str, str]], hf_token: gr.OAuthToken):
 
 
 
47
  client = InferenceClient(token=hf_token.token, model=MODEL_NAME)
48
 
49
+ web_context = ""
50
+ if needs_search(message):
51
+ web_context = search_web(message)
52
+
53
  messages = [{"role": "system", "content": SYSTEM_MESSAGE}]
54
+ if web_context:
55
+ messages.append({"role": "system", "content": f"Web context:\n{web_context}"})
56
+
57
  messages.extend(history)
58
  messages.append({"role": "user", "content": message})
59
 
60
  response = ""
61
+ for msg in client.chat_completion(
 
62
  messages,
63
  max_tokens=MAX_TOKENS,
64
  stream=True,
65
  temperature=TEMPERATURE,
66
  top_p=TOP_P,
67
  ):
68
+ choices = msg.choices
69
  token = ""
70
  if len(choices) and choices[0].delta.content:
71
  token = choices[0].delta.content
 
78
  chatbot = gr.ChatInterface(
79
  respond,
80
  type="messages",
81
+ additional_inputs=[],
82
  )
83
 
84
  with gr.Blocks() as demo:
 
87
  chatbot.render()
88
 
89
  if __name__ == "__main__":
90
+ demo.launch()