Skip to main content
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.5.0 Discord

📖 Read the introduction blog post | 📚 Documentation

What's New in v1.5.0

  • PolicyHotSwapManager (tealtiger.core.engine.v1_3) — validate and hot-swap governance policy bundles at runtime. Schema, integrity hash, capability negotiation and signature checks; FREEZE rules persist across swaps and are never removed by a bundle that omits them. Bundle hashes are byte-compatible with the TypeScript SDK.
  • PolicyTester.test_policy() now raises instead of returning a false pass. It previously returned decision="allow" for every input, including policies that denied the request. Use PolicyTestRunner for real policy testing — see Policy Test Harness below.
  • Lint gate cleaned and ruff pinned, so it stops drifting stricter on its own.

Observe Mode (Zero-Config Adoption)

observe() — one line to instrument any LLM client with full visibility and an instant kill switch:

  • observe(client) — Zero-config proxy wrapping for any of 12 supported LLM providers
  • Automatic Cost Tracking — Per-request, per-session, per-agent cost accumulation across all providers
  • Behavioral Baseline — Statistical profiling (P50/P95/P99 latency, token distribution, cost patterns)
  • PII Detection (REPORT_ONLY) — Passive PII scanning without blocking — visibility before enforcement
  • freeze() / unfreeze() — Instant kill switch to halt any agent immediately, zero policy required
  • Structured Audit Trail — Every call logged with correlation IDs, cost, latency, and governance metadata
  • Governance Dashboard — Real-time overview with KPI metrics, defense pipeline, canary alerts, agent matrix
  • Under 5ms overhead — All instrumentation is in-process, deterministic, and offline-capable
pip install tealtiger

🚀 Quick Start

pip install tealtiger
import asyncio
from tealtiger import TealOpenAI, GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail

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

    # Create guarded client — drop-in replacement for OpenAI
    client = TealOpenAI(
        api_key="your-openai-key",
        agent_id="my-agent",
        guardrail_engine=engine
    )

    response = await client.chat.completions.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())

🌐 Supported Providers

Three clients are importable from the package root; the rest import from tealtiger.clients.

Provider Client Import from Models
OpenAI TealOpenAI tealtiger GPT-4, GPT-3.5 Turbo
Anthropic TealAnthropic tealtiger Claude 3, Claude 2
Azure TealAzureOpenAI tealtiger GPT-4, GPT-3.5
Google TealGemini tealtiger.clients Gemini Pro, Ultra
AWS TealBedrock tealtiger.clients Claude, Titan, Jurassic, Command, Llama
Cohere TealCohere tealtiger.clients Command, Embed
Mistral TealMistral ⚠️ see note Large, Medium, Small, Mixtral
from tealtiger import TealOpenAI
from tealtiger.clients import TealGemini

⚠️ TealMistral is currently broken. It imports the mistralai v0.x API (from mistralai.client import MistralClient), which v1.0 removed. Because the dependency floor is unbounded (mistralai>=0.1.0), any current mistralai install raises ImportError. Tracked separately — do not rely on this client until it is ported to the v1 API.

🛡️ 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(parallel_execution=True, 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, IBANs, passport numbers), 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,      # consecutive failures before opening
    timeout=30000,            # ms to wait before attempting to close
    half_open_requests=3      # successes in half-open before closing
)

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

TealAudit — Audit Logging & Redaction

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

from tealtiger import TealAudit, RedactionLevel
from tealtiger.core.audit.teal_audit import AuditConfig, ConsoleOutput

audit = TealAudit(
    outputs=[ConsoleOutput()],   # or CustomOutput for your own sink
    config=AuditConfig(
        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, ExecutionContextOptions

context = ContextManager.create_context(ExecutionContextOptions(
    tenant_id="acme-corp",
    application="customer-support",   # not `app`
    environment="production",         # not `env`
))

# Context propagates through TealEngine, TealAudit, and all providers
response = await client.chat.completions.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:

Use PolicyTestRunner, not PolicyTester. PolicyTester is a deprecated placeholder that never evaluated anything — as of v1.5.0 it raises NotImplementedError rather than returning a misleading allow.

from tealtiger import PolicyTestRunner, TestCorpora

tester = PolicyTestRunner(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 49 models and enforce spending limits:

from tealtiger import CostTracker, BudgetManager, InMemoryCostStorage, TokenUsage

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 — takes a TokenUsage, not a dict
estimate = tracker.estimate_cost(
    "gpt-4",
    TokenUsage(input_tokens=1000, output_tokens=500, total_tokens=1500),
    "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 covers 7 out of 10 OWASP ASIs through its SDK-only architecture:

ASI Vulnerability Coverage Components
ASI01 Goal Hijacking & Prompt Injection 🟡 Partial TealGuard, TealEngine
ASI02 Tool Misuse & Unauthorized Actions 🟢 Full TealEngine
ASI03 Identity & Access Control Failures 🟢 Full TealEngine
ASI04 Supply Chain Vulnerabilities 🔧 Support TealAudit
ASI05 Unsafe Code Execution 🟢 Full TealEngine
ASI06 Memory & Context Corruption 🟢 Full TealEngine, TealGuard
ASI07 Inter-Agent Communication Security ❌ Platform N/A
ASI08 Cascading Failures & Resource Exhaustion 🟢 Full TealCircuit
ASI09 Harmful Content Generation 🔧 Support TealGuard
ASI10 Rogue Agent Behavior 🟢 Full TealAudit

📖 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

Metadata

Release files for tealtiger 1.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tealtiger 1.5.0
File Size Uploaded
tealtiger-1.5.0.tar.gz 8.8 MB Details

Built distribution (wheel)

Table of built distributions (wheels) for tealtiger 1.5.0
File Interpreter ABI Platform
tealtiger-1.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 9.1 MB

Release files / tealtiger-1.5.0.tar.gz

Download URL tealtiger-1.5.0.tar.gz
Size 8.8 MB
Tags Source
SHA-256 checksum
How to use checksums
0e1ad48c06a698c90a95e1b6354ec295ee532d1c74063002dcde5748158e1a00
BLAKE2b-256 checksum
How to use checksums
676619a59dfa3392ed032533a22fdd1c93fc7f6e4cdfa2cc0944b585d12fce35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Release files / tealtiger-1.5.0-py3-none-any.whl

Download URL tealtiger-1.5.0-py3-none-any.whl
Size 284.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a379137246f28ee03c37764c46d84fa40d1054d9832550842a3b9220a564b3d8
BLAKE2b-256 checksum
How to use checksums
997b66137a915ba8513626cc5b6a70443901b6625dfac7b122251dcb557552d7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Release history Release notifications | RSS feed

This release

1.5.0 This release

2 release files

1.4.1

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page