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.1.37) wraps a Vercel AI SDK language model. Your code keeps using generateText() and streamText(). It requires ai 6 and builds on agentid-sdk.

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

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 });

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; the full history is masked locally, not checked as one Guard input.
  • Tool calls and binary parts are not transformed.
  • Only calls through the wrapped model are protected. A parallel openai(...) call in the same route bypasses AgentID.