aaa.algos¶
Tool-using loops¶
ToolLoop ¶
ToolLoop(
tools: ToolRegistry,
*,
system: str = "",
model: str | None = None,
max_turns: int = 10,
params: dict[str, Any] | None = None,
tool_names: list[str] | None = None,
name: str | None = None,
stream: bool = False,
recall: RecallConfig | bool | None = None,
)
Bases: LLMLoop
Native function-calling loop: model proposes tool calls, results are fed back, until it answers in plain text. Bad/unknown/failed calls come back to the model as errors.
ReAct ¶
Bases: LLMLoop
Classic text-protocol ReAct (Thought/Action/Observation) for models or gateways without native tool calling. Prefer ToolLoop when tool calling is available.
LLMLoop ¶
LLMLoop(
tools: ToolRegistry,
*,
system: str = "",
model: str | None = None,
max_turns: int = 10,
params: dict[str, Any] | None = None,
tool_names: list[str] | None = None,
name: str | None = None,
stream: bool = False,
recall: RecallConfig | bool | None = None,
)
Shared engine for tool-using LLM loops. Subclasses decide how the model's reply maps
to actions (on_reply) and how tool results are shown back (observations).
request_for ¶
The request for the next model call given the loop state (a hook for loops whose tools or model
depend on state, like Swarm). Ordinary loops ignore the state.
first_request ¶
The run's first model request. If the input says a provider already holds the start of this
conversation (input["provider_state"] = {"state_id": ..., "covered": n}, set by sessions), say so.
with_memory ¶
Insert the recalled memories as a system message after the existing system prompt.
Planning and delegation¶
PlanAndExecute ¶
PlanAndExecute(
executor: Algorithm,
*,
model: str | None = None,
max_parallel: int = 3,
max_replans: int = 1,
synthesize: bool = True,
planner_system: str = _PLAN_SYSTEM,
review_progress: bool = False,
)
Plan once (LLM, structured), execute steps as child runs of executor honoring the
dependency DAG with bounded parallelism, replan on step failure (bounded), then synthesize.
The plan lives on the log as events, so it is inspectable, resumable and replayable.
Plan ¶
Bases: BaseModel
Step ¶
Bases: BaseModel
SelfRefine ¶
SelfRefine(
*,
max_rounds: int = 3,
model: str | None = None,
system: str = "",
params: dict[str, Any] | None = None,
)
One model drafts, critiques its own draft, and rewrites it, until the critique accepts, the rewrite changes nothing, or
max_rounds rewrites have been made. Cheaper than GeneratorCritic (no second model) and weaker for the same reason: the
critic shares the writer's blind spots, so prefer a real check (GenerateTestRepair) when you can write one.
Result: {"answer", "rounds", "stopped"} where stopped is accepted, unchanged, max_rounds or unchecked (a critique call failed).
ChainOfVerification ¶
ChainOfVerification(
*,
max_questions: int = 5,
model: str | None = None,
system: str = "",
params: dict[str, Any] | None = None,
)
Chain-of-Verification: draft an answer, plan fact-checking questions, answer each question without seeing the draft (so a mistake in the draft is not repeated), then revise the draft against those answers.
Result: {"answer", "draft", "checks": [{"question", "answer"}], "revised"}.
BestOfN ¶
BestOfN(
n: int = 5,
*,
score: Callable[[str, str], float] | None = None,
verifier_tool: str | None = None,
threshold: float | None = None,
judge_model: str | None = None,
model: str | None = None,
system: str = "",
temperature: float = 0.8,
extract: Callable[[str], str] = str.strip,
)
Sample n candidates in parallel, score each with a verifier, return the best.
The verifier is one of: a pure score(task, candidate) -> float (deterministic and free of I/O, because it runs inside the
algorithm), a tool named by verifier_tool (called with {"task", "candidate"}; it returns a number or {"score": number}), or by
default a separate model call that rates 0 to 10. With threshold, the lowest-numbered candidate that reaches it is returned as soon as
every earlier candidate has been scored (so the answer never depends on which call finished first).
Result: {"answer", "score", "scores", "selected", "n", "early_stop"}.
LeastToMost ¶
LeastToMost(
*,
max_subquestions: int = 6,
model: str | None = None,
system: str = "",
params: dict[str, Any] | None = None,
)
Least-to-most prompting: the model splits the question into at most max_subquestions easier ones, then answers them in order,
each answer seeing the earlier ones; the last step is the original question. If the split fails or comes back empty the
original question is answered directly.
Result: {"answer", "steps": [{"question", "answer"}]} (the final step is the original question).
SelfAsk ¶
SelfAsk(
*,
max_followups: int = 4,
lookup_tool: str | None = None,
model: str | None = None,
system: str = "",
params: dict[str, Any] | None = None,
)
Self-ask: the model answers directly or writes Follow up: <question>; the follow-up is answered (by a separate model call, or
by lookup_tool called with {"query": question}) and the loop continues, for at most max_followups follow-ups, then the
model must give So the final answer is: .... A reply in neither form is taken as the final answer.
Result: {"answer", "followups": [{"question", "answer"}], "turns"}.
GraphOfThoughts ¶
GraphOfThoughts(
ops: tuple[Op, ...] | list[Op] | None = None,
*,
model: str | None = None,
scorer_model: str | None = None,
system: str = "You solve problems by producing and improving thoughts.",
temperature: float = 0.8,
)
Run a graph of operations over thoughts and return the best final thought.
Result: {"answer", "score", "thoughts", "operations"} (thoughts is how many thoughts the operations hold in total).
Op
dataclass
¶
One operation. generate writes n new thoughts (from the task, or building on its inputs); aggregate merges all input thoughts
into one; refine improves each input thought; score rates each input thought 0 to 10; keep_best keeps the n highest scored.
LATS ¶
LATS(
*,
iterations: int = 6,
branching: int = 3,
depth_limit: int = 5,
exploration: float = 1.4,
solved_score: float = 9.0,
reflect_below: float = 4.0,
model: str | None = None,
scorer_model: str | None = None,
system: str = "You solve problems one reasoning step at a time.",
temperature: float = 0.8,
)
Tree search over reasoning steps with reflections.
Stops when a finished path scores at least solved_score, when iterations are used, or when nothing can be expanded.
A finished path scoring below reflect_below gets a short written lesson that later expansions see. Costs at most
iterations * branching * 3 model calls.
Result: {"answer", "score", "path", "solved", "iterations", "explored", "reflections"}. Without any finished path the
outcome is NO_SOLUTION carrying the best partial path.
ReWOO ¶
ReWOO(
registry: ToolRegistry,
*,
tool_names: list[str] | None = None,
max_steps: int = 8,
on_step_error: str = "fail",
max_evidence_chars: int = 4000,
model: str | None = None,
system: str = "",
)
Bases: _ToolPlanner
Reasoning WithOut Observation: one planning call writes every tool call up front (with #E1-style placeholders for earlier
results), the tools run without the model in the loop, and one solver call writes the answer from the evidence. Two model calls
however many tools there are, against ReAct's one per step; the price is that the plan cannot react to a surprising result.
Result: {"text", "plan": [{"id", "tool", "arguments"}], "evidence": {id: result}, "rounds": 1}.
LLMCompiler ¶
Bases: _ToolPlanner
Plan, execute in parallel, join.
Result: {"text", "plan", "evidence", "rounds"}. If the joiner keeps asking to replan after max_replans rounds, its last answer is used when
it gave one, otherwise the run ends NO_SOLUTION with the evidence.
HierarchicalAgent ¶
HierarchicalAgent(
workers: Mapping[str, Algorithm],
*,
descriptions: Mapping[str, str] | None = None,
max_subgoals: int = 6,
max_parallel: int = 3,
max_depth: int = 3,
child_budget: Budget | None = None,
on_child_failure: str = "fail",
synthesize: bool = True,
model: str | None = None,
system: str = "You are a manager who delegates work to specialists.",
name: str = "hierarchical",
)
Manager over named workers.
workers maps a name to the algorithm that does that kind of work (descriptions tells the manager what each is for). The manager
writes sub-goals {id, worker, goal, depends_on}; ids, worker names and the dependency graph are checked before any child starts.
Ready sub-goals run as child runs (at most max_parallel at once), each under child_budget, and each sees only its own goal and the results of
the sub-goals it depends on. max_depth bounds nesting: a manager at that depth refuses to delegate.
Result: {"text", "subgoals": [{"id", "worker", "goal", "result"}], "depth"}.
CorrectiveRAG ¶
CorrectiveRAG(
index: Index,
*,
web_tool: Tool | None = None,
min_relevant: int = 1,
max_rewrites: int = 1,
**kw: Any,
)
Bases: _Rag
Corrective RAG: retrieve, grade every passage, and act on the grades.
Enough relevant passages (min_relevant) and the question is answered from them. Otherwise the query is rewritten and retrieval repeated
(up to max_rewrites times); if that still fails and a web_tool was given, it is called with the last query and its results are graded too.
With nothing relevant anywhere the run ends NO_SOLUTION instead of guessing.
web_tool is the operator's fallback (a web or enterprise search tool taking a query); it is added to rag.tools, so attach
ToolHandler(rag.tools). Result: {"text", "sources", "queries", "route", "graded"} with route one of index, rewritten, web.
SelfRAG ¶
SelfRAG(
index: Index,
*,
adaptive: bool = True,
max_candidates: int = 3,
max_rewrites: int = 1,
**kw: Any,
)
Bases: _Rag
Self-RAG as an algorithm: the model decides whether the question needs retrieval at all, then writes one candidate answer per retrieved
passage (so no answer mixes sources) and judges each candidate with reflection fields: is the passage relevant, is the answer
supported by it (full, partial, none) and how useful is it (1 to 5). The best supported candidate wins. If none is supported the query
is rewritten and the round repeated (max_rewrites), after which the run ends NO_SOLUTION carrying the best candidate rather than presenting
an unsupported answer as grounded.
Result: {"text", "source", "supported", "useful", "queries", "rounds", "route"} (route is retrieved or direct).
AdaptiveRAG ¶
Bases: _Rag
Adaptive RAG: match the retrieval to the question. A first call routes it: direct (answer from the model's own knowledge, no retrieval),
single (one retrieval, then answer) or iterative (up to max_hops rounds of "search again or answer", for questions that need
several facts). An unusable routing answer falls back to single.
Result: {"text", "route", "hops", "sources", "queries"}.
SkillLibrary ¶
SkillLibrary(
memory: Memory,
sandbox: Sandbox,
*,
limits: Limits | None = None,
max_skills: int = 200,
)
Verified skills in a Memory, run only in a Sandbox.
The memory must keep meta as it is given (the native and fake memories do). scope is always the application's, built from the run (see
skill_tools), never from model output.
Skill
dataclass
¶
skill_tools ¶
find_skill, list_skills, run_skill and save_skill for a tool loop. Finding is read-only; running and saving execute code, so they wait
for approval unless you turn that off for a sandbox you would trust with the worst code the model could write.
VoyagerAgent ¶
VoyagerAgent(
library: SkillLibrary,
*,
extra_tools: list[Tool] | None = None,
requires_approval: bool = True,
max_turns: int = 14,
**kw: Any,
)
Bases: ToolLoop
A tool loop that finds, writes, verifies and reuses skills.
Verification is enforced by save_skill (the test must pass in the sandbox before anything is stored), and running skills waits for approval by
default. Attach ToolHandler(agent.tools). Result: {"text", "turns"} like any ToolLoop.
VoyagerCurriculum ¶
VoyagerCurriculum(
agent: VoyagerAgent,
goal: str,
*,
max_tasks: int = 5,
child_budget: Budget | None = None,
model: str | None = None,
)
Voyager's automatic curriculum: propose a task, let a VoyagerAgent attempt it, remember how it went, propose the next.
Each round lists the skills the library holds (a tool call), asks the model for one new task from the goal, the skills and the tasks already tried
(shown as quoted data), and runs the agent on it as a child run under child_budget. Everything the agent does is as gated as ever: skills are
saved only after their test passes in the sandbox, and running or saving waits for approval unless you turned that off. The curriculum adds no new
power: it only chooses what to attempt, at most max_tasks times, never the same task twice, and stops when the model says done.
Attach ToolHandler(agent.tools) for the agent you pass. Result: {"attempted": [{"task", "ok", "answer"}], "skills": [names], "stopped"} with
stopped done, max_tasks or no_new_task. At most max_tasks proposal calls plus the agent's own.
MemoryReflection ¶
MemoryReflection(
memory: Memory,
*,
window: int = 20,
threshold: float = 40.0,
questions: int = 3,
insights_per_question: int = 2,
k: int = 8,
model: str | None = None,
scorer_model: str | None = None,
)
Reflect on the recent memories of the run's scope.
threshold is the summed importance (each memory 1 to 10) the recent window must reach before anything is asked; below it the run ends
{"reflected": False} having spent only the scoring calls. Attach ToolHandler(reflection.tools).
Result: {"reflected", "importance", "questions", "insights": [{"text", "sources"}], "written"}. At most window + 1 + questions model calls.
rank_memories ¶
rank_memories(
items: list[MemoryItem],
importance: dict[str, float],
now: datetime,
*,
half_life_hours: float = 72.0,
weights: tuple[float, float, float] = (1.0, 1.0, 1.0),
) -> list[MemoryItem]
Order memories by recency + importance + relevance (each scaled to 0..1 across items), best first; ties keep the input order.
Recency halves every half_life_hours; importance is the 1 to 10 score in importance[id] (5 when unknown); relevance is the memory's own search
score. Pure, so it can be tested and tuned.
SelfManagedMemory ¶
SelfManagedMemory(
memory: Memory,
*,
blocks: dict[str, int] | None = None,
extra_tools: list[Tool] | None = None,
k: int = 5,
**kw: Any,
)
Bases: ToolLoop
A tool loop with MemGPT-style memory. At the start of each run the core blocks are read and placed in the system prompt (quoted); the
model edits them and archival memory with tools. Attach ToolHandler(agent.tools); give the LLMHandler a context policy to keep long conversations in the window.
self_memory_tools ¶
self_memory_tools(
memory: Memory,
*,
blocks: dict[str, int] | None = None,
k: int = 5,
) -> list[Tool]
The five memory tools, bound to memory and to fixed core-block labels and limits.
optimize_prompt
async
¶
optimize_prompt(
engine: Engine,
build: Callable[[str], Algorithm],
dataset: Dataset,
metrics: Sequence[Metric],
proposer: LLMClient,
*,
baseline: str,
rounds: int = 2,
variants: int = 3,
holdout: float = 0.3,
seed: int = 0,
objective: Callable[
[EvalReport], float
] = default_objective,
max_evaluations: int = 500,
margin: float = 0.0,
instructions: str = "",
proposer_model: str | None = None,
case_budget: Budget | None = None,
concurrency: int = 4,
) -> OptimizeResult
Search for a better system prompt for the algorithm build(prompt) makes. See the module docstring for the guarantees.
build must return a fresh algorithm each call; give each a distinct name if your engine is distributed.
OptimizeResult
dataclass
¶
OptimizeResult(
baseline: str,
best: str,
baseline_dev: float,
best_dev: float,
baseline_holdout: float,
best_holdout: float,
improved: bool,
candidates: list[Candidate] = list(),
dev_cases: int = 0,
holdout_cases: int = 0,
evaluations: int = 0,
diff: str = "",
)
split_dataset ¶
A deterministic dev / held-out split: cases are ordered by a hash of (seed, id), so it does not depend on file order.
MixtureOfAgents ¶
MixtureOfAgents(
*,
proposers: int = 3,
layers: int = 2,
models: Sequence[str | None] | None = None,
personas: Sequence[str] | None = None,
aggregator_model: str | None = None,
model: str | None = None,
temperature: float = 0.7,
system: str = "",
)
Layered proposers with an aggregator.
Layer 0: proposers independent answers to the task (each may have its own models[i] and personas[i]). Each later layer: every proposer
sees all the previous layer's answers and writes an improved one. Finally the aggregator combines the last layer. A proposer whose call fails
drops out of that layer; a layer with no answers fails the run. At most proposers * layers + 1 calls.
Result: {"answer", "layers": [[answers...]]}.
Blackboard ¶
Blackboard(
experts: Mapping[str, str | Expert],
*,
max_rounds: int = 6,
max_entry_chars: int = 2000,
model: str | None = None,
controller_model: str | None = None,
system: str = "",
)
Experts build a shared answer on a common board, one contribution per round.
Who contributes next is decided in one of two ways. An expert with Expert(..., when=..., auto=True) is a knowledge source: as soon as its trigger
holds on the current board it contributes, without the chair being asked (the first such expert, in the order given, if several are ready). When no
automatic expert is ready, the chair reads the board and names who goes next, or done; it may only pick experts that have no trigger or whose trigger
holds now. A named expert writes one contribution (capped at max_entry_chars) appended under their name; at the end a solver writes the answer
from the board.
Everything that matters is bounded and checked in code: triggers are plain functions of the board (an exception counts as "not triggered"), an expert
a triggered expert contributes once unless it may repeat, an unknown or ineligible name ends the session, a failed expert call is skipped, and rounds are capped. At most
2 * max_rounds + 1 model calls (automatic rounds need no chair call).
Result: {"answer", "board": [{"author", "text"}], "rounds"}.
Auction ¶
Auction(
workers: Mapping[str, Algorithm],
*,
descriptions: Mapping[str, str] | None = None,
rule: str = "best_value",
min_confidence: float = 0.2,
max_cost: float = 1000.0,
fallback: bool = True,
child_budget: Budget | None = None,
model: str | None = None,
)
Award a task to the best bidder.
Each worker is asked for {"cost": estimated effort >= 0, "confidence": 0 to 1, "approach"}. Bids below min_confidence or above max_cost are
rejected. The rule ranks the rest: best_value = confidence / (1 + cost), lowest_cost, or highest_confidence. The winner runs the task under
child_budget; if it fails and fallback is on, the next-ranked bidder runs it.
Result: {"text", "winner", "tried": [names], "bids": {name: {"cost", "confidence"}}}. Calls: one bid per worker plus the winner's own.
RolePlaySOP ¶
A pipeline of roles passing validated documents.
Result: {"document": <last role's document>, "documents": {role: document}, "roles": [...], "repairs": n}. At most
len(roles) * (max_repairs + 1) model calls.
Role
dataclass
¶
AskHuman ¶
Answer, or ask a person and wait.
Result: {"answer", "questions": [{"question", "answer"}], "asked"}. At most max_questions + 1 model calls.
ComputerUse ¶
ComputerUse(
env: Environment,
*,
max_steps: int = 12,
max_repeats: int = 3,
stall_limit: int = 3,
reset_first: bool = True,
vision: bool = False,
model: str | None = None,
system: str = "",
)
Drive an environment toward a goal.
Attach ToolHandler(agent.tools). Result: {"answer", "steps": [{"action", "arguments", "ok"}], "stopped"} with stopped one of finished,
max_steps, repeat, stall (the last three come with outcome NO_SOLUTION). At most max_steps + 1 model calls.
Environment ¶
Bases: Protocol
ActionSpec ¶
Bases: BaseModel
Observation ¶
Bases: BaseModel
What the environment shows after an action. fingerprint changes when the state does (used to notice a stuck loop).
image is an optional screenshot (base64 of a PNG or JPEG, image_type says which). When there is one, the fingerprint is the picture's digest: what a person
would see is what counts, so a page whose text moves while the picture does not is a stalled page, and the reverse.
FakeEnvironment ¶
A deterministic environment for tests and offline examples: named pages, and actions that move between them.
Actions: click(target) and type(target, text) (side effects), scroll(direction) and read() (none). click:<target> or type:<target> in a
page's on map names the page it leads to; anything else leaves the page as it is. log records every action performed.
env_tools ¶
env_reset, env_observe, env_act and env_act_confirm bound to env.
env_act runs only actions that declare no side effect; env_act_confirm runs the others and waits for approval. Calls are serialised.
BrowserEnvironment ¶
BrowserEnvironment(
allowed_hosts: Sequence[str],
start_url: str,
*,
headless: bool = True,
allow_private_networks: bool = False,
max_elements: int = 40,
max_text_chars: int = 4000,
timeout_ms: int = 10000,
executable_path: str | None = None,
pin_dns: bool = True,
allowed_ports: Sequence[int] = (80, 443),
screenshots: bool = False,
screenshot_quality: int = 60,
max_image_bytes: int = 400000,
)
One browser page, restricted to allowed_hosts. See the module docstring for the guarantees.
max_elements caps the controls listed to the model; timeout_ms bounds every page operation. Use async with or call aclose().
CodeAct ¶
CodeAct(
sandbox: Sandbox,
*,
max_steps: int = 6,
limits: Limits | None = None,
requires_approval: bool = True,
observation_chars: int = 2000,
max_code_chars: int = 20000,
model: str | None = None,
system: str = _PROMPT,
params: dict[str, Any] | None = None,
tools: ToolRegistry | None = None,
tool_names: list[str] | None = None,
max_tool_calls: int = 8,
max_result_chars: int = 20000,
)
A write-run-observe loop over a sandbox.
Attach ToolHandler(agent.tools). Result: {"answer", "steps": [{"code", "exit_code", "stdout", "stderr"}], "turns"}; running out of max_steps without
an answer ends NO_SOLUTION. At most max_steps + 1 model calls.
Anytime ¶
Escalate along a ladder while the budget allows.
Result: {"value", "rung", "tried", "degraded", "stopped"} where stopped is accepted (a rung's result was good enough), exhausted (the ladder ran out) or
budget (the next rung could not be afforded). degraded is true unless the accepted rung was the first choice.
Rung
dataclass
¶
Router ¶
Router(
routes: dict[str, Route | Algorithm],
*,
classifier: Callable[[dict[str, Any]], str | None]
| None = None,
default: str | None = None,
model: str | None = None,
)
Pick exactly one specialist and delegate (as a child run). Deterministic classifier
first (cheap, testable); the LLM only decides what rules don't. Returns the child's outcome.
Supervisor ¶
Supervisor(
workers: dict[str, tuple[Algorithm, str]],
*,
extra_tools: list[Tool] | None = None,
**kw: Any,
)
Bases: ToolLoop
Centralized coordinator: an LLM delegates sub-tasks to named worker algorithms (each a
child run: own budget accounting, cancelled with the parent). Parallelism is bounded by the
'delegate' pool. Attach ToolHandler(supervisor.tools).
Verification loops¶
GenerateTestRepair ¶
Bases: _Refine
Candidate is checked by a deterministic named validator (tests, linter, schema, rules) served by ValidationHandler. Accepts only what the validator accepts.
GeneratorCritic ¶
Bases: _Refine
Candidate is judged by a separate LLM critic call. Weaker than deterministic checks (the critic is probabilistic); always bounded by max_iterations.
Deterministic control flow¶
WorkflowGraph ¶
Deterministic DAG execution: no LLM decides control flow. Ready nodes run in parallel;
tools bring approval gates, timeouts, idempotency and budgets. Cyclic/stateful control
flow belongs to FSM. Output = output node id, a callable(results), or all results.
Node
dataclass
¶
Node(
id: str,
tool: str,
after: list[str] = list(),
args: Callable[
[dict[str, Any], dict[str, Any]], dict[str, Any]
]
| dict[str, Any]
| None = None,
when: Callable[[dict[str, Any], dict[str, Any]], bool]
| None = None,
on_error: str = "fail",
)
One workflow step = one tool call. args(results, input) builds its arguments from
upstream outputs; when(results, input) can skip it (skipped nodes yield None).
FSM ¶
FSM(
initial: str,
transitions: dict[str, dict[str, Transition]],
terminal: set[str],
on_enter: dict[
str, Callable[[Event, dict[str, Any]], list[Event]]
]
| None = None,
)
Explicit finite-state machine driven by external/internal events. transitions[state]
[event_type] is the next state or a function(event, input) -> next state | None (guard).
on_enter[state](event, input) may return events (request a tool, an LLM call, ...).
Reaching a terminal state completes the run with the path taken. The current state is a
fold of aaa.fsm.transitioned events, so it survives restarts.
Ensembles and retrieval¶
SelfConsistency ¶
SelfConsistency(
n: int = 5,
*,
temperature: float = 0.8,
model: str | None = None,
system: str = "Think step by step, then end with a line 'Answer: <final answer>'.",
extract: Callable[[str], str] = default_extract,
)
Sample N independent answers in parallel and return the majority (ties -> earliest). Only worthwhile when answers can be compared exactly (math, classification, extraction).
RAGAgent ¶
Bases: ToolLoop
Agentic RAG: a ToolLoop whose tool is retrieval over any Index. The model decides
when/what to retrieve and is told to ground and cite. Attach ToolHandler(rag.tools).
Authoring helpers¶
base ¶
llm_request ¶
llm_request(
parent: Event,
req: LLMRequest,
tag: str = "main",
*,
prev: str | None = None,
) -> Event
Build an aaa.llm.requested event.
With prev (the id of the previous request event of the SAME conversation), req.messages
must hold only the messages appended since that request's reply; the event then stores just
that delta plus a pointer. The LLM handler reconstructs the full transcript the provider
needs, so the log (and algorithm state) grows linearly with turns, not quadratically.
tool_request ¶
finish ¶
parse_json_obj ¶
Best-effort: a JSON object from raw model text (fenced or surrounded by prose).
Reasoning algorithms¶
Reflexion ¶
Reflexion(
*,
validator: str | None = None,
system: str = "",
model: str | None = None,
critic_model: str | None = None,
critic_system: str = _CRITIC_SYSTEM,
max_trials: int = 3,
keep_reflections: int = 5,
params: dict[str, Any] | None = None,
extract_code: bool = False,
)
Trial -> evaluate -> (if rejected) reflect -> new trial, at most max_trials times.
The evaluator is a deterministic named validator (validator="...", served by ValidationHandler) or, if none is given,
an LLM critic. keep_reflections bounds how many lessons enter the prompt (the most recent ones).
Result: {"candidate", "trials", "reflections"}; a run that never passes ends NO_SOLUTION carrying the best-effort
last attempt and the reflections.
Debate ¶
Debate(
agents: int = 3,
rounds: int = 1,
*,
judge: bool = True,
personas: list[str] | None = None,
model: str | None = None,
judge_model: str | None = None,
system: str = "Think step by step, then end with a line 'Answer: <final answer>'.",
extract: Callable[[str], str] = default_extract,
temperature: float = 0.7,
)
agents debaters answer rounds + 1 times (round 0 independently, later rounds after reading the others' previous
answers). judge=True (default) asks one more model call to rule on the final answers; judge=False takes the majority
of the extracted final answers. personas gives each debater its own system prompt.
Result: {"answer", "rounds", "agents", "answers": [[round-0 answers], ...], "judged": bool}.
Swarm ¶
Swarm(
agents: Mapping[str, Agent],
tools: ToolRegistry,
*,
start: str,
max_handoffs: int = 6,
**kw: Any,
)
Bases: ToolLoop
A ToolLoop whose active agent can change. Attach ToolHandler(swarm.tools) as usual (the registry holds every tool;
each agent sees only its own). Result is the final agent's reply plus the agent that gave it:
{"text", "turns", "agent", "handoffs": [[from, to], ...]}.
Agent
dataclass
¶
Agent(
instructions: str,
tools: list[str] = list(),
handoffs: list[str] = list(),
description: str = "",
model: str | None = None,
)
TreeOfThoughts ¶
TreeOfThoughts(
*,
depth: int = 3,
width: int = 2,
branching: int = 3,
stop_score: float | None = 9.0,
model: str | None = None,
scorer_model: str | None = None,
system: str = "You solve problems one reasoning step at a time.",
temperature: float = 0.8,
)
Beam search over reasoning steps.
At each of up to depth levels, every node of the beam gets branching proposed next steps; each proposal is scored 0-10 by
a separate call; the best width survive. A proposal that starts with FINAL: is a complete answer. The search stops when the
best node of a level is final, when its score reaches stop_score, or at the last level, and returns the best path.
Result: {"answer", "score", "path": [steps...], "depth", "explored"}.