TypeScript SDK
Lightweight TypeScript client for implementing Superagent in your app
A lightweight client for calling the Superagent Guard and Redact endpoints from TypeScript or JavaScript projects.
Installation
npm install superagent-ai
# or
pnpm add superagent-ai
# or
yarn add superagent-aiUsage
import { createClient } from "superagent-ai";
const client = createClient({
apiBaseUrl: process.env.SUPERAGENT_API_BASE_URL, // Optional, defaults to https://app.superagent.sh/api
apiKey: process.env.SUPERAGENT_API_KEY!,
});
// Guard: Analyze commands for security threats
const guardResult = await client.guard("Write a hello world script", {
onBlock: (reason) => {
console.warn("Guard blocked command:", reason);
},
onPass: () => {
console.log("Guard approved command!");
},
});
if (guardResult.rejected) {
console.log("Blocked:", guardResult.reasoning);
} else {
console.log("Approved");
}
// Redact: Remove sensitive data from text
const redactResult = await client.redact(
"My email is john@example.com and SSN is 123-45-6789"
);
console.log(redactResult.redacted);
// Output: "My email is <REDACTED_EMAIL> and SSN is <REDACTED_SSN>"
// Verify: Check claims against source materials
const verifyResult = await client.verify(
"The company was founded in 2020 and has 500 employees",
[
{
name: "About Us",
content: "Founded in 2020, our company has grown rapidly...",
url: "https://example.com/about"
},
{
name: "Team Page",
content: "We currently have over 450 team members...",
url: "https://example.com/team"
}
]
);
console.log(verifyResult.claims);
// Output: Array of claim verifications with verdicts, evidence, and reasoningAPI Reference
createClient(options)
Creates a new Superagent client.
Options:
apiKey(required) – API key provisioned in SuperagentapiBaseUrl(optional) – Base URL for the API (defaults tohttps://app.superagent.sh/api)fetch(optional) – Custom fetch implementation (defaults to globalfetch)timeoutMs(optional) – Request timeout in milliseconds
client.guard(input, callbacks?)
Analyzes text or a PDF file for security threats.
Parameters:
Prop
Type
Returns: Promise<GuardResult>
Prop
Type
GuardDecision:
Prop
Type
client.redact(input, options?)
Redacts sensitive data from text or PDF files.
Parameters:
Prop
Type
RedactOptions:
Prop
Type
Returns: Promise<RedactResult>
Prop
Type
client.verify(text, sources)
Verifies claims in text against provided source materials.
Parameters:
Prop
Type
Source:
Prop
Type
Returns: Promise<VerifyResult>
Prop
Type
ClaimVerification:
Prop
Type
Claim Verification
You can verify claims in text against provided source materials:
const client = createClient({
apiKey: process.env.SUPERAGENT_API_KEY!,
});
const result = await client.verify(
"The company was founded in 2020 and has 500 employees.",
[
{
name: "About Us",
content: "Founded in 2020, our company has grown rapidly...",
url: "https://example.com/about"
},
{
name: "Team Page",
content: "We currently have over 450 team members...",
url: "https://example.com/team"
}
]
);
// Iterate through claims to check verdicts
for (const claim of result.claims) {
console.log(`Claim: ${claim.claim}`);
console.log(`Verdict: ${claim.verdict ? '✓ True' : '✗ False'}`);
console.log(`Evidence: ${claim.evidence}`);
console.log(`Reasoning: ${claim.reasoning}`);
console.log(`Sources: ${claim.sources.map(s => s.name).join(', ')}`);
console.log('---');
}How it works:
- The
textparameter contains the claims you want to verify - The
sourcesarray provides the reference materials against which claims are verified - The AI analyzes each claim and determines if it's supported, contradicted, or unverifiable
- Returns detailed results with verdicts, evidence quotes, reasoning, and source references
- Only uses information explicitly stated in the provided sources
Use cases:
- Fact-checking articles or content against authoritative sources
- Verifying marketing claims against product documentation
- Validating information in reports against source data
- Checking consistency between different documents
- Automated compliance verification
Detected PII/PHI Types
The redaction feature detects and replaces:
- Email addresses →
<REDACTED_EMAIL> - Social Security Numbers →
<REDACTED_SSN> - Credit cards (Visa, Mastercard, Amex) →
<REDACTED_CC> - Phone numbers (US format) →
<REDACTED_PHONE> - IP addresses (IPv4/IPv6) →
<REDACTED_IP> - API keys & tokens →
<REDACTED_API_KEY> - AWS access keys →
<REDACTED_AWS_KEY> - Bearer tokens →
Bearer <REDACTED_TOKEN> - MAC addresses →
<REDACTED_MAC> - Medical record numbers →
<REDACTED_MRN> - Passport numbers →
<REDACTED_PASSPORT> - IBAN →
<REDACTED_IBAN> - ZIP codes →
<REDACTED_ZIP>
Custom Entity Redaction
You can specify custom entities to redact using natural language descriptions by passing an entities option to the redact() method:
const client = createClient({
apiKey: process.env.SUPERAGENT_API_KEY!,
});
const result = await client.redact(
"My credit card is 4532-1234-5678-9010 and my email is john@example.com",
{ entities: ["credit card numbers", "email addresses"] }
);
// The model will redact the specified entity types based on your natural language descriptionsHow it works:
- The
entitiesarray is sent to the redaction API in the request body - You can describe entities in natural language (e.g., "credit card numbers", "social security numbers", "phone numbers")
- The AI model interprets your descriptions and redacts matching content
- This allows for flexible, context-aware redaction beyond predefined patterns
Examples of entity descriptions:
["credit card numbers", "social security numbers"]["email addresses", "phone numbers", "IP addresses"]["API keys", "passwords", "authentication tokens"]["medical record numbers", "patient names"]["company names", "project codenames"]
URL Whitelisting
You can specify URLs that should not be redacted by passing a urlWhitelist option to the redact() method:
const client = createClient({
apiKey: process.env.SUPERAGENT_API_KEY!,
});
const result = await client.redact(
"Check out https://github.com/user/repo and https://secret.com/data",
{ urlWhitelist: ["https://github.com", "https://example.com"] }
);
// Output: "Check out https://github.com/user/repo and <URL_REDACTED>"The whitelist is applied locally after redaction, meaning:
- The text is sent to the redact API (URLs are not yet redacted by the API)
- The response is processed locally
- URLs not matching the whitelist prefixes are replaced with
<URL_REDACTED> - URLs matching the whitelist prefixes are preserved as-is
- The final result is returned
How it works:
- Whitelisted URLs (those starting with any prefix in
urlWhitelist) remain unchanged - Non-whitelisted URLs are replaced with
<URL_REDACTED> - The matching is done using prefix comparison (e.g.,
"https://github.com"matches"https://github.com/user/repo")
PDF File Redaction
You can redact sensitive information from PDF files. The API supports two output formats:
Option 1: Get Redacted PDF File (format="pdf")
Returns a PDF file with redactions applied:
import { readFileSync, writeFileSync } from 'fs';
const client = createClient({
apiKey: process.env.SUPERAGENT_API_KEY!,
});
// Read PDF file
const pdfBuffer = readFileSync('sensitive-document.pdf');
const pdfBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
// Get redacted PDF file
const result = await client.redact(
pdfBlob, // Pass file as first parameter
{
format: "pdf", // Returns redacted PDF
entities: ["SSN", "credit card numbers", "email addresses"]
}
);
// Save the redacted PDF
if (result.pdf) {
const arrayBuffer = await result.pdf.arrayBuffer();
writeFileSync('redacted-output.pdf', Buffer.from(arrayBuffer));
console.log('Redacted PDF saved to redacted-output.pdf');
}Option 2: Get Redacted Text (format="json", default)
Returns JSON with the redacted text extracted from the PDF:
import { readFileSync } from 'fs';
const client = createClient({
apiKey: process.env.SUPERAGENT_API_KEY!,
});
const pdfBuffer = readFileSync('sensitive-document.pdf');
const pdfBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
// Get redacted text from PDF
const result = await client.redact(
pdfBlob, // Pass file as first parameter
{
format: "json", // Returns JSON with redacted text (default)
entities: ["SSN", "credit card numbers", "email addresses"]
}
);
console.log(result.redacted); // Redacted text extracted from the PDF
console.log(result.reasoning); // Explanation of what was redactedHow it works:
- Pass the file object (File or Blob) directly as the first parameter
- The SDK automatically uses multipart/form-data encoding for file inputs
format="pdf"returns a redacted PDF file as a Blobformat="json"(default) extracts text from the PDF, redacts it, and returns as JSON- You can combine file redaction with
entitiesto specify custom entity types
Use cases:
- Redact sensitive data from contracts, invoices, or legal documents
- Process medical records while maintaining HIPAA compliance
- Sanitize financial documents before sharing
- Prepare documents for public release by removing confidential information
PDF File Guard Analysis
You can analyze PDF files for security threats using the Guard method. The API analyzes the PDF content and returns a JSON response with the security assessment:
Analyze PDF Files
Analyzes a PDF file and returns JSON with security assessment:
import { createClient } from "superagent-ai";
import { readFileSync } from 'fs';
const client = createClient({
apiKey: process.env.SUPERAGENT_API_KEY!,
});
// Read PDF file
const pdfBuffer = readFileSync('document.pdf');
const pdfBlob = new Blob([pdfBuffer], { type: 'application/pdf' });
// Analyze PDF file for security threats
const result = await client.guard(
pdfBlob, // Pass file as first parameter
{
onBlock: (reason) => console.warn("Guard blocked:", reason),
onPass: () => console.log("Guard approved!"),
}
);
// Check the analysis result
if (result.rejected) {
console.log(`Document contains security threats: ${result.reasoning}`);
if (result.decision) {
console.log(`Violation types: ${result.decision.violation_types}`);
console.log(`CWE codes: ${result.decision.cwe_codes}`);
}
} else {
console.log(`Document is safe: ${result.reasoning}`);
}How it works:
- Pass the file object (File or Blob) directly as the first parameter
- The SDK automatically uses multipart/form-data encoding for file inputs
- The guard extracts text from the PDF and analyzes it for security threats
- Returns JSON with
rejected,reasoning,decision, andusagefields - You can use the
onBlockandonPasscallbacks to handle the analysis results
Use cases:
- Analyze uploaded documents for malicious content before processing
- Validate PDF attachments for security threats
- Screen documents for prompt injection attempts
- Ensure document safety before feeding to AI models
Error Handling
import { GuardError } from "superagent-ai";
try {
const result = await client.guard("command");
} catch (error) {
if (error instanceof GuardError) {
console.error("Guard error:", error.message);
}
}