Ir para o conteúdo

17 · A referência da API Python

Tudo neste guia é alcançado a partir de um único pacote Python, o stalwart-agents. A sua referência completa, cada nome público com a sua assinatura, os seus argumentos, o que devolve e o que levanta, e um exemplo, é gerada a partir das próprias docstrings do pacote e servida em api.stalwart.it/sdk/reference, em inglês. Este capítulo lista cada nome público dos quatro módulos que um cliente importa, cada um apontando para a sua entrada lá, para que o guia e a referência não possam descrever dois pacotes diferentes.

$ pip install stalwart-agents                # everything: the agents, the client, the gateway, the runtime
$ pip install "stalwart-agents[anthropic]"   # with a model provider: anthropic, openai, google, mistral or ollama

A primeira linha instala tudo; a segunda, também um provedor de modelo. Python 3.10 a 3.14. A documentação do próprio pacote, página por página, fica em api.stalwart.it/pt/sdk, em português, e em inglês.

stalwart_agents: o agente

A superfície do Construtor de Bots: um agente, as suas ferramentas, o arquivo de onde ele é lido e os erros que ele levanta. Ela não nomeia nenhum framework de agentes, em lugar nenhum (Parte I).

As descrições são as próprias docstrings do pacote, em inglês, como a referência completa as mostra.

Nome Tipo O que é
TOOL_WORDS valor The words a tool may carry, as @tool(...) and agent.yaml both spell them.
Agent classe An agent: its tools, its rules, its model, and the agents it hands off to.
AgentFile classe What agent.yaml declares: the agents, their tools, the stores and the rulebook.
AgentFileError classe agent.yaml says something this release cannot read, at a line of the file.
HunterUnavailable classe The checker could not be run, so nothing was checked -- never a clean result.
LicenceRequired classe Nothing in this package answers without an activated licence: the message says how to get one.
ModelKeyMissing classe The model's provider needs a key the environment does not hold: variable names it.
ModelUnavailable classe The model named cannot be used here: the message says what to install or change.
NotVerified classe The agent has a way through its checks: findings names each, with its rule and tool.
Reply classe What the agent said, and anything that waits for the person.
RulebookNotHeld classe The agent declares a rulebook the tool check does not hold, and it could not be registered.
RunTooLong classe A run took more steps than its limit: limit and steps say how many.
StalwartError classe Something stopped a command; the message says what to change.
StateConflict classe Two steps of a run wrote to the same part of its state at once: steps names them.
StorageError classe The store the runs are kept in could not be read or written: store names it.
ThumbRefused classe A thumb that would record a false case, refused: the message says what to thumb instead.
Tool classe A tool as the file declares it: its words, its schema, the line that declared it, and what runs it.
ToolUnavailable classe An agent lists a tool with nothing to run it: declare its source (python, mcp, openapi).
VerifyResult classe What verify found: the lints, the findings, the scan's summary and whether the gate held.
Waiting classe A call that waits for a person: what it is, why, and the decisions it takes.
__version__ valor The package's version: 1.0.
export função Writes the graph agent.yaml builds, as the verifier reads it, to @p out: stalwart verify --export-only.
load função Read @p path, an agent.yaml.
render função The report stalwart verify prints.
tool função Declares a plain function a tool, with the words of agent.yaml.
verify função Check the agent @p path declares: the code checks here, then the bug hunter on the service.

stalwart_agents.client: o cliente

A API da Stalwart a partir do Python: planos e verificações de ferramentas na sua própria máquina, e os produtos de verificação como jobs (Parte II e Parte V).

As descrições são as próprias docstrings do pacote, em inglês, como a referência completa as mostra.

