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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -157
app.py CHANGED
@@ -1,189 +1,110 @@
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("Starting Improved AI Agent...")
9
 
10
- # Используем более умную модель для фактов
11
- self.model = pipeline(
12
- "text-generation",
13
- model="microsoft/DialoGPT-medium", # Более качественная чем small
14
- max_length=300,
15
- temperature=0.3, # Меньше креативности, больше фактов
16
- do_sample=True
17
- )
18
 
19
- # Инициализируем поиск
20
- self.ddgs = DDGS()
21
- print("Improved AI Agent ready!")
22
-
23
- def search_web(self, query):
24
- """Поиск в интернете через DuckDuckGo"""
25
- try:
26
- results = list(self.ddgs.text(query, max_results=3))
27
- if results:
28
- # Собираем информацию из нескольких результатов
29
- combined_info = []
30
- for result in results[:2]: # Берем первые 2 результата
31
- text = result.get('body', '')
32
- if text and len(text) > 10: # Фильтруем слишком короткие
33
- combined_info.append(text[:200]) # Ограничиваем длину
34
-
35
- if combined_info:
36
- return " | ".join(combined_info)
37
- return None
38
- except Exception as e:
39
- print(f"Search error: {e}")
40
- return None
41
-
42
- def is_factual_question(self, question):
43
- """Определяем, является ли вопрос фактологическим"""
44
- question_lower = question.lower()
45
 
46
- factual_keywords = [
47
- 'what', 'who', 'when', 'where', 'which', 'how many', 'how much',
48
- 'capital', 'population', 'president', 'country', 'city',
49
- 'define', 'definition', 'is the', 'are the'
50
- ]
 
51
 
52
- return any(keyword in question_lower for keyword in factual_keywords)
53
-
54
  def chat(self, message, history):
55
- print(f"User: {message}")
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  try:
58
- # Для фактологических вопросов используем поиск
59
- if self.is_factual_question(message):
60
- search_result = self.search_web(message)
61
-
62
- if search_result:
63
- # Промпт с найденной информацией
64
- prompt = f"""Based on this information: {search_result}
65
-
66
- Question: {message}
67
-
68
- Provide a concise and accurate answer:"""
69
- else:
70
- # Если поиск не сработал, используем общий промпт
71
- prompt = f"""Answer this question accurately: {message}
72
-
73
- If you don't know the exact answer, say so."""
74
- else:
75
- # Для не-фактологических вопросов используем обычный чат
76
- prompt = f"User: {message}\nAssistant:"
77
-
78
- # Генерируем ответ
79
- response = self.model(
80
- prompt,
81
- max_length=400,
82
- num_return_sequences=1,
83
- temperature=0.3, # Низкая температура для фактов
84
- do_sample=True,
85
- pad_token_id=50256,
86
- repetition_penalty=1.3
87
- )
88
-
89
- # Извлекаем ответ
90
- full_text = response[0]['generated_text']
91
 
92
- if "Answer:" in full_text:
93
- answer = full_text.split("Answer:")[-1].strip()
94
- elif "Assistant:" in full_text:
95
- answer = full_text.split("Assistant:")[-1].strip()
96
- else:
97
- answer = full_text.replace(prompt, "").strip()
98
 
99
- # Очищаем ответ
100
- clean_answer = self.clean_response(answer)
101
-
102
- # Если ответ явно неправильный, даем запасной ответ
103
- if self.is_wrong_answer(clean_answer, message):
104
- clean_answer = "I'm not sure about that. Let me search for more information."
105
- search_fallback = self.search_web(message)
106
- if search_fallback:
107
- clean_answer = f"Based on what I found: {search_fallback[:300]}..."
108
-
109
- print(f"Assistant: {clean_answer[:100]}...")
110
- return clean_answer
111
 
112
  except Exception as e:
 
113
  print(f"Error: {e}")
114
- return "Let me check that for you. Could you rephrase your question?"
115
-
116
- def is_wrong_answer(self, answer, question):
117
- """Проверяем, явно ли неправильный ответ"""
118
- answer_lower = answer.lower()
119
- question_lower = question.lower()
120
-
121
- # Если вопрос про столицу, но ответ не похож на название города
122
- if 'capital' in question_lower:
123
- # Проверяем, содержит ли ответ название города
124
- if not any(indicator in answer_lower for indicator in ['city', 'capital', 'is']):
125
- return True
126
- # Если ответ содержит "ambassador" или подобное для вопроса о столице - это ошибка
127
- if 'ambassador' in answer_lower:
128
- return True
129
-
130
- return False
131
-
132
- def clean_response(self, text):
133
- """Очистка ответа"""
134
- # Убираем технические части
135
- text = re.sub(r'Based on this information:.*?Provide a concise answer:', '', text, flags=re.DOTALL)
136
- text = re.sub(r'Question:.*?Answer:', '', text, flags=re.DOTALL)
137
-
138
- # Берем первую релевантную часть
139
- sentences = text.split('.')
140
- clean_sentences = []
141
-
142
- for sentence in sentences:
143
- sentence = sentence.strip()
144
- if sentence and len(sentence) > 5:
145
- clean_sentences.append(sentence)
146
- if len(clean_sentences) >= 2: # Ограничиваем 2 предложениями
147
- break
148
 
149
- result = '. '.join(clean_sentences)
150
- if result and not result.endswith('.'):
151
- result += '.'
 
 
 
 
 
 
152
 
153
- if len(result) > 300:
154
- result = result[:297] + "..."
155
 
156
- return result if result else "I need more information to answer that accurately."
 
 
 
 
157
 
158
- # Создаем агента
159
- agent = ImprovedAIAgent()
160
 
161
- # Создаем интерфейс
162
- with gr.Blocks() as app:
163
- gr.Markdown("# Improved AI Assistant")
164
- gr.Markdown("I can answer factual questions using web search")
165
-
166
- chatbot = gr.Chatbot(
167
- height=400,
168
- show_copy_button=True
169
- )
170
 
 
 
171
  msg = gr.Textbox(
172
  label="Your question",
173
- placeholder="Ask me factual questions...",
174
  lines=2
175
  )
176
-
177
- clear = gr.Button("Clear Chat")
178
 
179
  def respond(message, chat_history):
180
- bot_message = agent.chat(message, chat_history)
181
- chat_history.append((message, bot_message))
 
 
182
  return "", chat_history
183
 
 
184
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
185
- clear.click(lambda: None, None, chatbot, queue=False)
186
 
 
187
  if __name__ == "__main__":
188
- print("Starting Improved AI Assistant...")
189
- app.launch()
 
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:
84
+ gr.Markdown("# My AI Assistant")
85
+ gr.Markdown("Ask me anything! I can search the internet for current information.")
 
 
 
 
 
86
 
87
+ # Создаем чат-интерфейс
88
+ chatbot = gr.Chatbot(height=400)
89
  msg = gr.Textbox(
90
  label="Your question",
91
+ placeholder="Ask me anything...",
92
  lines=2
93
  )
94
+ clear_btn = gr.Button("Clear Chat")
 
95
 
96
  def respond(message, chat_history):
97
+ # Получаем ответ от агента
98
+ bot_response = ai_agent.chat(message, chat_history)
99
+ # Добавляем в историю чата
100
+ chat_history.append((message, bot_response))
101
  return "", chat_history
102
 
103
+ # Обработчики событий
104
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
105
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
106
 
107
+ # Запускаем приложение
108
  if __name__ == "__main__":
109
+ print("Starting AI Chat Assistant...")
110
+ chat_interface.launch(share=True)