[BUG] AttributeError: 'list' object has no attribute 'get'
Description
this seems to be a misidentification of a dictionary as a list though i may be missing something
Steps to Reproduce
from a new install use the create crew command and select ollama run the crew and the error will appear.
Expected behavior
I expected my crew to execute but instead it stalls out on this error regardless of the formatting changes i make.
Screenshots/Code snippets
crewai run /home/ghebner/anaconda3/envs/crewAI/lib/python3.12/site-packages/pydantic/_internal/_config.py:345: UserWarning: Valid config keys have changed in V2:
- 'fields' has been removed warnings.warn(message, UserWarning) Running the Crew /home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/pydantic/_internal/_config.py:345: UserWarning: Valid config keys have changed in V2:
- 'fields' has been removed
warnings.warn(message, UserWarning)
Traceback (most recent call last):
File "/home/ghebner/crewAI/developercrew1/.venv/bin/run_crew", line 8, in
sys.exit(run()) ^^^^^ File "/home/ghebner/crewAI/developercrew1/src/developercrew1/main.py", line 21, in run Developercrew1().crew().kickoff(inputs=inputs) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/crewai/project/utils.py", line 7, in memoized_func cache[key] = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/crewai/project/annotations.py", line 80, in wrapper task_instance = task_method(self) ^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/crewai/project/utils.py", line 7, in memoized_func cache[key] = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/crewai/project/annotations.py", line 23, in wrapper result = func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/src/developercrew1/crew.py", line 60, in code_writing_task return Task( ^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/pydantic/main.py", line 214, in init validated_self = self.pydantic_validator.validate_python(data, self_instance=self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/crewai/agents/agent_builder/base_agent.py", line 137, in process_model_config return process_config(values, cls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ghebner/crewAI/developercrew1/.venv/lib/python3.12/site-packages/crewai/utilities/config.py", line 18, in process_config config = values.get("config", {}) ^^^^^^^^^^ AttributeError: 'list' object has no attribute 'get' An error occurred while running the crew: Command '['uv', 'run', 'run_crew']' returned non-zero exit status 1.
Operating System
Ubuntu 20.04
Python Version
3.10
crewAI Version
0.86.0
crewAI Tools Version
0.25.8
Virtual Environment
Conda
Evidence
AttributeError: 'list' object has no attribute 'get' An error occurred while running the crew: Command '['uv', 'run', 'run_crew']' returned non-zero exit status 1.
Possible Solution
none
Additional context
none
Can you share your code please
I have included crew.py, agents.yaml and tasks.yaml. full disclosure i am relatively inexperienced and this is my first bug post. I appreciate any assistance. I've been stumped by this by an embarrassingly long period of time though my gut says I'm missing something obvious i cant find it.
the following is crew.py:
from crewai import Agent, Crew, Process, Task from crewai.project import CrewBase, agent, crew, task from crewai_tools import ( CodeInterpreterTool, FileReadTool, RagTool, FileWriterTool, )
CodeInterpreter=CodeInterpreterTool() FileWriter=FileWriterTool() FileRead=FileReadTool() Rag1=RagTool()
@CrewBase class Developercrew1(): """Developercrew1 crew"""
# Learn more about YAML configuration files here:
# Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended
# Tasks: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'
# If you would like to add tools to your agents, you can learn more about it here:
# https://docs.crewai.com/concepts/agents#agent-tools
@agent
def code_writer(self) -> Agent:
return Agent(
config=self.agents_config['code_writer'],
tools=[CodeInterpreter, FileWriter, FileRead, Rag1],
verbose=True
)
@agent
def safety_and_security(self) -> Agent:
return Agent(
config=self.agents_config['safety_and_security'],
tools=[CodeInterpreter, FileWriter, FileRead, Rag1],
verbose=True
)
@agent
def quality_control(self) -> Agent:
return Agent(
config=self.agents_config['quality_control'],
tools=[CodeInterpreter, FileWriter, FileRead, Rag1],
verbose=True
)
# To learn more about structured task outputs,
# task dependencies, and task callbacks, check out the documentation:
# https://docs.crewai.com/concepts/tasks#overview-of-a-task
@task
def code_writing_task(self) -> Task:
return Task(
config=self.tasks_config['code_writing_task'],
output_file='code_writing_task_output.md'
)
@task
def safety_and_security_task(self) -> Task:
return Task(
config=self.tasks_config['safety_and_security_task'],
output_file='safety_and_security_task_output.md'
)
@task
def quality_control_task(self) -> Task:
return Task(
config=self.tasks_config['quality_control_task'],
output_file='quality_control_task_output.md'
)
@crew
def crew(self) -> Crew:
"""Creates the Developercrew1 crew"""
# To learn how to add knowledge sources to your crew, check out the documentation:
# https://docs.crewai.com/concepts/knowledge#what-is-knowledge
return Crew(
agents=self.agents, # Automatically created by the @agent decorator
tasks=self.tasks, # Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
planning=True,
memory=True,
embedder={
"provider": "ollama",
"config": {
"model": "nomic-embed-text"
}
},
)
# process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/
the following is agents.yaml:
code_writer: role: > senior code writer goal: > to produce high quality well researched code that adheres to the best coding practices backstory: > I am a highly skilled software developer with expertise in multiple programming languages and frameworks with my primary responsibility being to write clean maintainable code for various applications
safety_and_security: role: > safety and security goal: > to identify and mitigate potential security risks in code as well as preventing malicious actions and ensure that all code adheres to security best practices and compliance requirements backstory: > I am a cybersecurity expert with a deep understanding of software vulnerabilities threat models and secure coding practices with my primary responsibility being the safety and security of all code produced by the team
quality_control: role: > quality control goal: > to preform thorough code reviews and identify performance issues as well as ensuring all code meets the highest standards of quality and reliability while complying with all laws and regulations that could apply backstory: > I am a seasoned software tester with extensive experience in code review testing methodologies and quality assurance with my primary responsibilities being the quality and legal compliance of generated code and outputs produced by other agents
The following is tasks.yaml:
code_writing_task: description: > write the complete python code for a playable snake game the game should adhere to classic snake mechanics including player control of a snake that grows by eating food and avoids self collisions and wall collisions expected_output: > a fully functional python code for a playable snake game including snake movement food generation collision detection with self and walls as well as score keeping agent: code_writer
safety_and_security_task: description: > analyze the code generated in task 1 for potential security vulnerabilities or risks including checking for security holes malicious code buffer overflows and other issues that could harm users or systems expected_output: > a detailed report outlining potential security concerns safety hazards and recommendations for secure coding practices to mitigate risks agent: safety_and_security
quality_control_task: description: > test and evaluate the game code from task 1 ensure the snake game functions correctly and compliantly while adhering to the classic snake game concept test edge cases and standard game play expected_output: > a comprehensive quality control report detailing testing processes methods used and test cases with identified issues like bugs and glitches and recommendations for improvement as well as confirmation that the game successfully accomplishes all objectives in a playable format agent: quality_control
This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This issue was closed because it has been stalled for 5 days with no activity.
Did anyone found any solutions for this ?
I am having the same issue, please reopen and fix
I was able to get it to work, but I am starting to remove CrewAI tools altogether as they are a bit confusing and lack support. However, here is a way to make it work. There are a few considerations to keep in mind:
- You must ensure that YAML is in a dictionary format. Here is an example:
agents:
sql_dev:
role: "Senior Database Developer"
goal: "Construct and execute SQL queries based on a request"
backstory: "some text"
- There were also issues with loading the YAML file automatically, so I created a function for it. Here it is:
def load_yaml_config(self, file_path):
full_path = os.path.join(os.getcwd(), file_path)
try:
with open(full_path, 'r') as file:
return yaml.safe_load(file)
except FileNotFoundError:
logger.error(f"Config file not found: {full_path}")
return {}
except yaml.YAMLError as e:
logger.error(f"Error parsing YAML file: {e}")
return {}
- Here is how I was using it in my
CrewBaseclass:
self.agents_config = self.load_yaml_config("agents/expenses/config/agents.yaml")
-
Also, in my
CrewBaseclass, I was returning the list of agents and tasks. -
Initially, I thought the "get" error was because of this since I was previously using lists instead of dictionaries. Once this was ensured, I realized there were inherent issues with using the
@tooldecorator. I wasn't exactly able to figure out why, but it wasn't working. So instead, I used thetoolslibrary provided in LangChain and made the tools as normal functions. -
When I needed the tools, I had to get the list of tools from somewhere. So I made a function to return the list of tools like this:
tools = [
Tool(
name="name1",
func=mytool._func_name1,
description="List the..."
),
Tool(
name="name2",
func=mytool._func_name2,
description="Get the..."
)
]
- Then, this is how you can use your tool in your agent:
@agent
def agent_name1(self) -> Agent:
name1_tools = get_tool("args")
return Agent(
llm=self.llm,
config=self.agents_config["keyname"]["keyname"], # Must match your YAML structure
allow_delegation=False,
tools=name1_tools,
verbose=True,
)
IMPORTANT:
If you are using any tools that are implemented in a LangChain library, you will need a wrapper class for your LLM to execute properly. (I do not guarantee that this will always work.)
Here is the wrapper class:
class CrewAILangChainAdapter(BaseLanguageModel, BaseModel):
crewai_llm: Any = Field(..., description="Reference to CrewAI LLM instance")
class Config:
arbitrary_types_allowed = True
def __init__(self, crewai_llm: Any, **kwargs):
# Explicit Pydantic constructor
super().__init__(
crewai_llm=crewai_llm,
**kwargs
)
@property
def _llm_type(self) -> str:
return "crewai_adapter"
def _generate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
**kwargs: Any,
) -> LLMResult:
generations = []
for prompt in prompts:
response = self.crewai_llm.call(prompt)
generations.append([Generation(text=response)])
return LLMResult(generations=generations)
async def _agenerate(
self,
prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
return await asyncio.get_event_loop().run_in_executor(
None, self._generate, prompts, stop, run_manager, kwargs
)
def _format_response(self, response: Any) -> str:
"""Handle different response formats from CrewAI"""
if isinstance(response, str):
return response
if hasattr(response, "text"):
return response.text
if hasattr(response, "generations"):
return response.generations[0].text
return str(response)
def generate_prompt(
self,
prompts: List[PromptValue],
stop: Optional[List[str]] = None,
callbacks: Any = None,
**kwargs: Any,
) -> LLMResult:
return self._generate([p.to_string() for p in prompts], stop=stop, **kwargs)
async def agenerate_prompt(
self,
prompts: List[PromptValue],
stop: Optional[List[str]] = None,
callbacks: Any = None,
**kwargs: Any,
) -> LLMResult:
return await self._agenerate([p.to_string() for p in prompts], stop=stop, **kwargs)
def predict(self, text: str, **kwargs: Any) -> str:
return self._generate([text], **kwargs).generations[0][0].text
def predict_messages(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
**kwargs: Any,
) -> BaseMessage:
raise NotImplementedError("CrewAI adapter doesn't support chat messages")
async def apredict(self, text: str, **kwargs: Any) -> str:
result = await self._agenerate([text], **kwargs)
return result.generations[0][0].text
async def apredict_messages(
self,
messages: List[BaseMessage],
stop: Optional[List[str]] = None,
**kwargs: Any,
) -> BaseMessage:
raise NotImplementedError("CrewAI adapter doesn't support async chat messages")
def invoke(self, input: str, **kwargs: Any) -> str:
"""Handle single string inputs through Runnable interface"""
return self.predict(input, **kwargs)
def stream(self, input: str, **kwargs: Any) -> Iterator[str]:
response = self.predict(input, **kwargs)
for word in response.split():
yield word + " "
async def astream(self, input: str, **kwargs: Any) -> AsyncIterator[str]:
response = await self.apredict(input, **kwargs)
for word in response.split():
yield word + " "
Hey folks, I see sthis is an issue still, even on newer verisons? I just tried with our latest version and didn't get the erro out of the box, used Ollama as isntructed. Is it a specific tool you are using or model that is triggering the error?
I think that might be it as the tool that we were using made us use an older version and that tool was critical so we had to use this hack solution , just posted if somebody needed to know !