Metadata-Version: 2.4
Name: tracetokens
Version: 1.0.0
Summary: Open-Source AI Observability Gateway, Token & Micro-Cost Engine
Author-email: Jinil Patel <ajinilpatel@gmail.com>
License: MIT
Keywords: ai,observability,llm-gateway,openai,vertex-ai,cost-tracking,token-counter,tracetokens
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.110.0
Requires-Dist: uvicorn[standard]>=0.28.0
Requires-Dist: pydantic>=2.6.0
Requires-Dist: pydantic-settings>=2.2.0
Requires-Dist: sqlalchemy>=2.0.28
Requires-Dist: aiosqlite>=0.20.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: tiktoken>=0.6.0
Requires-Dist: python-dotenv>=1.0.1

# 🌌 TraceTokens — Open-Source AI Observability & Gateway Platform

<p align="center">
  <img src="docs/assets/dashboard_preview.jpg" alt="TraceTokens AI Observability Dashboard" width="100%" style="border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);" />
</p>

<p align="center">
  <strong>The 1-Line Open-Source AI Observability Gateway, Token & Micro-Dollar Cost Engine.</strong><br>
  Track exact token consumption, micro-dollar costs, streaming TTFT latency, and PII guardrails across OpenAI, Anthropic Claude, Google Vertex AI / Gemini, DeepSeek, Groq, and local models.
</p>

<p align="center">
  <a href="https://pypi.org/project/tracetokens/"><img src="https://img.shields.io/badge/PyPI-v1.0.0-blue.svg?logo=pypi" alt="PyPI"></a>
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-indigo.svg" alt="License: MIT"></a>
  <a href="https://fastapi.tiangolo.com"><img src="https://img.shields.io/badge/Backend-FastAPI%200.110+-009688.svg?logo=fastapi" alt="FastAPI"></a>
  <a href="https://reactjs.org"><img src="https://img.shields.io/badge/Frontend-React%2018%20%2B%20Vite-61DAFB.svg?logo=react" alt="React"></a>
  <a href="https://hub.docker.com"><img src="https://img.shields.io/badge/Docker-Ready-2496ED.svg?logo=docker" alt="Docker"></a>
  <a href="https://github.com/jinilpatel7/TraceTokens"><img src="https://img.shields.io/github/stars/jinilpatel7/TraceTokens?style=social" alt="GitHub Stars"></a>

</p>


---

## 🧐 What is TraceTokens?

Modern AI applications send millions of prompts to LLM providers. Yet, engineering and platform teams face critical challenges:
1. **Unpredictable AI Bills & Runaway Costs:** No granular per-request dollar attribution for agents, microservices, or users.
2. **Opaque Streaming Latency:** Hard to track Time-To-First-Token (TTFT) and token generation speed across different models.
3. **Data Privacy & PII Leaks:** Customer emails, credit cards, SSNs, and credentials get sent unredacted to third-party model providers.
4. **Cloud Lock-in:** Difficult to stream trace metrics into enterprise data warehouses like **GCP BigQuery, AWS S3, Azure, or PostgreSQL**.

**TraceTokens** solves this with a lightweight **1-line Python SDK** and **Universal AI Gateway Proxy** that automatically calculates token counts, micro-dollar costs, measures latencies, scrubs PII, and streams traces to your cloud data warehouse — **costing you $0.00 in platform fees.**

---

## 📊 Live Observability Request Log Example

Every single inference through TraceTokens produces a rich, structured telemetry trace:

| Trace ID | Timestamp | Model | Provider | Input Tokens | Output Tokens | Total Tokens | TTFT | Latency | Request Cost ($ USD) | Status |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| `trc_8f2a1` | `09:30:15 UTC` | **GPT-4o** | OpenAI | 420 | 650 | 1,070 | 185ms | 540ms | **$0.007550** | `200 OK` |
| `trc_9c4b2` | `09:30:22 UTC` | **Claude 3.5 Sonnet**| Anthropic | 610 | 890 | 1,500 | 210ms | 780ms | **$0.015180** | `200 OK` |
| `trc_3e7d9` | `09:30:40 UTC` | **Gemini 2.0 Flash** | Google | 1,240 | 480 | 1,720 | 95ms | 320ms | **$0.000316** | `200 OK` |
| `trc_1a9f5` | `09:31:05 UTC` | **DeepSeek V3** | DeepSeek | 850 | 920 | 1,770 | 140ms | 460ms | **$0.000376** | `200 OK` |
| `trc_5d8c3` | `09:31:18 UTC` | **Llama 3.3 70B** | Groq | 320 | 410 | 730 | 80ms | 190ms | **$0.000512** | `200 OK` |

---

## 🚀 Instant 1-Line Drop-in (Zero Code Changes)

### 1. Install the Library
```bash
pip install tracetokens
```

### 2. Add 1 Line in Your Python Application
```python
import tracetokens

# 1-Line Auto-Instrumentation for OpenAI, Anthropic, Gemini, Vertex AI
tracetokens.init(project="Customer Support AI")

# Your existing code continues to work with ZERO modifications:
from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Analyze our quarterly cloud metrics."}]
)

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

# View real-time spend anywhere in your application:
print(tracetokens.get_spend())
# -> {'total_requests': 1, 'total_spend_usd': 0.000075, 'total_tokens': 240}
```

### 3. Open the Observability Dashboard Anytime
In your terminal, simply run:
```bash
tracetokens dashboard
```
Your browser will automatically open at `http://localhost:8000` with live KPI cards, spend trend charts, model distribution donuts, and deep request trace inspectors!

---

## ☁️ Multi-Cloud Enterprise Storage Matrix

TraceTokens is **100% cloud-agnostic**. You can run locally with zero-configuration SQLite or stream traces into any cloud data warehouse:

```python
import tracetokens

# 1. 🌐 Google Cloud Platform (GCP)
# GCP BigQuery Data Warehouse
tracetokens.init(project="GCP Pipeline", storage="bigquery://my-gcp-project.ai_analytics.traces")
# GCP Cloud SQL (PostgreSQL / MySQL)
tracetokens.init(project="GCP App", storage="postgresql://user:pass@/dbname?host=/cloudsql/project:region:instance")
# Google Cloud Storage (GCS)
tracetokens.init(project="GCP Data Lake", storage="gs://my-ai-traces-bucket/production/")

# 2. 🟧 Amazon Web Services (AWS)
# AWS RDS / Aurora (PostgreSQL / MySQL)
tracetokens.init(project="AWS Prod", storage="postgresql://admin:secret@aurora-cluster.us-east-1.rds.amazonaws.com:5432/tracetokens")
# Amazon S3 Bucket (JSONL / Parquet Data Lake)
tracetokens.init(project="AWS S3", storage="s3://my-enterprise-bucket/ai-observability/")
# Amazon Redshift
tracetokens.init(project="AWS Redshift", storage="redshift://awsuser:pwd@redshift-cluster.region.redshift.amazonaws.com:5439/dev")

# 3. 🔷 Microsoft Azure
# Azure Database for PostgreSQL / MySQL
tracetokens.init(project="Azure Service", storage="postgresql://user:pass@my-azure-db.postgres.database.azure.com:5432/traces?sslmode=require")
# Azure Blob Storage
tracetokens.init(project="Azure Lake", storage="azure://ai-container/traces/")

# 4. 🔴 Oracle Cloud Infrastructure (OCI)
# Oracle Autonomous Database / OCI PostgreSQL
tracetokens.init(project="OCI App", storage="oracle://admin:pwd@adb.us-ashburn-1.oraclecloud.com:1522/dbname")
# OCI Object Storage
tracetokens.init(project="OCI Storage", storage="oci://my-bucket@my-namespace/traces/")

# 5. ❄️ Snowflake & ClickHouse
# Snowflake Warehouse
tracetokens.init(project="Snowflake OLAP", storage="snowflake://user:pass@my-org-account/AI_DB/PUBLIC")
# ClickHouse Fast Analytics
tracetokens.init(project="ClickHouse", storage="clickhouse://default:pass@clickhouse-server:8123/default")

# 6. 🔀 Multi-Cloud Fan-Out (Store locally AND stream to AWS S3 + GCP BigQuery simultaneously!)
tracetokens.init(project="Enterprise Multi-Cloud", storage=[
    "sqlite://./local_cache.db",
    "s3://my-aws-bucket/traces/",
    "bigquery://gcp-project.dataset.traces"
])
```

---

## 💻 Integrations & Framework Examples

### 1. OpenAI SDK Drop-in Redirection
```python
from openai import OpenAI

# Simply redirect base_url to TraceTokens Gateway
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="aig_demo_sandbox_key"
)

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write an async worker in Python."}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

### 2. Google Vertex AI & Gemini
```python
import httpx

response = httpx.post(
    "http://localhost:8000/v1/chat/completions",
    headers={"Authorization": "Bearer aig_demo_sandbox_key"},
    json={
        "model": "gemini-2.0-flash",
        "messages": [{"role": "user", "content": "Analyze cloud sustainability patterns."}]
    }
)
print(response.json())
```

### 3. LangChain Drop-in
```python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-4o",
    openai_api_base="http://localhost:8000/v1",
    openai_api_key="aig_demo_sandbox_key"
)

response = llm.invoke("Explain RAG architectures.")
print(response.content)
```

### 4. cURL Direct HTTP Request
```bash
curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer aig_demo_sandbox_key" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "user", "content": "Hello TraceTokens!"}
    ],
    "stream": false
  }'
