Packages

A Gleam library for building and orchestrating agents on the BEAM.

Current section

Files

Jump to
pig src pig@tool.erl
Raw

src/pig@tool.erl

-module(pig@tool).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/pig/tool.gleam").
-export([new_registry/0, register/2, lookup/2, list_definitions/1, list_tool_prompts/1]).
-export_type([tool_error/0, tool/0, tool_registry/0, tool_prompt/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(
" Tool types and registry for the pig agent library.\n"
"\n"
" A `Tool` pairs a `ToolDefinition` (schema for the LLM) with a handler\n"
" function. The handler receives parsed `dynamic.Dynamic` arguments and\n"
" returns either a `json.Json` result or a structured `ToolError`.\n"
).
-type tool_error() :: {tool_error, binary()}.
-type tool() :: {tool,
pig_protocol@tool_definition:tool_definition(),
fun((gleam@dynamic:dynamic_()) -> {ok, gleam@json:json()} |
{error, tool_error()})}.
-type tool_registry() :: {tool_registry, gleam@dict:dict(binary(), tool())}.
-type tool_prompt() :: {tool_prompt, binary(), binary()}.
-file("src/pig/tool.gleam", 34).
?DOC(" Create an empty tool registry.\n").
-spec new_registry() -> tool_registry().
new_registry() ->
{tool_registry, maps:new()}.
-file("src/pig/tool.gleam", 40).
?DOC(
" Register a tool in the registry. If a tool with the same name already\n"
" exists, it is overwritten.\n"
).
-spec register(tool_registry(), tool()) -> tool_registry().
register(Registry, Tool) ->
{tool_registry,
gleam@dict:insert(
erlang:element(2, Registry),
erlang:element(2, erlang:element(2, Tool)),
Tool
)}.
-file("src/pig/tool.gleam", 49).
?DOC(" Look up a tool by name. Returns `Error(Nil)` if not found.\n").
-spec lookup(tool_registry(), binary()) -> {ok, tool()} | {error, nil}.
lookup(Registry, Name) ->
gleam_stdlib:map_get(erlang:element(2, Registry), Name).
-file("src/pig/tool.gleam", 54).
?DOC(" List all tool definitions in the registry.\n").
-spec list_definitions(tool_registry()) -> list(pig_protocol@tool_definition:tool_definition()).
list_definitions(Registry) ->
_pipe = erlang:element(2, Registry),
_pipe@1 = maps:values(_pipe),
gleam@list:map(_pipe@1, fun(T) -> erlang:element(2, T) end).
-file("src/pig/tool.gleam", 67).
?DOC(
" Extract name and description from each tool in the registry.\n"
" Used to auto-compose an \"Available tools\" section in the system prompt.\n"
).
-spec list_tool_prompts(tool_registry()) -> list(tool_prompt()).
list_tool_prompts(Registry) ->
_pipe = erlang:element(2, Registry),
_pipe@1 = maps:values(_pipe),
gleam@list:map(
_pipe@1,
fun(T) ->
{tool_prompt,
erlang:element(2, erlang:element(2, T)),
erlang:element(3, erlang:element(2, T))}
end
).