Packages

Gleam SDK for the Anthropic Claude API with agentic tool-use loop and BEAM concurrency

Current section

Files

Jump to
claude_gleam src claude@agent@actor.erl
Raw

src/claude@agent@actor.erl

-module(claude@agent@actor).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/claude/agent/actor.gleam").
-export([run_with_events/3, start/3]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-file("src/claude/agent/actor.gleam", 30).
?DOC(
" Run the agent loop, calling the provided callback with events at each step.\n"
"\n"
" This is a synchronous function that blocks until the agent completes.\n"
" The `on_event` callback is invoked at each notable step, giving the caller\n"
" visibility into the agent's progress.\n"
"\n"
" ## Example\n"
"\n"
" ```gleam\n"
" actor.run_with_events(config, \"Hello\", fn(event) {\n"
" case event {\n"
" agent.Started(id) -> io.println(\"Started: \" <> id)\n"
" agent.Done(result) -> io.println(\"Done!\")\n"
" _ -> Nil\n"
" }\n"
" })\n"
" ```\n"
).
-spec run_with_events(
claude@agent@config:agent_config(),
binary(),
fun((claude@agent:agent_event()) -> nil)
) -> {ok, claude@agent:agent_result()} | {error, claude@agent:agent_error()}.
run_with_events(Config, Prompt, On_event) ->
Session_id = <<"agent-"/utf8,
(erlang:integer_to_binary(erlang:system_time()))/binary>>,
On_event({started, Session_id}),
Initial_messages = [claude@types@message:new_user(Prompt)],
claude@agent:event_loop(
Config,
lists:reverse(Initial_messages),
0,
0,
0,
On_event
).
-file("src/claude/agent/actor.gleam", 69).
?DOC(
" Start an agent in a new BEAM process, sending events to the given subject.\n"
"\n"
" The agent runs asynchronously in a spawned process. Events are sent to\n"
" the caller's subject as they occur, so the caller can receive them from\n"
" their mailbox.\n"
"\n"
" Returns the Pid of the spawned agent process.\n"
"\n"
" ## Example\n"
"\n"
" ```gleam\n"
" let events = process.new_subject()\n"
" let pid = actor.start(config, \"Hello\", events)\n"
"\n"
" // Receive events from the agent\n"
" case process.receive(events, 30_000) {\n"
" Ok(agent.Started(id)) -> io.println(\"Agent started: \" <> id)\n"
" Ok(agent.Done(result)) -> io.println(\"Agent done!\")\n"
" _ -> io.println(\"Timeout or other event\")\n"
" }\n"
" ```\n"
).
-spec start(
claude@agent@config:agent_config(),
binary(),
gleam@erlang@process:subject(claude@agent:agent_event())
) -> gleam@erlang@process:pid_().
start(Config, Prompt, Caller) ->
proc_lib:spawn_link(
fun() ->
_ = run_with_events(
Config,
Prompt,
fun(Event) -> gleam@erlang@process:send(Caller, Event) end
),
nil
end
).