# novyx-langchain

[![PyPI version](https://img.shields.io/pypi/v/novyx-langchain.svg)](https://pypi.org/project/novyx-langchain/)
[![Python versions](https://img.shields.io/pypi/pyversions/novyx-langchain.svg)](https://pypi.org/project/novyx-langchain/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Downloads](https://img.shields.io/pypi/dm/novyx-langchain.svg)](https://pypi.org/project/novyx-langchain/)

**Persistent memory + rollback + audit trail for LangChain agents.**

The ONLY LangChain memory provider with Magic Rollback, cryptographic audit trails, and compliance-grade trace logging.

```python
from novyx_langchain import NovyxMemory
from langchain.chains import ConversationChain
from langchain_openai import ChatOpenAI

memory = NovyxMemory(api_key="nram_xxx", session_id="user-123")
chain = ConversationChain(llm=ChatOpenAI(), memory=memory)

response = chain.invoke({"input": "My name is Alice"})

# NEW in v2.0: Rollback mistakes
memory.rollback("2 hours ago")

# Cryptographic audit trail
audit = memory.audit(limit=50)
```

## What's New in v2.0

- **🔙 Magic Rollback** - Undo memory mistakes with time-travel (`memory.rollback("2 hours ago")`)
- **📜 Cryptographic Audit Trail** - SHA-256 hashing, tamper detection, built into all tiers
- **🔐 Trace Audit** - Compliance-grade logging with RSA signatures (Pro+)
- **🚀 Unified API** - All features in one package powered by Novyx Core

## Features

### Core Features (All Tiers)

- **Semantic retrieval** - Finds relevant context, not just recent messages
- **LangGraph native** - First-class checkpointer support with rollback
- **Multi-tenant** - Built for production SaaS applications
- **< 100ms latency** - Fast semantic search via Novyx Core
- **Cryptographic audit** - SHA-256 hashing on all writes (retention varies by tier)

### Pro+ Features

- **Magic Rollback** - Time-travel debugging for memory
- **Trace audit** - RSA-signed compliance logging
- **Extended retention** - 30+ day audit retention
- **Audit export** - CSV/JSON export of full audit trail
- **Anomaly detection** - Real-time alerts on suspicious patterns

## Installation

```bash
pip install novyx-langchain
```

For LangGraph support:
```bash
pip install "novyx-langchain[langgraph]"
```

## Quick Start

### 1. Get an API Key

Sign up at [novyxlabs.com](https://novyxlabs.com) to get your API key.

### 2. Basic Memory with Rollback

```python
from novyx_langchain import NovyxMemory
from langchain.chains import ConversationChain
from langchain_openai import ChatOpenAI

# Create persistent memory
memory = NovyxMemory(
    api_key="nram_tenant_xxx",
    session_id="user-123",
    k=10,  # Retrieve top 10 relevant memories
)

# Use with any LangChain chain
chain = ConversationChain(
    llm=ChatOpenAI(model="gpt-4"),
    memory=memory,
)

# Conversations persist automatically
response = chain.invoke({"input": "Remember that I prefer dark mode"})

# Made a mistake? Roll back!
memory.rollback("1 hour ago")

# View audit trail
audit = memory.audit(limit=50)
for entry in audit:
    print(f"{entry['timestamp']}: {entry['operation']}")
```

### 3. LangGraph Checkpointer with Rollback

```python
from langgraph.graph import StateGraph, END
from novyx_langchain import NovyxCheckpointer

# Create checkpointer
checkpointer = NovyxCheckpointer(api_key="nram_tenant_xxx")

# Build your graph
builder = StateGraph(AgentState)
builder.add_node("agent", agent_node)
builder.add_node("tools", tool_node)
builder.set_entry_point("agent")
builder.add_edge("agent", END)

# Compile with persistence
graph = builder.compile(checkpointer=checkpointer)

# Run with thread_id
config = {"configurable": {"thread_id": "conv-123"}}
result = graph.invoke({"messages": [HumanMessage("Hello!")]}, config)

# NEW: Rollback checkpoint to any point
checkpointer.rollback_to_checkpoint(
    thread_id="conv-123",
    checkpoint_id="abc123"
)
```

### 4. Integrity-Protected Memory

```python
from novyx_langchain import NovyxIntegrityMemory

# Cryptographic audit trail built-in (no extra credentials needed)
memory = NovyxIntegrityMemory(
    api_key="nram_tenant_xxx",
    session_id="user-123"
)

chain = ConversationChain(llm=llm, memory=memory)

# All writes are cryptographically audited
response = chain.invoke({"input": "Store sensitive context"})

# Verify audit integrity
verification = memory.verify_audit()
if verification['valid']:
    print(f"✅ Verified {verification['total_entries']} audit entries")
else:
    print(f"⚠️ Integrity issues: {verification['errors']}")
```

### 5. Compliance Mode (Pro+)

```python
from novyx_langchain import NovyxTracedMemory

# Automatically traces all memory operations
memory = NovyxTracedMemory(
    api_key="nram_tenant_xxx",
    session_id="user-123",
    agent_id="my-agent",
    trace_reads=False,  # Optional: trace read operations (verbose)
)

chain = ConversationChain(llm=llm, memory=memory)

# Every memory operation is automatically logged with RSA signature
response = chain.invoke({"input": "Remember my credit card ends in 1234"})

# Complete trace (auto-completed on cleanup)
result = memory.complete_trace()
print(f"Trace signature: {result['signature'][:32]}...")
print(f"Total steps: {result['total_steps']}")

# Verify trace integrity
verification = memory.verify_trace()
if verification['valid']:
    print(f"✅ Verified {verification['steps_verified']} trace steps")
```

## API Reference

### NovyxMemory

Main memory class, compatible with `ConversationBufferMemory`.

```python
NovyxMemory(
    api_key: str,              # Novyx API key
    session_id: str,           # Unique session identifier
    k: int = 10,               # Number of memories to retrieve
    semantic_search: bool = True,  # Use semantic (vs recency) retrieval
    return_messages: bool = False,  # Return Message objects vs string
    min_relevance: float = 0.3,    # Minimum relevance score
)
```

**Core Methods:**
- `load_memory_variables(inputs)` - Load relevant memories
- `save_context(inputs, outputs)` - Save conversation turn
- `clear()` - Clear session memory
- `search(query, limit)` - Semantic search
- `store_memory(content, tags, importance)` - Store custom memory

**NEW in v2.0 - Rollback & Audit:**
- `rollback(target, dry_run=False)` - Rollback to timestamp/relative time (Pro+)
- `rollback_preview(target)` - Preview rollback changes (Pro+)
- `audit(limit, operation)` - Get audit trail entries
- `audit_export(format)` - Export audit log (Pro+)
- `usage()` - Get current usage vs limits

### NovyxChatMessageHistory

For use with `RunnableWithMessageHistory`:

```python
from langchain_core.runnables.history import RunnableWithMessageHistory
from novyx_langchain import NovyxChatMessageHistory

def get_session_history(session_id: str):
    return NovyxChatMessageHistory(
        api_key="nram_xxx",
        session_id=session_id,
    )

chain_with_history = RunnableWithMessageHistory(
    chain,
    get_session_history,
)
```

### NovyxCheckpointer

LangGraph checkpoint persistence:

```python
NovyxCheckpointer(
    api_key: str,              # Novyx API key
    namespace: str = "langgraph",  # Namespace for isolation
)
```

**Methods:**
- `put(config, checkpoint, metadata)` - Store checkpoint
- `get_tuple(config)` - Get checkpoint
- `list(config)` - List checkpoints
- `clear_thread(thread_id)` - Clear thread checkpoints

**NEW in v2.0 - Rollback:**
- `rollback_to_checkpoint(thread_id, checkpoint_id, dry_run=False)` - Rollback to specific checkpoint (Pro+)
- `rollback_thread(thread_id, target, dry_run=False)` - Rollback thread to relative time (Pro+)

### NovyxIntegrityMemory

Memory with cryptographic audit trail:

```python
NovyxIntegrityMemory(
    api_key: str,              # Novyx API key
    session_id: str,
    verify_on_read: bool = False,  # Verify audit on every read
    audit_checks: bool = True,     # Enable automatic audit checks
    # ... same options as NovyxMemory
)
```

**Additional Methods:**
- `verify_audit()` - Verify cryptographic integrity
- `get_audit_summary(limit)` - Get audit summary stats
- `export_audit(format, output_file)` - Export audit trail (Pro+)
- `rollback_with_verification(target, dry_run)` - Rollback + verify (Pro+)

### NovyxTracedMemory (Pro+)

Compliance-grade memory with automatic trace logging:

```python
NovyxTracedMemory(
    api_key: str,              # Novyx API key (must be Pro+ tier)
    session_id: str,
    agent_id: str = "langchain-agent",  # Agent identifier for tracing
    trace_reads: bool = False,  # Trace read operations (verbose)
    # ... same options as NovyxMemory
)
```

**Additional Methods:**
- `complete_trace()` - Complete trace with RSA signature
- `verify_trace()` - Verify trace integrity
- `get_trace_status()` - Get current trace status

## Examples

### Multi-Tenant Setup

```python
def get_memory_for_user(user_id: str, tier: str = "free") -> NovyxMemory:
    return NovyxMemory(
        api_key=f"nram_{tenant_id}_xxx",  # Tenant-specific key
        session_id=f"user-{user_id}",
        k=20 if tier == "pro" else 10,  # More memories for Pro users
    )

# Each user has isolated memory
alice_memory = get_memory_for_user("alice", tier="pro")
bob_memory = get_memory_for_user("bob", tier="free")
```

### Rollback After Error

```python
memory = NovyxMemory(api_key="nram_xxx", session_id="user-123")

# Store some memories
chain = ConversationChain(llm=llm, memory=memory)
response = chain.invoke({"input": "My password is hunter2"})  # Oops!

# Preview rollback
preview = memory.rollback_preview("1 minute ago")
print(f"Will restore {preview['artifacts_modified']} memories")

# Execute rollback
result = memory.rollback("1 minute ago")
print(f"Rolled back to {result['rolled_back_to']}")
```

### Audit Compliance

```python
memory = NovyxIntegrityMemory(api_key="nram_xxx", session_id="user-123")

# Run your agent
# ... agent operations ...

# Get audit summary
summary = memory.get_audit_summary(limit=100)
print(f"Total operations: {summary['total_operations']}")
print(f"Creates: {summary['by_type']['CREATE']}")
print(f"Deletes: {summary['by_type']['DELETE']}")
print(f"Integrity valid: {summary['integrity_valid']}")

# Export for compliance
memory.export_audit(format="csv", output_file="audit_2026-02.csv")
```

### Trace Audit for Compliance

```python
memory = NovyxTracedMemory(
    api_key="nram_xxx",
    session_id="user-123",
    agent_id="customer-support-bot"
)

# All operations are automatically traced
chain = ConversationChain(llm=llm, memory=memory)

for user_input in customer_conversation:
    response = chain.invoke({"input": user_input})

# Complete trace with RSA signature
result = memory.complete_trace()
print(f"Trace ID: {result['trace_id']}")
print(f"Signature: {result['signature']}")
print(f"Signed at: {result['signed_at']}")

# Verify later for compliance
verification = memory.verify_trace()
print(f"Trace valid: {verification['valid']}")
```

## Comparison

**novyx-langchain is the ONLY LangChain memory provider with rollback, cryptographic audit trails, and compliance-grade trace logging.**

| Feature | novyx-langchain | Mem0 | Zep | Supermemory | ConversationBufferMemory |
|---------|-----------------|------|-----|-------------|-------------------------|
| **Semantic search** | ✅ | ✅ | ✅ | ✅ | ❌ |
| **Magic Rollback** | ✅ (Pro+) | ❌ | ❌ | ❌ | ❌ |
| **Cryptographic audit trail** | ✅ (All tiers) | ❌ | ❌ | ❌ | ❌ |
| **Compliance trace logging** | ✅ (Pro+) | ❌ | ❌ | ❌ | ❌ |
| **LangGraph native** | ✅ | ❌ | ❌ | ❌ | ❌ |
| **Multi-tenant** | ✅ | ✅ | ✅ | ❌ | ❌ |
| **Self-hostable** | ✅ | ❌ | ✅ | ✅ | N/A |
| **Open source** | ✅ | ❌ | ❌ | ✅ | ✅ |
| **< 100ms latency** | ✅ | ✅ | ✅ | ❓ | ✅ |
| **Tamper detection** | ✅ | ❌ | ❌ | ❌ | ❌ |
| **Policy enforcement** | ✅ (Pro+) | ❌ | ❌ | ❌ | ❌ |

### Why Choose Novyx?

1. **Only provider with rollback** - Undo mistakes with time-travel
2. **Only provider with audit trails** - Cryptographic verification on all tiers
3. **Only provider with compliance logging** - RSA-signed trace audit for regulated industries
4. **LangGraph native** - First-class checkpoint support with rollback
5. **Open source** - Full transparency and self-hosting option
6. **Multi-tenant** - Built for production SaaS from day one

## Pricing

| Tier | Price | Memories | API Calls | Rollbacks | Audit | Trace Audit |
|------|-------|----------|-----------|-----------|-------|-------------|
| **Free** | $0 | 5,000 | 5,000/mo | 10/month | 7 days | ❌ |
| **Starter** | $12/mo | 25,000 | 25,000/mo | 30/month | 14 days | ❌ |
| **Pro** | $39/mo | Unlimited | 100,000/mo | Unlimited | 30 days | ✅ |
| **Enterprise** | $199/mo | Unlimited | Unlimited | Unlimited | 90 days | ✅ + Priority |

## Breaking Changes in v2.0

### Removed
- `NovyxIntegrityMemory` no longer requires `integrity_api_key` and `integrity_secret` - audit is now built into Core

### Changed
- All classes now use the unified Novyx SDK (`novyx>=2.0.0`)
- `NovyxRAMClient` is now a wrapper around the Novyx SDK (backward compatible)
- Audit features are built into all tiers (with retention limits)

### Added
- `NovyxMemory.rollback()` - Magic Rollback
- `NovyxMemory.audit()` - Audit trail access
- `NovyxCheckpointer.rollback_to_checkpoint()` - Checkpoint rollback
- `NovyxTracedMemory` - Compliance-grade trace logging (Pro+)
- All new methods for rollback, audit, and trace features

## Migration from v0.1.x

```python
# v0.1.x
from novyx_langchain import NovyxIntegrityMemory

memory = NovyxIntegrityMemory(
    api_key="nram_xxx",
    integrity_api_key="int_xxx",  # REMOVED in v2.0
    integrity_secret="secret",     # REMOVED in v2.0
    session_id="user-123"
)

# v2.0
from novyx_langchain import NovyxIntegrityMemory

memory = NovyxIntegrityMemory(
    api_key="nram_xxx",  # Audit is now built-in!
    session_id="user-123"
)
```

## License

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

## Links

- [Documentation](https://docs.novyxlabs.com/integrations/langchain)
- [GitHub](https://github.com/novyxlabs/novyx-langchain)
- [Novyx Core](https://novyxlabs.com)
- [Pricing](https://novyxlabs.com/pricing)
- [Discord](https://discord.gg/novyx)
