MADtoBAD commited on
Commit
e1b4d89
·
verified ·
1 Parent(s): de90e17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -74
app.py CHANGED
@@ -1,105 +1,112 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForCausalLM
3
- import torch
4
 
5
- class FixedAIAgent:
6
  def __init__(self):
7
- print("Loading DialoGPT-small...")
8
 
9
- # Загружаем модель и токенизатор
10
- self.tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
11
- self.model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
12
 
13
- # Добавляем pad token если его нет
14
- if self.tokenizer.pad_token is None:
15
- self.tokenizer.pad_token = self.tokenizer.eos_token
16
-
17
- print("DialoGPT-small loaded successfully!")
 
 
 
 
 
 
18
 
19
  def chat(self, message, history):
 
 
20
  try:
21
- # Форматируем историю для DialoGPT
22
- input_text = self.format_conversation(message, history)
 
23
 
24
- # Токенизируем входной текст
25
- inputs = self.tokenizer.encode(input_text + self.tokenizer.eos_token, return_tensors='pt')
 
26
 
27
- # Генерируем ответ
28
- with torch.no_grad():
29
- outputs = self.model.generate(
30
- inputs,
31
- max_length=1000,
32
- pad_token_id=self.tokenizer.eos_token_id,
33
- do_sample=True,
34
- temperature=0.7,
35
- top_k=50,
36
- top_p=0.95,
37
- repetition_penalty=1.2
38
- )
39
 
40
- # Декодируем ответ
41
- response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
 
42
 
43
- # Извлекаем только новый ответ (убираем историю)
44
- bot_response = self.extract_new_response(input_text, response)
45
-
46
- return bot_response
47
 
48
  except Exception as e:
49
- return f"Error: {str(e)}"
 
 
50
 
51
- def format_conversation(self, message, history):
52
- """Форматирует историю чата для DialoGPT"""
53
- # Начинаем с нового сообщения
54
- conversation = f"User: {message}"
55
 
56
- # Добавляем историю (последние 2-3 сообщения)
57
- if history:
58
- # Берем последние 2 обмена
59
- recent_history = history[-2:] if len(history) > 2 else history
60
-
61
- for user_msg, bot_msg in recent_history:
62
- conversation = f"User: {user_msg}\nBot: {bot_msg}\n" + conversation
63
 
64
- return conversation
65
-
66
- def extract_new_response(self, input_text, full_response):
67
- """Извлекает только новый ответ из полного ответа модели"""
68
- if input_text in full_response:
69
- # Убираем входной текст чтобы оставить только новый ответ
70
- new_response = full_response[len(input_text):].strip()
71
- # Убираем возможные префиксы
72
- if new_response.startswith("Bot:"):
73
- new_response = new_response[4:].strip()
74
- return new_response
75
- else:
76
- # Если не нашли входной текст, возвращаем как есть
77
- return full_response
 
 
78
 
79
  # Создаем агента
80
- agent = FixedAIAgent()
81
 
82
- # Создаем интерфейс
83
- with gr.Blocks() as app:
84
- gr.Markdown("# AI Chat Assistant")
85
- gr.Markdown("Powered by DialoGPT-small")
 
 
 
 
 
 
86
 
87
- chatbot = gr.Chatbot(height=400, label="Chat History")
88
  msg = gr.Textbox(
89
- label="Your message",
90
- placeholder="Type your message here...",
91
  lines=2
92
  )
93
- clear = gr.Button("Clear Chat")
 
94
 
95
  def respond(message, chat_history):
96
- bot_message = agent.chat(message, chat_history)
97
- chat_history.append((message, bot_message))
 
 
98
  return "", chat_history
99
 
 
100
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
101
- clear.click(lambda: None, None, chatbot)
102
 
 
103
  if __name__ == "__main__":
104
- print("Starting AI Chat...")
105
- app.lalunch()
 
1
  import gradio as gr
2
+ from smolagents import CodeAgent, DuckDuckGoSearchTool
3
+ from smolagents.models import TransformersModel
4
 
5
+ class WorkingAIAgent:
6
  def __init__(self):
7
+ print("Starting AI agent with web search...")
8
 
9
+ # Используем маленькую модель
10
+ self.model = TransformersModel("microsoft/DialoGPT-small")
 
11
 
12
+ # Инструмент для поиска в интернете
13
+ self.search_tool = DuckDuckGoSearchTool()
14
+
15
+ # Создаем агента с поиском
16
+ self.agent = CodeAgent(
17
+ tools=[self.search_tool],
18
+ model=self.model,
19
+ max_steps=3
20
+ )
21
+
22
+ print("AI agent with web search is ready!")
23
 
24
  def chat(self, message, history):
25
+ print(f"User: {message}")
26
+
27
  try:
28
+ # Простой промпт для агента
29
+ prompt = f"""
30
+ Please answer this question: {message}
31
 
32
+ If you need to find current information, use the search tool.
33
+ Give a clear and helpful response.
34
+ """
35
 
36
+ # Получаем ответ от агента
37
+ response = self.agent.run(prompt)
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Очищаем ответ
40
+ clean_response = self.clean_answer(response)
41
+ print(f"AI: {clean_response[:100]}...")
42
 
43
+ return clean_response
 
 
 
44
 
45
  except Exception as e:
46
+ error_msg = f"I encountered an error. Please try again with a different question."
47
+ print(f"Error: {e}")
48
+ return error_msg
49
 
50
+ def clean_answer(self, text):
51
+ """Убираем технические детали из ответа"""
52
+ if not text:
53
+ return "I couldn't find an answer to that question."
54
 
55
+ # Разбиваем на строки и фильтруем
56
+ lines = text.split('\n')
57
+ clean_lines = []
 
 
 
 
58
 
59
+ for line in lines:
60
+ line_lower = line.lower()
61
+ # Пропускаем технические строки
62
+ if any(word in line_lower for word in ['tool:', 'searching', 'step', 'using tool']):
63
+ continue
64
+ if line.strip(): # Добавляем только непустые строки
65
+ clean_lines.append(line.strip())
66
+
67
+ # Собираем обратно
68
+ result = ' '.join(clean_lines)
69
+
70
+ # Ограничиваем длину
71
+ if len(result) > 800:
72
+ result = result[:797] + "..."
73
+
74
+ return result if result else "I found some information but couldn't format it properly."
75
 
76
  # Создаем агента
77
+ ai_agent = WorkingAIAgent()
78
 
79
+ # Создаем интерфейс чата
80
+ with gr.Blocks(title="AI Assistant with Web Search") as app:
81
+ gr.Markdown("# AI Assistant with Web Search")
82
+ gr.Markdown("Ask me anything and I'll search the internet for answers!")
83
+
84
+ # Чат интерфейс
85
+ chatbot = gr.Chatbot(
86
+ height=400,
87
+ label="Conversation"
88
+ )
89
 
 
90
  msg = gr.Textbox(
91
+ label="Your question",
92
+ placeholder="Ask me anything... (I can search the web!)",
93
  lines=2
94
  )
95
+
96
+ clear_btn = gr.Button("Clear Chat")
97
 
98
  def respond(message, chat_history):
99
+ # Получаем ответ от агента
100
+ bot_response = ai_agent.chat(message, chat_history)
101
+ # Добавляем в историю чата
102
+ chat_history.append((message, bot_response))
103
  return "", chat_history
104
 
105
+ # Настраиваем обработчики
106
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
107
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
108
 
109
+ # Запускаем приложение
110
  if __name__ == "__main__":
111
+ print("AI Assistant starting...")
112
+ app.launch(share=True)