Update app.py
Browse files
app.py
CHANGED
|
@@ -1,105 +1,112 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
-
import
|
| 4 |
|
| 5 |
-
class
|
| 6 |
def __init__(self):
|
| 7 |
-
print("
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
self.
|
| 11 |
-
self.model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-small")
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
def chat(self, message, history):
|
|
|
|
|
|
|
| 20 |
try:
|
| 21 |
-
#
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 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 |
-
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
bot_response = self.extract_new_response(input_text, response)
|
| 45 |
-
|
| 46 |
-
return bot_response
|
| 47 |
|
| 48 |
except Exception as e:
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
def
|
| 52 |
-
"""
|
| 53 |
-
|
| 54 |
-
|
| 55 |
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
|
| 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 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
| 78 |
|
| 79 |
# Создаем агента
|
| 80 |
-
|
| 81 |
|
| 82 |
-
# Создаем интерфейс
|
| 83 |
-
with gr.Blocks() as app:
|
| 84 |
-
gr.Markdown("# AI
|
| 85 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
chatbot = gr.Chatbot(height=400, label="Chat History")
|
| 88 |
msg = gr.Textbox(
|
| 89 |
-
label="Your
|
| 90 |
-
placeholder="
|
| 91 |
lines=2
|
| 92 |
)
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
def respond(message, chat_history):
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
return "", chat_history
|
| 99 |
|
|
|
|
| 100 |
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 101 |
-
|
| 102 |
|
|
|
|
| 103 |
if __name__ == "__main__":
|
| 104 |
-
print("
|
| 105 |
-
app.
|
|
|
|
| 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)
|