Ir para o conteúdo

tempest_fastapi_sdk.agents

Agentes de IA sobre os modelos que você já hospeda: ferramentas, memória e o loop de execução.

« IA e visão computacional


agents

AI agents over the models you already self-host.

An agent takes a goal, decides what to do, calls tools, and reports what it did. That last part is the difference from a chat pipeline: the run comes back with a step-by-step trace — arguments, outputs, timings, failures — plus whatever files it produced.

>>> from tempest_fastapi_sdk.agents import Agent, generate_image_tool
>>> agent = Agent(
...     OllamaGenerator("llama3.2"),
...     tools=[generate_image_tool(image_generator)],
... )
>>> run = await agent.run("Draw a red bicycle at sunset.")
>>> run.output, run.tool_calls
>>> run.artifacts[0].data       # the PNG bytes

The tools in :mod:tempest_fastapi_sdk.agents.builtin wrap the models the SDK already runs locally — text, image, audio, RAG — so an agent composes what is there rather than reaching for a paid API. They chain through named artifacts: an agent can draw a picture and then ask the vision model to check it, without either the bytes touching disk or base64 touching the prompt.

Submodule import, like genai and modelops: from tempest_fastapi_sdk.agents import Agent. Imports with no optional extra — the heavy work lives in the objects you inject.

APPROVAL_TOKEN module-attribute

APPROVAL_TOKEN: str = 'APPROVED'

What the critic says when it accepts.

The whole reply, stripped of surrounding whitespace, must equal this token (case-insensitively). A prefix match would read "APPROVED? No — the intro is wrong" as an approval, and a critic run that stopped on a budget is never an approval whatever it said.

AgentBackend module-attribute

What Agent accepts as its model.

A backend without chat_with_tools still drives a toolless agent; the loop probes for the method and falls back to :meth:ChatBackend.chat.

AgentDependency module-attribute

AgentDependency = Callable[..., Agent] | Callable[..., Awaitable[Agent]]

A FastAPI dependency returning the agent that serves one request.

Anything FastAPI accepts in Depends works: a function taking the Request, one declaring its own Depends (the current user, a database session), sync or async. A dependency shared with owner is resolved once per request — FastAPI caches it — so the factory and the run see the same principal.

DEFAULT_CRITIC_PROMPT module-attribute

DEFAULT_CRITIC_PROMPT: str = "You are reviewing another agent's work against the goal below. If it fully satisfies the goal, reply with exactly APPROVED and nothing else. Otherwise list what is wrong and what to change, in specific terms the author can act on. Do not rewrite it yourself."

Instruction given to the critic in :func:refine.

The exact-token approval matters: a critic asked for free-form judgement hedges, and "looks good, though you might consider..." is impossible to branch on. One reserved word makes the decision machine-readable while the rejection stays free-form, which is the half that needs to be expressive.

DEFAULT_MAX_DEPTH module-attribute

DEFAULT_MAX_DEPTH: int = 3

How many delegations deep a chain may go before it is refused.

Three is enough for a coordinator to reach a specialist that consults one helper, and shallow enough that a cycle is caught long before it costs real time.

DEFAULT_SYSTEM_PROMPT module-attribute

DEFAULT_SYSTEM_PROMPT: str = "You are a capable assistant working towards the user's goal. Use the available tools when they help and answer directly when they do not. When a tool fails, read the error and try a different approach rather than repeating the same call. When you have the answer, reply with it and stop calling tools."

The default instruction given to the model.

Written to counter the two failure modes that dominate small local models: calling a tool when a direct answer would do, and retrying an identical failing call until the budget runs out.

FINAL_ANSWER_TOOL module-attribute

FINAL_ANSWER_TOOL: str = 'final_answer'

Name of the tool the model calls to deliver a structured answer.

LOAD_SKILL_TOOL module-attribute

LOAD_SKILL_TOOL: str = 'load_skill'

Name of the tool an agent calls to open a skill.

OwnerDependency module-attribute

OwnerDependency = Callable[..., str] | Callable[..., Awaitable[str]]

A FastAPI dependency returning the calling principal's id.

Agent

Agent(
    generator: AgentBackend,
    *,
    tools: Sequence[AgentTool] = (),
    skills: Sequence[Skill] = (),
    system_prompt: str = DEFAULT_SYSTEM_PROMPT,
    budget: AgentBudget | None = None,
    moderator: ModerationBackend | None = None,
    run_sink: AgentRunSink | None = None,
    metrics: Any = None,
    name: str = "agent",
    expose_tool_errors: bool = False,
    parse_text_tool_calls: bool = True,
)

A goal-driven loop over a tool-calling text backend.

Example:

>>> agent = Agent(
...     OllamaGenerator("llama3.2"),
...     tools=[generate_image_tool(image_generator)],
...     budget=AgentBudget(max_steps=8, max_seconds=90),
... )
>>> run = await agent.run("Draw a red bicycle and tell me the seed.")
>>> run.succeeded, run.tool_calls
(True, ['generate_image'])

Attributes:

Name Type Description
generator AgentBackend

The text backend driving the loop.

tools list[AgentTool]

What the model may call.

system_prompt str

The instruction prepended to every run.

budget AgentBudget

The ceilings a run must not cross.

name str

This agent's name, recorded on each run.

Configure the agent.

Parameters:

Name Type Description Default
generator AgentBackend

A text backend — TextGenerator, OllamaGenerator, or anything implementing :class:~tempest_fastapi_sdk.agents.ToolCallingBackend. A plain :class:~tempest_fastapi_sdk.agents.ChatBackend (chat only) is accepted and runs toolless.

required
tools Sequence[AgentTool]

What the model may call. An empty sequence makes this a single-shot answerer.

()
skills Sequence[Skill]

Capabilities loaded on demand. Only each one's name and one-line description sit in the prompt; the full instructions and the skill's own tools arrive when the model loads it. This is how an agent can have many capabilities without the prompt growing to match.

()
system_prompt str

The instruction prepended to every run.

DEFAULT_SYSTEM_PROMPT
budget AgentBudget | None

Ceilings; a default :class:~tempest_fastapi_sdk.agents.AgentBudget when None.

None
moderator ModerationBackend | None

When set, the goal is checked before the run starts and the answer before it is returned. A rejection stops the run with :attr:StopReasonEnum.BLOCKED rather than raising. A moderator that raises also stops it with BLOCKED (the output says moderation was unavailable, the exception is logged): failing open would return unchecked text as checked text.

None
run_sink AgentRunSink | None

Where finished runs go — in-memory, a database table, your own callable. Sink failures never fail the run.

None
metrics Any

Optional :class:~tempest_fastapi_sdk.genai.GenAIMetrics; each run records duration under the op "agent".

None
name str

This agent's name, recorded on each run.

'agent'
expose_tool_errors bool

