Skip to content
AgentIDDocs

Type at least two characters to search titles, headings and content.

↑ ↓ to navigate↵ to open
AgentID Docs

SDKs & API

Vercel AI SDK

Wrap any Vercel AI SDK model with withAgentId to guard, mask and log generateText and streamText calls.

agentid-vercel-sdk (version 0.2.0) wraps a Vercel AI SDK language model. Your code keeps using generateText() and streamText(). It requires ai 6 and builds on agentid-sdk.

Prerequisites

  • An AI system with the SDK / API target; see Register an AI system.
  • Its System ID and an API key (sk_live_...), kept on the server.
  • ai version 6 (a required peer dependency) and the provider package for your model. agentid-sdk is installed with the package as a dependency.
  • Outbound HTTPS from your runtime to app.getagentid.com, or to your own server on-premise (set baseUrl).

Install

npm install ai agentid-vercel-sdk @ai-sdk/openai

Use the provider package you need, for example @ai-sdk/anthropic instead of @ai-sdk/openai.

AGENTID_API_KEY=sk_live_...
AGENTID_SYSTEM_ID=00000000-0000-0000-0000-000000000000

systemId is always passed in code. apiKey is optional: when you leave it out, AGENTID_API_KEY is read from the environment. After the first call, check the result with Verify your integration.

Wrap the model

app/api/chat/route.tsTypeScript
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";
import { AgentIdSecurityError, withAgentId } from "agentid-vercel-sdk";

const secureModel = withAgentId(openai("gpt-4o"), {
  systemId: process.env.AGENTID_SYSTEM_ID!,
  apiKey: process.env.AGENTID_API_KEY!,
});

try {
  const result = await generateText({
    model: secureModel,
    messages: conversationMessages,
  });
  console.log(result.text);
} catch (error) {
  if (error instanceof AgentIdSecurityError) {
    console.error("Blocked by AgentID:", error.reason);
  } else {
    throw error;
  }
}

Streaming works the same way with streamText({ model: secureModel, ... }). Telemetry is collected from a forked stream, so the user-visible stream is not delayed. The wrapper runs in Edge and Node.js runtimes.

What the wrapper does

  1. Calls Guard before the provider request.
  2. Throws AgentIdSecurityError (with reason, verdict, clientEventId, systemId) when the prompt is blocked, before any provider cost.
  3. Masks the text parts of the full prompt history when SDK-side masking is on, and sends the protected history to the provider.
  4. Restores placeholders in the returned result or stream when restoration is on.
  5. Logs the completion with usage and finalizes the telemetry after the stream closes.
systemIdstringrequired

AI system ID.

apiKeystring

API key. Defaults to AGENTID_API_KEY.

baseUrlstring

AgentID API base URL.

piiMaskingboolean

Force local masking on; omit to follow the dashboard.

strictModeboolean

Fail-closed on Guard connectivity failures.

failureMode"fail_open" | "fail_close"

Override the system's failure mode.

clientFastFailboolean

Local preflight before Guard.

guardTimeoutMsnumber

Guard timeout in ms.

ingestTimeoutMsnumber

Ingest timeout in ms.

userId, requestIdentity, expectedLanguages, clientEventId, telemetryvarious

Default request context.

onTelemetryErrorfunction

Called when stream observation or ingest fails.

Per-request context

Override the context per call through providerOptions.agentid:

await generateText({
  model: secureModel,
  prompt: "Summarize this customer ticket.",
  providerOptions: {
    agentid: {
      userId: "customer-123",
      expectedLanguages: ["en"],
      clientEventId: "11111111-1111-4111-8111-111111111111",
    },
  },
});

Supported keys: userId, requestIdentity, expectedLanguages, clientEventId, telemetry.

Chat UIs with useChat()

For React chat UIs, mask the transcript before it leaves the browser and keep placeholder mappings local:

chat.tsxTSX
import { useAgentIdChat } from "agentid-vercel-sdk/react";

export function Chat() {
  const chat = useAgentIdChat({
    api: "/api/chat",
    uiTranscript: "masked",
    providerTranscript: "masked",
    persistenceTranscript: "masked",
  });
  // render chat.messages ...
  return null;
}

agentid-vercel-sdk/react needs @ai-sdk/react. Without the hook, pass createAgentIdChatTransport({ api, mappingStore, ... }) as the transport of useChat(); createAgentIdSessionStorageMappingStore() and createAgentIdMemoryMappingStore() keep request-local mappings. Keep the server route on withAgentId(...).

Do not render transformed_input as the user's own message; keep the raw message in local UI state if you want users to see their text.

Manual history protection

For a custom route that cannot use the wrapper yet:

import { protectMessageHistory } from "agentid-vercel-sdk";

const protectedHistory = protectMessageHistory(body.messages, { pii: true, secrets: true });
const result = streamText({ model: customModel, messages: protectedHistory.messages });

Tool calls and multi-step runs

With tools and stopWhen, the AI SDK calls the model once per step. The wrapper:

  • Logs tool-call parts as metadata.tool_calls (toolCallId, name, input; at most 32 calls, input up to 4,000 characters). A step with only tool calls is logged as one [assistant tool_call name(input)] line per call.
  • Checks the tool results of a step with Guard as tool output (origin: "tool_output", metadata.content_role: "tool_output", tool_name). A blocked result throws AgentIdSecurityError and ends the run.
  • Checks the turn's replayed assistant text and tool-call inputs with the tool results, so values that only appear there are masked too; if masking cannot be placed back, the step throws AgentIdSecurityError (tool_turn_masking_unverified) instead of sending raw values.
  • Checks the replayed user prompt again in the same step, so its masking does not depend on state from earlier steps. Restoration uses only placeholders issued for this step.
  • Gives every step its own event id. With a clientEventId, the first step uses it and later steps use ids derived from it; steps then share workflow_run_id and later steps set parent_event_id to the first step. Every step carries workflow_step_index.
  • With masking on and restoration off, tool-call input is masked before your tools run. With masking on, tool-call input returned to your code is masked like text and known placeholders are restored when restoration is on, so tools run with real values. Streamed tool-input-delta parts are passed through unchanged.

Workflow telemetry

The package re-exports the workflow helpers of agentid-sdk (AgentID, createAgentIdWorkflowTrail, createAgentIdCorrelationId, createAgentIdTelemetryContext). See Agent workflows.

Limits

  • The wrapper expects a text user prompt. Prompts with only files raise AgentIdPromptExtractionError.
  • Pre-flight Guard input is the last user message plus supported inline attachments on it, or the step's tool results; the full history is masked locally, not checked as one Guard input.
  • Binary parts and streamed tool-input-delta parts are not transformed.
  • Only calls through the wrapped model are protected. A parallel openai(...) call in the same route bypasses AgentID.