Итерация 3, финальная
This commit is contained in:
@@ -1,50 +1,96 @@
|
||||
# executor.py
|
||||
from langchain_classic.agents import AgentExecutor
|
||||
from langchain.agents import create_agent
|
||||
from langchain_ollama import ChatOllama
|
||||
from langchain_core.prompts import ChatPromptTemplate
|
||||
from config import LLM_HOST, MODEL_NAME
|
||||
|
||||
from typing import List, Dict
|
||||
from langchain_ollama import ChatOllama
|
||||
from config import LLM_HOST, MODEL_NAME
|
||||
import time
|
||||
|
||||
class ExecutorAgent:
|
||||
def __init__(self, tools):
|
||||
def __init__(self, tools, llm=None):
|
||||
self.tools = tools
|
||||
self.llm = ChatOllama(
|
||||
self.llm = llm or ChatOllama(
|
||||
model=MODEL_NAME,
|
||||
temperature=0.0,
|
||||
base_url=LLM_HOST
|
||||
)
|
||||
self.agent = self._create_agent()
|
||||
|
||||
def _create_agent(self):
|
||||
prompt = ChatPromptTemplate.from_messages([
|
||||
("system", "Ты - исполнитель. У тебя есть доступ к инструментам. Выполняй шаги плана последовательно."),
|
||||
("human", "{input}"),
|
||||
("placeholder", "{agent_scratchpad}")
|
||||
])
|
||||
agent = create_agent(self.llm, self.tools, prompt)
|
||||
return AgentExecutor(agent=agent, tools=self.tools, verbose=True)
|
||||
|
||||
"""Устаревший агент-исполнитель. Теперь используется DeveloperAgent напрямую."""
|
||||
|
||||
def __init__(self, tools=None):
|
||||
# Этот класс больше не используется, оставлен для обратной совместимости
|
||||
pass
|
||||
|
||||
def execute_plan(self, plan: List[Dict]) -> List[Dict]:
|
||||
"""Выполняет план шаг за шагом через инструменты"""
|
||||
results = []
|
||||
for step in plan:
|
||||
tool_name = step["tool"]
|
||||
args = step["args"]
|
||||
# Превращаем шаг в текстовую команду для агента
|
||||
command = f"Вызови инструмент {tool_name} с аргументами {args}"
|
||||
result = self.agent.invoke({"input": command})
|
||||
results.append({
|
||||
"step": step,
|
||||
"output": result["output"],
|
||||
"success": True # можно анализировать ошибки
|
||||
})
|
||||
total_steps = len(plan)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"🚀 Начало выполнения плана ({total_steps} шагов)")
|
||||
print(f"{'='*60}")
|
||||
|
||||
for i, step in enumerate(plan, 1):
|
||||
tool_name = step.get("tool", "unknown")
|
||||
args = step.get("args", {})
|
||||
description = step.get("description", "")
|
||||
|
||||
print(f"\n{'─'*60}")
|
||||
print(f"📍 Шаг {i}/{total_steps}: {tool_name}")
|
||||
if description:
|
||||
print(f" 📝 Описание: {description}")
|
||||
print(f" 📦 Аргументы: {args}")
|
||||
print(f" ─────────────────────────────")
|
||||
|
||||
# Находим инструмент по имени
|
||||
tool = None
|
||||
for t in self.tools:
|
||||
if t.name == tool_name:
|
||||
tool = t
|
||||
break
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
if tool:
|
||||
try:
|
||||
result = tool.invoke(args)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
results.append({
|
||||
"step": step,
|
||||
"output": str(result),
|
||||
"success": True,
|
||||
"duration": elapsed
|
||||
})
|
||||
|
||||
print(f" ✅ Успех ({elapsed:.2f}s)")
|
||||
print(f" 📤 Результат: {str(result)[:100]}{'...' if len(str(result)) > 100 else ''}")
|
||||
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
results.append({
|
||||
"step": step,
|
||||
"output": str(e),
|
||||
"success": False,
|
||||
"error": str(e),
|
||||
"duration": elapsed
|
||||
})
|
||||
|
||||
print(f" ❌ Ошибка ({elapsed:.2f}s)")
|
||||
print(f" 💥 {type(e).__name__}: {str(e)[:100]}")
|
||||
else:
|
||||
results.append({
|
||||
"step": step,
|
||||
"output": f"Tool '{tool_name}' not found",
|
||||
"success": False,
|
||||
"duration": 0
|
||||
})
|
||||
|
||||
print(f" ❌ Инструмент '{tool_name}' не найден")
|
||||
|
||||
# Итоговая статистика
|
||||
success_count = sum(1 for r in results if r.get("success", False))
|
||||
failed_count = total_steps - success_count
|
||||
total_duration = sum(r.get("duration", 0) for r in results)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"📊 ИТОГИ ВЫПОЛНЕНИЯ")
|
||||
print(f"{'='*60}")
|
||||
print(f"✅ Успешно: {success_count}/{total_steps}")
|
||||
print(f"❌ Ошибки: {failed_count}")
|
||||
print(f"⏱️ Общее время: {total_duration:.2f}s")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
return results
|
||||
"""Устаревший метод - теперь выполняется напрямую через DeveloperAgent"""
|
||||
raise NotImplementedError("Этот метод больше не используется. Используйте DeveloperAgent.develop() напрямую.")
|
||||
Reference in New Issue
Block a user