# Best practices (/docs/api/best-practices)



Both official SDKs implement everything on this page for you already. If
you're integrating in a language we don't have an SDK for, this is the
behavior to replicate so your client behaves the same way under load,
network failure, and rate limiting.

## Rate limits [#rate-limits]

Requests are rate-limited per API key. When you exceed the limit, you get
back a `429`:

```json
{ "error": "Rate limit exceeded", "code": "RATE_LIMITED" }
```

A `429` response includes a `Retry-After` header (seconds) when the server
can tell you exactly how long to wait — honor it when present, and only
fall back to your own backoff schedule when it's absent.

## Retries [#retries]

Retry `429` and `5xx` responses, and network-level failures (connection
resets, timeouts) — not other `4xx` responses, which mean the request
itself was invalid or unauthorized and won't succeed on retry.

Both SDKs retry up to **3 attempts** by default, with exponential backoff
and jitter between them. A minimal version of the same algorithm:

```ts
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    try {
      return await fn();
    } catch (err) {
      const retryable = isRetryable(err); // 429, 5xx, or network error
      if (!retryable || attempt >= maxRetries) throw err;

      const retryAfter = getRetryAfterSeconds(err); // from the response header, if present
      const backoffMs = retryAfter
        ? retryAfter * 1000
        : Math.min(1000 * 2 ** attempt, 30_000);
      const jitterMs = Math.random() * backoffMs * 0.2;

      await new Promise((resolve) => setTimeout(resolve, backoffMs + jitterMs));
    }
  }
}
```

<Callout type="warn">
  Don't retry indefinitely, and don't retry non-idempotent side effects
  blindly. A scan call is safe to retry (it has no side effects beyond
  logging), but if you've wrapped it in your own workflow with side
  effects downstream of the decision, make sure retrying the scan itself
  doesn't also re-trigger those.
</Callout>

## Timeouts [#timeouts]

Set a client-side request timeout — the API doesn't hold connections open
indefinitely, but a hung connection on your end can still block a request
thread or event-loop tick forever without one. Both SDKs default to
**30 seconds**; that's a reasonable starting point unless you're scanning
unusually large documents (see the SDKs' `timeout` option if you need to
tune this).

## Session grouping [#session-grouping]

Pass a `sessionId` on every scan belonging to the same agent turn or
conversation (the prompt, any RAG lookups, tool calls, and the model's
reply) to correlate them:

```json title="request body"
{ "text": "…", "sessionId": "sess_a1b2c3" }
```

This is what powers the [live event stream](/docs/typescript/guides/live-events)
and groups related scans in the dashboard's audit log — generate one per
conversation/turn (a UUID is fine) and thread it through every scan call
for that turn.

## Scanning tool outputs [#scanning-tool-outputs]

An agent reads what its tools return: a web page, a document, an API
response. An attacker who controls that content can plant instructions the
model then follows, without ever writing to the user's prompt. This is
indirect prompt injection, and the tool result is where it enters.

| Content                        | Scan before        | Method           |
| ------------------------------ | ------------------ | ---------------- |
| A tool result                  | The model reads it | `scanToolOutput` |
| A tool call the model proposes | The tool runs      | `scanToolCall`   |
| The model's reply              | The user sees it   | `scanResponse`   |

Scan every tool result, not only the ones from tools you consider risky: a
trusted tool that fetches third-party content returns third-party content.
Scan the call as well as the result, because an injected instruction usually
shows up as an unexpected call (a different tool, or arguments the user never
asked for). Each scan is one request, so an agent turn with several tool
steps makes several. Cache a verdict for a result you have already scanned
rather than scanning it again on every step.