Hand the text of an unexpected tool exception (anything but :class:AgentToolError) to the model and record it on the step. Off by default: the model reads "tool failed: <Type>", the step records "<Type>: the tool failed (details withheld)", and the full exception goes to the log either way. An arbitrary exception can carry a DSN, a token or a URL with its API key; the trace is what the HTTP router, the SSE stream and the run sinks expose, and the model can repeat what it reads to the user. With it on, the text passes through a mask of the obvious credential shapes (?apikey=, Authorization, a URL's password) first — a backstop for development, not a guarantee. :class:AgentToolError messages always reach both as written.

False
parse_text_tool_calls bool

When a reply has no native tool_calls, read its text as a call: one JSON object {"name", "arguments"} (or a list of them, or several separated by whitespace), optionally in a single markdown fence, whose name is a tool available in that turn. Such a call runs like a native one: the assistant turn is echoed back with the call in tool_calls and empty content, and the tool step carries from_text=True. Some models choose the right tool and arguments but write the call in content; without this the JSON becomes the run's answer. Turn it off when a legitimate answer can be a JSON object whose name matches a tool name.

True

tool_names property

tool_names: list[str]

Return the names the model can call, in order.

Returns:

Type Description
list[str]

list[str]: The configured tool names.

run async

run(goal: str, *, context: AgentContext | None = None) -> AgentRun

Work towards goal and return the full record.

Example:

>>> run = await agent.run("Summarise the latest sales report.")
>>> run.stop_reason
<StopReasonEnum.COMPLETED: 'completed'>

Parameters:

Name Type Description Default
goal str

What the agent should accomplish.

required
context AgentContext | None

A pre-seeded context — use it to hand the agent artifacts it should start from (an audio clip to transcribe, an image to look at).

None

Returns:

Name Type Description
AgentRun AgentRun

The answer, the trace, the artifacts and the reason

AgentRun

the run ended. Check

AgentRun

attr:~tempest_fastapi_sdk.agents.AgentRun.succeeded before

AgentRun

trusting the output — a budget-truncated run still carries text.

run_structured async

run_structured(
    goal: str,
    output: type[OutputT],
    *,
    context: AgentContext | None = None,
    allow_text_fallback: bool = True,
) -> StructuredRun[OutputT]

Work towards goal and return a validated object.

Convenience wrapper over :func:~tempest_fastapi_sdk.agents.run_structured. The agent gains a temporary answer tool shaped like output; calling it is how the model finishes, which keeps the answer inside the tool-calling path instead of asking for JSON as prose.

Example:

>>> run = await agent.run_structured("Read the invoice.", Invoice)
>>> run.data.total_cents if run.has_data else run.parse_error

Parameters:

Name Type Description Default
goal str

What the agent should accomplish.

required
output type[OutputT]

A Pydantic model describing the answer.

required
context AgentContext | None

A pre-seeded context.

None
allow_text_fallback bool

Try to parse JSON out of a prose reply when the model ignores the tool.

True

Returns:

Type Description
StructuredRun[OutputT]

StructuredRun[OutputT]: The run record with data set, or

StructuredRun[OutputT]

parse_error explaining why it is not.

stream async

stream(goal: str, *, context: AgentContext | None = None) -> AsyncIterator[AgentStep]

Work towards goal, yielding each step as it completes.

The run is finalized (and sent to the sink) once the iterator is exhausted; abandoning it early leaves no record, which is the correct behaviour for a cancelled request.

Example:

>>> async for step in agent.stream("Draw a cat"):
...     print(step.kind, step.name)

Parameters:

Name Type Description Default
goal str

What the agent should accomplish.

required
context AgentContext | None

A pre-seeded context.

None

Yields:

Name Type Description
AgentStep AsyncIterator[AgentStep]

Each model turn and tool call, in order.

AgentArtifact

Bases: BaseSchema

A binary result a tool produced — an image, an audio clip, a file.

Artifacts are named because that is how they are referenced later: a tool that draws returns "chart.png", and the next step can ask the vision model to describe "chart.png" without anything being written to disk. The bytes travel in memory for the length of the run.

Attributes:

Name Type Description
name str

Unique name within the run.

media_type str

IANA type ("image/png", "audio/wav").

data bytes

The raw content.

description str | None

What it is, for the model and for a human reading the trace.

size_bytes property

size_bytes: int

Return how many bytes the artifact holds.

Returns:

Name Type Description
int int

The content length.

AgentArtifactSchema

Bases: BaseSchema

One artifact's metadata, without the bytes.

Attributes:

Name Type Description
name str

The artifact name, used to fetch it.

media_type str

IANA media type.

size_bytes int

How large it is.

description str | None

What it is.

AgentBudget

Bases: BaseSchema

The ceilings a run must not cross.

An agent loop without a ceiling is an unbounded bill and an unbounded outage. Steps alone are not enough: one tool call can hang, so the wall-clock limit is what actually protects a request. Both default to something small enough to be safe and large enough to be useful.

Attributes:

Name Type Description
max_steps int

Total steps — model turns plus tool calls.

max_seconds float | None

Wall-clock ceiling, or None for no time limit (only sensible for offline batch work).

max_tool_calls int | None

Total tool invocations, or None to bound them by max_steps alone.

AgentContext dataclass

AgentContext(
    goal: str = "",
    artifacts: dict[str, AgentArtifact] = dict(),
    state: dict[str, Any] = dict(),
    depth: int = 0,
    deadline: float | None = None,
    parent: str | None = None,
    agent: str | None = None,
    run_id: str | None = None,
    owner: str | None = None,
    opened_skills: set[str] = set(),
    answer: Any = None,
)

What a tool can see about the run it is part of.

Attributes:

Name Type Description
goal str

The goal the agent was given.

artifacts dict[str, AgentArtifact]

Everything produced so far, by name. A tool reads from it to consume an earlier result and never has to know which step produced it.

state dict[str, Any]

Free-form scratch space shared across the run's tools, for callers wiring their own coordination.

depth int

How many delegations deep this run is. 0 is the top-level run; a sub-agent sees 1, its own sub-agent 2. It is what stops A delegating to B delegating back to A forever.

deadline float | None

A time.monotonic() instant this run must not run past, inherited from the caller. A sub-agent may finish sooner than its own budget allows but never later than its parent's clock, because the parent is the one holding a request open.

parent str | None

Name of the agent that delegated here, for reading a nested trace.

agent str | None

Name of the agent running under this context. Set by the agent at the start of each run, so a delegation tool can tell its child who the parent is.

run_id str | None

Identifier of the run using this context. Assigned by the agent at the start of each run (a context reused for a second run gets a new one) and copied onto :attr:~tempest_fastapi_sdk.agents.AgentRun.run_id.

owner str | None

Who the run belongs to — a user or tenant id. Copied onto :attr:~tempest_fastapi_sdk.agents.AgentRun.owner and inherited by delegated runs; the HTTP router sets it from its owner dependency and filters history by it.

opened_skills set[str]

Skills loaded by the agent running under this context. Deliberately not kept in :attr:state, which a delegated child shares: a skill one agent opened must not expose its tools to the other.

answer Any

The structured answer a final-answer tool recorded, per context for the same reason.

child

child(*, goal: str, parent: str) -> AgentContext

Derive the context a delegated agent should run under.

The child gets its own artifact namespace — a sub-agent that writes report.md must not silently overwrite the parent's report.md — and its own loaded skills and answer slot, while inheriting the deadline, the owner, the shared :attr:state and one more level of depth. Whatever it produces is merged back explicitly by the caller, so the parent decides what to keep.

Parameters:

Name Type Description Default
goal str

The sub-goal being delegated.

required
parent str

The delegating agent's name.

required

Returns:

Name Type Description
AgentContext AgentContext

The child context.

claim_artifact_name

claim_artifact_name(requested: str | None, default: str) -> str

Return the name a tool should store a new artifact under.

A name the model chose is honoured only when it is free: saving over an existing artifact would silently destroy an input, so it is refused with a message the model can act on. With no chosen name the default is made unique instead, because a generated default colliding is the tool's problem, not the model's.

Parameters:

Name Type Description Default
requested str | None

The filename the model passed, if any.

required
default str

The tool's own default name.

required

Returns:

Name Type Description
str str

A free artifact name.

Raises:

Type Description
AgentToolError

When requested names an existing artifact.

require_artifact

require_artifact(name: str) -> AgentArtifact

Return an artifact by name, or fail with a message for the model.

Parameters:

Name Type Description Default
name str

The artifact the tool needs.

required

Returns:

Name Type Description
AgentArtifact AgentArtifact

The stored artifact.

Raises:

Type Description
AgentToolError

When nothing is registered under name. The message lists what is available, because the usual cause is the model inventing a filename, and a bare "not found" gives it nothing to correct with.

unique_artifact_name

unique_artifact_name(name: str) -> str

Return name, or the first free variant of it on this run.

chart.png becomes chart-1.png, then chart-2.png: the extension survives so the media type still reads right, and a name already taken — an input the caller seeded, an earlier step's output — is never reused.

Parameters:

Name Type Description Default
name str

The desired artifact name.

required

Returns:

Name Type Description
str str

A name no artifact on this context holds.

AgentRun

Bases: BaseSchema

The complete record of one agent execution.

Attributes:

Name Type Description
goal str

What the agent was asked to do.

output str

The final answer.

steps list[AgentStep]

The trace, in order.

artifacts list[AgentArtifact]

Everything the run produced.

stop_reason StopReasonEnum

Why it ended — check this before trusting output.

seconds float

Total wall-clock duration.

agent str

The agent's name, for traces holding more than one.

run_id str

Stable identifier of this run — what the HTTP router addresses a kept run by. A position in a history list is not an identifier: it shifts every time a newer run arrives.

owner str | None

Who the run belongs to, when the caller said (AgentContext.owner); None otherwise.

succeeded property

succeeded: bool

Return whether the model finished on its own terms.

Returns:

Name Type Description
bool bool

True only for :attr:StopReasonEnum.COMPLETED. A run cut

bool

off by a budget may still carry useful text, but calling it a

bool

success would hide a truncation; a run whose model answered with

bool

nothing ends :attr:StopReasonEnum.EMPTY_RESPONSE, so a successful

bool

run never ends on an empty model reply.

tool_calls property

tool_calls: list[str]

Return the tool names invoked, in order.

Returns:

Type Description
list[str]

list[str]: One entry per tool step, including failed ones and

list[str]

delegations — a delegation is invoked by tool name like any

list[str]

other call, so leaving it out would under-count what the model

list[str]

asked for.

artifact

artifact(name: str) -> AgentArtifact | None

Return one artifact by name.

Parameters:

Name Type Description Default
name str

The artifact name.

required

Returns:

Type Description
AgentArtifact | None

AgentArtifact | None: The artifact, or None when the run

AgentArtifact | None

produced no artifact under that name.

AgentRunRequestSchema

Bases: BaseSchema

Request body for POST /run and POST /run/stream.

Attributes:

Name Type Description
goal str

What the agent should accomplish.

AgentRunResponseSchema

Bases: BaseSchema

Response body for POST /run.

Mirrors :class:~tempest_fastapi_sdk.agents.AgentRun with the artifact bytes replaced by metadata, so the payload stays small and JSON-safe.

Attributes:

Name Type Description
run_id str

The run's stable id — what the artifact URL uses.

goal str

What was asked.

output str

The final answer.

stop_reason str

Why the run ended.

succeeded bool

Whether the model finished on its own terms.

seconds float

Total duration.

agent str

The agent's name.

steps list[dict[str, Any]]

The trace.

artifacts list[AgentArtifactSchema]

What it produced.

from_run classmethod

from_run(run: AgentRun) -> AgentRunResponseSchema

Build the response from a finished run.

Parameters:

Name Type Description Default
run AgentRun

The completed run.

required

Returns:

Name Type Description
AgentRunResponseSchema AgentRunResponseSchema

The JSON-safe view.

AgentRunSink

Bases: Protocol

Where a finished run goes.

Called once per run, after the answer is assembled. The agent swallows whatever this raises — a storage failure must not turn a completed run into a failed request.

The parameter is positional-only, so a plain function works whatever it names it — async def store(finished: AgentRun) -> None is an AgentRunSink. With a named parameter mypy and basedpyright rejected every sink not spelled run.

AgentStep

Bases: BaseSchema

One entry in the run's trace.

Attributes:

Name Type Description
index int

Position in the run, from 0.

kind StepKindEnum

Whether the model or a tool produced it.

name str

The tool name, or "chat" for a model turn.

arguments dict[str, Any]

Arguments the model passed to the tool.

output str

What the step produced, as the model saw it.

artifacts list[str]

Names of artifacts this step created.

error str | None

The failure, when the step failed. A failed step is still a step: the error is fed back to the model as an observation, so it can correct course.

seconds float

Wall-clock duration.

from_text bool

The model wrote this tool call as JSON in its reply text rather than in native tool_calls; see Agent(parse_text_tool_calls=...).

total_steps property

total_steps: int

Return this step plus every nested step beneath it.

Returns:

Name Type Description
int int

The step count of the whole subtree, so a caller can see

int

the real cost of a delegation instead of counting it as one.

AgentTool dataclass

AgentTool(
    name: str, description: str, parameters: dict[str, Any], handler: ToolHandler
)

One capability the model can invoke by name.

Example:

>>> async def add(arguments: dict[str, Any], _ctx: AgentContext) -> str:
...     return str(arguments["a"] + arguments["b"])
>>> tool = AgentTool(
...     name="add",
...     description="Add two numbers.",
...     parameters={
...         "type": "object",
...         "properties": {
...             "a": {"type": "number"},
...             "b": {"type": "number"},
...         },
...         "required": ["a", "b"],
...     },
...     handler=add,
... )

Attributes:

Name Type Description
name str

The function name the model calls.

description str

What it does, written for the model. This is the only thing steering tool choice, so it is worth more care than the implementation.

parameters dict[str, Any]

JSON-schema of the arguments.

handler ToolHandler

Async (arguments, context) implementation.

from_tool classmethod

from_tool(tool: Tool) -> AgentTool

Adapt a chat-pipeline :class:~tempest_fastapi_sdk.genai.Tool.

The pipeline's tools take one argument and return a string, so the adapter drops the context and wraps the result. Use it to reuse tools already written for AIChatPipeline without touching them.

Parameters:

Name Type Description Default
tool Tool

The chat-pipeline tool.

required

Returns:

Name Type Description
AgentTool AgentTool

The same capability, agent-shaped.

invoke async

invoke(arguments: dict[str, Any], context: AgentContext) -> ToolResult

Run the handler and normalize what it returns.

Parameters:

Name Type Description Default
arguments dict[str, Any]

Parsed arguments from the model.

required
context AgentContext

The run context.

required

Returns:

Name Type Description
ToolResult ToolResult

The handler's result, wrapped when it returned a

ToolResult

plain string.

Raises:

Type Description
Exception

Whatever the handler raised. The agent catches it, records the step as failed and passes the message back to the model; it is not swallowed here, so a caller invoking a tool directly still sees the real failure.

to_spec

to_spec() -> dict[str, Any]

Render the tool as an OpenAI / Ollama function specification.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The {"type": "function", "function": {...}}

dict[str, Any]

spec passed to a backend's chat_with_tools.

AgentToolError

Bases: Exception

A tool failed in a way the model should hear about.

Raising this (rather than returning text) marks the step as failed in the trace while still feeding the message back to the model as an observation, so it can try something else.

Its message is treated as written for an audience: it is fed to the model and recorded verbatim on the step, which is what the HTTP router, the SSE stream and every run sink expose. Any other exception reaches neither by default: the model reads "tool failed: <Type>" and the step keeps only the type, because an arbitrary exception can carry a DSN, a token or a URL with its API key, the trace is served to clients, and the model can repeat what it reads. Raise this one when the model should know what went wrong — and the text is safe to show.

BaseAgentRunModel

Bases: BaseModel

One agent run, persisted for audit and debugging.

Abstract — subclass it (setting __tablename__) in the project, or build a concrete class with :func:make_agent_run_model. Inherits the SDK base columns (id / is_active / created_at / updated_at); created_at is when the run was recorded.

Artifacts are not stored: they are bytes, often megabytes of them, and a run table is not a blob store. What is kept is their names and media types, so a reader knows what was produced and can look for it wherever the caller put it.

from_run classmethod

from_run(run: AgentRun) -> BaseAgentRunModel

Build a row from a finished run.

Parameters:

Name Type Description Default
run AgentRun

The completed run.

required

Returns:

Name Type Description
BaseAgentRunModel BaseAgentRunModel

The unsaved row.

BaseFactModel

Bases: BaseModel

One durable fact, as a row.

Abstract — subclass it (setting __tablename__) in the project, or build a concrete class with :func:make_fact_model. Inherits the SDK base columns; updated_at on the row and :attr:Fact.updated_at both track the last write.

A fact is identified by (subject, key). There is deliberately no unique constraint declared here — the SDK cannot know whether your table is partitioned or shared — so add one in your migration:

UNIQUE (subject, key)

Without it a race between two writes leaves two rows, and reads start returning whichever the database feels like.

to_fact

to_fact() -> Fact

Return this row as a :class:~tempest_fastapi_sdk.agents.Fact.

Returns:

Name Type Description
Fact Fact

The schema form.

ChatBackend

Bases: Protocol

The minimum an agent needs: turn a message list into a reply.

chat async

chat(messages: list[dict[str, Any]]) -> str

Return the model's reply for a chat messages list.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation, oldest first.

required

Returns:

Name Type Description
str str

The reply text.

DbAgentRunSink

DbAgentRunSink(db: AsyncDatabaseManager, model: type[BaseAgentRunModel])

An :class:AgentRunSink that writes each run to the database.

Example:

>>> model = make_agent_run_model()
>>> agent = Agent(generator, run_sink=DbAgentRunSink(db, model))

Attributes:

Name Type Description
model type[BaseAgentRunModel]

The concrete run table.

Configure the sink.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager; a short transaction is opened per run.

required
model type[BaseAgentRunModel]

The concrete run table.

required

DbFactStore

DbFactStore(db: AsyncDatabaseManager, model: type[BaseFactModel])

A :class:~tempest_fastapi_sdk.agents.FactStore backed by a table.

Example:

>>> model = make_fact_model()
>>> store = DbFactStore(db, model)
>>> agent = Agent(generator, tools=fact_tools(store, subject=user_id))

Each operation opens its own short transaction, so a fact written mid run is visible to the next step even if the run later fails — which is what you want from something the agent asserted as true.

Attributes:

Name Type Description
model type[BaseFactModel]

The concrete fact table.

Configure the store.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager.

required
model type[BaseFactModel]

The concrete fact table.

required

all async

all(*, subject: str | None = None) -> list[Fact]

Return every fact for subject, sorted by key.

Parameters:

Name Type Description Default
subject str | None

Whose facts.

None

Returns:

Type Description
list[Fact]

list[Fact]: The facts; empty when there are none.

forget async

forget(key: str, *, subject: str | None = None) -> bool

Delete one fact.

Parameters:

Name Type Description Default
key str

The fact's key.

required
subject str | None

Whose fact.

None

Returns:

Name Type Description
bool bool

Whether a row was removed.

get async

get(key: str, *, subject: str | None = None) -> Fact | None

Return one fact, or None when it was never written.

Parameters:

Name Type Description Default
key str

The fact's key.

required
subject str | None

Whose fact.

None

Returns:

Type Description
Fact | None

Fact | None: The stored fact.

put async

put(key: str, value: str, *, subject: str | None = None) -> Fact

Write one fact, replacing any previous value.

Read-then-write rather than a dialect-specific upsert, because the SDK targets both PostgreSQL and SQLite. Concurrent writers to the same key are what the UNIQUE (subject, key) constraint on your table is for — see :class:BaseFactModel.

Parameters:

Name Type Description Default
key str

The fact's key.

required
value str

What to believe.

required
subject str | None

Whose fact.

None

Returns:

Name Type Description
Fact Fact

The stored fact.

Fact

Bases: BaseSchema

One durable, editable thing the agent knows.

Attributes:

Name Type Description
key str

Stable identifier — "plan", "timezone".

value str

What is believed.

subject str | None

Who or what it is about, when the store holds facts for more than one subject (a user id, a tenant).

updated_at float

Unix timestamp of the last write.

FactStore

Bases: Protocol

Where durable facts live.

Deliberately tiny: four operations, all keyed. Anything that can do those is a valid store — a dict, a table, Redis, your own settings service. The point of facts is that they are addressable, so the interface stays addressable too.

all async

all(*, subject: str | None = None) -> list[Fact]

Return every fact for a subject, sorted by key.

forget async

forget(key: str, *, subject: str | None = None) -> bool

Delete one fact; return whether it existed.

get async

get(key: str, *, subject: str | None = None) -> Fact | None

Return one fact, or None.

put async

put(key: str, value: str, *, subject: str | None = None) -> Fact

Write one fact and return it.

InMemoryAgentRunSink

InMemoryAgentRunSink(max_runs: int = 100)

Keep the last N runs in process memory.

Bounded on purpose: runs carry their artifacts, so an unbounded list of image-generating runs is a memory leak with a slow fuse. When the buffer is full the oldest run is dropped.

Example:

>>> sink = InMemoryAgentRunSink(max_runs=50)
>>> agent = Agent(generator, run_sink=sink)
>>> await agent.run("...")
>>> sink.recent(5)

Attributes:

Name Type Description
max_runs int

How many runs to keep.

Configure the buffer.

Parameters:

Name Type Description Default
max_runs int

How many runs to keep before dropping the oldest.

100

Raises:

Type Description
ValueError

When max_runs is not positive.

clear

clear() -> None

Drop every kept run.

get

get(run_id: str) -> AgentRun | None

Return the kept run with run_id.

Parameters:

Name Type Description Default
run_id str

The run's :attr:~tempest_fastapi_sdk.agents.AgentRun.run_id.

required

Returns:

Type Description
AgentRun | None

AgentRun | None: The run, or None when it was never kept or

AgentRun | None

has already been dropped from the buffer.

recent

recent(limit: int | None = None) -> list[AgentRun]

Return the most recent runs, newest first.

Parameters:

Name Type Description Default
limit int | None

How many to return; None for all kept.

None

Returns:

Type Description
list[AgentRun]

list[AgentRun]: The runs, newest first.

InMemoryFactStore

InMemoryFactStore()

A :class:FactStore backed by a dict.

For tests, single-process services and getting started. Facts vanish on restart, which is the one thing durable facts are supposed not to do — swap it for a database-backed store before it matters.

Create an empty store.

all async

all(*, subject: str | None = None) -> list[Fact]

Return every fact for subject, sorted by key.

Parameters:

Name Type Description Default
subject str | None

Whose facts.

None

Returns:

Type Description
list[Fact]

list[Fact]: The facts; empty when there are none.

forget async

forget(key: str, *, subject: str | None = None) -> bool

Delete one fact.

Parameters:

Name Type Description Default
key str

The fact's key.

required
subject str | None

Whose fact.

None

Returns:

Name Type Description
bool bool

Whether a fact was removed.

get async

get(key: str, *, subject: str | None = None) -> Fact | None

Return one fact, or None when it was never written.

Parameters:

Name Type Description Default
key str

The fact's key.

required
subject str | None

Whose fact.

None

Returns:

Type Description
Fact | None

Fact | None: The stored fact.

put async

put(key: str, value: str, *, subject: str | None = None) -> Fact

Write one fact, replacing any previous value.

Parameters:

Name Type Description Default
key str

The fact's key.

required
value str

What to believe.

required
subject str | None

Whose fact.

None

Returns:

Name Type Description
Fact Fact

The stored fact.

LoopIteration

Bases: BaseSchema

One round of a loop.

Attributes:

Name Type Description
index int

Round number, from 0.

run AgentRun

What the agent produced this round.

accepted bool

Whether the predicate (or critic) accepted it.

critique str | None

The critic's notes, for :func:refine.

LoopResult

Bases: BaseSchema

Everything a loop produced, not just its last answer.

Attributes:

Name Type Description
goal str

The original goal.

output str

The accepted answer, or the last one attempted.

iterations list[LoopIteration]

Every round, in order.

accepted bool

Whether any round was accepted. False means the loop ran out of rounds or time — the output is the best attempt, not an approved one.

seconds float

Total wall-clock across every round.

artifacts property

artifacts: list[AgentArtifact]

Return the accepted round's artifacts, else the last round's.

Returns:

Type Description
list[AgentArtifact]

list[AgentArtifact]: The artifacts a caller should ship. Earlier rounds'

list[AgentArtifact]

artifacts are reachable through :attr:iterations, but

list[AgentArtifact]

returning all of them here would hand back rejected drafts

list[AgentArtifact]

alongside the approved one.

final_run property

final_run: AgentRun | None

Return the last round's run.

Returns:

Type Description
AgentRun | None

AgentRun | None: The final run, or None when no round ran

AgentRun | None

(which happens only when the deadline was already past).

rounds property

rounds: int

Return how many rounds ran.

Returns:

Name Type Description
int int

The iteration count.

RedisFactStore

RedisFactStore(redis: Any, *, prefix: str = 'agent:facts')

A :class:~tempest_fastapi_sdk.agents.FactStore backed by Redis.

One hash per subject, so listing a subject's facts is a single HGETALL and every operation is O(1) — the access pattern facts actually have.

Example:

>>> store = RedisFactStore(redis, prefix="agent:facts")
>>> agent = Agent(generator, tools=fact_tools(store, subject=user_id))

Attributes:

Name Type Description
prefix str

Key prefix for the hashes.

Configure the store.

Parameters:

Name Type Description Default
redis Any

A redis.asyncio.Redis client.

required
prefix str

Key prefix; the hash for a subject is "{prefix}:{subject}".

'agent:facts'

all async

all(*, subject: str | None = None) -> list[Fact]

Return every fact for subject, sorted by key.

Parameters:

Name Type Description Default
subject str | None

Whose facts.

None

Returns:

Type Description
list[Fact]

list[Fact]: The facts; empty when there are none.

forget async

forget(key: str, *, subject: str | None = None) -> bool

Delete one fact.

Parameters:

Name Type Description Default
key str

The fact's key.

required
subject str | None

Whose fact.

None

Returns:

Name Type Description
bool bool

Whether the field existed.

get async

get(key: str, *, subject: str | None = None) -> Fact | None

Return one fact, or None.

Parameters:

Name Type Description Default
key str

The fact's key.

required
subject str | None

Whose fact.

None

Returns:

Type Description
Fact | None

Fact | None: The stored fact.

put async

put(key: str, value: str, *, subject: str | None = None) -> Fact

Write one fact, replacing any previous value.

Parameters:

Name Type Description Default
key str

The fact's key.

required
value str

What to believe.

required
subject str | None

Whose fact.

None

Returns:

Name Type Description
Fact Fact

The stored fact.

Skill dataclass

Skill(
    name: str, description: str, instructions: str = "", tools: list[AgentTool] = list()
)

A named capability with instructions and tools of its own.

Attributes:

Name Type Description
name str

Short identifier the model uses to load it. Keep it lowercase and specific — it appears in every prompt.

description str

One line saying when this skill applies. This is the only text the model sees before loading, so it has to be enough to choose on: say what the skill is for, not how it works.

instructions str

The full guidance, revealed on load. Length is not a concern here — that is the point of the split.

tools list[AgentTool]

Tools that become callable once loaded. They are hidden until then, so their names and schemas cost nothing while unused.

body

body() -> str

Return what the model receives when it loads this skill.

Returns:

Name Type Description
str str

The instructions plus, when the skill carries tools, a

str

note naming them — a model that just loaded a skill needs to

str

be told the tools exist, since they were absent from the

str

prompt a moment ago.

summary

summary() -> str

Return the one-line entry shown in the system prompt.

Returns:

Name Type Description
str str

"- name: description".

StepKindEnum

Bases: BaseStrEnum

What produced one step of the trace.

  • MODEL — the language model was asked to think or answer.
  • TOOL — a tool the model chose was invoked.
  • AGENT — the work was delegated to another agent, whose own trace hangs off :attr:AgentStep.children. Distinct from TOOL because a delegation is the one step that can cost as much as a whole run, and reading a trace where the expensive step looks like a function call is how you misread where the time went.

StopReasonEnum

Bases: BaseStrEnum

Why a run ended.

Only COMPLETED means the model decided it was done. The rest are the agent cutting the run short, and a caller that treats them alike will ship truncated answers as finished ones.

  • COMPLETED — the model answered without asking for another tool.
  • MAX_STEPS — the step budget ran out first.
  • TIMEOUT — the wall-clock budget ran out first.
  • MAX_TOOL_CALLS — the tool-call budget ran out first.
  • ERROR — the model backend itself failed.
  • BLOCKED — moderation rejected the goal or the answer, or the moderator itself failed. A moderator that raises fails closed: an unchecked answer is never returned as if it had been checked.
  • EMPTY_RESPONSE — the model ended its turn with neither text nor a tool call (whitespace-only text counts as none). It is not COMPLETED because there is no answer to hand back, and it is not ERROR because the backend did not fail: the call returned, the model just said nothing. Small models do this: qwen2.5:0.5b on Ollama 0.30.11 in CPU, with a goal needing one tool, ended 58 of 200 runs like this. Retrying is the caller's choice — run_until(agent, goal, until=succeeded) re-runs it.

StructuredRun

Bases: AgentRun, Generic[OutputT]

An agent run whose answer is a validated model.

Attributes:

Name Type Description
data OutputT | None

The structured answer, or None when the run ended without producing one — a budget ran out, moderation blocked it, the model replied with nothing, the model never called the answer tool, or what it passed did not validate. Only a :attr:~tempest_fastapi_sdk.agents.StopReasonEnum.COMPLETED run carries data: an answer recorded by a run that was then blocked or cut short is dropped, not returned. Always check it; a run can be :attr:~tempest_fastapi_sdk.agents.AgentRun.succeeded and still carry None here if the fallback parse also failed.

parse_error str | None

Why the structured answer is missing, when it is.

has_data property

has_data: bool

Return whether a structured answer was produced.

Returns:

Name Type Description
bool bool

True when :attr:data is set.

SupportsImageGeneration

Bases: Protocol

What :func:~tempest_fastapi_sdk.agents.generate_image_tool draws with.

Satisfied by :class:~tempest_fastapi_sdk.genai.ImageGenerator; any other engine qualifies by rendering a prompt into :class:~tempest_fastapi_sdk.genai.GeneratedImage values. The tool passes the prompt positionally and always passes config.

generate

generate(
    prompt: str, /, *, config: ImageGenerationConfig | None = None
) -> Awaitable[Sequence[GeneratedImage]]

Render prompt into one or more images.

Parameters:

Name Type Description Default
prompt str

What to draw.

required
config ImageGenerationConfig | None

Steps and seed the model asked for; None for the engine's defaults.

None

Returns:

Type Description
Awaitable[Sequence[GeneratedImage]]

Awaitable[Sequence[GeneratedImage]]: The rendered images; the

Awaitable[Sequence[GeneratedImage]]

tool keeps the first.

SupportsMemorySearch

Bases: Protocol

What :func:recall_prompt needs from a semantic chat memory.

:class:~tempest_fastapi_sdk.genai.rag.ChatMemory (ChromaDB) and :class:~tempest_fastapi_sdk.genai.rag.PgChatMemory (pgvector) both satisfy it as shipped. The parameters are keyword-only because that is how both backends declare them; a backend of your own may widen their types (user_id: str | UUID, top_k: int | None) and add further optional parameters.

search

search(*, user_id: str, query: str, top_k: int) -> Awaitable[Sequence[MemoryHit]]

Return the past messages most relevant to query.

Parameters:

Name Type Description Default
user_id str

Whose history to search.

required
query str

The natural-language query.

required
top_k int

How many hits to return at most.

required

Returns:

Type Description
Awaitable[Sequence[MemoryHit]]

Awaitable[Sequence[MemoryHit]]: The hits, best first.

SupportsVisionGenerate

Bases: Protocol

What :func:~tempest_fastapi_sdk.agents.describe_image_tool reads with.

Satisfied by :class:~tempest_fastapi_sdk.genai.VisionTextGenerator. Each image arrives as raw bytes (a run artifact) or as the absolute path string of a file under the tool's path_root, so an engine that only takes base64 strings does not qualify.

generate

generate(prompt: str, /, *, images: list[bytes | str]) -> Awaitable[str]

Answer prompt about images.

Parameters:

Name Type Description Default
prompt str

The question about the image.

required
images list[bytes | str]

Raw image bytes or file paths.

required

Returns:

Type Description
Awaitable[str]

Awaitable[str]: The model's answer.

SupportsWebRetrieve

Bases: Protocol

What :func:~tempest_fastapi_sdk.agents.web_search_tool searches with.

Satisfied by :class:~tempest_fastapi_sdk.genai.rag.WebSearch: a query in, a prompt-ready context block out.

retrieve

retrieve(query: str, /, *, max_results: int = 5) -> Awaitable[str]

Search the web and build a context block for query.

Parameters:

Name Type Description Default
query str

What to search for.

required
max_results int

How many results to read.

5

Returns:

Type Description
Awaitable[str]

Awaitable[str]: The context block; empty when nothing matched.

ToolCallingBackend

Bases: ChatBackend, Protocol

A chat backend that can also ask for tools by name.

chat_with_tools async

chat_with_tools(
    messages: list[dict[str, Any]], tools: list[dict[str, Any]]
) -> dict[str, Any]

Return a reply that may request tool calls.

Parameters:

Name Type Description Default
messages list[dict[str, Any]]

The conversation so far, including assistant turns with tool_calls and role: tool results.

required
tools list[dict[str, Any]]

JSON-schema specs of the tools the model may call this turn.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A message dict with content and, when the

dict[str, Any]

model asked for tools, a tool_calls list. Each call's

dict[str, Any]

arguments may be a dict or a JSON string.

ToolResult

Bases: BaseSchema

What a tool hands back: text for the model, artifacts for the caller.

The split matters. A tool that generates an image cannot put PNG bytes into a prompt — the model gets text ("generated chart.png, 512x512") and the caller gets the bytes. A tool with nothing binary to return can be written as a plain str and is wrapped into one of these.

Attributes:

Name Type Description
text str

What the model reads as the tool's output.

artifacts list[AgentArtifact]

Binary results, if any.

run AgentRun | None

The delegated run, when the tool was an agent.

final bool

Whether this result ends the run. A submission tool (the structured final_answer) sets it so calling the tool is finishing, instead of the model being asked for one more turn it does not need.

of classmethod

of(value: ToolResult | str) -> ToolResult

Normalize a handler's return value into a ToolResult.

Parameters:

Name Type Description Default
value ToolResult | str

What the handler returned.

required

Returns:

Name Type Description
ToolResult ToolResult

value itself, or a text-only result wrapping it.

agent_tool

agent_tool(
    agent: Agent,
    *,
    name: str | None = None,
    description: str | None = None,
    max_depth: int = DEFAULT_MAX_DEPTH,
    share_artifacts: bool = True,
) -> AgentTool

Expose an agent as a tool another agent can call.

Example:

>>> researcher = Agent(generator, tools=[web_search_tool(search)],
...                    name="researcher")
>>> writer = Agent(
...     generator,
...     tools=[agent_tool(researcher,
...                       description="Research a topic on the web.")],
...     name="writer",
... )
>>> run = await writer.run("Write a short brief about PIX.")
>>> run.steps[1].kind, run.steps[1].children[0].name
('agent', 'chat')

The delegated run's outcome is reported back to the caller as text — including why it stopped. A parent told only the partial answer of a timed-out child would present it as a complete one.

Parameters:

Name Type Description Default
agent Agent

The specialist to delegate to.

required
name str | None

The function name the model calls; defaults to "ask_<agent name>".

None
description str | None

What this specialist is for, written for the calling model. Defaults to a generic line — worth overriding, since this text is the only basis the caller has for choosing between specialists.

None
max_depth int

Refuse to delegate beyond this nesting depth.

DEFAULT_MAX_DEPTH
share_artifacts bool

Merge the child's artifacts into the parent's run, prefixed with the child's name so two specialists writing report.md cannot clobber each other.

True

Returns:

Name Type Description
AgentTool AgentTool

The delegation tool.

describe_image_tool

describe_image_tool(
    vision_generator: SupportsVisionGenerate,
    *,
    name: str = "describe_image",
    description: str | None = None,
    path_root: str | Path | None = None,
) -> AgentTool

Build a tool that reads an image with a vision-language model.

This is the other half of :func:generate_image_tool: together they let an agent draw something and then judge what it drew.

By default the tool reads only run artifacts. Reading files from disk is opt-in: pass path_root and the model may name a path, which must resolve (symlinks included) to a regular file inside that directory.

Parameters:

Name Type Description Default
vision_generator SupportsVisionGenerate

A :class:~tempest_fastapi_sdk.genai.VisionTextGenerator, or any engine that answers about raw bytes or file paths.

required
name str

The function name the model calls.

'describe_image'
description str | None

What the tool does, written for the model. None picks a default that mentions path only when path_root is set.

None
path_root str | Path | None

Directory the path argument is confined to. None (the default) disables path.

None

Returns:

Name Type Description
AgentTool AgentTool

The image-understanding tool.

Raises:

Type Description
ValueError

When path_root is not an existing directory.

FileNotFoundError

When path_root does not exist.

discover_skills

discover_skills(directory: str | Path, *, pattern: str = '*/SKILL.md') -> list[Skill]

Load every skill file under directory, sorted by name.

Lets a deployment add a capability by dropping in a file, without a code change — the counterpart to defining skills in Python when they need tools.

Parameters:

Name Type Description Default
directory str | Path

The directory to scan.

required
pattern str

Glob for the skill files, relative to directory.

'*/SKILL.md'

Returns:

Type Description
list[Skill]

list[Skill]: The skills found, sorted by name. Empty when the

list[Skill]

directory does not exist — a missing skills directory is a valid

list[Skill]

state, not an error, so a service starts fine without one.

fact_tools

fact_tools(
    store: FactStore,
    *,
    subject: str | None = None,
    prefix: str = "fact",
    allow_forget: bool = True,
) -> list[AgentTool]

Build the durable-fact tools over store.

Facts are what you reach for when something is true and should stay true: a preference, an account id, a policy the agent must not re-ask about. Because they are keyed, you can list them, correct one, and show a user exactly what the system believes — none of which is possible with semantic recall.

Parameters:

Name Type Description Default
store FactStore

Where facts live.

required
subject str | None

Whose facts this agent reads and writes. Pass the user or tenant id in a multi-tenant service; leaving it None gives one shared namespace, which is right for a single-purpose agent and wrong for anything per-user.

None
prefix str

Prefix for the tool names.

'fact'
allow_forget bool

Include the delete tool. Turn it off when facts are curated elsewhere and the model should only read — a model that can delete what it disagrees with will.

True

Returns:

Type Description
list[AgentTool]

list[AgentTool]: Remember, recall-by-key, list, and optionally

list[AgentTool]

forget.

facts_prompt async

facts_prompt(
    store: FactStore,
    *,
    subject: str | None = None,
    heading: str = "What you already know",
) -> str

Render the stored facts as a system-prompt block.

Injecting facts beats making the model look them up: by the time it knows to ask about a timezone it has usually already answered in the wrong one. Facts are short and few, so the prompt cost is small and the payoff is that the model cannot fail to consult them.

Parameters:

Name Type Description Default
store FactStore

Where facts live.

required
subject str | None

Whose facts.

None
heading str

Heading for the block.

'What you already know'

Returns:

Name Type Description
str str

The block, or an empty string when nothing is stored — so an

str

agent with an empty store keeps exactly the prompt it had.

final_answer_tool

final_answer_tool(
    output: type[BaseModel],
    *,
    name: str = FINAL_ANSWER_TOOL,
    description: str | None = None,
) -> AgentTool

Build the tool an agent calls to deliver its structured answer.

Exposed on its own because it is occasionally useful directly — a multi-agent flow where only the last specialist reports structurally, for instance.

Parameters:

Name Type Description Default
output type[BaseModel]

The answer's shape.

required
name str

The tool name.

FINAL_ANSWER_TOOL
description str | None

Override the instruction shown to the model.

None

Returns:

Name Type Description
AgentTool AgentTool

The submission tool. Its handler validates the answer,

AgentTool

records it on the run context (AgentContext.answer) and returns

a AgentTool

class:~tempest_fastapi_sdk.agents.ToolResult with

AgentTool

final=True whose text is the answer as JSON — so the call ends

AgentTool

the run, and that JSON is the run's output the moderator checks.

AgentTool

An answer that does not validate is an ordinary tool error the model

AgentTool

reads and corrects; the run goes on.

generate_image_tool

generate_image_tool(
    image_generator: SupportsImageGeneration,
    *,
    name: str = "generate_image",
    description: str = "Draw an image from a text prompt and save it under a name. Use the returned name with other tools to inspect or send it.",
    default_steps: int | None = None,
) -> AgentTool

Build a tool that draws an image and registers it as an artifact.

Example:

>>> tool = generate_image_tool(ImageGenerator("stabilityai/sdxl-turbo"))

Parameters:

Name Type Description Default
image_generator SupportsImageGeneration

An :class:~tempest_fastapi_sdk.genai.ImageGenerator, or any engine with the same generate shape.

required
name str

The function name the model calls.

'generate_image'
description str

What the tool does, written for the model.

'Draw an image from a text prompt and save it under a name. Use the returned name with other tools to inspect or send it.'
default_steps int | None

Denoising steps when the model does not ask for a count. Set it to the value your checkpoint wants — a turbo model needs ~4 and a full one ~30, and the model choosing blind is how a render takes ten times too long.

None

Returns:

Name Type Description
AgentTool AgentTool

The image-generation tool.

load_skill_tool

load_skill_tool(skills: Sequence[Skill], *, name: str = LOAD_SKILL_TOOL) -> AgentTool

Build the tool an agent calls to open one of its skills.

Parameters:

Name Type Description Default
skills Sequence[Skill]

The available skills.

required
name str

The tool name.

LOAD_SKILL_TOOL

Returns:

Name Type Description
AgentTool AgentTool

The loader. Loading twice is a no-op that says so, so a

AgentTool

model that forgets it already read a skill does not waste a step

AgentTool

re-reading it.

loaded_skills

loaded_skills(context: AgentContext) -> set[str]

Return the names of the skills loaded during this run.

Useful in a trace or a test: it says which capabilities the agent actually reached for, which is usually the first thing you want to know when it took a wrong turn. Only the agent running under context counts: a delegated child has its own context, so a skill it loaded is not reported (or opened) here.

Parameters:

Name Type Description Default
context AgentContext

The run context.

required

Returns:

Type Description
set[str]

set[str]: The loaded skill names; empty when none were.

make_agent_router

make_agent_router(
    agent: Agent | AgentDependency,
    *,
    run_store: InMemoryAgentRunSink | None = None,
    prefix: str = "/api/agent",
    tags: list[str] | None = None,
    owner: OwnerDependency | None = None,
    docs_locale: str | None = None,
) -> APIRouter

Build a router exposing one agent.

Endpoints:

  • POST {prefix}/run — run to completion, return the record.
  • POST {prefix}/run/stream — stream each step as an SSE event; the closing done event carries {"run_id": ...}.
  • GET {prefix}/runs — recent runs (only with a run_store).
  • GET {prefix}/runs/{run_id}/artifacts/{name} — download an artifact from a kept run (only with a run_store). name may contain /, which is how a delegated agent's artifacts are named (illustrator/bike.png).

Example:

>>> store = InMemoryAgentRunSink(max_runs=50)
>>> agent = Agent(generator, tools=tools, run_sink=store)
>>> app.include_router(
...     make_agent_router(agent, run_store=store, owner=current_user_id),
... )

A prompt that depends on the caller passes a factory instead:

>>> async def agent_for(user_id: str = Depends(current_user_id)) -> Agent:
...     prompt = BASE_PROMPT + await facts_prompt(facts, subject=user_id)
...     return Agent(generator, system_prompt=prompt, run_sink=store)
>>> app.include_router(
...     make_agent_router(agent_for, run_store=store, owner=current_user_id),
... )

Parameters:

Name Type Description Default
agent Agent | AgentDependency

The agent to expose — one fixed instance, or a FastAPI dependency returning the Agent for each request. The dependency is resolved before the run starts, on every endpoint that runs the agent; the history and artifact endpoints never call it. A per-request agent must write to the same run_store for its runs to show up there.

required
run_store InMemoryAgentRunSink | None

The same sink the agent writes to. Without it the history endpoints are not mounted, because there would be nothing to read — a run's artifacts live only as long as something holds the run.

None
prefix str

URL prefix.

'/api/agent'
tags list[str] | None

OpenAPI tags. Defaults to ["agent"].

None
owner OwnerDependency | None

A FastAPI dependency returning the caller's principal id (a user or tenant id), resolved on every request like any Depends. Each run is tagged with it (AgentRun.owner), GET /runs lists only the caller's runs, and an artifact of another caller's run answers 404 exactly like a run that does not exist. Without it every caller sees every kept run — only acceptable when a single principal can reach the router at all.

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

Raises:

Type Description
TypeError

When agent is neither an Agent nor callable.

make_agent_run_model

make_agent_run_model(
    *, tablename: str = "agent_runs", class_name: str = "AgentRunModel"
) -> type[BaseAgentRunModel]

Build a concrete agent-run model bound to tablename.

For tests and lightweight scripts; production code should subclass :class:BaseAgentRunModel by hand so migrations pick it up statically.

Parameters:

Name Type Description Default
tablename str

The table name.

'agent_runs'
class_name str

The generated class name.

'AgentRunModel'

Returns:

Type Description
type[BaseAgentRunModel]

type[BaseAgentRunModel]: The concrete model class.

make_fact_model

make_fact_model(
    *, tablename: str = "agent_facts", class_name: str = "FactModel"
) -> type[BaseFactModel]

Build a concrete fact model bound to tablename.

For tests and lightweight scripts; production code should subclass :class:BaseFactModel by hand so migrations pick it up statically.

Parameters:

Name Type Description Default
tablename str

The table name.

'agent_facts'
class_name str

The generated class name.

'FactModel'

Returns:

Type Description
type[BaseFactModel]

type[BaseFactModel]: The concrete model class.

municipality_search_tool

municipality_search_tool(
    *,
    name: str = "find_brazilian_city",
    description: str = "Find the Brazilian city (municipality) a text mentions, with its state, IBGE code and coordinates. Pass the user's sentence as it was written, or just the city name; pass 'uf' when the state is known. When several cities share the name and no state is given, all are returned and you should ask the user which one.",
    limit: int = 5,
) -> AgentTool

Build a tool that finds Brazilian municipalities in a text.

Uses :func:~tempest_fastapi_sdk.geo.find_municipalities_in_text on the text, keeping only the given state when the model passes uf; when that finds nothing, falls back to :func:~tempest_fastapi_sdk.geo.search_municipalities on the whole text as a name. Offline: no model and no network.

The state filters the sentence's matches rather than replacing the sentence search: a model that passed uf="SC" together with "vou pra floripa semana que vem" got "nothing found" before, because the whole sentence was looked up as a city name.

Parameters:

Name Type Description Default
name str

The function name the model calls.

'find_brazilian_city'
description str

What the tool does, written for the model.

"Find the Brazilian city (municipality) a text mentions, with its state, IBGE code and coordinates. Pass the user's sentence as it was written, or just the city name; pass 'uf' when the state is known. When several cities share the name and no state is given, all are returned and you should ask the user which one."
limit int

Matches to return.

5

Returns:

Name Type Description
AgentTool AgentTool

The municipality tool.

name_search_tool

name_search_tool(
    index: FuzzyIndex[Any] | SemanticNameIndex[Any] | HybridNameIndex[Any],
    *,
    name: str = "search_names",
    description: str = "Find entries of a known list whose name matches what the user wrote, tolerating typos (and synonyms when the list is indexed by meaning). Returns one entry per line: name, value and why it matched.",
    limit: int = 5,
) -> AgentTool

Build a tool that searches a name index.

Parameters:

Name Type Description Default
index FuzzyIndex[Any] | SemanticNameIndex[Any] | HybridNameIndex[Any]

The index to search. FuzzyIndex searches synchronously; the two semantic indexes are awaited.

required
name str

The function name the model calls.

'search_names'
description str

What the tool does, written for the model. Say what the list holds (products, cities, categories): it is the only text steering the model to the tool.

'Find entries of a known list whose name matches what the user wrote, tolerating typos (and synonyms when the list is indexed by meaning). Returns one entry per line: name, value and why it matched.'
limit int

Matches to return when the model does not say.

5

Returns:

Name Type Description
AgentTool AgentTool

The search tool.

recall_prompt async

recall_prompt(
    memory: SupportsMemorySearch,
    query: str,
    *,
    user_id: str,
    top_k: int = 4,
    heading: str = "Possibly relevant from earlier conversations",
) -> str

Render semantic recall as a system-prompt block.

Calls memory.search(user_id=..., query=..., top_k=...) on a :class:~tempest_fastapi_sdk.genai.rag.ChatMemory, :class:~tempest_fastapi_sdk.genai.rag.PgChatMemory, or anything else shaped like :class:SupportsMemorySearch, so the agent starts a run already holding what past conversations might contribute. Recall is fuzzy: it surfaces text that looks related, which is why it belongs behind a heading that says "possibly" rather than being presented as fact.

Recall is an enhancement, so a backend outage does not stop the agent: the failure is logged at WARNING on this module's logger and the block comes back empty. A broken contract is not an outage — AttributeError and TypeError (an object without search, or one whose search takes other arguments) propagate, because swallowing them is how an agent used to run with no memory and no sign of it.

Parameters:

Name Type Description Default
memory SupportsMemorySearch

The chat memory to search.

required
query str

The goal, used as the search query.

required
user_id str

Whose history to search.

required
top_k int

How many hits to include.

4
heading str

Heading for the block.

'Possibly relevant from earlier conversations'

Returns:

Name Type Description
str str

The block, or an empty string when nothing is found or the

str

memory backend fails.

Raises:

Type Description
AttributeError

When memory has no search.

TypeError

When memory.search does not accept the arguments.

refine async

refine(
    worker: Agent,
    critic: Agent,
    goal: str,
    *,
    max_rounds: int = 3,
    max_seconds: float | None = None,
    critic_prompt: str = DEFAULT_CRITIC_PROMPT,
) -> LoopResult

Generate, critique and revise until the critic approves.

Example:

>>> result = await refine(writer, reviewer, "Write release notes.")
>>> result.accepted
True
>>> result.iterations[0].critique
'Too vague about the breaking change...'

A second agent reading the first one's output catches what the author cannot — the same reason code review works on people. The critic never rewrites: forcing it to describe the fix keeps the work (and the accountability for it) with the worker, and a critic that rewrites tends to smuggle in its own errors unreviewed.

Parameters:

Name Type Description Default
worker Agent

Produces the answer.

required
critic Agent

Judges it. Give it no tools unless it needs them to verify — a critic with a search tool will research instead of reviewing.

required
goal str

What to accomplish.

required
max_rounds int

Hard ceiling on worker attempts.

3
max_seconds float | None

Wall-clock ceiling across all rounds, inherited by both agents.

None
critic_prompt str

The critic's instruction. It must ask for the exact token APPROVED; see :data:DEFAULT_CRITIC_PROMPT.

DEFAULT_CRITIC_PROMPT

Returns:

Name Type Description
LoopResult LoopResult

Every round with its critique, and whether the critic

LoopResult

ever approved.

Raises:

Type Description
ValueError

When max_rounds is not positive.

retrieve_tool

retrieve_tool(
    retriever: SupportsRetrieve,
    *,
    name: str = "search_documents",
    description: str = "Search the indexed document corpus and return the passages that best match a question.",
    top_k: int = 5,
) -> AgentTool

Build a tool that queries a RAG corpus.

Parameters:

Name Type Description Default
retriever SupportsRetrieve

A :class:~tempest_fastapi_sdk.genai.rag.Retriever or HybridRetriever (anything with retrieve).

required
name str

The function name the model calls.

'search_documents'
description str

What the tool does, written for the model.

'Search the indexed document corpus and return the passages that best match a question.'
top_k int

Passages to return when the model does not say.

5

Returns:

Name Type Description
AgentTool AgentTool

The corpus-search tool.

run_structured async

run_structured(
    agent: Agent,
    goal: str,
    output: type[OutputT],
    *,
    context: AgentContext | None = None,
    allow_text_fallback: bool = True,
    extraction_retry: bool = True,
) -> StructuredRun[OutputT]

Run an agent and get a validated object back.

Example:

>>> class Summary(BaseSchema):
...     headline: str
...     bullets: list[str]
...
>>> run = await run_structured(agent, "Summarise the report.", Summary)
>>> run.data.headline if run.has_data else run.parse_error

The agent is given a temporary final_answer tool shaped like output; calling it is how the model finishes. That keeps the answer inside the tool-calling path the backend already handles well, instead of asking it to emit JSON as text and hoping.

Parameters:

Name Type Description Default
agent Agent

The agent to run. It is not mutated — the answer tool is added to a shallow copy that keeps everything else the agent was built with (skills, moderator, sink, metrics, budget, name), so the same agent stays usable for unstructured runs.

required
goal str

What to accomplish.

required
output type[OutputT]

The answer's shape.

required
context AgentContext | None

A pre-seeded context.

None
allow_text_fallback bool

When the model answers in prose instead of calling the tool, try to parse JSON out of that text. Set False to treat prose as a failure — stricter, and worth it when a wrong-but-parseable answer is more dangerous than no answer.

True
extraction_retry bool

When prose carries no JSON either, make one more call whose only tool is the answer tool, asking the model to restate what it just said in that shape. Small local models routinely work the task out correctly and then answer in prose regardless of instructions; this recovers the answer they already have instead of discarding the whole run. It costs one extra model call, which is the right trade whenever the alternative is losing the work.

True

Returns:

Type Description
StructuredRun[OutputT]

StructuredRun[OutputT]: The usual run record plus data. When

StructuredRun[OutputT]

data is None, parse_error says why.

run_until async

run_until(
    agent: Agent,
    goal: str,
    *,
    until: Verdict,
    max_rounds: int = 3,
    max_seconds: float | None = None,
    feedback: Callable[[AgentRun, int], str] | None = None,
    context: AgentContext | None = None,
) -> LoopResult

Run an agent repeatedly until an answer passes until.

Example:

>>> def compiles(run: AgentRun) -> bool:
...     return "def " in run.output and run.succeeded
>>> result = await run_until(agent, "Write a factorial function.",
...                          until=compiles, max_rounds=4)
>>> result.accepted, result.rounds

The predicate is where the value is: a check that actually runs the output — parses the JSON, imports the module, hits the endpoint — is a far harder gate than asking the model whether it is happy, and it is the reason this loop can improve on a single run at all.

Parameters:

Name Type Description Default
agent Agent

The agent to run.

required
goal str

What to accomplish.

required
until Verdict

Returns True when an answer is good enough. Sync or async.

required
max_rounds int

Hard ceiling on attempts. Reached without acceptance, the loop returns the last attempt with accepted=False.

3
max_seconds float | None

Wall-clock ceiling across all rounds. Each round inherits what is left, so the loop cannot overrun by one agent's budget. A deadline already on context (a loop running inside a delegation, say) is kept when it is earlier — the loop can shorten the caller's clock, never extend it.

None
feedback Callable[[AgentRun, int], str] | None

Builds the next round's goal from the rejected run. Defaults to restating the goal with the failed attempt attached — a model that cannot see its previous attempt tends to reproduce it.

None
context AgentContext | None

A pre-seeded context for round one.

None

Returns:

Name Type Description
LoopResult LoopResult

Every round, and whether any was accepted.

Raises:

Type Description
ValueError

When max_rounds is not positive.

save_artifact_tool

save_artifact_tool(
    *,
    name: str = "save_text",
    description: str = "Save a block of text as a named file the caller will receive.",
) -> AgentTool

Build a tool that turns text into a downloadable artifact.

Useful as the last step of a run whose product is a document rather than a chat reply — the text comes back as bytes the caller can write or serve, instead of being buried in the final message.

Parameters:

Name Type Description Default
name str

The function name the model calls.

'save_text'
description str

What the tool does, written for the model.

'Save a block of text as a named file the caller will receive.'

Returns:

Name Type Description
AgentTool AgentTool

The text-saving tool.

schema_of

schema_of(model: type[BaseModel]) -> dict[str, Any]

Return the JSON-schema a tool-calling model should see for model.

Pydantic emits $defs + $ref for nested models. Most local tool-calling models handle a flat object far more reliably, so nested definitions are inlined and the bookkeeping keys dropped. What is left is a plain {"type": "object", "properties": …} — the shape every backend documents.

A self-referential model (a tree, a thread of replies) cannot be inlined — the expansion never ends. Each reference is expanded at most once per branch; a reference back into a definition already being expanded stays a $ref, and only those definitions are kept under $defs. A model without recursion still comes out with no $defs at all.

Parameters:

Name Type Description Default
model type[BaseModel]

The arguments model.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The inlined schema.

scratchpad

scratchpad(context: AgentContext) -> dict[str, str]

Return the notes taken during a run.

Parameters:

Name Type Description Default
context AgentContext

The run context.

required

Returns:

Type Description
dict[str, str]

dict[str, str]: The notes, empty when none were taken.

scratchpad_tools

scratchpad_tools(*, prefix: str = 'note') -> list[AgentTool]

Build the within-run scratchpad tools.

A long run derives things — a total, a file path, a decision — several steps before it needs them. Without somewhere to park them the model either re-derives (slow, and the second answer may differ) or carries them in the conversation, where they compete with everything else for attention.

The scratchpad lives on :attr:AgentContext.state, so it disappears when the run ends. That is the feature: a note from an unrelated run turning up mid-task is worse than no notes at all.

Parameters:

Name Type Description Default
prefix str

Prefix for the tool names — note_write / note_read / note_list by default.

'note'

Returns:

Type Description
list[AgentTool]

list[AgentTool]: Three tools: write, read, list.

skill_from_markdown

skill_from_markdown(path: str | Path) -> Skill

Read a skill from a Markdown file with YAML-ish frontmatter.

The format is the one Claude Code uses, so the same file works in both places:

---
name: invoicing
description: Read and validate Brazilian invoices (NF-e).
---

Full instructions go here, as long as they need to be.

Only name and description are read from the frontmatter; the body becomes the instructions. Tools cannot come from a file — they are Python — so attach them afterwards with skill.tools.append(...).

Parameters:

Name Type Description Default
path str | Path

The Markdown file.

required

Returns:

Name Type Description
Skill Skill

The parsed skill.

Raises:

Type Description
FileNotFoundError

When the file does not exist.

ValueError

When the frontmatter is missing or has no name.

skills_prompt

skills_prompt(skills: Sequence[Skill], *, tool_name: str = LOAD_SKILL_TOOL) -> str

Return the system-prompt block advertising the available skills.

Parameters:

Name Type Description Default
skills Sequence[Skill]

The available skills.

required
tool_name str

Name of the loader tool.

LOAD_SKILL_TOOL

Returns:

Name Type Description
str str

The block to append to the agent's system prompt, or an empty

str

string when there are no skills (so an agent without skills keeps

str

exactly the prompt it had).

speak_tool

speak_tool(
    text_to_speech: SpeechSynthesizer,
    *,
    name: str = "speak",
    description: str = "Turn text into spoken audio and save it under a name. Use it when the answer should be heard rather than read.",
) -> AgentTool

Build a tool that synthesizes speech into an artifact.

Parameters:

Name Type Description Default
text_to_speech SpeechSynthesizer

A :class:~tempest_fastapi_sdk.genai.audio.TextToSpeech, or any backend with the same synthesize shape.

required
name str

The function name the model calls.

'speak'
description str

What the tool does, written for the model.

'Turn text into spoken audio and save it under a name. Use it when the answer should be heard rather than read.'

Returns:

Name Type Description
AgentTool AgentTool

The speech-synthesis tool.

structured_verdict

structured_verdict(run: StructuredRun[Any]) -> bool

Accept a structured run only when it carries validated data.

A :data:~tempest_fastapi_sdk.agents.Verdict for use with :func:~tempest_fastapi_sdk.agents.run_until, so a loop can retry until the model actually produces the shape you asked for.

Parameters:

Name Type Description Default
run StructuredRun[Any]

The run to judge.

required

Returns:

Name Type Description
bool bool

True when the run completed and produced data.

succeeded

succeeded(run: AgentRun) -> bool

Accept a run only when the model finished on its own terms.

The simplest useful :data:Verdict, and a reminder that a run stopped by a budget still carries text: without a check like this a loop would happily accept truncated work.

Parameters:

Name Type Description Default
run AgentRun

The run to judge.

required

Returns:

Name Type Description
bool bool

True when the stop reason is

bool

attr:~tempest_fastapi_sdk.agents.StopReasonEnum.COMPLETED.

team_tools

team_tools(
    agents: dict[Agent, str] | list[Agent], *, max_depth: int = DEFAULT_MAX_DEPTH
) -> list[AgentTool]

Turn several specialists into a tool set for a coordinator.

Example:

>>> coordinator = Agent(
...     generator,
...     tools=team_tools({
...         researcher: "Research facts on the web.",
...         illustrator: "Draw images from a description.",
...     }),
... )

A thin convenience over :func:agent_tool — it exists because passing the description alongside each agent is the shape that keeps the descriptions readable next to each other, and those descriptions are what the coordinator actually chooses on.

Parameters:

Name Type Description Default
agents dict[Agent, str] | list[Agent]

Either a mapping of agent to description, or a plain list using each agent's default description.

required
max_depth int

Passed through to every delegation tool.

DEFAULT_MAX_DEPTH

Returns:

Type Description
list[AgentTool]

list[AgentTool]: One delegation tool per specialist.

text_tool

text_tool(
    name: str,
    description: str,
    handler: Callable[..., Awaitable[ToolReturn]],
    *,
    parameters: dict[str, Any] | None = None,
) -> AgentTool

Build a tool that takes a single text argument.

The shape covers most hand-written tools (look something up, transform a string) and saves restating the same JSON-schema each time.

Example:

>>> tool = text_tool(
...     "shout",
...     "Return the text in upper case.",
...     lambda arguments, _ctx: _upper(arguments["text"]),
... )

Parameters:

Name Type Description Default
name str

The function name the model calls.

required
description str

What the tool does, written for the model.

required
handler Callable[..., Awaitable[ToolReturn]]

Async (arguments, context) implementation.

required
parameters dict[str, Any] | None

Override the generated schema when the tool takes more than text.

None

Returns:

Name Type Description
AgentTool AgentTool

The tool, ready to hand to an agent.

tool

tool(name: str, description: str) -> Callable[[TypedHandler], AgentTool]

Build an :class:~tempest_fastapi_sdk.agents.AgentTool from a handler.

The arguments model is read from the handler's first parameter annotation, and its JSON-schema is what the language model sees. The handler is called with a validated instance of that model.

Example:

>>> class SearchArgs(BaseSchema):
...     query: str = Field(description="What to search for.")
...     limit: int = Field(default=5, ge=1, le=50)
...
>>> @tool("search", "Search the knowledge base.")
... async def search(args: SearchArgs, ctx: AgentContext) -> str:
...     return await backend.find(args.query, limit=args.limit)

Constraints declared on the model (ge, le, max_length, enums) are enforced too, so a model asking for 500 results is corrected before your code sees it.

Parameters:

Name Type Description Default
name str

The function name the language model calls.

required
description str

What the tool does, written for the model. This is the only text steering tool choice, so it earns more care than the implementation.

required

Returns:

Type Description
Callable[[TypedHandler], AgentTool]

Callable[[TypedHandler], AgentTool]: The decorator.

Raises:

Type Description
TypeError

At decoration time, when the handler does not take (args, context) with a Pydantic-annotated first parameter.

transcribe_audio_tool

transcribe_audio_tool(
    speech_to_text: SpeechTranscriber,
    *,
    name: str = "transcribe_audio",
    description: str | None = None,
    path_root: str | Path | None = None,
) -> AgentTool

Build a tool that turns audio into text.

By default the tool reads only run artifacts. Reading files from disk is opt-in: pass path_root and the model may name a path, which must resolve (symlinks included) to a regular file inside that directory. A URL is never accepted as path.

Parameters:

Name Type Description Default
speech_to_text SpeechTranscriber

A :class:~tempest_fastapi_sdk.genai.audio.SpeechToText, an :class:~tempest_fastapi_sdk.genai.OllamaSpeech, or any backend that accepts raw bytes or a file path.

required
name str

The function name the model calls.

'transcribe_audio'
description str | None

What the tool does, written for the model. None picks a default that mentions path only when path_root is set.

None
path_root str | Path | None

Directory the path argument is confined to. None (the default) disables path.

None

Returns:

Name Type Description
AgentTool AgentTool

The transcription tool.

Raises:

Type Description
ValueError

When path_root is not an existing directory.

FileNotFoundError

When path_root does not exist.

typed_tool

typed_tool(
    name: str,
    description: str,
    model: type[ArgsT],
    handler: Callable[[ArgsT, AgentContext], Coroutine[Any, Any, ToolReturn]],
) -> AgentTool

Build a typed tool without the decorator.

Same behaviour as :func:tool, for the cases where the handler is a lambda, a bound method, or comes from somewhere the decorator cannot reach — the args model is passed explicitly instead of being read from an annotation.

Parameters:

Name Type Description Default
name str

The function name the model calls.

required
description str

What the tool does, written for the model.

required
model type[ArgsT]

The arguments model.

required
handler Callable[[ArgsT, AgentContext], Coroutine[Any, Any, ToolReturn]]

Async implementation taking the validated model.

required

Returns:

Name Type Description
AgentTool AgentTool

The tool.

web_search_tool

web_search_tool(
    web_search: SupportsWebRetrieve,
    *,
    name: str = "search_web",
    description: str = "Search the web and return the extracted text of the top results. Use it for facts that may have changed recently.",
    max_results: int = 3,
) -> AgentTool

Build a tool that searches the web through a self-hosted SearXNG.

Parameters:

Name Type Description Default
web_search SupportsWebRetrieve

A :class:~tempest_fastapi_sdk.genai.rag.WebSearch.

required
name str

The function name the model calls.

'search_web'
description str

What the tool does, written for the model.

'Search the web and return the extracted text of the top results. Use it for facts that may have changed recently.'
max_results int

Results to fetch when the model does not say.

3

Returns:

Name Type Description
AgentTool AgentTool

The web-search tool.