Create an agent with tool
How-To Guide: Create an Agent with a Calculator Tool This guide demonstrates how to create a custom skill (tool) and integrate it into an agent, allowing it to perform calculations.
1. Define the Calculator Skill¤
A skill is a regular Python function decorated with @skill. Let's create my_skills.py with a simple calculator function.
# my_skills.py
from crewmaster.skill import skill
from typing import Optional
@skill
def calculate(expression: str) -> str:
"""Calculates the result of a mathematical expression.
Args:
expression (str): The mathematical expression to evaluate, e.g., "2 + 2".
Returns:
str: The result of the calculation.
"""
try:
# Warning: Using eval() is dangerous in production without careful sanitization.
result = eval(expression)
return f"The result of {expression} is {result}"
except Exception as e:
return f"Error: Could not calculate the expression. {e}"
2. Create the Agent with the Skill¤
Now, let's create the agent in calculator_agent.py. We import our calculate skill and pass it to the agent's skills list.
# calculator_agent.py
from crewmaster.agent import AgentBase
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
from .my_skills import calculate
class CalculatorAgent(AgentBase):
job_description = "You are an expert at performing mathematical calculations."
skills = [calculate]
def __init__(self, llm_service: ChatOpenAI):
super().__init__(llm_service=llm_service)
- Write the Pytest Test Finally, let's write a test to verify our agent can use the calculate skill.
# tests/test_calculator_agent.py
import pytest
from langchain_openai import ChatOpenAI
from crewmaster.core.runnables import run_in_thread
from calculator_agent import CalculatorAgent, CalculationInput
@pytest.fixture
def llm():
return ChatOpenAI(model_name="gpt-3.5-turbo")
def test_calculator_agent(llm):
agent = CalculatorAgent(llm_service=llm)
input_data = CalculationInput(query="What is 15 multiplied by 8?")
result = run_in_thread(agent.invoke, input_data)
# We expect the agent to use the tool and return the correct result
assert "120" in result.message.response
Run pytest to execute the test. The agent will use its LLM to identify that it needs to perform a calculation, call the calculate skill with the expression "15 * 8", and incorporate the result into its final response.