Metadata-Version: 2.5
Name: oridio
Version: 0.1.0
Summary: Official Python SDK for Oridio — AI Control Plane
Project-URL: Homepage, https://oridio.org
Project-URL: Repository, https://github.com/Oridio-org/ORIDIO
Project-URL: Documentation, https://oridio.org/docs
Author-email: Oridio <team@oridio.org>
License: Apache-2.0
Keywords: ai,control-plane,langchain,langgraph,llm,openai,proxy
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: httpx>=0.27.0
Requires-Dist: opentelemetry-api>=1.20.0
Requires-Dist: opentelemetry-instrumentation-httpx>=0.45b0
Requires-Dist: opentelemetry-instrumentation-requests>=0.45b0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: typing-extensions>=4.0.0
Requires-Dist: websockets>=12.0
Provides-Extra: dev
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Requires-Dist: types-requests; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-openai>=0.1.0; extra == 'langchain'
Description-Content-Type: text/markdown

# Oridio Python SDK

[![PyPI version](https://badge.fury.io/py/oridio.svg)](https://badge.fury.io/py/oridio)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

The official Python SDK for [Oridio](https://oridio.org) — the Enterprise AI Control Plane.

Oridio is a high-performance, drop-in OpenAI-compatible proxy that provides:
- 🛡️ **Policy Enforcement:** Set cost limits, redact PII, block toxic content, and detect prompt injections before they reach the LLM.
- ⚡ **Semantic Caching:** Serve identical or semantically similar requests instantly from cache, saving tokens and reducing latency.
- 🔀 **Intelligent Routing:** Automatically route requests to fallback models when primary providers experience downtime.
- 📊 **Observability & Audit:** Full telemetry, usage analytics, and SOC2-compliant audit logs.
- 🤖 **Agent-Ready:** Native integration with LangGraph, CrewAI, and other agentic frameworks out of the box.

## Installation

Install the base package:
```bash
pip install oridio
```

If you are using LangChain, you can install the optional dependencies:
```bash
pip install "oridio[langchain]"
```

## Quick Start

### 1. Drop-in OpenAI Replacement

Use the `OridioClient` exactly as you would use the `OpenAI` client. All your existing code will continue to work, but with added security and caching.

```python
import oridio

client = oridio.OridioClient(
    api_key="sk-or-your-key",
    proxy_url="http://localhost:8080",      # Point to your Oridio proxy
)

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Explain quantum computing in one sentence."}],
)
print(response.choices[0].message.content)
print(f"Cache hit: {response.cache_hit}")  # True on repeated or similar requests
```

### 2. LangGraph / LangChain Integration (Zero Code Change)

Because Oridio acts as an OpenAI-compatible endpoint, integrating with LangChain is as simple as overriding the `base_url`.

```python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-4o",
    base_url="http://localhost:8080/v1",    # Point to your Oridio proxy
    api_key="sk-or-your-key",
)
```

### 3. Asynchronous Usage

For high-throughput or asynchronous applications, use the `AsyncOridioClient`.

```python
import asyncio
from oridio import AsyncOridioClient

async def main():
    async with AsyncOridioClient(api_key="sk-or-your-key") as client:
        response = await client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": "Hello async!"}],
        )
        print(response.choices[0].message.content)

asyncio.run(main())
```

## Advanced Policy Management

The SDK also allows you to interact with the **Oridio Control Plane** to manage policies programmatically.

```python
client = oridio.OridioClient(
    admin_token="your-admin-token",
    control_plane_url="http://localhost:3000",
)

# Create an advanced policy for cost optimization and safety
policy = client.policies.create({
    "name": "strict-production-guardrails",
    "rules": [
        {
            "id": "cost-limit",
            "name": "Daily Cost Limit",
            "action": "block",
            "conditions": {"cost_limit": {"daily_usd": 100}}
        },
        {
            "id": "pii-redaction",
            "name": "Redact Sensitive Info",
            "action": "redact",
            "pii_types": ["EMAIL", "CREDIT_CARD", "SSN"]
        }
    ]
})

# Deploy the policy to all active Data Planes (Proxies)
client.policies.deploy(policy.id)
print(f"Deployed policy: {policy.name}")
```

## Error Handling

Oridio provides strongly-typed exceptions so your applications can react gracefully to policy blocks or rate limits.

```python
from oridio import OridioPolicyBlockedError, OridioRateLimitError, OridioAuthError

try:
    response = client.chat.completions.create(model="gpt-4o", messages=[...])
except OridioPolicyBlockedError as e:
    # Handle requests blocked by your custom guardrails (e.g., PII detected, cost limit exceeded)
    print(f"🚨 Request Blocked: {e.reason}")
    print(f"Triggered Rules: {e.rules_matched}")
except OridioRateLimitError as e:
    # Handle Oridio or provider rate limits
    print(f"⏳ Rate limited. Retry after {e.retry_after} seconds.")
except OridioAuthError:
    print("❌ Invalid API key.")
```

## API Key Management & Usage Analytics

Manage programmatic access and track spend:

```python
# Create a scoped key
key = client.keys.create(name="production-backend-key", spend_limit_usd=50)
print(f"Secret: {key.secret}")  # Store securely! Only shown once.

# Track Usage
records = client.usage.list(limit=100)
total_cost = sum(r.estimated_cost_usd for r in records)
cache_hits = sum(1 for r in records if r.cache_hit)
print(f"Total spend: ${total_cost:.4f} | Cache hits: {cache_hits}/{len(records)}")
```

## Examples

See [`examples/`](../../examples/) for full working demos:
- `basic_proxy.py` — Simple script showing basic chat completion via Oridio.
- `advanced_policy.py` — Demonstrates catching and handling policy enforcement blocks.
- `langgraph_example.py` — LangGraph ReAct agent with policy enforcement.
- `crewai_example.py` — Multi-agent CrewAI pipeline with cost tracking.

---

## Known Limitations & Intentional Gaps

| Feature | Status | Notes |
|---|---|---|
| `keys.create()` response | Fixed in SDK | CP returns `{"status": "success", "data": {"id": ..., "key": ...}}`. The SDK unwraps this and normalises `key` → `secret`. |
| `keys.list()` response | Handled | CP may return a flat array or `{"data": [...]}` — both are handled. |
| `estimated_cost_usd` for unknown models | By design | When `estimated_cost_known=False`, cost is `0.0` (not a real zero). Do not aggregate for spend reporting without checking this flag. |
| `McpServer.sandbox_preference` | Documented | Default is `"process"`. Firecracker requires KVM-capable Linux hosts; will hard-deny when `require_strong_isolation=True` and Firecracker is unavailable. |
| Async MCP client | Not yet implemented | `AsyncOridioClient` exposes `chat.completions.create` but not the full MCP management API. Use the synchronous `OridioClient` for MCP admin operations. |
| Admin dashboard | Deferred | No web UI. All operations use this SDK or the REST API directly. |
| SSO / SAML | Not implemented | Auth is via static admin token or JWT. |