The official SDKs do this for you in their agent integrations, from 0.3.0:
the TypeScript Vercel AI SDK middleware and the Python OpenAI Agents SDK
guardrails scan tool results and tool calls by default. See
[Tool scanning](/docs/typescript/integrations/vercel-ai-sdk#tool-scanning) and
[Tool guardrails](/docs/python/integrations/openai-agents-sdk#tool-guardrails).
Each has a switch to turn either scan off if you only want prompt scanning.

### Fail open or fail closed [#fail-open-or-fail-closed]

Decide what your client does when a scan fails (gateway down, network error,
timeout, a non-2xx response after your retries). The scan did not return a
verdict, so you either proceed unscanned (fail open) or refuse to proceed
(fail closed).

|                                       | Fail open                                                                                                            | Fail closed                                                                                                                    |
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| A Tawa outage                         | Your app keeps working, unscanned for the duration                                                                   | The calls that need a scan fail                                                                                                |
| An attacker who can cause scan errors | Gets unscanned traffic through                                                                                       | Gets nothing through                                                                                                           |
| Good fit                              | Chat and assistants where availability matters more than a short unscanned window, with errors logged and alerted on | Agents that can act on the world (send, pay, write, delete), regulated workloads, tool results from sources you do not control |

Whichever you choose, record every failed scan so an outage is visible, and
do not let an unscanned result silently look like a clean one. The official
SDK integrations **fail open by default** from 0.3.0 (`failClosed: true` in
TypeScript, `fail_closed=True` in Python restores the strict behaviour). A
common split is to fail closed on tool calls and tool results for agents that
take irreversible actions, and open for plain chat.

## The decision [#the-decision]

`decision.action` is `ALLOW` or `BLOCK`: act on it directly. `decision.needs_review`
(boolean) is `true` when the engine was uncertain, and `decision.engine_action`
is the engine's own label (`ALLOW`, `REVIEW`, `BLOCK`, `HARD_BLOCK`).

* Branch on `action`. Do not treat `needs_review` as a hold: the action is
  already final.
* Treat a missing `needs_review` as `false` and a missing `engine_action` as
  equal to `action`. Both are absent on a gateway that predates the
  [review flag](/docs/typescript/guides/review-flag), where `action` is the
  engine's raw label and can still be `REVIEW`.
* Accept unknown fields and unknown `action` values rather than failing on
  them.
* Retrieval scans return `aggregate.needs_review` and
  `aggregate.review_chunk_ids` next to `worst_action` and
  `flagged_chunk_ids`.
* Live events keep `action` as the engine's label and add `needs_review` and
  `enforced_action`.

## Errors [#errors]

Every error response is JSON with a human-readable `error` message and a
machine-readable `code`:

```json
{ "error": "Invalid API key", "code": "INVALID_API_KEY" }
```

| Status | Meaning                    | Retry?                    |
| ------ | -------------------------- | ------------------------- |
| `400`  | Malformed request body     | No                        |
| `401`  | Missing or invalid API key | No                        |
| `429`  | Rate limited               | Yes — honor `Retry-After` |
| `5xx`  | Server error               | Yes — backoff             |

Network-level failures (connection refused, DNS failure, timeout) never
reach this shape at all — treat anything that isn't a parseable HTTP
response as retryable the same way you'd treat a `5xx`.

## Stability [#stability]

<Callout type="warn" title="Don't build on exact score thresholds">
  We continuously retrain and recalibrate the underlying detection models.
  `risk`, `confidence`, and `score_breakdown` are useful diagnostic signal,
  but their exact values and `score_breakdown`'s shape can shift between
  model versions; the same input scoring `0.87` today isn't guaranteed to
  score `0.87` after a model update, even though its `action` will
  typically stay consistent. Threshold on `risk`. Use `confidence` to
  decide how much to trust a verdict. `action` stays the stable contract;
  exact `risk` values can shift after recalibration. Treat
  `score_breakdown` as opaque debug detail, not something to threshold
  against directly.
</Callout>

The path-based version (`/v1/...`) covers the request/response
**shape** — fields won't be removed or repurposed within a version. It does
not freeze the detection model itself; accuracy and scoring improve
continuously within a version, which is precisely why the callout above
matters.
