Skip to content

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.

type ToolCall = { id: String, name: String, input: JsonValue }

The model asks to run the tool name with input. id pairs it with its result.

type AgentError = HttpError | ApiError | BadReply | Refused | OutOfTokens | TooManyTurns | NoKey

Why a run stopped without an answer.

type ApiError = { status: Int, kind: String, message: String }

The API answered with an error: its status, kind and message.

type BadReply = { reason: String }

The API’s answer isn’t what this module reads.

type Refused

The model declined to answer.

type OutOfTokens

The reply reached the provider’s output limit before it ended.

type TooManyTurns = { turns: Int }

The model still called tools after this many turns.

type NoKey

The environment has no ANTHROPIC_API_KEY.

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
| User

Who speaks. Each provider maps it to its own word (assistant, model, developer, …).

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)
| AgentError

One piece of a streamed response. End carries the whole message; an AgentError ends the 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.

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.

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).

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.

fn of(chunks: List[Chunk]) -> Stream

A stream of these chunks.

fn headers(self) -> List[(String, String)]

The request’s headers.

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.

fn user(text: String) -> Message

A message from the user.

fn system(text: String) -> Message

The system prompt, the conversation’s first message.

fn input_schema(f: Type) -> JsonValue

The JSON Schema of a function’s input: an object with a property per parameter not bound, each required unless it is an Option.

fn schema_of(t: Type, depth: Int) -> JsonValue

The 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.

fn request_json(
model: String,
max_tokens: Natural,
effort: String,
conversation: List[Message],
tools: List[Tool],
stream: Bool,
) -> String

The request’s JSON: the System messages’ text as system, the others as messages, the model’s reasoning summarized.

fn text_of(m: Message) -> String

The text of a message, its parts joined.

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.

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.

fn calls_of(m: Message) -> List[ToolCall]

The tool calls of a message, in order.

fn answer(tools: List[Tool], c: ToolCall) -> Content

Runs the tool a call names, as its result. An unknown tool is a failed result, so the model can correct itself.

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.

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.

fn claude(net: Net, env: Environment) -> Result[Claude, AgentError]

Claude with the key in the environment’s ANTHROPIC_API_KEY.

fn read_message(body: String) -> Result[(List[Content], String), AgentError]

A response’s blocks as content, and why it stopped.

fn pause_limit() -> Int where it == 8

How many times a turn may be paused (pause_turn) and sent back: 8.

fn event_data(line: String where starts_with(it, "data:")) -> String

A data: line’s value: what follows data:, less one space after it.

  • impl Iterator[Chunk] for Stream
  • impl Model for Claude