Metadata-Version: 2.4
Name: computecapx
Version: 0.1.0
Summary: Enterprise FinOps & AI governance SDK — monitor costs, enforce budgets, and prevent runaway AI loops across every cloud provider.
Author-email: computecapx <computecapx@gmail.com>
Maintainer-email: computecapx <computecapx@gmail.com>
Project-URL: Homepage, https://computecapx.com
Project-URL: Documentation, https://computecapx.com/docs
Project-URL: Repository, https://github.com/computecapx/computecapx-python
Project-URL: Bug Tracker, https://github.com/computecapx/computecapx-python/issues
Project-URL: Changelog, https://github.com/computecapx/computecapx-python/blob/main/CHANGELOG.md
Keywords: finops,ai,monitoring,llm,cost,governance,openai,anthropic,gemini,cloud,telemetry,observability
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: Office/Business :: Financial
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
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: Programming Language :: Python :: 3 :: Only
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Requires-Dist: psutil>=5.9.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Dynamic: license-file

# ComputeCapX Python SDK

[![PyPI version](https://badge.fury.io/py/computecapx.svg)](https://badge.fury.io/py/computecapx)
[![Python versions](https://img.shields.io/pypi/pyversions/computecapx.svg)](https://pypi.org/project/computecapx/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

The official Python SDK for [ComputeCapX](https://computecapx.com) — enterprise FinOps and AI governance. Monitor AI API costs, enforce budget policies, detect runaway agent loops, and stream real-time infrastructure telemetry across every major cloud provider — with **zero code changes** to your existing AI calls.

---

## Features

- **Universal AI Instrumentation** — Automatically intercepts OpenAI, Anthropic, Google Gemini, Groq, Mistral, Cohere, and any HTTP-based LLM API. No code changes required.
- **Real-time Budget Enforcement** — Blocks API calls the moment a project exceeds its budget limit. The block is synchronous and cannot be bypassed.
- **Runaway Loop Circuit Breaker** — Detects and throttles AI agent feedback loops with three escalation tiers before they cause financial damage.
- **Multi-Cloud Infrastructure Telemetry** — Auto-detects AWS, GCP, Azure, Oracle Cloud, DigitalOcean, Vercel, and Netlify via metadata APIs with no configuration.
- **Distributed Tracing** — Captures network calls (urllib3), database queries (SQLite, PostgreSQL), and AI call chains for full cost attribution per trace.
- **Crash Handler** — Hooks `sys.excepthook` to emit a final trace on fatal errors so every execution has a complete record.
- **Zero-Code CLI Mode** — Use `computecapx-run` to instrument any existing script or server without touching its source.
- **Non-Blocking** — All telemetry is batched and sent asynchronously. Zero impact on your application latency.

---

## Installation

```bash
pip install computecapx
```

**Requirements:** Python 3.8+

---

## Quick Start

### Option 1: Zero-code CLI wrapper (Recommended)

No code changes required. Save your credentials once and run any script with full telemetry.

```bash
# 1. Install the SDK
pip install computecapx

# 2. Save credentials once
computecapx login --key YOUR_API_KEY --project YOUR_PROJECT_ID

# 3. Run any script or server with full monitoring
computecapx-run python my_agent.py
computecapx-run uvicorn app:main
computecapx-run --no-cloud python my_local_script.py
```

That's it. No imports, no code changes, no `.env` files.

---

### Option 2: Environment Variables

Set your credentials in your shell or deployment platform and the SDK picks them up automatically.

```bash
export COMPUTECAPX_API_KEY=your_api_key_here
export COMPUTECAPX_PROJECT_ID=your_project_id_here
```

```python
import computecapx
computecapx.instrument()  # reads from env vars automatically

import openai
client = openai.OpenAI(api_key="sk-...")
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)
```

---

### Option 3: Pass credentials directly (Testing only)

You can pass credentials directly in code. This is useful for quick testing, or if you are dynamically loading keys from a secret manager (like AWS Secrets Manager).

> **Warning:** Do not hardcode credentials in production or commit them to version control.

```python
import computecapx

computecapx.instrument(
    api_key="YOUR_API_KEY",
    project_id="YOUR_PROJECT_ID",
)
```

---

## Environment Variables

| Variable | Description |
|---|---|
| `COMPUTECAPX_API_KEY` | Your SDK API key |
| `COMPUTECAPX_PROJECT_ID` | Your project ID |
| `COMPUTECAPX_DISABLE_LOOP_CHECK` | Set to `true` to disable the AI loop circuit breaker |

---

## `instrument()` Reference

```python
computecapx.instrument(
    api_key=None,               # SDK API key (or set COMPUTECAPX_API_KEY)
    project_id=None,            # Project ID (or set COMPUTECAPX_PROJECT_ID)
    claim_infrastructure=True,  # Send cloud heartbeats — set False for local dev
    instrument_ai=True,         # Intercept AI calls and enforce policies
    backend_url=None,           # Override backend (self-hosted only)
)
```

**Credential resolution order:**
1. Direct argument
2. Environment variable (`COMPUTECAPX_API_KEY` / `COMPUTECAPX_PROJECT_ID`)
3. CLI config file (`~/.computecapx/config.json` written by `computecapx login`)

---

## CLI Commands

```bash
# Authenticate and save credentials to ~/.computecapx/config.json
computecapx login --key YOUR_API_KEY --project YOUR_PROJECT_ID

# Update the default project
computecapx set-project YOUR_PROJECT_ID

# Run diagnostics and test backend connectivity
computecapx status
```

---

## `computecapx-run` Flags

```bash
computecapx-run [flags] <script.py or module> [script args...]

  --no-cloud    Disable infrastructure heartbeats (auto-enabled on local)
  --no-ai       Disable AI call interception
  --no-loop     Disable the runaway loop circuit breaker
```

---

## Runaway Loop Circuit Breaker

The circuit breaker automatically detects repetitive AI agent patterns:

| Tier | Trigger | Action |
|---|---|---|
| Warning | 5 similar requests in 10 seconds | 2-second throttle applied |
| Throttle | 10 similar requests in 20 seconds | 5-second throttle applied |
| Block | 20 requests in 60 seconds | `ComputeCapAILoopBlocker` raised, task permanently blocked |

---

## Supported AI Providers

| Provider | Detection Method |
|---|---|
| OpenAI | HTTP intercept (httpx + requests) |
| Anthropic | HTTP intercept (httpx + requests) |
| Google Gemini | HTTP intercept + gRPC (`sys.meta_path` hook) |
| Groq | HTTP intercept |
| Mistral | HTTP intercept |
| Cohere | HTTP intercept |
| Any OpenAI-compatible API | HTTP intercept |

---

## Supported Cloud Providers

| Provider | Detection Method |
|---|---|
| AWS EC2 | IMDSv2 token + metadata endpoint |
| Google Cloud (GCP) | Compute Metadata Server |
| Microsoft Azure | Instance Metadata Service |
| DigitalOcean | Droplet Metadata API |
| Oracle Cloud (OCI) | OPCv2 metadata endpoint |
| Vercel | `VERCEL` environment variable |
| Netlify | `NETLIFY` environment variable |
| Local / Container | Hostname fallback |

---

## Error Classes

Both errors inherit from `BaseException` so they cannot be accidentally swallowed by a bare `except Exception` in user code.

```python
from computecapx import ComputeCapBudgetExceededError, ComputeCapAILoopBlocker

try:
    response = openai_client.chat.completions.create(...)
except ComputeCapBudgetExceededError:
    print("Monthly budget limit reached — request blocked by ComputeCapX.")
except ComputeCapAILoopBlocker:
    print("Runaway agent loop detected — task permanently halted.")
```

---

## License

MIT License — see [LICENSE](LICENSE) for details.

© 2026 [ComputeCapX](https://computecapx.com)