Nome Tipo O que é
STREAM_DEGRADED valor The event the iterator yields once when it falls back to polling.
ApiError classe An error the service answered with.
Artifact classe One artefact of a job, fetched through the client that read the job.
ArtifactRef classe An earlier job's artefact, passed as an input by its id.
AsyncArtifact classe One artefact of a job, fetched through the async client that read the job.
AsyncClient classe The Stalwart API, over HTTP, with plans and tool checks answered on your own host.
AsyncEventStream classe The async iterator await client.stream(job_id) returns.
AsyncJob classe A submitted job, for wait=False: read it, wait for it, stream it, or cancel it.
AsyncSession classe A conversation over an AsyncClient.
AuthenticationError classe 401: no key, or a key that does not verify.
BatchResult classe verify_batch: one record per row, and counters derived from the records.
CassetteMiss classe A request the cassette does not hold.
CassetteStale classe A cassette recorded under a catalogue or vocabulary digest that has since moved.
CertificateCheck classe What the checker established: verified, not_self_contained or failed, and why.
Client classe The Stalwart API, over HTTP, with plans and tool checks answered on your own host.
ComputePrompt classe The prompt the runtime built for a calculation: the text a model is given, and its parts.
ConcurrencyLimitError classe 429: every concurrent slot is taken.
ConfigurationError classe No key, a bad base URL, or a runtime asked for that is not there.
ConfirmationToken classe What a confirm answer hands back, for the call once a person approved it.
CounterexampleResult classe enumerate_counterexamples: proposals with no expect or gate, verdicts only.
DeriveExpectationsResult classe derive_expectations: the derived table.
DerivePinsResult classe derive_pins: the obligations and their pin sets; the caveat is in caveats.
DigestMismatch classe A download whose bytes do not hash to the digest the service named.
EnumeratePropertiesResult classe enumerate_properties: candidate rows with no id, expect or gate; the caveat is in caveats.
Event classe One frame: its type, its place in the job's sequence, when, and its body.
EventStream classe The sync iterator client.stream(job_id) returns.
Finding classe One hunt or graph finding: its rule, severity, location, witness, fix, replay state and OWASP entries.
ForestResult classe verify_forest: one record per property.
GuardrailResult classe verify_guardrail and generate_and_verify.
History classe The checks a session has made: entries of names and digests, and the token covering them.
HuntResult classe hunt and verify_graph: findings, the coverage statement and the assumptions the scan used.
IdempotencyKeyReusedError classe 409: an idempotency key spent on a different request.
InputTooLargeError classe 413: an input past its cap.
InvalidRequestError classe 400: a request of the wrong shape.
Job classe A submitted job, for wait=False: read it, wait for it, stream it, or cancel it.
JobFailedError classe A job that ended failed: no payload.
NotEntitledError classe 403: the key lacks a grant.
NotFoundError classe 404: no such object for this tenant.
OwaspEntry classe One OWASP entry a finding realises: its list, its edition-qualified id, title and link.
PersonalDataError classe A request bound for Stalwart's servers holds personal data, so nothing was sent.
PersonalDataFinding classe One match: its kind (a key of KINDS) and where it is.
PlanItem classe One step of a plan: a tool, ask, compute, decline or unread step, and the rule that made it.
QlsError classe Every error the SDK raises.
QuotaExceededError classe 429 on a monthly meter: waiting will not help until it resets.
RateLimitError classe 429: a per-minute or per-stream limit.
RefusedError classe 409 refused: a combination of choices that cannot answer the question asked.
ReplayResult classe replay_certificate, run by the service: replay is replayed, failed or out_of_scope.
Result classe Every job's answer: the verdict, its caveats, its artefacts and the binary's own object.
Selection classe The reader's answer to one instruction: the call, or the question to ask instead.
SelectorUnavailableError classe Nothing here can answer a plan or a tool check: no licensed local runtime, and no router_url.
ServiceError classe 5xx, after the retries.
Session classe A conversation over a Client.
StreamError classe A stream that could not be resumed, by streaming or by polling.
ToolCheck classe One tool call's answer: allow, confirm or refuse.
TurnPlan classe A turn read into steps, with the session's next context.
__version__ valor The package's version: 1.0.
async_session_from_json função A session to_json wrote, restored over an async client.
check_certificate função Runs here, offline: checks a certificate on this machine with the vendored reference checker.
session_from_json função A session to_json wrote, restored over @p client.

stalwart_agents.langchain: para equipes que já usam o LangGraph

O roteador, o nó de ferramentas protegido e o resto, como middleware do LangChain e partes do LangGraph (capítulo 27).

As descrições são as próprias docstrings do pacote, em inglês, como a referência completa as mostra.

Nome Tipo O que é
Call classe One call a stub recorded: the tool, its arguments, its place in the run, and whether a rollback made it as an undo.
Guard classe Routing, the tool check and sagas for plain Python.
RespondingChatModel classe Answers every call with what its function returns for the conversation so far.
ScriptedChatModel classe Returns its script's messages in order, whatever it is asked.
StalwartFeedbackCallback classe Remembers each run's turn and tool, and posts a thumb on it.
StalwartRouterMiddleware classe Routes the latest user turn before the model is called.
StalwartToolGuardMiddleware classe Checks every tool call before it runs, whoever chose it.
StubTools classe The catalogue's tools as stubs, with the calls they recorded and the text planted in them.
__version__ valor The package's version: 1.0.
arguments_for função Arguments for a call to @p tool: each declared property, filled by its declared kind.
current_idempotency_key função The idempotency key of the write being made, inside a tool a guarded call runs; None outside one.
fixture_value função The smallest value of a JSON schema's type: what a stub returns for it.
register_catalogue função Registers @p tools as the tenant's catalogue: a new version, linted (POST /v1/catalogues).
tool_call função A model turn that calls one tool.
tool_definitions função The tools as LangChain tool definitions: name, description, argument schema and metadata.

stalwart_agents.gateway: o gateway MCP

O gateway que verifica cada chamada de ferramenta no caminho até um servidor MCP (capítulo 37).

As descrições são as próprias docstrings do pacote, em inglês, como a referência completa as mostra.

Nome Tipo O que é
CONFIRMATION_UNAVAILABLE valor The answer a confirmation gets where nobody can be asked.
Audit classe Append-only decisions, one JSON object a line; in memory, and in a file where one is named.
Gateway classe The enforcement point.
GatewayApp classe The ASGI application in front of a Gateway.
GatewaySession classe One MCP session: the agent it is for, the check's history, the labels it carries, the undo stack.
HttpUpstream classe An MCP server over streamable HTTP, at @p url.
__version__ valor The package's version: 1.0.
gating_decision_id função The gating record's identity, computed byte for byte as the runtime's audit record computes it.