MADtoBAD commited on
Commit
93ede06
·
verified ·
1 Parent(s): c46b91a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -42
app.py CHANGED
@@ -1,83 +1,196 @@
1
  import gradio as gr
2
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
 
 
3
 
4
- class SimpleAIAgent:
5
  def __init__(self):
6
- print("Initializing AI Agent...")
7
 
8
- # Используем языковую модель от Hugging Face
9
- self.model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")
10
-
11
- # Инструмент для поиска в интернете
12
- self.search_tool = DuckDuckGoSearchTool()
13
-
14
- # Создаем агента который может искать в интернете
15
- self.agent = CodeAgent(
16
- tools=[self.search_tool],
17
- model=self.model,
18
- max_steps=4
19
  )
20
 
 
 
21
  print("AI Agent ready!")
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def chat(self, message, history):
24
  """
25
  Основная функция для общения с агентом
26
  """
27
  print(f"User asked: {message}")
28
 
29
- # Создаем инструкцию для агента
30
- prompt = f"""
31
- The user asked: {message}
32
-
33
- Please provide a helpful and accurate answer.
34
- If you need current information, use the search tool to find it online.
35
- Keep your response clear and conversational.
36
- """
37
-
38
  try:
39
- # Получаем ответ от агента
40
- response = self.agent.run(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Очищаем ответ от технических деталей
43
- clean_response = self.clean_answer(response)
44
- print(f"Agent replied: {clean_response[:100]}...")
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  return clean_response
47
 
48
  except Exception as e:
49
- error_msg = f"Sorry, I encountered an error: {str(e)}"
50
  print(f"Error: {e}")
51
- return error_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def clean_answer(self, answer):
54
  """
55
  Убираем техническую информацию из ответа агента
56
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  lines = answer.split('\n')
58
  clean_lines = []
59
 
60
  for line in lines:
61
- # Пропускаем строки про инструменты и процесс поиска
62
- lower_line = line.lower()
63
- if any(word in lower_line for word in ['tool:', 'searching', 'step', 'using tool']):
64
- continue
65
-
66
- # Пропускаем пустые строки в начале
67
- if line.strip():
68
  clean_lines.append(line)
69
 
70
  # Собираем обратно в текст
71
- result = '\n'.join(clean_lines).strip()
 
 
 
72
 
73
  # Если ответ слишком длинный, обрезаем
74
- if len(result) > 1500:
75
- result = result[:1497] + "..."
76
 
77
- return result if result else "I couldn't find a good answer to that question."
78
 
79
  # Создаем экземпляр агента
80
- ai_agent = SimpleAIAgent()
81
 
82
  # Создаем интерфейс чата
83
  with gr.Blocks(title="My AI Assistant") as chat_interface:
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+ from ddgs import DDGS
4
+ import re
5
 
6
+ class ImprovedAIAgent:
7
  def __init__(self):
8
+ print("Initializing Improved AI Agent...")
9
 
10
+ # Используем более подходящую модель для вопросов и ответов
11
+ self.model = pipeline(
12
+ "text-generation",
13
+ model="microsoft/DialoGPT-medium", # Более качественная чем small
14
+ max_length=400,
15
+ temperature=0.7,
16
+ do_sample=True
 
 
 
 
17
  )
18
 
19
+ # Инициализируем поиск
20
+ self.ddgs = DDGS()
21
  print("AI Agent ready!")
22
 
23
+ def needs_web_search(self, question):
24
+ """Определяем, нужен ли поиск в интернете для этого вопроса"""
25
+ question_lower = question.lower()
26
+
27
+ # Ключевые слова, которые требуют актуальной информации
28
+ search_keywords = [
29
+ 'current', 'today', 'now', 'latest', 'recent', 'weather',
30
+ 'news', '2024', '2023', 'update', 'breaking',
31
+ 'how to', 'tutorial', 'guide', 'steps to'
32
+ ]
33
+
34
+ # Вопросы, начинающиеся с what, who, when, where (фактологические)
35
+ factual_patterns = [
36
+ 'what is', 'who is', 'when did', 'where is', 'which country',
37
+ 'capital of', 'population of', 'president of'
38
+ ]
39
+
40
+ return (any(keyword in question_lower for keyword in search_keywords) or
41
+ any(question_lower.startswith(pattern) for pattern in factual_patterns))
42
+
43
+ def search_web(self, query):
44
+ """Поиск в интернете через DuckDuckGo"""
45
+ try:
46
+ results = list(self.ddgs.text(query, max_results=2))
47
+ if results:
48
+ # Собираем информацию из результатов
49
+ combined_info = []
50
+ for result in results:
51
+ text = result.get('body', '')
52
+ if text and len(text) > 20: # Фильтруем слишком короткие
53
+ combined_info.append(text[:300]) # Ограничиваем длину
54
+
55
+ if combined_info:
56
+ return " ".join(combined_info)
57
+ return None
58
+ except Exception as e:
59
+ print(f"Search error: {e}")
60
+ return None
61
+
62
  def chat(self, message, history):
63
  """
64
  Основная функция для общения с агентом
65
  """
66
  print(f"User asked: {message}")
67
 
 
 
 
 
 
 
 
 
 
68
  try:
69
+ # Определяем, нужен ли поиск в интернете
70
+ if self.needs_web_search(message):
71
+ search_result = self.search_web(message)
72
+
73
+ if search_result:
74
+ # Используем найденную информацию
75
+ prompt = f"""Based on this information: {search_result}
76
+
77
+ Please answer this question: {message}
78
+
79
+ Provide a clear and accurate answer:"""
80
+ else:
81
+ # Если поиск не дал результатов
82
+ prompt = f"""Please answer this question: {message}
83
+
84
+ If you don't know the answer, please say so."""
85
+ else:
86
+ # Для общих вопросов используем обычный промпт
87
+ prompt = f"User: {message}\nAssistant:"
88
+
89
+ # Генерируем ответ
90
+ response = self.model(
91
+ prompt,
92
+ max_length=500,
93
+ num_return_sequences=1,
94
+ temperature=0.7,
95
+ do_sample=True,
96
+ pad_token_id=50256,
97
+ repetition_penalty=1.2
98
+ )
99
 
100
+ # Извлекаем ответ
101
+ full_text = response[0]['generated_text']
 
102
 
103
+ # Извлекаем только ответ ассистента
104
+ if "Assistant:" in full_text:
105
+ answer = full_text.split("Assistant:")[-1].strip()
106
+ elif "answer:" in full_text.lower():
107
+ # Ищем после "answer:"
108
+ answer_match = re.search(r'answer:\s*(.*)', full_text, re.IGNORECASE)
109
+ answer = answer_match.group(1).strip() if answer_match else full_text
110
+ else:
111
+ # Убираем промпт из ответа
112
+ answer = full_text.replace(prompt, "").strip()
113
+
114
+ # Очищаем ответ
115
+ clean_response = self.clean_answer(answer)
116
+
117
+ # Проверяем, не является ли ответ бессмысленным
118
+ if self.is_nonsense_response(clean_response, message):
119
+ clean_response = "I'm not sure about that. Could you provide more context or rephrase your question?"
120
+
121
+ print(f"Assistant: {clean_response[:100]}...")
122
  return clean_response
123
 
124
  except Exception as e:
 
125
  print(f"Error: {e}")
126
+ return "I'm here to help! What would you like to know?"
127
+
128
+ def is_nonsense_response(self, response, question):
129
+ """Проверяем, является ли ответ бессмысленным"""
130
+ if not response or len(response) < 5:
131
+ return True
132
+
133
+ response_lower = response.lower()
134
+ question_lower = question.lower()
135
+
136
+ # Если ответ повторяет вопрос
137
+ if question_lower in response_lower and len(response) < len(question) + 10:
138
+ return True
139
+
140
+ # Если ответ содержит явно неподходящие фразы
141
+ nonsense_phrases = [
142
+ 'the user asked', 'please answer', 'based on this information',
143
+ 'provide a clear', 'i cannot answer', 'as an ai'
144
+ ]
145
+
146
+ if any(phrase in response_lower for phrase in nonsense_phrases):
147
+ return True
148
+
149
+ return False
150
 
151
  def clean_answer(self, answer):
152
  """
153
  Убираем техническую информацию из ответа агента
154
  """
155
+ if not answer:
156
+ return "I don't have an answer for that question."
157
+
158
+ # Убираем технические фразы
159
+ clean_patterns = [
160
+ r'based on this information:.*?provide a clear answer:',
161
+ r'please answer this question:.*?if you don\'t know',
162
+ r'user:.*?assistant:',
163
+ ]
164
+
165
+ for pattern in clean_patterns:
166
+ answer = re.sub(pattern, '', answer, flags=re.IGNORECASE | re.DOTALL)
167
+
168
+ # Разбиваем на строки и фильтруем
169
  lines = answer.split('\n')
170
  clean_lines = []
171
 
172
  for line in lines:
173
+ line = line.strip()
174
+ if line and len(line) > 3:
175
+ # Пропускаем технические строки
176
+ if any(word in line.lower() for word in ['tool:', 'searching', 'step', 'using tool']):
177
+ continue
 
 
178
  clean_lines.append(line)
179
 
180
  # Собираем обратно в текст
181
+ result = ' '.join(clean_lines)
182
+
183
+ # Убираем лишние пробелы
184
+ result = re.sub(r'\s+', ' ', result).strip()
185
 
186
  # Если ответ слишком длинный, обрезаем
187
+ if len(result) > 800:
188
+ result = result[:797] + "..."
189
 
190
+ return result if result else "I couldn't find a clear answer to that question."
191
 
192
  # Создаем экземпляр агента
193
+ ai_agent = ImprovedAIAgent()
194
 
195
  # Создаем интерфейс чата
196
  with gr.Blocks(title="My AI Assistant") as chat_interface: