Metadata-Version: 2.4
Name: moven-sdk
Version: 0.2.0
Summary: The in-process circuit breaker for AI Agents. Intercept runaway loops and cost spikes in sub-millisecond real time.
Home-page: https://moven.dev
Author: Moven AI
Author-email: Moven AI <support@moven.dev>
License: MIT
Project-URL: Homepage, https://moven.dev
Project-URL: Documentation, https://moven.dev/docs
Project-URL: Repository, https://github.com/Moven-AI/moven-python-sdk
Project-URL: Tracker, https://github.com/Moven-AI/moven-python-sdk/issues
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: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.25.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.20.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Provides-Extra: all
Requires-Dist: langchain-core; extra == "all"
Requires-Dist: crewai; extra == "all"
Requires-Dist: openai; extra == "all"
Requires-Dist: anthropic; extra == "all"
Dynamic: author
Dynamic: home-page
Dynamic: requires-python

# ⚡ Moven Python SDK (`moven-sdk`)

> **The Synchronous Circuit Breaker for Autonomous AI Agents in Python.**
> Real-time, in-process safety fuses that detect runaway tool loops, hallucinated parameters, and cost spikes before your credit card burns.

[![PyPI version](https://img.shields.io/pypi/v/moven-sdk.svg?style=flat-square&color=0055FF)](https://pypi.org/project/moven-sdk/)
[![Python Version](https://img.shields.io/pypi/pyversions/moven-sdk.svg?style=flat-square)](https://pypi.org/project/moven-sdk/)
[![license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE)
[![Zero Latency](https://img.shields.io/badge/latency-%3C0.8ms-success.svg?style=flat-square)](#)

---

## 💡 Why Moven?

Observability platforms (LangSmith, Langfuse, Helicone) record what happened **after** your agent finishes. If your agent enters an unhandled 150-step loop at 2 AM, traditional tools show you a $300 bill in the morning.

**Moven sits synchronously in the execution loop**. It evaluates deterministic heuristics in **< 0.8ms** on every tool call and trips the fuse mid-flight before money burns.

---

## ✨ Core Capabilities

- ⚡ **Zero-Latency In-Memory Hot-Path**: In-memory static heuristics evaluate in `< 0.8ms` without network proxies.
- 🔁 **Canonical Deep Parameter Hashing**: SHA-256 canonical serialization detects duplicate parameter loops regardless of dict key order.
- 💸 **Dynamic Live Pricing Engine**: Real-time token math synced from `https://api.moven.dev/v1/models` calculates exact dollar savings when loops are intercepted.
- 🛡️ **Zero-Trust Hallucination Guard**: Intercepts unpopulated placeholder arguments (`TODO_...`, `REPLACE_ME`, `None`) and non-existent schema parameters.
- ⏪ **Ctrl+Z Step Checkpoints**: Automatically snapshots agent state & prompts before every tool execution for instant time-travel rewinds.
- 🤖 **Multi-Model Dynamic Auto-Fallback**: Automatically tracks token burn rates and provides in-memory model tiering.
- 🌐 **Python Framework Adapters**: Native support for LangChain, LangGraph, CrewAI, AutoGen, OpenAI Python SDK, Anthropic Python SDK, and custom functions via `@breaker.protect`.

---

## 📦 Installation

```bash
pip install moven-sdk
```

---

## 🚀 Quick Start Examples

### 1. Protect Agent Tools with Decorator

```python
from moven_sdk import MovenCircuitBreaker, BreakerConfig

# Initialize in-memory circuit breaker
breaker = MovenCircuitBreaker(
    BreakerConfig(
        project_id="a263283f-2d0b-4ce1-a40d-37103f09a160",
        max_repeats=3,               # Trip fuse after 3 identical tool calls
        spend_ceiling_usd=2.00,       # Stop runaway spend at $2.00
        max_turns=15,                 # Max recursion depth
        model_name="openai/gpt-4o",   # Used for real-time dollar calculation
    )
)

# Decorate any tool function
@breaker.protect
def query_vector_db(query: str, top_k: int = 5):
    # Your agent's tool execution logic
    return vector_store.similarity_search(query, k=top_k)
```

---

### 2. LangChain & LangGraph Callback Integration

```python
from moven_sdk import MovenCircuitBreaker, BreakerConfig
from moven_sdk.adapters.langchain import MovenLangChainCallbackHandler
from langchain_openai import ChatOpenAI

# Initialize circuit breaker and callback handler
breaker = MovenCircuitBreaker(
    BreakerConfig(
        project_id="my-langgraph-project",
        max_repeats=3,
        spend_ceiling_usd=1.50,
    )
)
handler = MovenLangChainCallbackHandler(breaker)

# Attach callback handler to your LLM or LangGraph workflow
llm = ChatOpenAI(model="gpt-4o", callbacks=[handler])
```

---

### 3. CrewAI Tool Integration

```python
from crewai import Agent, Task, Crew
from crewai.tools import tool
from moven_sdk import MovenCircuitBreaker, BreakerConfig

breaker = MovenCircuitBreaker(BreakerConfig(project_id="my-crewai-fleet"))

@tool("Search Internet")
@breaker.protect
def search_internet(query: str) -> str:
    """Searches the internet for relevant news."""
    return search_api.run(query)
```

---

### 4. Dynamic Live Model Pricing & Dollar Savings

Moven syncs live rates directly from `https://api.moven.dev/v1/models` and calculates accurate token and dollar savings when an infinite loop is aborted:

```python
from moven_sdk import MovenDynamicPricingEngine

# 0ms in-memory lookup synced with OpenRouter catalog
rates = MovenDynamicPricingEngine.get_model_rates("anthropic/claude-3.5-sonnet")
print(f"Claude Sonnet Input Rate: ${rates['prompt']}/1M tokens")

# Exact dollar savings calculation on tripped loops
savings = MovenDynamicPricingEngine.calculate_money_saved(
    model_name="openai/gpt-4o",
    total_tool_calls_made=5
)

print(f"Prevented Spend: ${savings['money_saved']} USD ({savings['prevented_tokens']:,} tokens prevented)")
```

---

## 🛠️ Python Framework Adapters Reference

| Framework | Exported Adapter |
| :--- | :--- |
| **Universal Function Decorator** | `@breaker.protect` |
| **LangChain / LangGraph** | `MovenLangChainCallbackHandler(breaker)` |
| **CrewAI** | `wrap_crewai_tool(breaker, func)` |
| **OpenAI Python SDK** | `MovenOpenAIWrapper(client, breaker)` |

---

## ⚙️ Configuration Reference (`BreakerConfig`)

```python
from moven_sdk import BreakerConfig

config = BreakerConfig(
    project_id="default",                       # Moven project ID
    agent_name="production_agent",             # Agent identifier
    max_repeats=3,                              # Trip on N consecutive identical tool invocations
    spend_ceiling_usd=2.00,                     # Maximum hard dollar spend ceiling
    max_turns=50,                               # Maximum execution steps per session
    model_name="openai/gpt-4o",                 # Model used for pricing calculation
    endpoint="https://api.moven.dev/events",    # Telemetry streaming endpoint
    strict_placeholders=True,                   # Block unpopulated template args (TODO_...)
    auto_heal_github=False,                     # Dispatch automated AST GitHub pull request
)
```

---

## 🧪 Running Tests

```bash
python -m pytest tests/
```

---

---

## 💬 Community & Support

- **Discord**: [Join the Moven Discord Community](https://discord.gg/Um6naf4c6Y)
- **Twitter / X**: [@movendev](https://x.com/movendev)
- **PyPI**: [pypi.org/project/moven-sdk](https://pypi.org/project/moven-sdk/0.1.0/)
- **Website**: [moven.dev](https://moven.dev)

---

## 📜 License

MIT © [Moven AI](https://moven.dev)

