How to Use CrewAI for Agents: Simple Guide
To use
CrewAI for agents, you first create an agent instance with specific tasks or goals, then run it to get responses or actions. Agents in CrewAI can be customized with prompts and tools to automate workflows or answer questions.Syntax
The basic syntax to create and use an agent in CrewAI involves initializing the agent with a task description and then calling its run() method to get results.
- Agent creation: Define the agent with a prompt or task.
- Run method: Executes the agent's logic and returns output.
python
from crewai import Agent # Create an agent with a task description agent = Agent(task="Answer questions about AI.") # Run the agent to get a response response = agent.run("What is machine learning?") print(response)
Output
Machine learning is a field of AI that enables systems to learn from data and improve over time without being explicitly programmed.
Example
This example shows how to create a simple CrewAI agent that answers questions about AI and then runs it with a sample question.
python
from crewai import Agent # Initialize the agent with a clear task agent = Agent(task="Provide simple explanations about AI concepts.") # Ask the agent a question answer = agent.run("Explain neural networks in simple terms.") print(answer)
Output
Neural networks are computer systems inspired by the human brain that help machines recognize patterns and learn from data.
Common Pitfalls
Common mistakes when using CrewAI agents include:
- Not providing a clear task or prompt, which leads to vague or incorrect answers.
- Forgetting to call the
run()method to execute the agent. - Passing inputs that are too complex without guiding the agent.
Always keep prompts simple and specific for best results.
python
from crewai import Agent # Wrong: No task defined, agent may not work well agent_wrong = Agent() response_wrong = agent_wrong.run("What is AI?") print(response_wrong) # Right: Clear task defined agent_right = Agent(task="Explain AI simply.") response_right = agent_right.run("What is AI?") print(response_right)
Output
None or vague response
Artificial Intelligence (AI) is the simulation of human intelligence in machines that are programmed to think and learn.
Quick Reference
Remember these tips when using CrewAI agents:
- Always define a clear
taskwhen creating an agent. - Use the
run()method to get the agent's output. - Keep input prompts simple and focused.
- Test your agent with different questions to improve accuracy.
Key Takeaways
Create agents with clear tasks to guide their responses.
Use the run() method to execute the agent and get answers.
Keep prompts simple and specific for best results.
Avoid creating agents without a defined task to prevent vague outputs.
Test your agent with various inputs to improve performance.