# SDK wrappers: scan agent output and report the AI system

These examples put Reglint between your model and your user in four common agent frameworks. Each one:

- sends the model's final text to `POST /api/monitor/scan` before anything is shown;
- reports which AI system produced it (`ai_system`: provider, model, name), so the agent's entry in the **AI register** shows the provider and model instead of "Not reported" (see [ai-system.md](ai-system.md));
- sends `agent_meta` (2026-11-12) with what the framework knows: model, provider, region, temperature, tools, a sha256 of the system prompt, SDK name and version. Fields it cannot know are `null`. The register then marks the identity **"Reported by SDK"**;
- sends the system prompt **text** as `agent_meta.system_prompt` on the first scan of the process and whenever the prompt changes (2026-11-13), so Reglint audits the prompt automatically;
- acts on the decision: `BLOCK` → don't deliver (the only hard stop), `REDACT` → deliver `redacted_output`, `ALERT_HITL` → hold for review (don't deliver yet), `ALERT` / `PASS` → deliver `redacted_output` when present (any identifier found is masked there whatever the decision; it equals the text when nothing was masked), else the text.

All four use the same request and response. They are starting points to copy, not packages to install.

| Framework | Hook used | Language |
|---|---|---|
| [LangChain](#langchain-python) | a runnable step after the model | Python |
| [LangChain — callback handler](#langchain-callback-handler) | a `BaseCallbackHandler` on the final output | Python |
| [LangChain.js](#langchainjs) | a runnable step after the model | TypeScript |
| [Vercel AI SDK](#vercel-ai-sdk) | a wrapper around `generateText` | TypeScript |
| [OpenAI Agents SDK](#openai-agents-sdk) | an output guardrail | Python |

## The call every wrapper makes

```http
POST https://www.reglint.ai/api/monitor/scan
x-api-key: rgl_...
Content-Type: application/json

{
  "agent_output": "<the model's final text>",
  "agent_name": "claims-assistant",
  "customer_id": "<your end user's id, optional>",
  "ai_system": { "provider": "OpenAI", "model": "gpt-4o-2024-08-06", "name": "Claims assistant" },
  "agent_meta": { "model": "gpt-4o-2024-08-06", "provider": "OpenAI", "provider_region": null, "temperature": 0.2,
                  "tools": [], "system_prompt_hash": "sha256:…", "sdk": "langchain", "sdk_version": "0.3.27",
                  "system_prompt": "<the system prompt text: first scan and after a change only>" }
}
```

**Automatic prompt audit (2026-11-13).** Every wrapper below always sends `system_prompt_hash` and, on the **first scan of the process and whenever the hash changes**, also the prompt text as `agent_meta.system_prompt` (at most 32,000 characters; a longer prompt is never sent, hash only). A small module-level set of already-sent hashes does this. When a scan carries the text and the agent has never been audited, or the prompt's hash differs from the last audited one, Reglint runs one prompt audit **after** the scan response: the scan itself is never delayed or changed, the audit counts as one scan against your quota, runs at most once per agent per 10 minutes and once per prompt hash ever, and the agent's **Build compliance** card shows "audited automatically on <date>". The text is never forwarded to the scan engine and never stored on the scan; the audit stores it like a manual one (purged after 90 days). The per-key switch is `auto_prompt_audit`: on for keys created after 2026-11-13 (from 2026-11-14 00:00 UTC), off for older keys until enabled (`PATCH /api/keys/:id/auto-prompt-audit` with `{ "autoPromptAudit": true }`). Scans that send the hash only behave as before: when it differs from the audited prompt, the actor card shows "prompt changed, re-audit needed".

You can still audit a prompt on demand with `POST /api/monitor/prompt-audit` and `{ "system_prompt", "agent_name" }` (see [ai-system.md](ai-system.md#prompt-audit-2026-11-12)), for example in CI before a prompt ships.

The response fields the wrappers use: `final_decision` (`BLOCK | REDACT | ALERT_HITL | ALERT | PASS`), `safe_to_deliver` (true only for `PASS` and `ALERT` — so the wrappers branch on `final_decision`, never on `safe_to_deliver` alone, or a `REDACT` would be blocked), `redacted_output` (the text with every identifier masked; present on every decision, equal to the original when nothing was masked), `scan_id`, and `ai_system` (what was recorded, with `source` and `reported`).

Keep the API key in an environment variable (`REGLINT_API_KEY`). Never put it in browser code.

## Failure policy: the key's "If Reglint can't answer in time" setting (default Block)

What happens when Reglint cannot be reached, times out, or answers with a server error (5xx) is set **per API key** by your admin in the Policy Editor: **Block the message** (the default for every key) or **Allow the message**. Every scan response for the key — a decision or an error — carries it as `on_error` (`"allow"` | `"block"`). When the API cannot be reached there is no response to read, so each wrapper keeps the last value it saw and, until it has seen one, blocks. A scan can take several seconds, so the examples use a 30-second timeout.

**Block** (default): the wrapper does not deliver the model's text and returns a fallback message. Nothing leaves unchecked, but answers stop while Reglint is down. Regulated customers should keep Block.
**Allow** (an explicit choice): the original, **unscanned** text reaches the user while Reglint is unavailable. That is availability over safety — nothing sent in that window is screened — and it is not recommended for regulated output.

Authentication and quota errors (401, 403, 429) always fail closed, whatever the setting says: they mean scans are not happening, and silently delivering would hide that. (The `REGLINT_FAIL_OPEN` environment variable used by earlier versions of these examples is gone; the key setting replaces it.)

## Identifiers: ALERT, always masked

An identifier finding (SSN, national ID, passport, driver licence, policy / insurance ID, card, account, IBAN, routing number) under a market the key has switched off, or with no article in the law of the key's countries, is `ALERT` — not `REDACT` or `BLOCK` — and carries `"identifier_no_article_cap": true`; whenever an identifier finding exists, `redacted_output` is present with the number masked, whatever the decision. That is why the wrappers deliver `redacted_output` on `PASS` / `ALERT` when it is present. Raise the class per key (REDACT / BLOCK) in Settings → API keys → Policy, in `rules_config`, or with a group key (`en`, `ar`, `ar.sa` …); your own setting is never capped. Details: /docs#identifiers.

## Getting the model name right

The AI register records a **model change** every time the reported model changes, and AI governance frameworks commonly treat a model change as a material modification. So:

- report the model id the provider **returned** (e.g. `gpt-4o-2024-08-06`), not an alias you configured (`gpt-4o`), when the framework exposes it. Every example below reads it from the response and falls back to the configured name;
- keep `provider` stable (`OpenAI`, `Anthropic`, `Azure OpenAI`, `Amazon Bedrock`, `Google`, …). Reglint folds common spellings, but a stable value is clearer;
- `name` is your name for the AI system, shown in the register.

---

## LangChain (Python)

Add the guard as the last step of the chain. It receives the model's `AIMessage`, scans its text and returns the text to deliver.

```python
import hashlib
import os
import langchain_core
import requests
from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableLambda

REGLINT_URL = "https://www.reglint.ai/api/monitor/scan"
FALLBACK = "I can't share that response. A member of our team will follow up."
# The key's on_error ("allow" | "block") from the last scan response; "block" until one is seen.
ON_ERROR = "block"
# Reglint audits the system prompt automatically: send its text on the first scan of this process and whenever
# it changes (at most 32,000 characters), its sha256 always.
_sent_prompt_hashes: set[str] = set()


def prompt_meta(text: str | None) -> dict:
    if not text:
        return {"system_prompt_hash": None}
    h = "sha256:" + hashlib.sha256(text.encode()).hexdigest()
    meta = {"system_prompt_hash": h}
    if h not in _sent_prompt_hashes and len(text) <= 32_000:
        meta["system_prompt"] = text
    _sent_prompt_hashes.add(h)
    return meta


def reglint_guard(agent_name: str, provider: str, system_name: str | None = None,
                  configured_model: str | None = None, system_prompt: str | None = None,
                  temperature: float | None = None, region: str | None = None):
    """Returns a runnable: AIMessage -> text that is safe to deliver."""

    def _guard(message: AIMessage, config=None) -> str:
        global ON_ERROR
        text = message.content if isinstance(message.content, str) else str(message.content)
        meta = message.response_metadata or {}
        # OpenAI integrations put the served model in "model_name", Anthropic in "model".
        model = meta.get("model_name") or meta.get("model") or configured_model
        customer_id = ((config or {}).get("metadata") or {}).get("customer_id")
        try:
            r = requests.post(
                REGLINT_URL,
                headers={"x-api-key": os.environ["REGLINT_API_KEY"]},
                json={
                    "agent_output": text,
                    "agent_name": agent_name,
                    "customer_id": customer_id,
                    "ai_system": {"provider": provider, "model": model, "name": system_name},
                    "agent_meta": {
                        "model": model, "provider": provider, "provider_region": region,
                        "temperature": temperature, "tools": [],
                        **prompt_meta(system_prompt),  # system_prompt_hash (+ system_prompt when new)
                        "sdk": "langchain", "sdk_version": langchain_core.__version__,
                    },
                },
                timeout=30,
            )
        except requests.RequestException:
            return text if ON_ERROR == "allow" else FALLBACK  # network error / timeout: the key's on_error
        try:
            body = r.json()
        except ValueError:
            body = None
        if isinstance(body, dict) and body.get("on_error") in ("allow", "block"):
            ON_ERROR = body["on_error"]
        if r.status_code in (401, 403, 429):
            return FALLBACK  # scans are not happening: always fail closed
        if not r.ok or not isinstance(body, dict):
            return text if ON_ERROR == "allow" else FALLBACK  # 5xx: the key's on_error
        result = body
        decision = result.get("final_decision")
        if decision == "REDACT":
            return result.get("redacted_output") or FALLBACK   # deliver the redacted text
        if decision in ("BLOCK", "ALERT_HITL"):
            return FALLBACK                                    # blocked, or held for review
        return result.get("redacted_output") or text           # PASS / ALERT: identifiers stay masked

    return RunnableLambda(_guard)


# Usage
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

SYSTEM = "You are a claims assistant."
prompt = ChatPromptTemplate.from_messages([("system", SYSTEM), ("human", "{question}")])
llm = ChatOpenAI(model="gpt-4o")
chain = prompt | llm | reglint_guard("claims-assistant", provider="OpenAI",
                                     system_name="Claims assistant", configured_model="gpt-4o",
                                     system_prompt=SYSTEM, temperature=llm.temperature)

answer = chain.invoke({"question": "What's the status of my claim?"},
                      config={"metadata": {"customer_id": "cust-1042"}})
```

For an agent built with LangGraph, put the same guard on the node that produces the final user-facing message, not on intermediate tool-calling turns.

### LangChain callback handler

If you would rather not add a step to the chain, a callback handler can scan the outermost chain's **final** output (not every intermediate step). A callback can observe the output but not replace it, so the handler records the scan and raises on `BLOCK` / `ALERT_HITL`, and `invoke_compliant()` returns the text to deliver. The same code is on the docs page (/docs#framework-recipes and the Arabic docs).

```python
# LangChain (Python): a callback handler that scans the chain's FINAL output with Reglint.
# A callback can observe the output but not replace it, so the handler records the scan and stops a BLOCK / held reply,
# and invoke_compliant() returns the text to deliver (redacted_output for REDACT and whenever an identifier was masked).
import hashlib, os
import langchain_core, requests
from langchain_core.callbacks import BaseCallbackHandler

REGLINT_ENDPOINT = "https://www.reglint.ai/api/monitor/scan"
FALLBACK = "I can't share that response. A member of our team will follow up."
HELD = "Your request is being reviewed. We'll follow up."
# The key's on_error ("allow" | "block") from the last scan response; "block" until one is seen.
ON_ERROR = "block"

class ReglintStopped(Exception):
    def __init__(self, scan: dict):
        super().__init__(scan.get("final_decision"))
        self.scan = scan

class ReglintCallbackHandler(BaseCallbackHandler):
    raise_error = True  # let ReglintStopped reach the caller

    def __init__(self, agent_name: str, provider: str, model: str, system_prompt: str | None = None):
        self.agent_name, self.provider, self.model, self.system_prompt = agent_name, provider, model, system_prompt
        self.scan: dict | None = None
        self._sent: set[str] = set()

    def _agent_meta(self) -> dict:
        meta = {"model": self.model, "provider": self.provider, "sdk": "langchain", "sdk_version": langchain_core.__version__}
        if self.system_prompt:
            h = "sha256:" + hashlib.sha256(self.system_prompt.encode()).hexdigest()
            meta["system_prompt_hash"] = h
            if h not in self._sent and len(self.system_prompt) <= 32_000:
                meta["system_prompt"] = self.system_prompt  # first scan / after a change: Reglint audits it
                self._sent.add(h)
        return meta

    def on_chain_end(self, outputs, *, run_id, parent_run_id=None, **kwargs):
        global ON_ERROR
        if parent_run_id is not None:  # only the outermost chain's final answer, not every step
            return
        text = outputs if isinstance(outputs, str) else getattr(outputs, "content", None) or str(outputs)
        unavailable = {"final_decision": "UNAVAILABLE"}
        try:
            r = requests.post(REGLINT_ENDPOINT, timeout=30,
                              headers={"x-api-key": os.environ["REGLINT_API_KEY"]},
                              json={"agent_output": text, "agent_name": self.agent_name, "actor_type": "agent",
                                    "ai_system": {"provider": self.provider, "model": self.model},
                                    "agent_meta": self._agent_meta()})
        except requests.RequestException:  # network error / timeout: the key's on_error
            if ON_ERROR == "allow":
                return                      # deliver unscanned (an explicit choice on the key)
            raise ReglintStopped(unavailable)
        try:
            body = r.json()
        except ValueError:
            body = None
        if isinstance(body, dict) and body.get("on_error") in ("allow", "block"):
            ON_ERROR = body["on_error"]
        if r.status_code in (401, 403, 429):
            raise ReglintStopped(unavailable)  # scans are not happening: always fail closed
        if not r.ok or not isinstance(body, dict):  # 5xx: the key's on_error
            if ON_ERROR == "allow":
                return
            raise ReglintStopped(unavailable)
        self.scan = body
        if body["final_decision"] in ("BLOCK", "ALERT_HITL"):
            raise ReglintStopped(body)

def invoke_compliant(chain, inputs: dict, handler: ReglintCallbackHandler) -> str:
    handler.scan = None
    try:
        output = chain.invoke(inputs, config={"callbacks": [handler]})
    except ReglintStopped as stop:
        return HELD if stop.scan.get("final_decision") == "ALERT_HITL" else FALLBACK  # BLOCK / unavailable
    text = output if isinstance(output, str) else getattr(output, "content", str(output))
    scan = handler.scan or {}  # empty: Reglint unavailable and the key's on_error is "allow"
    if scan.get("final_decision") == "REDACT":
        return scan.get("redacted_output") or FALLBACK
    return scan.get("redacted_output") or text  # PASS / ALERT: any identifier stays masked

# Usage
# handler = ReglintCallbackHandler("claims-assistant", provider="OpenAI", model="gpt-4o-2024-08-06", system_prompt=SYSTEM)
# answer = invoke_compliant(prompt | llm | StrOutputParser(), {"question": q}, handler)
```

## LangChain.js

```ts
import { createHash } from "node:crypto";
import { RunnableLambda } from "@langchain/core/runnables";
import type { AIMessage } from "@langchain/core/messages";

const REGLINT_URL = "https://www.reglint.ai/api/monitor/scan";
const FALLBACK = "I can't share that response. A member of our team will follow up.";
// The key's on_error ("allow" | "block") from the last scan response; "block" until one is seen.
let onError: "allow" | "block" = "block";
// Reglint audits the system prompt automatically: send its text on the first scan of this process and whenever it
// changes (at most 32,000 characters), its sha256 always.
const sentPromptHashes = new Set<string>();
function promptMeta(text: string | null | undefined): { system_prompt_hash: string | null; system_prompt?: string } {
  if (!text) return { system_prompt_hash: null };
  const hash = "sha256:" + createHash("sha256").update(text).digest("hex");
  const first = !sentPromptHashes.has(hash);
  sentPromptHashes.add(hash);
  return first && text.length <= 32_000 ? { system_prompt_hash: hash, system_prompt: text } : { system_prompt_hash: hash };
}

export function reglintGuard(opts: {
  agentName: string;
  provider: string;
  systemName?: string;
  configuredModel?: string;
  systemPrompt?: string;
  temperature?: number;
  region?: string;
}) {
  return RunnableLambda.from(async (message: AIMessage, config): Promise<string> => {
    const text = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
    const meta = (message.response_metadata ?? {}) as Record<string, unknown>;
    // OpenAI integrations put the served model in "model_name", Anthropic in "model".
    const model = (meta.model_name as string) ?? (meta.model as string) ?? opts.configuredModel;
    const customerId = (config?.metadata?.customer_id as string | undefined) ?? undefined;

    let res: Response;
    try {
      res = await fetch(REGLINT_URL, {
        method: "POST",
        headers: { "x-api-key": process.env.REGLINT_API_KEY!, "Content-Type": "application/json" },
        body: JSON.stringify({
          agent_output: text,
          agent_name: opts.agentName,
          customer_id: customerId,
          ai_system: { provider: opts.provider, model, name: opts.systemName },
          agent_meta: {
            model, provider: opts.provider, provider_region: opts.region ?? null, temperature: opts.temperature ?? null,
            tools: [], ...promptMeta(opts.systemPrompt), // system_prompt_hash (+ system_prompt when new)
            sdk: "langchain-js", sdk_version: null,
          },
        }),
        signal: AbortSignal.timeout(30_000),
      });
    } catch {
      return onError === "allow" ? text : FALLBACK; // network error / timeout: the key's on_error
    }
    const body = await res.json().catch(() => null);
    if (body?.on_error === "allow" || body?.on_error === "block") onError = body.on_error;
    if ([401, 403, 429].includes(res.status)) return FALLBACK; // always fail closed
    if (!res.ok || !body) return onError === "allow" ? text : FALLBACK; // 5xx: the key's on_error
    const result = body;
    if (result.final_decision === "REDACT") return result.redacted_output ?? FALLBACK; // deliver the redacted text
    if (result.final_decision === "BLOCK" || result.final_decision === "ALERT_HITL") return FALLBACK; // blocked / held
    return result.redacted_output ?? text; // PASS / ALERT: identifiers stay masked
  });
}

// Usage
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";

const SYSTEM = "You are a claims assistant.";
const prompt = ChatPromptTemplate.fromMessages([["system", SYSTEM], ["human", "{question}"]]);
const chain = prompt
  .pipe(new ChatOpenAI({ model: "gpt-4o" }))
  .pipe(reglintGuard({ agentName: "claims-assistant", provider: "OpenAI", systemName: "Claims assistant",
                       configuredModel: "gpt-4o", systemPrompt: SYSTEM }));

const answer = await chain.invoke(
  { question: "What's the status of my claim?" },
  { metadata: { customer_id: "cust-1042" } },
);
```

## Vercel AI SDK

Wrap `generateText`: generate, then scan, then return the text to deliver. `response.modelId` is the model id the provider returned.

```ts
import { createHash } from "node:crypto";
import { generateText } from "ai";

const REGLINT_URL = "https://www.reglint.ai/api/monitor/scan";
const FALLBACK = "I can't share that response. A member of our team will follow up.";
// The key's on_error ("allow" | "block") from the last scan response; "block" until one is seen.
let onError: "allow" | "block" = "block";
// Reglint audits the system prompt automatically: send its text on the first scan of this process and whenever it
// changes (at most 32,000 characters), its sha256 always.
const sentPromptHashes = new Set<string>();
function promptMeta(text: string | null | undefined): { system_prompt_hash: string | null; system_prompt?: string } {
  if (!text) return { system_prompt_hash: null };
  const hash = "sha256:" + createHash("sha256").update(text).digest("hex");
  const first = !sentPromptHashes.has(hash);
  sentPromptHashes.add(hash);
  return first && text.length <= 32_000 ? { system_prompt_hash: hash, system_prompt: text } : { system_prompt_hash: hash };
}

type GenerateArgs = Parameters<typeof generateText>[0];

export async function guardedGenerateText(
  args: GenerateArgs,
  opts: { agentName: string; provider: string; systemName?: string; customerId?: string },
): Promise<{ text: string; decision: string; scanId: string | null }> {
  const { text, response } = await generateText(args);
  const model = response.modelId ?? (typeof args.model === "string" ? args.model : args.model.modelId);
  const system = typeof args.system === "string" ? args.system : null;

  let res: Response;
  try {
    res = await fetch(REGLINT_URL, {
      method: "POST",
      headers: { "x-api-key": process.env.REGLINT_API_KEY!, "Content-Type": "application/json" },
      body: JSON.stringify({
        agent_output: text,
        agent_name: opts.agentName,
        customer_id: opts.customerId,
        ai_system: { provider: opts.provider, model, name: opts.systemName },
        agent_meta: {
          model, provider: opts.provider, provider_region: null, temperature: args.temperature ?? null,
          tools: Object.keys(args.tools ?? {}),
          ...promptMeta(system), // system_prompt_hash (+ system_prompt when new)
          sdk: "vercel-ai", sdk_version: null,
        },
      }),
      signal: AbortSignal.timeout(30_000),
    });
  } catch {
    // network error / timeout: the key's on_error (the last value seen)
    return { text: onError === "allow" ? text : FALLBACK, decision: "UNAVAILABLE", scanId: null };
  }
  const body = await res.json().catch(() => null);
  if (body?.on_error === "allow" || body?.on_error === "block") onError = body.on_error;
  if ([401, 403, 429].includes(res.status)) return { text: FALLBACK, decision: "UNAVAILABLE", scanId: null };
  if (!res.ok || !body) {
    return { text: onError === "allow" ? text : FALLBACK, decision: "UNAVAILABLE", scanId: null }; // 5xx
  }
  const result = body;
  return {
    // REDACT → the redacted text; BLOCK / ALERT_HITL (held) → fallback; PASS / ALERT → redacted_output when present.
    text: result.final_decision === "REDACT" ? (result.redacted_output ?? FALLBACK)
      : result.final_decision === "BLOCK" || result.final_decision === "ALERT_HITL" ? FALLBACK : (result.redacted_output ?? text),
    decision: result.final_decision,
    scanId: result.scan_id ?? null,
  };
}

// Usage (e.g. in a route handler)
import { openai } from "@ai-sdk/openai";

const { text } = await guardedGenerateText(
  { model: openai("gpt-4o"), system: "You are a claims assistant.", prompt: "What's the status of my claim?" },
  { agentName: "claims-assistant", provider: "OpenAI", systemName: "Claims assistant", customerId: "cust-1042" },
);
```

**Streaming (`streamText`).** Reglint scans complete text, so a streamed answer must be collected before it is shown: stream into a buffer, scan the full text when the stream ends, then send the guarded text to the user. Streaming tokens straight to the user and scanning afterwards would show the user text that a `BLOCK` was meant to stop.

## OpenAI Agents SDK

**Limitation.** An Agents SDK output guardrail can only trip (stop the run) or let the answer through: it cannot rewrite the answer and has no "hold for review". So by itself it expresses `BLOCK`, but not `REDACT` or `HITL`. The pattern below covers all five decisions — the guardrail trips on `BLOCK` and `ALERT_HITL` and hands the scan back as `output_info`; after the run your code delivers `redacted_output`; a held reply is sent only after a reviewer approves it in the Review Queue.

Use an **output guardrail**. Guardrails can stop an answer but cannot rewrite it, so the guardrail trips on `BLOCK` and passes the scan result back through `output_info`; your code then delivers `redacted_output` for `REDACT`.

```python
import hashlib
import os
from importlib.metadata import version
import httpx
from agents import (Agent, GuardrailFunctionOutput, OutputGuardrailTripwireTriggered,
                    RunContextWrapper, Runner, output_guardrail)

REGLINT_URL = "https://www.reglint.ai/api/monitor/scan"
FALLBACK = "I can't share that response. A member of our team will follow up."
# The key's on_error ("allow" | "block") from the last scan response; "block" until one is seen.
ON_ERROR = "block"
# Reglint audits the system prompt automatically: send its text on the first scan of this process and whenever
# it changes (at most 32,000 characters), its sha256 always.
_sent_prompt_hashes: set[str] = set()


def prompt_meta(text: str | None) -> dict:
    if not text:
        return {"system_prompt_hash": None}
    h = "sha256:" + hashlib.sha256(text.encode()).hexdigest()
    meta = {"system_prompt_hash": h}
    if h not in _sent_prompt_hashes and len(text) <= 32_000:
        meta["system_prompt"] = text
    _sent_prompt_hashes.add(h)
    return meta


@output_guardrail
async def reglint_guardrail(ctx: RunContextWrapper, agent: Agent, output: str) -> GuardrailFunctionOutput:
    global ON_ERROR
    model = agent.model if isinstance(agent.model, str) else None
    try:
        async with httpx.AsyncClient(timeout=30) as client:
            r = await client.post(
                REGLINT_URL,
                headers={"x-api-key": os.environ["REGLINT_API_KEY"]},
                json={
                    "agent_output": str(output),
                    "agent_name": agent.name,
                    "ai_system": {"provider": "OpenAI", "model": model, "name": agent.name},
                    "agent_meta": {
                        "model": model, "provider": "OpenAI", "provider_region": None,
                        "temperature": agent.model_settings.temperature,
                        "tools": [t.name for t in agent.tools],
                        # system_prompt_hash (+ system_prompt when new)
                        **prompt_meta(agent.instructions if isinstance(agent.instructions, str) else None),
                        "sdk": "openai-agents", "sdk_version": version("openai-agents"),
                    },
                },
            )
    except httpx.HTTPError:  # network error / timeout: the key's on_error (the last value seen)
        return GuardrailFunctionOutput(output_info={"unavailable": True}, tripwire_triggered=ON_ERROR != "allow")
    try:
        body = r.json()
    except ValueError:
        body = None
    if isinstance(body, dict) and body.get("on_error") in ("allow", "block"):
        ON_ERROR = body["on_error"]
    if r.status_code in (401, 403, 429):
        return GuardrailFunctionOutput(output_info={"unavailable": True}, tripwire_triggered=True)
    if not r.is_success or not isinstance(body, dict):  # 5xx: the key's on_error
        return GuardrailFunctionOutput(output_info={"unavailable": True}, tripwire_triggered=ON_ERROR != "allow")
    result = body
    # Trip on BLOCK and on a held item (ALERT_HITL); REDACT passes through and is delivered as redacted_output below.
    return GuardrailFunctionOutput(output_info=result, tripwire_triggered=result.get("final_decision") in ("BLOCK", "ALERT_HITL"))


agent = Agent(
    name="Claims assistant",
    instructions="You are a claims assistant.",
    model="gpt-4o",
    output_guardrails=[reglint_guardrail],
)


async def answer(question: str) -> str:
    try:
        run = await Runner.run(agent, question)
    except OutputGuardrailTripwireTriggered:
        return FALLBACK  # BLOCK, held for review (ALERT_HITL), or Reglint unavailable with on_error = block
    text = str(run.final_output)
    for g in run.output_guardrail_results:
        info = g.output.output_info or {}
        if info.get("redacted_output"):  # REDACT, and PASS / ALERT with an identifier masked
            return info["redacted_output"]
    return text
```

`Agent.model` is the name you configured; the Agents SDK does not expose the served model id to an output guardrail. If you pin a dated model (`gpt-4o-2024-08-06`), the register shows exactly that.

---

## Checking it worked

1. Run one request through your wrapped agent.
2. Open **Actors** in the dashboard. The agent's row shows the provider logo or name and the model, not "Not reported".
3. Open the agent's register entry. **Identity source** reads `sdk`, with the badge **Reported by SDK** and the SDK name and version.
4. Change the model and run again. The model-change timeline shows the change, marked as a material modification.
5. Open the agent's **Build compliance** card. A minute after the first scan (with the key's `auto_prompt_audit` on) it shows the prompt audit and "audited automatically on <date>". Change the system prompt, restart, scan again: a new audit follows (at most one per agent per 10 minutes).
