Rag.Agent.Tool behaviour (rag v0.3.4)
View SourceBehaviour for agent tools.
Tools are functions that agents can call to interact with external systems, retrieve information, or perform actions. Each tool must implement this behaviour.
Implementing a Tool
defmodule MyTool do
@behaviour Rag.Agent.Tool
@impl true
def name, do: "my_tool"
@impl true
def description, do: "Does something useful"
@impl true
def parameters do
%{
type: "object",
properties: %{
input: %{type: "string", description: "The input"}
},
required: ["input"]
}
end
@impl true
def execute(%{"input" => input}, context) do
# Perform the action
{:ok, "Result: #{input}"}
end
endContext
The context map passed to execute/2 contains:
:session_id- Current session identifier:user_id- User identifier (if available):repo- Ecto repo for database operations:router- Router for LLM calls- Any additional context provided by the agent
Summary
Callbacks
Returns a description of what the tool does. This is shown to the LLM to help it decide when to use the tool.
Executes the tool with the given arguments and context.
Returns the unique name of the tool.
Returns the JSON Schema for the tool's parameters.
Functions
Executes a tool with the given arguments and context.
Formats multiple tools for LLM function calling.
Formats a tool for LLM function calling.
Converts a tool module to a specification map.
Validates arguments against the tool's parameter schema.
Types
Callbacks
@callback description() :: String.t()
Returns a description of what the tool does. This is shown to the LLM to help it decide when to use the tool.
Executes the tool with the given arguments and context.
@callback name() :: String.t()
Returns the unique name of the tool.
@callback parameters() :: map()
Returns the JSON Schema for the tool's parameters.
Functions
Executes a tool with the given arguments and context.
This is a convenience function that delegates to the tool's
execute/2 callback.
Examples
iex> Tool.execute(MyTool, %{"input" => "test"}, %{})
{:ok, "Result: test"}
Formats multiple tools for LLM function calling.
Examples
iex> Tool.format_all_for_llm([Tool1, Tool2])
[%{name: "tool1", ...}, %{name: "tool2", ...}]
Formats a tool for LLM function calling.
Returns a map in the format expected by LLM providers for function/tool definitions.
Examples
iex> Tool.format_for_llm(MyTool)
%{name: "my_tool", description: "...", parameters: %{...}}
Converts a tool module to a specification map.
Examples
iex> Tool.to_spec(MyTool)
%{name: "my_tool", description: "...", parameters: %{...}}
Validates arguments against the tool's parameter schema.
Checks that all required fields are present.
Examples
iex> Tool.validate_args(MyTool, %{"input" => "test"})
:ok
iex> Tool.validate_args(MyTool, %{})
{:error, {:missing_required, ["input"]}}