Candil.Tool (Candil v3.0.0)

Copy Markdown View Source

Defines a callable tool that an LLM can invoke.

A tool wraps an Elixir function in a schema that the model can call. Use Candil.Tool.define/4 to register, Candil.Tool.list/0 to query, and Candil.Tool.call/2 to invoke.

Example

defmodule MyApp.Tools.Weather do
  use Candil.Tool,
    name: "get_weather",
    description: "Get the current weather for a city",
    schema: %{
      "type" => "object",
      "properties" => %{
        "city" => %{"type" => "string"}
      },
      "required" => ["city"]
    }

  def run(%{"city" => city}) do
    {:ok, %{temperature: 21, conditions: "sunny", city: city}}
  end
end

Candil.Tool.call("get_weather", %{"city" => "Madrid"})

Custom implementations

For tools that don't follow the use Candil.Tool macro, define a Candil.Tool.t/0 struct manually:

%Candil.Tool{
  name: "send_email",
  description: "Send an email to a user",
  schema: %{...},
  function: fn args -> MyApp.Mailer.send(args) end
}

Summary

Functions

Invoke a tool by name with the given args.

Returns a specification to start this module under a supervisor.

Define a tool at runtime. Either a Candil.Tool.t/0 struct or the four-tuple (name, description, schema, function).

List all registered tools.

Remove all registered tools. Useful for tests and hot-reload scenarios.

Validate that args matches the tool's JSON schema. Returns :ok if all required properties are present (best-effort; no full JSON-schema validation yet).

Types

t()

@type t() :: %Candil.Tool{
  description: String.t(),
  function: (map() -> {:ok, term()} | {:error, term()}),
  name: String.t(),
  schema: map()
}

Functions

call(name, args)

@spec call(String.t(), map()) :: {:ok, term()} | {:error, term()}

Invoke a tool by name with the given args.

Returns the tool's return value ({:ok, term()} | {:error, term()}) on success, or {:error, %Candil.Error{reason: :not_found}} if no tool with that name is registered.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

define(tool)

@spec define(t() | {String.t(), String.t(), map(), function()}) :: :ok

Define a tool at runtime. Either a Candil.Tool.t/0 struct or the four-tuple (name, description, schema, function).

list()

@spec list() :: [t()]

List all registered tools.

reset()

@spec reset() :: :ok

Remove all registered tools. Useful for tests and hot-reload scenarios.

start_link(opts \\ [])

validate_args(tool, args)

@spec validate_args(t(), map()) :: :ok | {:error, term()}

Validate that args matches the tool's JSON schema. Returns :ok if all required properties are present (best-effort; no full JSON-schema validation yet).