The first open-source AI agent security SDK with client-side guardrails π‘οΈ
Drop-in Client Wrappers - Secure AI clients with zero code changes!
- π TealOpenAI - Drop-in replacement for OpenAI client
- π TealAnthropic - Drop-in replacement for Anthropic client
- π TealAzureOpenAI - Drop-in replacement for Azure OpenAI client
- π° Cost Tracking - Monitor costs across 30+ models
- π΅ Budget Management - Enforce spending limits automatically
- π‘οΈ Automatic Security - Guardrails run on every request
- β‘ 100% Compatible - No migration needed
npm install tealtigerimport { GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail } from 'tealtiger';
// Create guardrail engine
const engine = new GuardrailEngine();
// Register guardrails
engine.registerGuardrail(new PIIDetectionGuardrail());
engine.registerGuardrail(new PromptInjectionGuardrail());
// Evaluate user input
const result = await engine.execute("Contact me at john@example.com");
if (!result.passed) {
console.log('Security check failed:', result.message);
console.log('Risk score:', result.riskScore);
}import { TealTiger } from 'tealtiger';
// Initialize the SDK
const guard = new TealTiger({
apiKey: 'your-api-key',
ssaUrl: 'https://ssa.TealTiger.io'
});
// Secure tool execution
const result = await guard.executeTool(
'web-search',
{ query: 'AI agent security' },
{ sessionId: 'user-session-123' }
);Detect and protect personally identifiable information:
import { PIIDetectionGuardrail } from 'tealtiger';
const guard = new PIIDetectionGuardrail({
action: 'redact', // or 'block', 'mask', 'allow'
customPatterns: [
{ name: 'custom-id', pattern: /ID-\d{6}/, category: 'identifier' }
]
});
const result = await guard.evaluate("My email is john@example.com");
// result.passed = false
// result.violations = [{ type: 'email', value: 'john@example.com', ... }]Detects:
- Email addresses
- Phone numbers (US, international)
- Social Security Numbers
- Credit card numbers
- Custom patterns
Block harmful content:
import { ContentModerationGuardrail } from 'tealtiger';
const guard = new ContentModerationGuardrail({
categories: ['hate', 'violence', 'harassment', 'self-harm'],
threshold: 0.7,
useOpenAI: true, // Optional: Use OpenAI Moderation API
openaiApiKey: 'your-key'
});
const result = await guard.evaluate("I hate everyone");
// result.passed = false
// result.riskScore = 85Prevent jailbreak attempts:
import { PromptInjectionGuardrail } from 'tealtiger';
const guard = new PromptInjectionGuardrail({
sensitivity: 'high', // 'low', 'medium', 'high'
customPatterns: [
/custom attack pattern/i
]
});
const result = await guard.evaluate("Ignore previous instructions and...");
// result.passed = false
// result.riskScore = 90Detects:
- Instruction injection
- Role-playing attacks
- System prompt leakage
- DAN jailbreaks
- Developer mode attempts
Execute multiple guardrails:
import {
GuardrailEngine,
PIIDetectionGuardrail,
ContentModerationGuardrail,
PromptInjectionGuardrail
} from 'tealtiger';
const engine = new GuardrailEngine({
mode: 'parallel', // or 'sequential'
timeout: 5000, // ms
continueOnError: true
});
// Register guardrails
engine.registerGuardrail(new PIIDetectionGuardrail());
engine.registerGuardrail(new ContentModerationGuardrail());
engine.registerGuardrail(new PromptInjectionGuardrail());
// Execute all guardrails
const result = await engine.execute(userInput);
console.log('Passed:', result.passed);
console.log('Risk Score:', result.riskScore);
console.log('Results:', result.results);Track AI model costs and enforce budgets automatically:
import { CostTracker } from 'tealtiger';
const tracker = new CostTracker({
enabled: true,
persistRecords: true,
enableBudgets: true,
enableAlerts: true
});
// Estimate cost before making a request
const estimate = tracker.estimateCost(
'gpt-4',
{
inputTokens: 1000,
outputTokens: 500,
totalTokens: 1500
},
'openai'
);
console.log(`Estimated cost: $${estimate.estimatedCost.toFixed(4)}`);// Calculate actual cost after API call
const actualCost = tracker.calculateActualCost(
'req-123',
'agent-456',
'gpt-4',
{
inputTokens: 1050,
outputTokens: 480,
totalTokens: 1530
},
'openai'
);
// Store cost record
await storage.store(actualCost);import { BudgetManager, InMemoryCostStorage } from 'tealtiger';
const storage = new InMemoryCostStorage();
const budgetManager = new BudgetManager(storage);
// Create a daily budget
const budget = budgetManager.createBudget({
name: 'Daily GPT-4 Budget',
limit: 10.0,
period: 'daily',
alertThresholds: [50, 75, 90, 100],
action: 'block', // or 'alert'
enabled: true
});
// Check budget before making a request
const budgetCheck = await budgetManager.checkBudget('agent-123', estimatedCost);
if (!budgetCheck.allowed) {
console.log('Request blocked - budget exceeded');
console.log(`Blocked by: ${budgetCheck.blockedBy?.name}`);
}
// Get budget status
const status = await budgetManager.getBudgetStatus(budget.id);
console.log(`Current spending: $${status?.currentSpending.toFixed(2)}`);
console.log(`Remaining: $${status?.remaining.toFixed(2)}`);
console.log(`Percentage used: ${status?.percentageUsed.toFixed(1)}%`);// Create budget for specific agent
const agentBudget = budgetManager.createBudget({
name: 'Agent 1 Budget',
limit: 5.0,
period: 'daily',
alertThresholds: [80, 100],
action: 'block',
scope: {
type: 'agent',
id: 'agent-1'
},
enabled: true
});30+ models across 4 providers:
- OpenAI: GPT-4, GPT-4 Turbo, GPT-3.5 Turbo, GPT-4 Vision
- Anthropic: Claude 3 Opus, Sonnet, Haiku
- Google: Gemini Pro, Gemini Pro Vision
- Cohere: Command, Command Light
Drop-in replacement for the OpenAI client with integrated security and cost tracking:
import {
TealOpenAI,
GuardrailEngine,
PIIDetectionGuardrail,
PromptInjectionGuardrail,
CostTracker,
BudgetManager,
InMemoryCostStorage
} from 'tealtiger';
// Set up guardrails
const guardrailEngine = new GuardrailEngine();
guardrailEngine.registerGuardrail(new PIIDetectionGuardrail());
guardrailEngine.registerGuardrail(new PromptInjectionGuardrail());
// Set up cost tracking
const storage = new InMemoryCostStorage();
const costTracker = new CostTracker({ enabled: true });
const budgetManager = new BudgetManager(storage);
budgetManager.createBudget({
name: 'Daily Budget',
limit: 10.0,
period: 'daily',
action: 'block',
enabled: true
});
// Create TealOpenAI client (100% API compatible with OpenAI)
const client = new TealOpenAI({
apiKey: process.env.OPENAI_API_KEY,
agentId: 'my-agent',
guardrailEngine,
costTracker,
budgetManager,
costStorage: storage
});
// Use exactly like OpenAI client
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is the capital of France?' }
],
max_tokens: 100
});
// Response includes security metadata
console.log('Response:', response.choices[0].message.content);
console.log('Guardrails passed:', response.security?.guardrailResult?.passed);
console.log('Cost:', `$${response.security?.costRecord?.actualCost.toFixed(4)}`);
console.log('Budget check:', response.security?.budgetCheck?.allowed);Features:
- β 100% API Compatible - Drop-in replacement for OpenAI client
- π‘οΈ Automatic Guardrails - Input and output validation
- π° Cost Tracking - Automatic cost calculation and storage
- π« Budget Enforcement - Blocks requests when budget exceeded
- π Security Metadata - Detailed security info in responses
- βοΈ Configurable - Enable/disable features as needed
Configuration Options:
const client = new TealOpenAI({
apiKey: 'your-api-key', // Required: OpenAI API key
agentId: 'my-agent', // Optional: Agent identifier
enableGuardrails: true, // Optional: Enable guardrails (default: true)
enableCostTracking: true, // Optional: Enable cost tracking (default: true)
guardrailEngine, // Optional: Custom guardrail engine
costTracker, // Optional: Custom cost tracker
budgetManager, // Optional: Budget manager
costStorage, // Optional: Cost storage
baseURL: 'https://api.openai.com', // Optional: Custom base URL
organization: 'org-id' // Optional: Organization ID
});
// Update configuration at runtime
client.updateConfig({
enableGuardrails: false,
agentId: 'new-agent-id'
});Error Handling:
try {
const response = await client.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello!' }]
});
} catch (error) {
if (error.message.includes('Guardrail check failed')) {
console.log('Request blocked by guardrails');
} else if (error.message.includes('Budget exceeded')) {
console.log('Budget limit reached');
} else {
console.log('Other error:', error.message);
}
}Drop-in replacement for the Anthropic client with integrated security and cost tracking:
import {
TealAnthropic,
GuardrailEngine,
PIIDetectionGuardrail,
PromptInjectionGuardrail,
CostTracker,
BudgetManager,
InMemoryCostStorage
} from 'tealtiger';
// Set up guardrails
const guardrailEngine = new GuardrailEngine();
guardrailEngine.registerGuardrail(new PIIDetectionGuardrail());
guardrailEngine.registerGuardrail(new PromptInjectionGuardrail());
// Set up cost tracking
const storage = new InMemoryCostStorage();
const costTracker = new CostTracker({ enabled: true });
const budgetManager = new BudgetManager(storage);
budgetManager.createBudget({
name: 'Daily Budget',
limit: 10.0,
period: 'daily',
action: 'block',
enabled: true
});
// Create TealAnthropic client (100% API compatible with Anthropic)
const client = new TealAnthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
agentId: 'my-agent',
guardrailEngine,
costTracker,
budgetManager,
costStorage: storage
});
// Use exactly like Anthropic client
const response = await client.messages.create({
model: 'claude-3-sonnet-20240229',
max_tokens: 100,
messages: [
{ role: 'user', content: 'What is the capital of France?' }
]
});
// Response includes security metadata
console.log('Response:', response.content[0].text);
console.log('Guardrails passed:', response.security?.guardrailResult?.passed);
console.log('Cost:', `$${response.security?.costRecord?.actualCost.toFixed(4)}`);
console.log('Budget check:', response.security?.budgetCheck?.allowed);Features:
- β 100% API Compatible - Drop-in replacement for Anthropic client
- π‘οΈ Automatic Guardrails - Input and output validation
- π° Cost Tracking - Automatic cost calculation for Claude models
- π« Budget Enforcement - Blocks requests when budget exceeded
- π Security Metadata - Detailed security info in responses
- βοΈ Configurable - Enable/disable features as needed
Configuration Options:
const client = new TealAnthropic({
apiKey: 'your-api-key', // Required: Anthropic API key
agentId: 'my-agent', // Optional: Agent identifier
enableGuardrails: true, // Optional: Enable guardrails (default: true)
enableCostTracking: true, // Optional: Enable cost tracking (default: true)
guardrailEngine, // Optional: Custom guardrail engine
costTracker, // Optional: Custom cost tracker
budgetManager, // Optional: Budget manager
costStorage, // Optional: Cost storage
baseURL: 'https://api.anthropic.com' // Optional: Custom base URL
});
// Update configuration at runtime
client.updateConfig({
enableGuardrails: false,
agentId: 'new-agent-id'
});Supported Models:
- Claude 3 Opus (
claude-3-opus-20240229) - Claude 3 Sonnet (
claude-3-sonnet-20240229) - Claude 3 Haiku (
claude-3-haiku-20240307) - Claude 2.1 (
claude-2.1) - Claude 2.0 (
claude-2.0) - Claude Instant (
claude-instant-1.2)
Drop-in replacement for the Azure OpenAI client with integrated security and cost tracking:
import {
TealAzureOpenAI,
GuardrailEngine,
PIIDetectionGuardrail,
PromptInjectionGuardrail,
CostTracker,
BudgetManager,
InMemoryCostStorage
} from 'tealtiger';
// Set up guardrails
const guardrailEngine = new GuardrailEngine();
guardrailEngine.registerGuardrail(new PIIDetectionGuardrail());
guardrailEngine.registerGuardrail(new PromptInjectionGuardrail());
// Set up cost tracking
const storage = new InMemoryCostStorage();
const costTracker = new CostTracker({ enabled: true });
const budgetManager = new BudgetManager(storage);
budgetManager.createBudget({
name: 'Daily Budget',
limit: 10.0,
period: 'daily',
action: 'block',
enabled: true
});
// Create TealAzureOpenAI client (100% API compatible with Azure OpenAI)
const client = new TealAzureOpenAI({
apiKey: process.env.AZURE_OPENAI_API_KEY,
endpoint: process.env.AZURE_OPENAI_ENDPOINT, // e.g., https://your-resource.openai.azure.com
apiVersion: '2024-02-15-preview',
agentId: 'my-agent',
guardrailEngine,
costTracker,
budgetManager,
costStorage: storage
});
// Use exactly like Azure OpenAI client
const response = await client.chat.completions.create({
deployment: 'gpt-4-deployment', // Your Azure deployment name
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is the capital of France?' }
],
max_tokens: 100
});
// Or use the deployments API (Azure-specific)
const response2 = await client.deployments.chat.completions.create({
deployment: 'gpt-35-turbo-deployment',
messages: [
{ role: 'user', content: 'Hello!' }
],
max_tokens: 50
});
// Response includes security metadata
console.log('Response:', response.choices[0].message.content);
console.log('Guardrails passed:', response.security?.guardrailResult?.passed);
console.log('Cost:', `${response.security?.costRecord?.actualCost.toFixed(4)}`);
console.log('Budget check:', response.security?.budgetCheck?.allowed);Features:
- β 100% API Compatible - Drop-in replacement for Azure OpenAI client
- π‘οΈ Automatic Guardrails - Input and output validation
- π° Cost Tracking - Automatic cost calculation with deployment mapping
- π« Budget Enforcement - Blocks requests when budget exceeded
- π Security Metadata - Detailed security info in responses
- βοΈ Configurable - Enable/disable features as needed
- π Azure AD Support - Azure Active Directory authentication
Configuration Options:
const client = new TealAzureOpenAI({
apiKey: 'your-api-key', // Required: Azure OpenAI API key
endpoint: 'https://your-resource.openai.azure.com', // Required: Azure endpoint
apiVersion: '2024-02-15-preview', // Optional: API version (default: 2024-02-15-preview)
agentId: 'my-agent', // Optional: Agent identifier
enableGuardrails: true, // Optional: Enable guardrails (default: true)
enableCostTracking: true, // Optional: Enable cost tracking (default: true)
guardrailEngine, // Optional: Custom guardrail engine
costTracker, // Optional: Custom cost tracker
budgetManager, // Optional: Budget manager
costStorage, // Optional: Cost storage
azureADToken: 'your-token' // Optional: Azure AD token for authentication
});
// Update configuration at runtime
client.updateConfig({
enableGuardrails: false,
agentId: 'new-agent-id'
});Deployment Name Mapping:
Azure OpenAI uses deployment names instead of model names. TealAzureOpenAI automatically maps deployment names to model names for accurate cost tracking:
// Deployment name β Model name mapping
'my-gpt-4-deployment' β 'gpt-4'
'my-gpt-4-32k-deployment' β 'gpt-4-32k'
'my-gpt-4-turbo-deployment' β 'gpt-4-turbo'
'my-gpt-35-turbo-deployment' β 'gpt-3.5-turbo'
'my-gpt-35-turbo-16k-deployment' β 'gpt-3.5-turbo-16k'The mapping is intelligent and works with common naming patterns. If your deployment name doesn't match, it defaults to gpt-3.5-turbo pricing.
Azure-Specific Features:
// Both APIs are supported:
// 1. Standard chat API
await client.chat.completions.create({ deployment: 'my-deployment', ... });
// 2. Deployments API (Azure-specific)
await client.deployments.chat.completions.create({ deployment: 'my-deployment', ... });
// Azure AD authentication
const client = new TealAzureOpenAI({
endpoint: 'https://your-resource.openai.azure.com',
azureADToken: 'your-azure-ad-token',
apiVersion: '2024-02-15-preview'
});// Add custom pricing for your models
tracker.addCustomPricing('custom-model-v1', {
model: 'custom-model-v1',
provider: 'custom',
inputCostPer1K: 0.01,
outputCostPer1K: 0.02,
lastUpdated: new Date().toISOString()
});- π PII Detection - Protect sensitive data
- π‘οΈ Content Moderation - Block harmful content
- π« Prompt Injection Prevention - Prevent attacks
- π° Cost Tracking - Monitor AI model costs
- π΅ Budget Management - Enforce spending limits
- β‘ Fast - Millisecond latency
- π Private - No data leaves your server
- π Runtime Security Enforcement - Mediate all agent tool/API calls
- π Policy-Based Access Control - Define and enforce security policies
- π Comprehensive Audit Trails - Track every agent action
- β‘ High Performance - <100ms latency for security decisions
- π Request Transformation - Automatically transform risky requests
- π Real-time Monitoring - Track agent behavior and security events
- Customer Support Bots - Protect customer PII
- Healthcare AI - HIPAA compliance
- Financial Services - Prevent data leakage
- E-commerce - Secure payment information
- Enterprise AI - Policy enforcement
- Education Platforms - Content safety
We welcome contributions! Please see our Contributing Guide.
MIT License - see LICENSE
- npm: https://www.npmjs.com/package/tealtiger
- GitHub: https://github.com/agentguard-ai/tealtiger
- Python SDK: https://pypi.org/project/tealtiger/
- Issues: https://github.com/agentguard-ai/tealtiger/issues
If you find TealTiger useful, please give us a star on GitHub! β
Made with β€οΈ by the TealTiger team