README.md

May 28, 2026 ยท View on GitHub

TealTiger Logo

TealTiger Python SDK

The first open-source AI agent security SDK with client-side guardrails ๐Ÿ›ก๏ธ

PyPI version Python versions Tests License: Apache 2.0 Documentation v1.3.0 Discord


NVIDIA Inception Program

๐Ÿ“– Read the introduction blog post | ๐Ÿ“š Documentation

What's New in v1.3.0 โ€” Autonomous Agent Governance

TealTiger v1.3 introduces cryptographically verifiable governance for autonomous AI agents with 7 new modules:

  • TealEngineV13 โ€” Pre/post evaluation pipeline with FREEZE rules, automation levels, NHI verification
  • TealProof โ€” Cryptographic governance receipts (Merkle trees + RFC 3161 timestamping)
  • TealFlow โ€” Declarative YAML governance workflows with org-level inheritance
  • TealClassifier โ€” Local ONNX-based ML inference for content classification (โ‰ค20ms)
  • TealDrift โ€” Behavioral drift detection with statistical baselines
  • TealState โ€” Context size governance with provenance metadata
  • TealTemporal โ€” Session TTL, cooldown periods, time-of-day restrictions
  • TealMonitor v2 โ€” Governance-owned cost ceilings, anomaly detection, reasoning-token budgets
  • OWASP Agentic Top 10 Policy Pack โ€” Zero-config governance for all 10 ASI risks
  • Platform Adapters โ€” AWS Bedrock Agents, AWS AgentCore, Azure AI Agent Service
  • 12 LLM Providers โ€” Added DeepSeek, Groq, Together AI, HuggingFace TGI, xAI
pip install tealtiger==1.3.0
  • GovernanceDashboard โ€” Governance visibility UI
  • BundleExporter โ€” Evidence export in SARIF v2.1.0, JUnit XML, and JSON
  • Docker Sidecar โ€” Language-agnostic governance via POST /evaluate over HTTP
# Three ways to use TealTiger v1.2
npm install tealtiger                                              # TypeScript
pip install tealtiger                                              # Python
docker run -p 8080:8080 tealtigeradmin/tealtiger-typescript:1.2    # Any language

๐Ÿš€ Quick Start

pip install "tealtiger[openai]"

The base package keeps provider SDKs optional. Install only the provider extra you need:

pip install tealtiger                    # Core guardrails, governance, cost tracking
pip install "tealtiger[openai]"          # TealOpenAI
pip install "tealtiger[azure-openai]"    # TealAzureOpenAI
pip install "tealtiger[anthropic]"       # TealAnthropic
pip install "tealtiger[gemini]"          # TealGemini
pip install "tealtiger[bedrock]"         # TealBedrock
pip install "tealtiger[cohere]"          # TealCohere
pip install "tealtiger[mistral]"         # TealMistral
pip install "tealtiger[all]"             # All provider SDKs

Gemini provider support depends on google-generativeai, which requires Python 3.9+.

import asyncio
from tealtiger import (
    TealOpenAI,
    TealOpenAIConfig,
    GuardrailEngine,
    PIIDetectionGuardrail,
    PromptInjectionGuardrail,
)

async def main():
    # Set up guardrails
    engine = GuardrailEngine()
    engine.register_guardrail(PIIDetectionGuardrail())
    engine.register_guardrail(PromptInjectionGuardrail())

    # Create a guarded provider client using the canonical Python client API.
    config = TealOpenAIConfig(
        api_key="your-openai-key",
        agent_id="my-agent",
        guardrail_engine=engine,
        enable_cost_tracking=False,
    )
    client = TealOpenAI(config)

    response = await client.chat.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello!"}]
    )

    print(response.choices[0]["message"]["content"])
    print(f"Guardrails passed: {response.security.guardrail_result.passed}")

asyncio.run(main())

Provider clients from tealtiger.clients are the canonical public API for LLM calls and are also re-exported from tealtiger. The TealTiger class remains the sidecar/tool-execution client for policy evaluation workflows, not the provider-call API.

Async/Await Usage

The Python SDK exposes async methods for provider calls and guardrail execution. Initialize clients inside your async application, then await each API call.

import asyncio
from tealtiger.clients import TealOpenAI, TealOpenAIConfig


async def main():
    config = TealOpenAIConfig(
        api_key="your-openai-key",
        enable_guardrails=True,
        enable_cost_tracking=False,
    )
    client = TealOpenAI(config)

    response = await client.chat.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "Hello!"}],
    )

    print(response.choices[0]["message"]["content"])


asyncio.run(main())

Use an async context manager when you want the SDK to close the underlying async HTTP client automatically.

import asyncio
from tealtiger.clients import TealOpenAI, TealOpenAIConfig


async def main():
    config = TealOpenAIConfig(
        api_key="your-openai-key",
        enable_guardrails=True,
    )

    async with TealOpenAI(config) as client:
        response = await client.chat.create(
            model="gpt-4",
            messages=[{"role": "user", "content": "Hello!"}],
        )
        print(response.choices[0]["message"]["content"])


asyncio.run(main())

๐ŸŒ Supported Providers

95%+ market coverage with 7 LLM providers:

ProviderClientModelsFeaturesInstall extra
OpenAITealOpenAIGPT-4, GPT-3.5 TurboChat, Completions, Embeddingstealtiger[openai]
AnthropicTealAnthropicClaude 3, Claude 2Chat, Streamingtealtiger[anthropic]
GoogleTealGeminiGemini Pro, UltraMultimodal, Safety Settingstealtiger[gemini]
AWSTealBedrockClaude, Titan, Jurassic, Command, LlamaMulti-model, Regionaltealtiger[bedrock]
AzureTealAzureOpenAIGPT-4, GPT-3.5Deployment-based, Azure ADtealtiger[azure-openai]
MistralTealMistralLarge, Medium, Small, MixtralEU Data Residency, GDPRtealtiger[mistral]
CohereTealCohereCommand, EmbedRAG, Citations, Connectorstealtiger[cohere]

๐Ÿ›ก๏ธ Key Features

TealEngine โ€” Policy Evaluation

Deterministic policy evaluation with multi-mode enforcement:

from tealtiger import TealEngine, PolicyMode, DecisionAction, ReasonCode

engine = TealEngine(
    policies=my_policies,
    mode={
        "default_mode": PolicyMode.ENFORCE,       # or MONITOR, REPORT_ONLY
        "policy_modes": {
            "tools.file_delete": PolicyMode.ENFORCE,
            "identity.admin_access": PolicyMode.ENFORCE
        }
    }
)

decision = engine.evaluate({
    "agent_id": "agent-001",
    "action": "tool.execute",
    "tool": "file_delete",
    "correlation_id": "req-12345"
})

if decision.action == DecisionAction.ALLOW:
    await execute_tool()
elif decision.action == DecisionAction.DENY:
    if ReasonCode.TOOL_NOT_ALLOWED in decision.reason_codes:
        raise ToolNotAllowedError(decision.reason)
elif decision.action == DecisionAction.REQUIRE_APPROVAL:
    await request_approval(decision)

# Risk-based routing
if decision.risk_score > 80:
    await escalate_to_human(decision)

Decision fields: action (ALLOW, DENY, REDACT, TRANSFORM, REQUIRE_APPROVAL, DEGRADE), reason_codes (standardized enums), risk_score (0-100), correlation_id, metadata

TealGuard โ€” Security Guardrails

Client-side guardrails that run in milliseconds with no server dependency:

from tealtiger import GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail, ContentModerationGuardrail

engine = GuardrailEngine(mode="parallel", timeout=5000)

engine.register_guardrail(PIIDetectionGuardrail(action="redact"))
engine.register_guardrail(PromptInjectionGuardrail(sensitivity="high"))
engine.register_guardrail(ContentModerationGuardrail(threshold=0.7))

result = await engine.execute(user_input)
print(f"Passed: {result.passed}")
print(f"Risk Score: {result.risk_score}")

Detects: PII (emails, phones, SSNs, credit cards), prompt injection, jailbreaks, harmful content, custom patterns.

TealCircuit โ€” Circuit Breaker

Cascading failure prevention with automatic failover:

from tealtiger import TealCircuit

circuit = TealCircuit(
    failure_threshold=5,
    reset_timeout=30000,
    monitor_interval=10000
)

# Wraps provider calls with circuit breaker protection
response = await circuit.execute(
    lambda: client.chat.create(model="gpt-4", messages=messages)
)

