Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix KeyError: 'key_name' in agent.py #1613

Conversation

GiovanniBalestrieri
Copy link

Problem:
When running crewai run, a KeyError: 'key_name' occurs if the key_name attribute is missing in the environment variables.

(latest-ai-development) userk@mycelium:~/development/git/vanto_ai_agents_cornerstone/cre
wai/latest_ai_development$ crewai run                                                   
Running the Crew                                                                        
Traceback (most recent call last):                                                      
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/bin/run_crew", line 8, in <module>                                           
    sys.exit(run())                                                                     
             ^^^^^                                                                      
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/src/latest_ai_development/main.py", line 13, in run                                
    LatestAiDevelopmentCrew().crew().kickoff(inputs=inputs)                             
    ^^^^^^^^^^^^^^^^^^^^^^^^^                                                           
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/lib/python3.12/site-packages/crewai/project/crew_base.py", line 35, in __init
__                                                                                      
    self.map_all_task_variables()                                                       
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/lib/python3.12/site-packages/crewai/project/crew_base.py", line 145, in map_a
ll_task_variables                                                                       
    self._map_task_variables(                                                           
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/lib/python3.12/site-packages/crewai/project/crew_base.py", line 178, in _map_
task_variables                                                                          
    self.tasks_config[task_name]["agent"] = agents[agent_name]()                        
                                            ^^^^^^^^^^^^^^^^^^^^                        
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/lib/python3.12/site-packages/crewai/project/utils.py", line 7, in memoized_fu
nc                                                                                      
    cache[key] = func(*args, **kwargs)                                                  
                 ^^^^^^^^^^^^^^^^^^^^^                                                  
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/src/latest_ai_development/crew.py", line 12, in researcher                         
    return Agent(                                                                       
           ^^^^^^                                                                       
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/lib/python3.12/site-packages/pydantic/main.py", line 212, in __init__        
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=sel
f)                                                                                      
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^
  File "/home/userk/development/git/vanto_ai_agents_cornerstone/crewai/latest_ai_develop
ment/.venv/lib/python3.12/site-packages/crewai/agent.py", line 160, in post_init_setup
    if env_var["key_name"] in unnacepted_attributes:
       ~~~~~~~^^^^^^^^^^^^
KeyError: 'key_name'
An error occurred while running the crew: Command '['uv', 'run', 'run_crew']' returned n
on-zero exit status 1.

Solution:
Added a conditional check in agent.py to skip processing key_name unless it exists. This prevents the error and ensures compatibility for setups where key_name is not required.

Proposed Fix: A conditional check can be added in agent.py to skip processing key_name unless it's present and valid:

if "key_name" in env_var and env_var["key_name"] in unnacepted_attributes:
continue

This ensures the error doesn’t occur when key_name is absent but unnecessary for the task.

Environment:

  • Python version: 3.12.3
  • CrewAI version: 0.80.0
  • CrewAI Tools: 0.14.0
  • Environment: Virtualenv

Files Modified:

agent.py

Testing:
Validated the fix without setting key_name as environment variable.

To test:

  • With key_name present.
  • With conflicting or unrelated environment variables.

> Problem:
When running crewai run, a KeyError: 'key_name' occurs if the key_name attribute is missing in the environment variables.

Solution:
Added a conditional check in agent.py to skip processing key_name unless it exists. This prevents the error and ensures compatibility for setups where key_name is not required.
@GiovanniBalestrieri
Copy link
Author

GiovanniBalestrieri commented Nov 15, 2024

Thanks for reviewing this pull request! While this conditional check resolves the immediate issue (KeyError: 'key_name'), I wanted to highlight some disadvantages of this approach and propose an alternative for consideration:

Disadvantages of the Current Fix

  • Silent Failures: The conditional check skips processing key_name when it’s missing. While this prevents errors, it may silently bypass necessary configurations for providers that rely on key_name. This could lead to unpredictable behavior in other parts of the system.

  • Not Targeted: The fix is generic and applies globally. However, the issue seems specific to the Ollama provider due to a missing key_name in its ENV_VARS configuration. Addressing it directly in ENV_VARS might be more precise.

  • Future Maintenance: If similar issues arise for other providers, maintainers might need to repeatedly patch agent.py for each case, leading to code clutter.

Proposed Alternative Approach as highlighted in this issue

Instead of adding a conditional check in agent.py, we could fix the root cause by updating the ENV_VARS configuration for the Ollama provider in constants.py:

# Add missing key_name for Ollama in ENV_VARS
ENV_VARS.update({
    "ollama": [
        {
            "prompt": "Enter your OLLAMA API_BASE (press Enter to skip)",
            "key_name": "API_BASE",  # This ensures API_BASE is properly defined
        },
        {
            "default": True,
            "API_BASE": "http://localhost:11434",  # Default for local Ollama setups
        }
    ]
})

Advantages of the Alternative

  • Targeted Fix: Directly addresses the misconfiguration for Ollama without affecting other providers or generic logic in agent.py.
  • Long-Term Solution: Ensures future users configuring Ollama won’t face the same issue.
  • Code Clarity: Keeps the logic for handling providers within the appropriate configuration file (constants.py).

@fricaro
Copy link

fricaro commented Nov 20, 2024

Really nice fix!
Thanks!

@bhancockio
Copy link
Collaborator

Closed by #1638

@bhancockio bhancockio closed this Nov 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants