my_agent / app.py
MADtoBAD's picture
Update app.py
c46b91a verified
raw
history blame
4.07 kB
import gradio as gr
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
class SimpleAIAgent:
def __init__(self):
print("Initializing AI Agent...")
# Используем языковую модель от Hugging Face
self.model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")
# Инструмент для поиска в интернете
self.search_tool = DuckDuckGoSearchTool()
# Создаем агента который может искать в интернете
self.agent = CodeAgent(
tools=[self.search_tool],
model=self.model,
max_steps=4
)
print("AI Agent ready!")
def chat(self, message, history):
"""
Основная функция для общения с агентом
"""
print(f"User asked: {message}")
# Создаем инструкцию для агента
prompt = f"""
The user asked: {message}
Please provide a helpful and accurate answer.
If you need current information, use the search tool to find it online.
Keep your response clear and conversational.
"""
try:
# Получаем ответ от агента
response = self.agent.run(prompt)
# Очищаем ответ от технических деталей
clean_response = self.clean_answer(response)
print(f"Agent replied: {clean_response[:100]}...")
return clean_response
except Exception as e:
error_msg = f"Sorry, I encountered an error: {str(e)}"
print(f"Error: {e}")
return error_msg
def clean_answer(self, answer):
"""
Убираем техническую информацию из ответа агента
"""
lines = answer.split('\n')
clean_lines = []
for line in lines:
# Пропускаем строки про инструменты и процесс поиска
lower_line = line.lower()
if any(word in lower_line for word in ['tool:', 'searching', 'step', 'using tool']):
continue
# Пропускаем пустые строки в начале
if line.strip():
clean_lines.append(line)
# Собираем обратно в текст
result = '\n'.join(clean_lines).strip()
# Если ответ слишком длинный, обрезаем
if len(result) > 1500:
result = result[:1497] + "..."
return result if result else "I couldn't find a good answer to that question."
# Создаем экземпляр агента
ai_agent = SimpleAIAgent()
# Создаем интерфейс чата
with gr.Blocks(title="My AI Assistant") as chat_interface:
gr.Markdown("# My AI Assistant")
gr.Markdown("Ask me anything! I can search the internet for current information.")
# Создаем чат-интерфейс
chatbot = gr.Chatbot(height=400)
msg = gr.Textbox(
label="Your question",
placeholder="Ask me anything...",
lines=2
)
clear_btn = gr.Button("Clear Chat")
def respond(message, chat_history):
# Получаем ответ от агента
bot_response = ai_agent.chat(message, chat_history)
# Добавляем в историю чата
chat_history.append((message, bot_response))
return "", chat_history
# Обработчики событий
msg.submit(respond, [msg, chatbot], [msg, chatbot])
clear_btn.click(lambda: None, None, chatbot, queue=False)
# Запускаем приложение
if __name__ == "__main__":
print("Starting AI Chat Assistant...")
chat_interface.launch(share=True)