```

---

## 🔑 Virtual API Keys & Budget Governance

Issue scoped API keys to different microservices or team members with strict spending caps and rate limits:

- 🛑 **Hard / Soft Monthly Budget Caps:** Automatically returns `429 Too Many Requests` when a team reaches their budget limit (e.g. $50/month).
- 🚦 **Sliding-Window Rate Limiting:** Prevent provider outages with Requests Per Minute (RPM) and Tokens Per Minute (TPM) enforcement.
- 🎯 **Model Whitelisting:** Restrict specific keys to cheaper models (e.g. allow only `gpt-4o-mini` or `gemini-2.0-flash`).

---

## 🛡️ Automated PII Masking & Privacy Guardrail

TraceTokens automatically sanitizes sensitive personal data prior to database logging:
- **Email Addresses:** `john.doe@company.com` ➔ `[EMAIL_MASKED]`
- **Credit Cards:** `4532-1234-5678-9012` ➔ `[CARD_MASKED]`
- **Social Security Numbers (SSN):** `123-45-6789` ➔ `[SSN_MASKED]`
- **API Keys & Credentials:** `sk-proj-abc...` ➔ `[API_KEY_MASKED]`
- **Bearer Tokens:** `Bearer eyJhbGciOi...` ➔ `Bearer [TOKEN_MASKED]`

---

## 🚀 1-Click Dashboard Deployment

Deploy the dashboard and gateway to production for your entire company to access:

| Platform | Deployment Type | 1-Click Action |
| :--- | :--- | :--- |
| **Render.com** | Free Cloud Web Service | [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com) |
| **Railway.app** | 1-Click Container Service | [![Deploy on Railway](https://railway.app/button.svg)](https://railway.app) |
| **GCP Cloud Run** | Serverless Container | `gcloud run deploy tracetokens --image tracetokens:latest --port 8000` |
| **AWS App Runner / ECS** | Managed Container | `aws apprunner create-service --service-name tracetokens ...` |
| **Kubernetes (EKS/GKE/AKS)**| Cloud Cluster | `kubectl apply -f k8s-deployment.yaml` |
| **Docker Compose** | Self-Hosted VM / VPS | `docker compose up -d` |

---

## 📈 Supported Model Pricing Matrix ($ / 1 Million Tokens)

TraceTokens contains an accurate, dynamic pricing table for 50+ frontier models:

| Model | Provider | Input Cost / 1M | Output Cost / 1M | Cached Input / 1M | Context Window |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **GPT-4o** | OpenAI | `$2.50` | `$10.00` | `$1.25` | 128,000 |
| **GPT-4o Mini** | OpenAI | `$0.15` | `$0.60` | `$0.075` | 128,000 |
| **OpenAI o1** | OpenAI | `$15.00` | `$60.00` | `$7.50` | 200,000 |
| **OpenAI o3-mini** | OpenAI | `$1.10` | `$4.40` | `$0.55` | 200,000 |
| **Claude 3.5 Sonnet** | Anthropic | `$3.00` | `$15.00` | `$0.30` | 200,000 |
| **Claude 3.5 Haiku** | Anthropic | `$0.80` | `$4.00` | `$0.08` | 200,000 |
| **Gemini 2.0 Flash** | Google | `$0.10` | `$0.40` | `$0.025` | 1,048,576 |
| **Gemini 1.5 Pro** | Google / Vertex | `$1.25` | `$5.00` | `$0.3125` | 2,097,152 |
| **DeepSeek V3** | DeepSeek | `$0.14` | `$0.28` | `$0.014` | 64,000 |
| **DeepSeek R1** | DeepSeek | `$0.55` | `$2.19` | `$0.14` | 64,000 |
| **Llama 3.3 70B** | Groq | `$0.59` | `$0.79` | `$0.59` | 128,000 |

---

## 🛠️ CLI Reference

```bash
# Launch the Observability Dashboard
tracetokens dashboard

# View real-time spend summary in terminal
tracetokens stats

# Start the standalone OpenAI-compatible proxy gateway
tracetokens proxy --port 8000
```

---

## 🤝 Contributing & Community

Contributions are what make the open-source community such an amazing place to learn, inspire, and create! Any contributions you make are **greatly appreciated**.

- 🐛 **Report a Bug / Request a Feature:** Open an issue on GitHub.
- 💡 **Submit a Pull Request:** Fork the repo, create your feature branch, and submit a PR.
- ⭐ **Support the Project:** If TraceTokens helps your AI projects, please give it a **Star on GitHub** — it helps more developers discover the platform!

---

## 📬 Connect & Author

Created and maintained by **Jinil Patel**:

- 💼 **LinkedIn:** [Jinil Patel](https://www.linkedin.com/in/jinil-patel-2a738b201/)
- ✉️ **Email:** [ajinilpatel@gmail.com](mailto:ajinilpatel@gmail.com)
- 🌐 **GitHub:** [TraceTokens Repository](https://github.com/jinilpatel7/TraceTokens)


Feel free to connect for questions, collaborations, or feedback!

---

## 📄 License

Distributed under the **MIT License**. Free for commercial and open-source use.

