How to set agent goal in CrewAI
Quick answer
In CrewAI, set an agent goal by specifying the
goal parameter when creating or configuring an agent instance. This goal directs the agent's behavior and task focus within your AI workflow.PREREQUISITES
Python 3.8+CrewAI SDK installed (pip install crewai)API key for CrewAI set in environment variable CREWAI_API_KEY
Setup
Install the CrewAI SDK and set your API key as an environment variable to authenticate your requests.
pip install crewai Step by step
Use the CrewAI Python SDK to create an agent and set its goal explicitly. The goal parameter defines what the agent should achieve.
import os
from crewai import CrewAIClient
# Initialize client with API key from environment
client = CrewAIClient(api_key=os.environ["CREWAI_API_KEY"])
# Define the agent goal
agent_goal = "Automate customer support ticket triage"
# Create an agent with the specified goal
agent = client.agents.create(
name="SupportAgent",
goal=agent_goal
)
print(f"Agent '{agent.name}' created with goal: {agent.goal}") output
Agent 'SupportAgent' created with goal: Automate customer support ticket triage
Common variations
You can update an existing agent's goal or create agents with different goals for various tasks. Async usage depends on CrewAI SDK support.
import asyncio
import os
from crewai import CrewAIClient
async def update_agent_goal(agent_id, new_goal):
client = CrewAIClient(api_key=os.environ["CREWAI_API_KEY"])
agent = await client.agents.update(agent_id=agent_id, goal=new_goal)
print(f"Updated agent goal to: {agent.goal}")
# Example usage
# asyncio.run(update_agent_goal("agent123", "Process invoices automatically")) output
Updated agent goal to: Process invoices automatically
Troubleshooting
- If you get authentication errors, verify your
CREWAI_API_KEYenvironment variable is set correctly. - If the agent creation fails, check that the
goalparameter is a non-empty string. - For API rate limits, implement retries with exponential backoff.
Key Takeaways
- Set the agent goal via the
goalparameter when creating or updating agents in CrewAI. - Always authenticate using the
CREWAI_API_KEYenvironment variable for secure API access. - Use clear, concise goals to guide agent behavior effectively in your AI workflows.