|
|
import gradio as gr |
|
|
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel |
|
|
|
|
|
class SimpleAIAgent: |
|
|
def __init__(self): |
|
|
print("Initializing AI Agent...") |
|
|
|
|
|
|
|
|
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) |