Expand description
High-level façade for building an LLM agent loop. Most application
code only depends on this crate — it re-exports the vocabulary from
ailoop_core (messages, stream chunks, hooks) and from the side
crates (ailoop-history, ailoop-tools, ailoop-prompts) you need
to wire a Conversation together.
§Happy path
let mut chat = ailoop::Conversation::builder(model)
.system_prompt("You are a helpful assistant.")
.build()?;
let outcome = chat.run("What is the speed of light?").await?;
println!("{}", outcome.final_text.unwrap_or_default());Conversation::run is the one-shot helper for CLI flows and
notebooks; Conversation::stream yields one StreamChunk at a
time when you want to render tokens, observe tool calls, or thread
events through middleware as they happen.
§Mini-index
Conversation— the agent loop. Construct viaConversation::builder.ConversationBuilder— builder pattern. Register tools withtool/tool_dyn, gate them withwith_capabilities/with_approval, and layer per-request defaults withtemperature,max_tokens, and friends.RunOutcome— whatConversation::runreturns. Aborts surface here asFinishReason::Aborted, not asErr.- Built-in middlewares:
AntiLoop(loop-detection abort),Sanitize(caller-supplied text rewrites at the model boundary),ApprovalMiddleware(human-in-the-loop gating),JsonTracer(NDJSON event sink). With thetracingfeature,TracingMiddlewareroutes the same events through thetracingcrate. SubAgentTool— wrap aConversationas aToolDynso a parent agent can delegate to it.advanced::run_chat— escape hatch for engine-level access without aHistoryin the loop.
Modules§
- advanced
- Lower-level entry points outside the
Conversationhappy path.
Structs§
- Anti
Loop - Middleware that aborts a run when the model gets stuck repeating itself. Two independent detectors run side by side:
- Approval
Middleware - Middleware that asks a user-supplied async callback whether each tool
call should proceed, returning the callback’s
ToolDecisionto the engine. - Cancellation
Token - A token which can be used to signal a cancellation request to one or more tasks.
- Char
Tokenizer - Fallback
Tokenizerthat approximates tokens astext.len() / 4. - Chat
Request - Per-turn request the engine assembles and the adapter lowers to the provider’s wire format.
- Conversation
- An agent loop bound to a single
CompletionModel, with history, tool registry, and middleware chain configured up front. Construct viaConversation::builder. - Conversation
Builder - Configuration builder for a
Conversation. Returned byConversation::builder. - Conversation
Snapshot - Persistable image of a conversation’s logical state.
- History
- Owns the message vector backing a single conversation, plus the budget and pin mask that govern how compaction reduces it.
- History
Builder - Configuration for a
History. - InMemory
History Store - Volatile
HistoryStorekept entirely in process memory. Intended for tests and short-lived sessions where durable persistence is not required. - Json
File History Store - JSON-backed
HistoryStorethat writes the full snapshot to a single file.savepretty-prints;loadreturnsOk(None)when the file does not exist (first run) so callers can seed an empty conversation without branching on the missing-file case. - Json
Tracer - Append-only NDJSON sink. Holds the open file behind a tokio
Mutexso concurrent runs sharing the sameArc<JsonTracer>cannot interleave bytes within a line. The inner handle isstd::fs::File: the writes are small (one JSON object) andtokio::fs::Filebuffers internally, which would silently swallow events on drop without an explicitflush().awaitbetween every emit. - Prompt
- Composable system prompt: an ordered list of
PromptSections. - Prompt
Builder - Fluent builder for
Prompt. Eachsectioncall appends to the running list;buildfinalizes it. - Prompt
Section - One section of a
Prompt. - Retry
Config - Backoff settings for
RetryingModel. - Retrying
Model - Decorator that retries setup-time failures of an inner
CompletionModelusing exponential backoff with optional jitter, honouringRetry-Afterwhen the inner error provides it. - RunConfig
- Per-run configuration consumed by the engine entry point.
- RunId
- Unique identifier for a single run of the engine.
- RunOutcome
- Summary of a completed (or aborted) run, returned by
Conversation::run. - RunStream
StreamofStreamChunks for a single in-flight run, returned byConversation::stream.- Sanitize
- Middleware that runs caller-supplied transformations at the points where text crosses the model boundary: user-message text and tool args on the way out, tool results on the way back in.
- StepId
- Unique identifier for one provider turn (one model call) within a run.
- SubAgent
Tool - Wraps a
Conversationso a parent agent can delegate to it as a regular tool. Pure composition: nothing in the engine or registry changes — the child runs on its ownCompletionModel, history, and middleware chain. - Summarize
Strategy - Compaction strategy that calls a
CompletionModelto summarize the dropped portion of the history into a single text message, instead of dropping it outright. - Tool
Activation - Per-run handle to the active tool set.
- Tool
Context - Context delivered to a tool handler on every dispatch.
- Tool
Definition - Tool description sent to the provider so the model can decide when and how to call it.
- Tool
Registry - Owns every tool a
Conversationcan dispatch to and tracks which of them are currently active. - Tool
Result Content - Body of a tool reply sent back to the model in a
UserBlock::ToolResult. - Truncate
Strategy - Default
CompactionStrategy: drop the oldest unpinned messages until the preserved tail starts at a safeUser-without-ToolResultboundary. Pinned messages from the dropped prefix survive verbatim at their relative position; the cut never strands aToolResultfrom itsToolCall. Reports underCompactionStrategy::nameas"truncate". - Usage
- Token counters reported by the provider for a turn.
Enums§
- Assistant
Block - One block inside a
Message::Assistantturn. - Build
Error - Errors accumulated by
ConversationBuilderand surfaced whenbuildis called. Distinct fromEngineError: these fire during setup, not during a run. - Compaction
Error - Failure surface of
CompactionStrategy::compact(and therefore ofHistory::compact_if_needed). - Engine
Error - Failure surface of
Conversation::run/Conversation::streamand the underlyingrun_chatengine. - Finish
Reason - Reason a provider turn (or an entire run) ended.
- From
Messages Error - Returned by
ConversationSnapshot::newandHistory::from_messageswhen the supplied parallel vectors are inconsistent. Surfaces at restore time so a malformed snapshot fails loudly instead of corrupting state silently. - Hook
Action - Decision returned from
ChatMiddleware::on_run_startedto optionally short-circuit a run before any provider call. - Json
File History Store Error HistoryStore::Errorvariant forJsonFileHistoryStore.- Message
- One turn in the conversation history exchanged with a provider.
- Retry
Classification - Outcome of
Retryable::retry_classification: whether the decorator should attempt the call again, and after how long. - Stream
Chunk - Event the engine emits as a run progresses.
- Tool
Activation Error - Failures from
ToolActivationmutations. - Tool
Choice - Constraint placed on the model’s tool selection for a single
request. Variant naming follows Anthropic’s wire vocabulary; the
Chat Completions adapter translates
Any→"required"andNone_→"none". - Tool
Decision - Decision returned from
ChatMiddleware::on_before_tool_callto optionally bypass or abort a tool invocation. - Tool
Registry Error - Errors surfaced by
ToolRegistryoperations. - ToolTag
- Capability tag attached to a
ToolDefinition. - User
Block - One block inside a
Message::Userturn.
Constants§
- DEFAULT_
HISTORY_ MAX_ TOKENS - Default token budget the internal
Historyis configured with whenConversationBuilder::with_historyis not called.
Traits§
- Chat
Middleware - Extension point invoked by the engine at every lifecycle event of a run.
- Compaction
Strategy - User-implementable strategy for shrinking a
History’s history whenHistory::compact_if_neededruns. - Completion
Client - Factory for
CompletionModelhandles bound to a provider account / endpoint. - Completion
Model - Provider-agnostic streaming completion contract.
- History
Store - Persistence backend for conversation snapshots.
- Retryable
- Adapter-side classification of an error as retryable or not.
- Tokenizer
- Counts tokens in text and full messages.
- Tool
- Typed tool entry point. Implement (or derive via
#[ailoop_tool]) to expose a function to the model with deserializedArgsin and a serializableOutputout. - ToolDyn
- Object-safe sibling of
Toolused wherever the registry needsArc<dyn ToolDyn>— runtime tool discovery (MCP, plugin loaders, config-driven catalogs). The blanketimpl<T: Tool> ToolDyn for Tpromotes every static tool to a dynamic one for free. - Tool
Json Type - Per-type JSON Schema fragment supplier for the
#[ailoop_tool]macro.
Type Aliases§
- Text
Predicate - Predicate used to compare two assistant text turns. Receives
(previous, current)and returnstruewhen the texts should count as a repeated turn for the loop detector. Default trims both sides and compares for equality, which absorbs the trailing newline that some providers emit at the end of a turn. - Text
Rewriter - Rewriter applied to a piece of text. Receives the current value and
returns either
Cow::Borrowed(input)(no change, zero allocation) orCow::Owned(new)(replace). The HRTB on the function signature lets callers return a borrow whose lifetime is tied to the input slice without naming it explicitly. - Tool
Args Rewriter - Rewriter applied to a tool’s
argsvalue. Receives the tool name so the callback can dispatch on it (match name { "fetch" => ..., _ => ()}) instead of forcing a per-tool registry. - Tool
Result Rewriter - Rewriter applied to a tool’s result before the model sees it.
Receives the tool name; mutate
resultin place to redact / scrub / truncate.