Hi, I’m getting this recurrent error from DirectoryReadTool, which I cannot solve no matter what I do, can anyone help me?
I’m using Python 3.12.8, crewai version 0.100.0, and crewai tools version 0.33.0.
PS C:\Users\gisse\venv\proyectos\Progesys\progesys\src> python crew.py
ERROR:main: Error al crear la Crew: ‘DirectoryReadTool’
ERROR:main:
Detalles del error:
ERROR:main:Traceback (most recent call last):
File “C:\Users\gisse\venv\proyectos\Progesys\progesys\src\crew.py”, line 159, in
crew_instance = ProgesysCrew().crew()
^^^^^^^^^^^^^^
File “C:\Users\gisse\venv\proyectos\Progesys\Lib\site-packages\crewai\project\crew_base.py”, line 35, in init
self.map_all_agent_variables()
File “C:\Users\gisse\venv\proyectos\Progesys\Lib\site-packages\crewai\project\crew_base.py”, line 143, in map_all_agent_variables
self._map_agent_variables(
File “C:\Users\gisse\venv\proyectos\Progesys\Lib\site-packages\crewai\project\crew_base.py”, line 171, in _map_agent_variables
tool_functionstool for tool in tools
~~~~~~~~~~~~~~^^^^^^
KeyError: ‘DirectoryReadTool’
PS C:\Users\gisse\venv\proyectos\Progesys\progesys\src>
Here’s some parte of crew.py related to this issue:
import os
from pathlib import Path
from dotenv import load_dotenv
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, task, crew
from crewai_tools import DirectoryReadTool
from tools.custom_tool import ExcelReaderTool
import sys
import logging
import yaml
Configuración de logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(name)
Cargar variables de entorno
load_dotenv()
Obtener clave API
openai_api_key = os.getenv(“OPENAI_API_KEY”)
if not openai_api_key:
raise ValueError(“ ERROR: La clave API de OpenAI no está definida. Verifica tu archivo .env.”)
Establecer el directorio fijo
directory_path = “C:\Users\gisse\Progesys”
Construir la ruta relativa al archivo YAML
base_dir = Path(file).resolve().parent
agents_config_path = base_dir / “config” / “agents.yaml”
tasks_config_path = base_dir / “config” / “tasks.yaml”
Función simplificada para cargar YAML sin placeholders
def cargar_yaml(ruta_archivo):
“”“Carga un archivo YAML directamente.”“”
with open(ruta_archivo, ‘r’, encoding=‘utf-8’) as archivo:
return yaml.safe_load(archivo)
Cargar las configuraciones
try:
agents_config = cargar_yaml(agents_config_path)
tasks_config = cargar_yaml(tasks_config_path)
logger.info(“ Configuraciones YAML cargadas correctamente”)
logger.info(f"Configuración de agentes: {agents_config.keys()}“)
except Exception as e:
logger.error(f" Error al cargar configuraciones YAML: {str(e)}”)
raise
Definir las herramientas
tool_functions = {
“DirectoryReadTool”: lambda: DirectoryReadTool(directory=directory_path),
“ExcelReaderTool”: lambda: ExcelReaderTool(),
}
logger.info(“ Herramientas disponibles: [‘DirectoryReadTool’, ‘ExcelReaderTool’]”)
@CrewBase
class ProgesysCrew:
“”“Definición de la Crew de Progesys usando CrewAI”“”
def __init__(self):
self.agents_config = agents_config
self.tasks_config = tasks_config
# 📌 Agentes
@agent
def lector_de_datos(self) -> Agent:
try:
tools_from_config = self.agents_config["lector_de_datos"]["tools"]
logger.info(f"Tools configuradas para lector_de_datos: {tools_from_config}")
# Asignar las herramientas predefinidas
tools = []
for tool_name in tools_from_config:
if tool_name == "DirectoryReadTool":
tools.append(tool_functions[tool_name])
logger.info("✅ Herramienta asignada: DirectoryReadTool")
# Directory is set at initialization, so we don't need to pass it here
directory_contents = tools[-1].run()
logger.info(f"Contenido del directorio: {directory_contents}")
elif tool_name == "ExcelReaderTool":
tools.append(tool_functions[tool_name]())
logger.info("✅ Herramienta asignada: ExcelReaderTool")
else:
logger.warning(f"⚠️ Advertencia: Herramienta no reconocida: {tool_name}")
continue
logger.info(f"Tools instanciadas: {[type(tool).__name__ for tool in tools]}")
return Agent(
config=self.agents_config["lector_de_datos"],
tools=tools,
verbose=True
)
except Exception as e:
logger.error(f"❌ Error en lector_de_datos: {str(e)}")
raise
# 📌 Tareas
@task
def leer_datos(self) -> Task:
return Task(config=self.tasks_config["leer_datos"], agent=self.lector_de_datos())
# 📌 Crew
@crew
def crew(self) -> Crew:
"""Crea y devuelve la Crew con agentes y tareas."""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
Ejecutar si el script se corre directamente
if name == “main”:
try:
logger.info(“\n🔍 Iniciando creación de la Crew…”)
# Crear la Crew
crew_instance = ProgesysCrew().crew()
logger.info("🚀 Crew creada con éxito. Lista para ejecutarse.")
except Exception as e:
logger.error(f"❌ Error al crear la Crew: {str(e)}")
# Imprimir más detalles del error
import traceback
logger.error("\nDetalles del error:")
logger.error(traceback.format_exc())
Also here’s some part of agents.yaml related to this issue:
lector_de_datos:
role: >
Lector de Datos
goal: >
Convertir datos de Excel a DataFrame de Pandas.
backstory: >
Soy un experto en manipulación de datos con Excel y Pandas, me aseguro que el contenido y estructura que voy a convertir, sea fiel reflejo del archivo original.
tools:
- “DirectoryReadTool”
- “ExcelReaderTool”
allow_delegation: false
verbose: true
memory: true
Tks!
Gisselle