Building my First Agent¤
This tutorial will guide you through the process of creating a simple agent and testing it using pytest.
1 Define the Agent's Job¤
First, let's create a new file my_agent.py. We'll define a class for our agent that inherits from crewmaster.agent.AgentBase. We need to provide a job_description to define its purpose.
# my_agent.py
from crewmaster.agent import AgentBase
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
# A simple input model for our agent
class SimpleInput(BaseModel):
query: str
class SimpleAgent(AgentBase):
job_description = "You are a simple agent that responds to greetings."
2 Create and Test the Agent¤
Next, let's create a pytest file test_my_agent.py to test our agent's behavior.
# tests/test_my_agent.py
import pytest
from langchain_openai import ChatOpenAI
from crewmaster.core.runnables import run_in_thread
from my_agent import SimpleAgent, SimpleInput
@pytest.fixture
def llm():
return ChatOpenAI(model_name="gpt-3.5-turbo")
def test_simple_agent_greeting(llm):
agent = SimpleAgent(llm_service=llm)
# We use a simple input model for our query
input_data = SimpleInput(query="Hello, how are you?")
# The agent's invoke method runs in a separate thread
result = run_in_thread(agent.invoke, input_data)
# We check if the agent's response contains a friendly greeting
assert "Hello" in result.message.response or "Hi" in result.message.response
def test_simple_agent_unknown_query(llm):
agent = SimpleAgent(llm_service=llm)
input_data = SimpleInput(query="What is the capital of France?")
result = run_in_thread(agent.invoke, input_data)
# We expect the agent to defer or state it cannot answer
assert "I cannot answer that question" in result.message.response
3 Run the Test¤
Run pytest from your terminal to execute the test.
pytest tests/test_my_agent.py
If the tests pass, you have successfully created and tested a basic agent!