std.agent
An LLM agent loop: the model calls tools, the loop runs them and answers, until a reply calls none.
The model is a Model: Claude calls Anthropic’s Messages API over HTTPS, or a mock in tests. A tool is a Tool: a function with derive Tool, or any type implementing it.
ToolCall
Section titled “ToolCall”type ToolCall = { id: String, name: String, input: JsonValue }The model asks to run the tool name with input. id pairs it with
its result.
AgentError
Section titled “AgentError”type AgentError = HttpError | ApiError | BadReply | Refused | OutOfTokens | TooManyTurns | NoKeyWhy a run stopped without an answer.
ApiError
Section titled “ApiError”type ApiError = { status: Int, kind: String, message: String }The API answered with an error: its status, kind and message.
BadReply
Section titled “BadReply”type BadReply = { reason: String }The API’s answer isn’t what this module reads.
Refused
Section titled “Refused”type RefusedThe model declined to answer.
OutOfTokens
Section titled “OutOfTokens”type OutOfTokensThe reply reached the provider’s output limit before it ended.
TooManyTurns
Section titled “TooManyTurns”type TooManyTurns = { turns: Int }The model still called tools after this many turns.
type NoKeyThe environment has no ANTHROPIC_API_KEY.
Message
Section titled “Message”type Message = { role: Role, content: List[Content] }One turn of the conversation. The system prompt is the first message,
a System one.
type Role = | System | Agent | UserWho speaks. Each provider maps it to its own word (assistant, model, developer, …).
Content
Section titled “Content”type Content = | Text(String) /// The model's reasoning: its text, and the provider's signature to send back with it. | Reasoning { text: String, signature: Option[String] } | ToolCall /// What the tool `id` gave back; `failed` marks an error the model should see. Only in a `User` message. | ToolResult { id: String, output: String, failed: Bool }A part of a message.
type Chunk = | TextChunk(String) | ReasoningChunk(String) | ToolCall | End(Message) | AgentErrorOne piece of a streamed response. End carries the whole message; an
AgentError ends the stream.
Stream
Section titled “Stream”type Stream = { source: Source }The chunks of a streamed message as they arrive (an Iterator), holding
the open connection. Stream.of(chunks) makes one from a list, for
mocks.
Source
Section titled “Source”type Source = | Listed(List[Chunk]) | Live(Sse)Where a stream’s chunks come from.
type Sse = { claude: Claude, conversation: List[Message], tools: List[Tool], body: Option[Body], reading: Reading, done: Bool, /// How many times the API paused this turn (`pause_turn`). pauses: Int where 0 <= it && it <= pause_limit() = 0,}A streamed response being read: the request, the open body, the content so far by the API’s block index, and chunks ready to give.
Claude
Section titled “Claude”type Claude = { net: Net, key: String, model: String = "claude-opus-5-5", max_tokens: Natural = 16000, /// `low`, `medium`, `high`, `xhigh` or `max`: how much the model thinks. effort: String = "high", url: String = "https://api.anthropic.com/v1/messages",}Claude through Anthropic’s Messages API (POST /v1/messages). Make one
with claude(net, env).
Reading
Section titled “Reading”type Reading = { content: List[Content] = [], /// The API's block index to its place in `content`. slots: Dict[Int, Int] = Dict {}, /// A tool call's input as it arrives, by block index. inputs: Dict[Int, String] = Dict {}, queued: List[Chunk] = [], stop: String = "",}What the events of a streamed reply have said so far: the content by the
API’s block index, and chunks ready to give. on_event reads one event
into it; it holds no connection.
type Turn = { queued: List[ToolCall] = [], reply: Option[Message] = None }A streamed reply as its chunks arrive: the tool calls to run, and the message once it ends.
Methods
Section titled “Methods”Stream.of
Section titled “Stream.of”fn of(chunks: List[Chunk]) -> StreamA stream of these chunks.
Claude.headers
Section titled “Claude.headers”fn headers(self) -> List[(String, String)]The request’s headers.
Traits
Section titled “Traits”capability trait Model { /// The next message, the model's, given the conversation (a system /// message first, if any, and ending with a user message) and the tools. fn response( mut self, conversation: List[Message], tools: List[Tool], ) -> Result[Message, AgentError] /// The next message as it is written: its chunks, then `End` with the /// whole message, or an `AgentError`. fn stream(mut self, conversation: List[Message], tools: List[Tool]) -> Stream}A model that continues a conversation: Claude, or a mock.
derivable(Function) trait Tool { /// The name the model calls it by. derived fn name(self) -> String /// What it does, for the model. derived fn description(self) -> String /// The JSON Schema of its input. derived fn schema(self) -> JsonValue /// Runs it on the model's input: the output as JSON text, or why it failed. derived fn call(self, input: JsonValue) -> Result[String, String]}A tool the model may call: its name, what it does, the JSON Schema of
its input, and the code that runs it on the model’s input, giving the
output as JSON text or a failure the model sees.
derive Tool for add makes the function add, used as a value, a tool:
its doc comment is the description, the schema comes from its
parameters’ types (each with a JSON form), and the call reads them from
the input and writes the Ok value back as JSON; an Err is a failed
call. derive Tool(bind: net) for search leaves net out of the schema:
the use gives it, search.with(net). Any other type can implement it.
Functions
Section titled “Functions”fn user(text: String) -> MessageA message from the user.
system
Section titled “system”fn system(text: String) -> MessageThe system prompt, the conversation’s first message.
input_schema
Section titled “input_schema”fn input_schema(f: Type) -> JsonValueThe JSON Schema of a function’s input: an object with a property per
parameter not bound, each required unless it is an Option.
schema_of
Section titled “schema_of”fn schema_of(t: Type, depth: Int) -> JsonValueThe JSON Schema of a type’s JSON form (std.json’s): Int an integer,
List[T] an array, a record an object of its fields, a union of atoms
an enum of their names, another union anyOf its members, a
refinement its base with the condition as its description. Past 8
levels (a recursive type), any value.
request_json
Section titled “request_json”fn request_json( model: String, max_tokens: Natural, effort: String, conversation: List[Message], tools: List[Tool], stream: Bool,) -> StringThe request’s JSON: the System messages’ text as system, the others
as messages, the model’s reasoning summarized.
text_of
Section titled “text_of”fn text_of(m: Message) -> StringThe text of a message, its parts joined.
read_event
Section titled “read_event”fn read_event(mut body: Body) -> Result[Option[String], AgentError]The next event’s data, its data: lines joined: None at the end of
the stream.
on_event
Section titled “on_event”fn on_event(mut r: Reading, data: String) -> Result[(), AgentError]What one event’s data changes, and the chunks it gives.
fn run( mut model: Model, mut conversation: List[Message], tools: List[Tool], max_turns: Natural,) -> Result[List[Message], AgentError]Asks the model for replies until one calls no tools: each reply is added
to conversation, then the results of its tool calls, in one User
message. At most max_turns replies. Returns the conversation.
calls_of
Section titled “calls_of”fn calls_of(m: Message) -> List[ToolCall]The tool calls of a message, in order.
answer
Section titled “answer”fn answer(tools: List[Tool], c: ToolCall) -> ContentRuns the tool a call names, as its result. An unknown tool is a failed result, so the model can correct itself.
run_streamed
Section titled “run_streamed”fn run_streamed( mut model: Model, mut conversation: List[Message], tools: List[Tool], max_turns: Natural, mut console: Console, reasoning: Bool,) -> Result[List[Message], AgentError]run, with each reply streamed: its text written to console as it
comes (its reasoning too, when reasoning), each tool call run once the
reply ends.
take_chunk
Section titled “take_chunk”fn take_chunk( mut turn: Turn, c: Chunk, reasoning: Bool,) -> Result[String, AgentError]Takes one chunk into turn: the text to show (reasoning only when
reasoning; "" for none), or the error a chunk carries.
claude
Section titled “claude”fn claude(net: Net, env: Environment) -> Result[Claude, AgentError]Claude with the key in the environment’s ANTHROPIC_API_KEY.
read_message
Section titled “read_message”fn read_message(body: String) -> Result[(List[Content], String), AgentError]A response’s blocks as content, and why it stopped.
pause_limit
Section titled “pause_limit”fn pause_limit() -> Int where it == 8How many times a turn may be paused (pause_turn) and sent back: 8.
event_data
Section titled “event_data”fn event_data(line: String where starts_with(it, "data:")) -> StringA data: line’s value: what follows data:, less one space after it.
Implementations
Section titled “Implementations”impl Iterator[Chunk] for Streamimpl Model for Claude