Generated from promptguard-sdk 2.4.1 as published on npm (sha256
f33873379c9b…). Signatures, parameters and descriptions are read from the package itself, so this page changes only when the pinned SDK version does. For a walkthrough, start with the guide.promptguard-sdk
PromptGuard Node.js SDK
Drop-in security for AI applications.
Option 1 - Auto-instrumentation (recommended)
@example
detectedUnpatched
Function · import { detectedUnpatched } from "promptguard-sdk" or import { detectedUnpatched } from "promptguard-sdk/auto"
getAppliedPatches
Function · import { getAppliedPatches } from "promptguard-sdk" or import { getAppliedPatches } from "promptguard-sdk/auto"
init (e.g. ["openai", "anthropic"]).
Because patches attach to the CJS-resolved provider modules, an ESM app can
call init() successfully and still be unprotected (see the dual-package
hazard note on init). Assert on this at startup when you rely on
enforce mode:
InitOptions
Interface · import { InitOptions } from "promptguard-sdk" or import { InitOptions } from "promptguard-sdk/auto"
apiKey?: stringbaseUrl?: stringmode?: "enforce" | "monitor"—"enforce"blocks violations,"monitor"logs only (default:"enforce").failOpen?: boolean— Allow LLM calls when Guard API is unreachable (default:true).scanResponses?: boolean— Also scan LLM responses (default:false).timeout?: number— HTTP timeout in ms for Guard API calls (default:10000).maxRetries?: number— Retry attempts for transient Guard API failures (network errors and 429/5xx responses) before thefailOpenpolicy governs. Default:3. Retries never change the eventual decision — seeGuardClientConfig.retryDelay?: number— Base delay in ms between Guard API retries (exponential backoff). Default:1000.logLevel?: LogLevel— SDK log verbosity (default:"warn"). Set to"silent"to suppress all SDK logging, or"info"/"debug"for the init banner and more detail. NOTE: this sets the process-global SDK log level (shared with the framework integrations); the most recent setter wins.silent?: boolean— Convenience shorthand forlogLevel: "silent".
init
Function · import { init } from "promptguard-sdk" or import { init } from "promptguard-sdk/auto"
openai, @anthropic-ai/sdk,
@google/generative-ai, cohere-ai, @aws-sdk/client-bedrock-runtime)
so every LLM call they make is scanned by the Guard API.
Limitation — ESM apps (dual-package hazard): patches are applied to the
module instances resolved via CommonJS require(). If your application runs
as native ESM ("type": "module" / .mjs) and the provider ships separate
ESM builds, your imported module instances can be different objects from
the patched CJS ones — in that case auto-instrumentation silently protects
nothing. Use getAppliedPatches as a runtime canary to verify the
providers you use were actually patched, and prefer the ESM-safe
alternatives: the LangChain callback handler
(promptguard-sdk/integrations/langchain), the Vercel AI SDK middleware
(promptguard-sdk/integrations/vercel-ai), or explicit GuardClient.scan()
calls. See README “Limitations: ESM apps”.
When zero patches could be applied, a warning is logged so a
misconfiguration never fails silently.
instrumentationReport
Function · import { instrumentationReport } from "promptguard-sdk" or import { instrumentationReport } from "promptguard-sdk/auto"
shutdown
Function · import { shutdown } from "promptguard-sdk" or import { shutdown } from "promptguard-sdk/auto"
ChatCompletionRequest
Interface · import { ChatCompletionRequest } from "promptguard-sdk"
model: stringmessages: Message[]temperature?: numbermaxTokens?: number— Maximum tokens to generate. Serialized to the wire asmax_tokens.[key: string]: unknown— OpenAI-compatible escape hatch: any additional keys (e.g.top_p,frequency_penalty,stop,tools) are forwarded verbatim to the proxy. Because these keys are not type-checked, a misspelled parameter is silently passed through rather than flagged at compile time — double-check the spelling of options not listed above. (stream: trueis the one key rejected: the client parses a single JSON response body, so it throws at runtime instead of forwarding.)
ChatCompletionResponse
Interface · import { ChatCompletionResponse } from "promptguard-sdk"
id: stringobject: stringcreated: numbermodel: stringchoices: Array<{ index: number; message: Message; finish_reason: string; }>usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }
Message
Interface · import { Message } from "promptguard-sdk"
role: "system" | "user" | "assistant" | "tool" | "function"content: string
PromptGuardConfig
Interface · import { PromptGuardConfig } from "promptguard-sdk"
apiKey: stringbaseUrl?: string— API base URL. Defaults to the public PromptGuard proxy (https://api.promptguard.co/api/v1/proxy) orPROMPTGUARD_BASE_URL. The/proxysuffix is appended automatically when missing.timeout?: number— HTTP timeout in milliseconds for each request attempt. Default:30000.maxRetries?: number— Number of retry attempts for transient failures (network errors and 429/5xx responses). Default:3. Set to0for strict at-most-once semantics. Negative values are clamped to0.retryDelay?: number— Base delay in ms between retries (exponential backoff). Default:1000.
RedactResult
Interface · import { RedactResult } from "promptguard-sdk"
original: stringredacted: stringpiiFound: string[]
RedTeamSummary
Interface · import { RedTeamSummary } from "promptguard-sdk"
totalTests: number— Normalized from the wire fieldtotal_tests.blocked: numberallowed: numberblockRate: number— Normalized from the wire fieldblock_rate.results: RedTeamTestResult[]
RedTeamTestResult
Interface · import { RedTeamTestResult } from "promptguard-sdk"
testName: string— Normalized from the wire fieldtest_name.prompt: stringdecision: stringreason: stringthreatType?: string— Normalized from the wire fieldthreat_type.confidence: numberblocked: booleandetails: Record<string, unknown>
SecurityScanResult
Interface · import { SecurityScanResult } from "promptguard-sdk"
blocked: booleandecision: "allow" | "block" | "redact"reason?: stringthreatType?: stringconfidence?: number
ToolValidationResult
Interface · import { ToolValidationResult } from "promptguard-sdk"
allowed: booleanriskScore: number— Normalized from the wire fieldrisk_score.riskLevel: string— Normalized from the wire fieldrisk_level.reason: stringwarnings: string[]blockedReasons: string[]— Normalized from the wire fieldblocked_reasons.
PromptGuard
Class · import { PromptGuard } from "promptguard-sdk"
chat: Chatsecurity: Securityagent: Agentredteam: RedTeamget baseUrl(): string— The base URL requests actually go to, after normalization.
new PromptGuard(...)
PromptGuard.request
PromptGuard.chat
Reached as PromptGuard.chat on an instance (a Chat; not constructed directly).
completions: ChatCompletions
PromptGuard.chat.completions
Reached as PromptGuard.chat.completions on an instance (a ChatCompletions; not constructed directly).
PromptGuard.chat.completions.create
PromptGuard.security
Reached as PromptGuard.security on an instance (a Security; not constructed directly).
PromptGuard.security.scan
PromptGuard.security.redact
PromptGuard.agent
Reached as PromptGuard.agent on an instance (a Agent; not constructed directly).
PromptGuard.agent.validateTool
PromptGuard.agent.stats
PromptGuard.redteam
Reached as PromptGuard.redteam on an instance (a RedTeam; not constructed directly).
/internal/redteam, which requires
platform-admin auth — so all of them returned 401 for every customer who
called them. The customer-facing plane is /api/v1/security-testing,
reachable with an ordinary API key carrying the proxy scope.
runAutonomous and intelligenceStats were removed rather than repointed:
the autonomous mutation loop is a cost-attack surface and stays back-office,
and /intelligence/stats exists on no plane at all (a 404 even for admins).
PromptGuard.redteam.listTests
PromptGuard.redteam.runTest
PromptGuard.redteam.runAll
PromptGuard.redteam.runCustom
PromptGuardError
Class · import { PromptGuardError } from "promptguard-sdk"
code: string— Machine-readable error code. Server-forwarded codes pass through verbatim (their own casing). Codes minted by the SDK itself use lower_snake_case:missing_api_key,streaming_not_supported,invalid_response_body,max_retries, and the fallbackunknown.statusCode: numbererrorType?: stringupgradeUrl?: stringcurrentPlan?: stringrequestsUsed?: numberrequestsLimit?: number
new PromptGuardError(...)
GuardApiError
Class · import { GuardApiError } from "promptguard-sdk" or import { GuardApiError } from "promptguard-sdk/guard"
readonly statusCode?: number
new GuardApiError(...)
GuardApiError.safeDescription
.message of a GuardApiError may embed the raw Guard API
response body (see GuardClient.scan), which can echo prompt
content. Loggers must use this instead of .message so they never
leak prompt content, response bodies, or the API key.
GuardClient
Class · import { GuardClient } from "promptguard-sdk" or import { GuardClient } from "promptguard-sdk/guard"
new GuardClient(...)
GuardClient.scan
GuardApiError on network/API errors so the caller
can decide whether to fail open or closed.
Two call styles are supported:
GuardClient.scan
GuardApiError on network/API errors so the caller
can decide whether to fail open or closed.
Two call styles are supported:
GuardClientConfig
Interface · import { GuardClientConfig } from "promptguard-sdk" or import { GuardClientConfig } from "promptguard-sdk/guard"
apiKey: stringbaseUrl?: stringtimeout?: numbermaxRetries?: number— Number of retry attempts for transient Guard API failures (network errors and 429/5xx responses). Default:3. Set to0for strict at-most-once semantics. Retries never change the eventual decision — after they are exhausted aGuardApiErroris thrown so the caller’sfailOpenpolicy governs, exactly as with no retries.retryDelay?: number— Base delay in ms between retries (exponential backoff). Default:1000.
GuardContext
Interface · import { GuardContext } from "promptguard-sdk" or import { GuardContext } from "promptguard-sdk/guard"
framework?: stringchainName?: string— Chain/pipeline name (camelCase, preferred).agentId?: string— Agent identifier (camelCase, preferred).sessionId?: string— Session identifier (camelCase, preferred).toolCalls?: Array<Record<string, unknown>>— Tool-call records for this turn (camelCase, preferred).metadata?: Record<string, unknown>chain_name?: string— @deprecated snake_case alias forchainName; kept for back-compat.agent_id?: string— @deprecated snake_case alias foragentId; kept for back-compat.session_id?: string— @deprecated snake_case alias forsessionId; kept for back-compat.tool_calls?: Array<Record<string, unknown>>— @deprecated snake_case alias fortoolCalls; kept for back-compat.
GuardContextWire
Interface · import { GuardContextWire } from "promptguard-sdk" or import { GuardContextWire } from "promptguard-sdk/guard"
framework?: stringchain_name?: stringagent_id?: stringsession_id?: stringtool_calls?: Array<Record<string, unknown>>metadata?: Record<string, unknown>
GuardDecision
Class · import { GuardDecision } from "promptguard-sdk" or import { GuardDecision } from "promptguard-sdk/guard"
readonly decision: stringreadonly eventId: stringreadonly confidence: numberreadonly threatType?: stringreadonly redactedMessages?: GuardMessage[]readonly threats: ThreatDetail[]readonly latencyMs: numberget blocked(): booleanget redacted(): booleanget allowed(): boolean
new GuardDecision(...)
data.decision is missing or not one of
allow / block / redact. A malformed body must never silently
default to “allow” — surfacing it as a GuardApiError lets the
caller’s explicit failOpen policy govern instead.
GuardMessage
Interface · import { GuardMessage } from "promptguard-sdk" or import { GuardMessage } from "promptguard-sdk/guard"
role: stringcontent: string
GuardRequestBody
Interface · import { GuardRequestBody } from "promptguard-sdk" or import { GuardRequestBody } from "promptguard-sdk/guard"
messages: GuardMessage[]direction: "input" | "output"model?: stringcontext?: GuardContextWire
GuardResponseBody
Interface · import { GuardResponseBody } from "promptguard-sdk" or import { GuardResponseBody } from "promptguard-sdk/guard"
decision: "allow" | "block" | "redact"event_id: stringconfidence: numberthreat_type?: stringredacted_messages?: GuardMessage[]threats: ThreatDetail[]latency_ms: number
PromptGuardBlockedError
Class · import { PromptGuardBlockedError } from "promptguard-sdk" or import { PromptGuardBlockedError } from "promptguard-sdk/guard"
readonly decision: GuardDecision
new PromptGuardBlockedError(...)
ScanOptions
Interface · import { ScanOptions } from "promptguard-sdk" or import { ScanOptions } from "promptguard-sdk/guard"
GuardClient.scan.
Fields
direction?: "input" | "output"model?: stringcontext?: GuardContext
ThreatDetail
Interface · import { ThreatDetail } from "promptguard-sdk" or import { ThreatDetail } from "promptguard-sdk/guard"
type: stringconfidence: numberdetails: string
PromptGuardCallbackHandler
Class · import { PromptGuardCallbackHandler } from "promptguard-sdk" or import { PromptGuardCallbackHandler } from "promptguard-sdk/integrations/langchain"
redact decision cannot be honored here. In enforce mode it is escalated
to a block (a PromptGuardBlockedError is thrown) rather than
silently sending the content the Guard API asked us to redact. If you need
actual redaction, use auto-instrumentation (init()) or explicit
GuardClient.scan() calls, which can rewrite the outgoing messages.
Properties
readonly name = "promptguard"readonly raiseError = true— Tell LangChain’s callback manager to re-throw errors from this handler.readonly awaitHandlers = true— Tell LangChain to await this handler before continuing.
new PromptGuardCallbackHandler(...)
PromptGuardCallbackHandler.handleLLMStart
PromptGuardCallbackHandler.handleChatModelStart
PromptGuardCallbackHandler.handleLLMEnd
PromptGuardCallbackHandler.handleLLMError
PromptGuardCallbackHandler.handleChainStart
PromptGuardCallbackHandler.handleChainEnd
PromptGuardCallbackHandler.handleChainError
PromptGuardCallbackHandler.handleToolStart
PromptGuardCallbackHandler.handleToolEnd
PromptGuardCallbackHandler.handleToolError
promptGuardMiddleware
Function · import { promptGuardMiddleware } from "promptguard-sdk" or import { promptGuardMiddleware } from "promptguard-sdk/integrations/vercel-ai"
LanguageModelMiddleware
interface (transformParams, plus wrapGenerate and wrapStream when
scanResponses is set). The hooks are generic over the call options and
results they pass through, so the object is assignable to the middleware
type of each supported ai major (checked by tests/vercel-ai-types.test.ts).
promptguard
Function · import { promptguard } from "promptguard-sdk" or import { promptguard } from "promptguard-sdk/integrations/vercel-ai"
promptGuardMiddleware(options) would scan it
under wrapLanguageModel — generated and streamed alike.
The wrapped model is the model it wraps in every other respect: its own
specification version, provider, model id, supported URLs and any other
property, so it is accepted wherever the original was and has the same
type. Options are the middleware’s; the API key defaults to
PROMPTGUARD_API_KEY, and a missing one throws here rather than on the
first call.
getLogLevel
Function · import { getLogLevel } from "promptguard-sdk"
LogLevel
Type · import { LogLevel } from "promptguard-sdk"
logging module, so this provides a
small, suppressible logger so the SDK does not write to stdout/stderr by
default. Mirrors the suppressibility of the Python SDK’s logging usage.
Levels (most → least verbose): “debug” < “info” < “warn” < “error” < “silent”.
Default level is “warn”: warnings/errors surface, info/debug are suppressed.
Set verbosity via setLogLevel (or the logLevel / silent options
on init() / integration constructors).
NOTE: the log level is process-global, not per-instance. Passing
logLevel / silent to init(), PromptGuardCallbackHandler, or
promptGuardMiddleware mutates the shared level for the whole process —
the most recently constructed instance wins. If you need different
verbosity for different clients, call setLogLevel around the
code paths you care about instead.
setLogLevel
Function · import { setLogLevel } from "promptguard-sdk"
CheckStatus
Type · import { CheckStatus } from "promptguard-sdk"
VerifyCheck
Interface · import { VerifyCheck } from "promptguard-sdk"
name: stringstatus: CheckStatusdetail: string
VerifyOptions
Interface · import { VerifyOptions } from "promptguard-sdk"
apiKey?: stringbaseUrl?: stringtimeout?: number— Per-request timeout in milliseconds.maxRetries?: number— Retry attempts per probe. Defaults to1, not the client’s3.retryDelay?: number— Backoff between retries, in milliseconds. Defaults to250.
VerifyReport
Interface · import { VerifyReport } from "promptguard-sdk"
ok: boolean— True when no check failed. Warnings do not clear it.checks: VerifyCheck[]checksPassed: numberchecksFailed: numberchecksWarned: numberinstrumentation: ReturnType<typeof instrumentationReport>baseUrl: string— The URL that was actually called, after base-URL normalization.sdkVersion: string
verify
Function · import { verify } from "promptguard-sdk"
PROMPTGUARD_API_KEY / PROMPTGUARD_BASE_URL from the environment.
Never rejects for a failed check: a check that threw would be useless in the
place this is most needed, which is a CI step or a pre-flight script that
wants every problem at once rather than only the first. A missing API key is
the one exception — that is a caller error, not a finding, and it throws
PromptGuardError with code missing_api_key like the rest of the SDK.
A warn means the request worked but the answer was not what a protected
setup should give — an injection that came back allowed, or a PII sample with
nothing detected. That is a policy question rather than a broken integration,
which is why it does not clear ok; it is still the thing to look at before
trusting the setup.
promptguard-sdk/auto
Auto-instrumentation for PromptGuard (Node.js).
Call init once at application startup to automatically
secure all LLM calls made through popular SDKs - regardless of
which framework (LangChain.js, Vercel AI SDK, etc.) sits on top.
@example
getGuardClient
Function · import { getGuardClient } from "promptguard-sdk/auto"
getMode
Function · import { getMode } from "promptguard-sdk/auto"
isFailOpen
Function · import { isFailOpen } from "promptguard-sdk/auto"
shouldScanResponses
Function · import { shouldScanResponses } from "promptguard-sdk/auto"
knownPatchNames
Function · import { knownPatchNames } from "promptguard-sdk/auto"
patched.
Not re-exported from index.ts: the package’s public surface is unchanged,
and this mirrors the Python SDK’s private _known_patches(). It exists so
the cross-SDK contract’s instrumentation_introspection section can assert
that both SDKs name the same providers — they did not, until v1.6.0 of the
contract: this SDK reported bedrock while Python reported boto3-bedrock.
promptguard-sdk/guard
Guard client - calls the PromptGuard Guard API for content scanning.
Used internally by auto-instrumentation patches and framework
integrations. Sends messages to POST /api/v1/guard and returns
the decision (allow / block / redact).
serializeGuardContext
Function · import { serializeGuardContext } from "promptguard-sdk/guard"
GuardContext (camelCase, with deprecated
snake_case aliases) into the snake_case wire shape. camelCase fields win
over their deprecated snake_case aliases; only defined fields are emitted so
the serialized body carries no camelCase keys and no explicit undefineds.
safeErrorLabel
Function · import { safeErrorLabel } from "promptguard-sdk/guard"
GuardApiError this emits only HTTP status + a static message
(never the response body or prompt content). Any other error type is a real
bug that the fail-open paths re-throw before reaching here, so we fall back
to a generic label rather than risk logging arbitrary contents.
promptguard-sdk/integrations/langchain
LangChain.js integration - PromptGuardCallbackHandler.
Implements the LangChain BaseCallbackHandler interface to scan prompts
before LLM calls and responses after, with rich context about chains,
tools, and agent steps.
@example
session_id with the call’s own
thread id: the thread_id LangGraph puts in every callback’s metadata, or a
thread_id / session_id / conversation_id set in config.metadata. A
call that names no thread sends no session id, unless the handler was given
a sessionId of its own.
PromptGuardCallbackOptions
Interface · import { PromptGuardCallbackOptions } from "promptguard-sdk/integrations/langchain"
mode?: "enforce" | "monitor"scanResponses?: boolean— Also scan LLM/tool outputs (default:false, consistent withinit()and the Vercel AI middleware). Enable explicitly if you want output scanning — every scan is a billable Guard API call.failOpen?: booleanlogLevel?: LogLevel— SDK log verbosity (default:"warn"). Set to"silent"to suppress logs. NOTE: this sets the process-global SDK log level (shared withinit()and other integrations); the most recently constructed instance wins.silent?: boolean— Convenience shorthand forlogLevel: "silent".sessionId?: string— The Conversation to name when a call carries no thread id of its own — for a handler that serves one conversation. A call’sthread_id(orsession_id/conversation_id) in its metadata always wins. Without either, no session id is sent.
promptguard-sdk/integrations/vercel-ai
Vercel AI SDK integration for the ai package.
Two ways in, with the same scanning:
promptguard(model)wraps a language model of ai 5, 6 or 7 (specification v2, v3 or v4), and the wrapped model is used wherever the original was:
promptGuardMiddleware(options)is the same scanning as AI SDK middleware, forwrapLanguageModel— useful alongside other middleware, and the way in on ai 4:
scanResponses: true, streamText() output is scanned too: in
enforce mode text is held until it has been scanned, a window
(streamWindowChars, default 1000 characters) at a time, and the complete
text is scanned before the stream finishes. See vercel-ai-output.ts for
the full behaviour and its guarantee.
Neither imports ai: the wrapper calls the middleware’s hooks the way
wrapLanguageModel does, so it works with whichever ai the application
has (ai@7 is ESM-only; this package is CommonJS) and loads without one.
PromptGuardMiddlewareOptions
Interface · import { PromptGuardMiddlewareOptions } from "promptguard-sdk/integrations/vercel-ai"
apiKey?: string— PromptGuard API key (default: thePROMPTGUARD_API_KEYenvironment variable).mode?: "enforce" | "monitor"scanResponses?: boolean— Scan the model’s output as well as its input (default:false). Applies togenerateText()and tostreamText()alike.failOpen?: booleanstreamWindowChars?: number— WithscanResponsesin enforce mode, how many new characters of streamed output are collected before the held text is scanned (default:1000; seeDEFAULT_STREAM_WINDOW_CHARSfor why). A smaller window delivers the first text sooner at the cost of more scans;Infinityholds the whole response for a single scan at the end.logLevel?: LogLevel— SDK log verbosity (default:"warn"). Set to"silent"to suppress logs. NOTE: this sets the process-global SDK log level (shared withinit()and other integrations); the most recently constructed instance wins.silent?: boolean— Convenience shorthand forlogLevel: "silent".sessionId?: string— The Conversation to name when a call names none of its own. The AI SDK has no conversation id, so a call names one withproviderOptions: { promptguard: { sessionId } }(providerMetadataonai@4), which wins over this. Without either, no session id is sent.
LanguageModelLike
Interface · import { LanguageModelLike } from "promptguard-sdk/integrations/vercel-ai"
promptguard() relies on.
Fields
readonly specificationVersion: stringreadonly modelId: string