TealAudit โ€” Audit Logging & Redaction

Versioned audit events with security-by-default PII redaction:

from tealtiger import TealAudit, RedactionLevel, FileOutput

audit = TealAudit(
    outputs=[FileOutput("./audit.log")],
    config={
        "input_redaction": RedactionLevel.HASH,    # SHA-256 hash + size (default)
        "output_redaction": RedactionLevel.HASH,
        "detect_pii": True,
        "debug_mode": False
    }
)

Redaction levels: HASH (default, production-safe), SIZE_ONLY, CATEGORY_ONLY, FULL, NONE (debug only).

Correlation IDs & Traceability

End-to-end request tracking across all components:

from tealtiger import ContextManager

context = ContextManager.create_context(
    tenant_id="acme-corp",
    app="customer-support",
    env="production"
)

# Context propagates through TealEngine, TealAudit, and all providers
response = await client.chat.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello"}],
    context=context
)

# Query audit logs by correlation_id
events = await audit.query(correlation_id=context.correlation_id)

Features: Auto-generated UUID v4 correlation IDs, OpenTelemetry-compatible trace IDs, HTTP header propagation, multi-tenant support.

Policy Test Harness

Validate policy behavior before production deployment:

from tealtiger import PolicyTester, TestCorpora

tester = PolicyTester(engine)
report = tester.run_suite({
    "name": "Customer Support Policy Tests",
    "tests": [
        {
            "name": "Block file deletion",
            "context": {"agent_id": "support-001", "action": "tool.execute", "tool": "file_delete"},
            "expected": {"action": DecisionAction.DENY, "reason_codes": [ReasonCode.TOOL_NOT_ALLOWED]}
        },
        *TestCorpora.prompt_injection(),
        *TestCorpora.pii_detection()
    ]
})

print(f"Tests: {report.passed}/{report.total} passed")
# CLI usage
python -m tealtiger.cli.test ./policies/*.test.json --coverage --format=junit --output=./results.xml

Cost Tracking & Budget Management

Track costs across 50+ models and enforce spending limits:

from tealtiger import CostTracker, BudgetManager, InMemoryCostStorage

storage = InMemoryCostStorage()
tracker = CostTracker()
budget_manager = BudgetManager(storage)

budget_manager.create_budget({
    "name": "Daily GPT-4 Budget",
    "limit": 10.0,
    "period": "daily",
    "alert_thresholds": [50, 75, 90, 100],
    "action": "block",
    "enabled": True
})

# Estimate before request
estimate = tracker.estimate_cost("gpt-4", {"input_tokens": 1000, "output_tokens": 500}, "openai")

# Check budget
check = await budget_manager.check_budget("agent-123", estimate)
if not check.allowed:
    print(f"Blocked by: {check.blocked_by.name}")

๐Ÿ›ก๏ธ OWASP Top 10 for Agentic Applications Coverage

TealTiger v1.2.0 covers 7 out of 10 OWASP ASIs through its SDK-only architecture:

ASIVulnerabilityCoverageComponents
ASI01Goal Hijacking & Prompt Injection๐ŸŸก PartialTealGuard, TealEngine
ASI02Tool Misuse & Unauthorized Actions๐ŸŸข FullTealEngine
ASI03Identity & Access Control Failures๐ŸŸข FullTealEngine
ASI04Supply Chain Vulnerabilities๐Ÿ”ง SupportTealAudit
ASI05Unsafe Code Execution๐ŸŸข FullTealEngine
ASI06Memory & Context Corruption๐ŸŸข FullTealEngine, TealGuard
ASI07Inter-Agent Communication SecurityโŒ PlatformN/A
ASI08Cascading Failures & Resource Exhaustion๐ŸŸข FullTealCircuit
ASI09Harmful Content Generation๐Ÿ”ง SupportTealGuard
ASI10Rogue Agent Behavior๐ŸŸข FullTealAudit

๐Ÿ“– Complete OWASP ASI Mapping | OWASP Top 10 for Agentic Applications

๐ŸŽฏ 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 and audit trails
  • Education Platforms โ€” Content safety

๐Ÿ“š Documentation

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide.

๐Ÿ“„ License

Apache 2.0 โ€” see LICENSE


Made with โค๏ธ by the TealTiger team