Skip to content

TypeScript/JavaScript SDK for AI Agent Security - Drop-in security for LangChain, CrewAI, AutoGPT and custom agents

License

Notifications You must be signed in to change notification settings

agentguard-ai/tealtiger-typescript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
TealTiger Logo

TealTiger SDK

The first open-source AI agent security SDK with client-side guardrails πŸ›‘οΈ

npm version npm downloads Tests License: MIT TypeScript

✨ What's New in v1.0.0

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

πŸš€ Quick Start

Installation

npm install tealtiger

Client-Side Guardrails (New!)

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

Server-Side Security

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

πŸ›‘οΈ Client-Side Guardrails

PIIDetectionGuardrail

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

ContentModerationGuardrail

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 = 85

PromptInjectionGuardrail

Prevent 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 = 90

Detects:

  • Instruction injection
  • Role-playing attacks
  • System prompt leakage
  • DAN jailbreaks
  • Developer mode attempts

GuardrailEngine

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

πŸ’° Cost Tracking & Budget Management

Track AI model costs and enforce budgets automatically:

Cost Estimation

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

Actual Cost Tracking

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

Budget Management

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

Agent-Scoped Budgets

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

Supported Models

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 Client Wrappers

TealOpenAI

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

TealAnthropic

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)

TealAzureOpenAI

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

Custom Pricing

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

πŸ“‹ Features

Client-Side (Offline)

  • πŸ” 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

Server-Side (Platform)

  • πŸ” 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

🎯 Use Cases

  • 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

πŸ“š Documentation

🀝 Contributing

We welcome contributions! Please see our Contributing Guide.

πŸ“„ License

MIT License - see LICENSE

πŸ”— Links

🌟 Star Us!

If you find TealTiger useful, please give us a star on GitHub! ⭐


Made with ❀️ by the TealTiger team

About

TypeScript/JavaScript SDK for AI Agent Security - Drop-in security for LangChain, CrewAI, AutoGPT and custom agents

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published