Normandy.Tools.Examples.Calculator behaviour
(normandy v0.6.0)
View Source
A calculator tool for performing basic arithmetic operations.
Now uses Normandy's schema-based tool definition for automatic validation and reduced boilerplate code.
Examples
iex> {:ok, calculator} = Calculator.validate(%{operation: "add", a: 5, b: 3})
iex> Normandy.Tools.BaseTool.run(calculator)
{:ok, 8}
iex> {:ok, calculator} = Calculator.validate(%{operation: "divide", a: 10, b: 0})
iex> Normandy.Tools.BaseTool.run(calculator)
{:error, "Cannot divide by zero"}Schema-Based Benefits
- Automatic JSON schema generation
- Runtime validation before execution
- Reduced code (~60% less than manual approach)
- Better error messages with field paths
- Type coercion and constraint checking
Summary
Callbacks
Executes the tool with validated inputs.
Callbacks
Executes the tool with validated inputs.
This function must be implemented by the tool. It receives a validated struct with all fields populated according to the schema.
Returns {:ok, result} on success or {:error, reason} on failure.
Examples
@impl Normandy.Tools.SchemaBaseTool
def execute(%__MODULE__{operation: "add", a: a, b: b}) do
{:ok, a + b}
end
def execute(%__MODULE__{operation: "divide", a: _a, b: 0}) do
{:error, "Division by zero"}
end
Functions
Validates input parameters against the tool's schema.
Returns {:ok, struct} on success or {:error, errors} on validation failure.
Examples
iex> Elixir.Normandy.Tools.Examples.Calculator.validate(%{operation: "add", a: 5, b: 3})
{:ok, %Elixir.Normandy.Tools.Examples.Calculator{operation: "add", a: 5, b: 3}}
iex> Elixir.Normandy.Tools.Examples.Calculator.validate(%{operation: "invalid"})
{:error, [%{path: [:a], message: "is required", constraint: :required}]}
Validates and raises on error.
Returns the validated struct or raises Normandy.Schema.ValidationError.