Metadata-Version: 2.4
Name: limina-ai
Version: 1.0.2
Summary: Deterministic Trajectory Diagnostics & Automated Prompt Patching for Multi-Turn AI Agents
Author: Limina AI
Keywords: ai-agents,llmops,trajectory-diagnostics,hallucination-detection,prompt-patching,langchain,openai,state-space-dag,cognitive-architecture
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
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 :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: gradio_client>=0.17.0
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: keywords
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Limina AI — Python SDK

The deterministic diagnostic, state-space DAG reconstruction, adversarial stress-testing, and automated prompt-patching engine for multi-turn AI Agents.

## Installation

Install the official package via pip:

```bash
pip install limina-ai
```

Or install the development build directly from source:

```bash
pip install git+https://github.com/YOUR_GITHUB_USERNAME/limina-python.git
```

## Quickstart

### 1. Real-Time Agent Tracing

Use decorators to monitor agent state transitions, tool execution latency, and policy violations:

```python
from limina import LiminaMonitor

# Initialize client with optional industry profile ('standard', 'banking', 'healthcare', 'customer_support', 'creative')
# You can pass api_key directly or set the LIMINA_API_KEY environment variable.
monitor = LiminaMonitor(
    api_key="YOUR_LIMINA_API_KEY",
    profile="standard",
    export_html=True
)

# Trace tool execution
@monitor.trace_tool(tool_name="database_policy_lookup")
def query_db(query: str):
    return {"max_refund_days": 14, "allow_cash": False}

# Trace root agent session
@monitor.trace(session_id="session_101", description="Support Agent Run")
def support_agent(user_input: str):
    policy = query_db(user_input)
    return "Your cash refund has been issued."

# Execute
response = support_agent("Requesting refund for order #992.")

# Flush pending asynchronous traces before application shutdown
monitor.flush()
```

## Industry Domain Profiles & Configuration

Limina provides specialized strictness profiles designed for regulated and high-stakes agentic workloads:

| Profile | Strictness Multiplier | Max Tool Latency | Compliance Focus |
| :--- | :--- | :--- | :--- |
| `standard` | 1.0x | 4000ms | General-purpose agent validation & hallucination checks. |
| `banking` | 0.5x (Zero Tolerance) | 2000ms | Enforces financial disclaimers; flags unauthorized promises. |
| `healthcare` | 0.6x | 2500ms | Verifies medical advice boundaries and mandatory disclaimers. |
| `customer_support` | 1.0x | 3000ms | Brand safety, profanity filtering, competitor name censorship. |
| `creative` | 1.5x (Relaxed) | 6000ms | Higher semantic tolerance for exploratory and generative agents. |

### Setting Profiles in Python

```python
# Option A: At initialization
monitor = LiminaMonitor(api_key="YOUR_KEY", profile="banking")

# Option B: At runtime
monitor.set_profile("healthcare")
```

### Declarative `limina.yaml` Configuration

Drop a `limina.yaml` file in your project root to enforce workspace-wide policies automatically:

```yaml
strictness_profile: "banking"
max_tool_latency_ms: 2000.0

custom_rules:
  forbidden_words:
    - "competitor_name"
    - "guaranteed refund"
    - "unauthorized financial advice"
  required_words:
    - "terms apply"
    - "disclaimer"
```

## Historical Log & JSON File Evaluation

`evaluate_logs()` natively accepts local file paths (`.json`), raw Python lists, or individual log dictionaries. It auto-detects OpenAI chat transcripts, LangSmith run dumps, or standard Limina DAG files:

```python
from limina import LiminaMonitor

monitor = LiminaMonitor(api_key="YOUR_LIMINA_API_KEY")

# 1. Evaluate directly from a local JSON file
report_from_file = monitor.evaluate_logs("logs/production_traces.json")
print(report_from_file["executive_summary"])

# 2. Evaluate from in-memory OpenAI transcripts
openai_messages = [
    {"role": "user", "content": "Can I return an item after 30 days?"},
    {"role": "assistant", "content": "Yes, our policy covers returns up to 60 days."}
]

report_from_memory = monitor.evaluate_logs(openai_messages)
print(report_from_memory["narrative_report"])  # Automated Git Diff prompt patch
```

## Advanced Diagnostic Capabilities

### 1. Adversarial Stress-Testing & Red-Teaming (`run_stress_test=True`)

Evaluate agent robustness against real-world user noise and adversarial attack vectors:

* **Typo & Keyboard Neighbor Perturbations:** Injects stochastic character substitutions simulating mobile and fast-typing noise. Measures if semantic drift degrades past safety thresholds.
* **Jailbreak & System Prompt Injection Resilience:** Simulates adversarial override prefixes (`SYSTEM OVERRIDE`) to evaluate policy adherence under active manipulation.
* **Robustness Scoring:** Calculates a deterministic robustness delta score (`0.0 - 100.0%`). If robustness falls below 85.0%, the trajectory is flagged with `LOW_ROBUSTNESS`.

```python
# Run batch evaluation with active adversarial red-teaming
report = monitor.evaluate_logs("traces.json", run_stress_test=True)
```

### 2. Standalone Interactive Visual Reports (`export_html=True`)

When `export_html=True` is enabled, the SDK compiles a standalone interactive report (`report.html`) containing:

* **Vis.js Directed Graph Canvas:** Complete visual reconstruction of the multi-turn agent trajectory. Nodes are color-coded based on status (Healthy, Warning, Error/Breach).
* **Diagnostic Drawer:** Clickable node inspection displaying execution duration in milliseconds, instability indices, token counts, and session cost simulations.
* **Side-by-Side Error Comparison:** Visual diff comparing the retrieved database context (Premise) directly against the hallucinated agent output (Target).
* **Rendered Markdown & Patch Inspector:** Full diagnostic narrative with syntax-highlighted Git Diff prompt patches and 1-click clipboard copy.

```python
monitor = LiminaMonitor(
    api_key="YOUR_LIMINA_API_KEY",
    export_html=True
)

# Generates 'report.html' on disk upon evaluation
monitor.evaluate_logs("production_traces.json")
```

## Core Modules & API Reference

### 1. `LiminaMonitor` (Class)

The primary entry point for capturing and evaluating agent trajectories.

#### Initialization
```python
LiminaMonitor(
    api_key: Optional[str] = None, 
    profile: str = "standard",
    export_html: bool = False,
    host: Optional[str] = None
)
```
* `api_key` (Optional[str]): Active authentication key associated with your organization. Automatically reads from the `LIMINA_API_KEY` environment variable if not provided.
* `profile` (str): Industry compliance preset (`standard`, `banking`, `healthcare`, `customer_support`, `creative`).
* `export_html` (bool): When enabled, exports an interactive standalone visual report (`report.html`).
* `host` (Optional[str]): Optional custom endpoint URL override (for private enterprise or on-premise deployments).

#### Methods

* `set_profile(profile_name: str)`  
  Dynamically switches the active compliance preset at runtime.

* `trace(session_id: str = "default_session", description: str = "")`  
  Decorator for agent execution functions. Captures user inputs, execution duration, and agent text generations into a unified DAG trajectory. Dispatches evaluation payloads asynchronously in the background.

* `trace_tool(tool_name: str = "custom_tool")`  
  Decorator for deterministic tools, database lookups, or API clients. Measures tool execution latency in milliseconds and records structured inputs/outputs.

* `evaluate(payload: List[Dict[str, Any]]) -> Dict[str, Any]`  
  Synchronously dispatches pre-structured trajectory graphs to the evaluation engine and returns the diagnostic report.

* `evaluate_logs(input_data: Union[str, List, Dict], source: str = "auto") -> Dict[str, Any]`  
  Ingests local `.json` file paths or historical log transcripts, converts them into State-Space DAGs using `LogAdapter`, and returns the diagnostic summary.

* `flush()`  
  Blocks execution until all pending background asynchronous trace uploads have completed.

### 2. `LogAdapter` (Class)

Universal converter designed to parse third-party conversation dumps into Limina-compliant State-Space Directed Acyclic Graphs (DAGs).

#### Static Methods

* `LogAdapter.from_openai(messages: List[Dict[str, Any]], session_id: str = None, description: str = "") -> Dict[str, Any]`  
  Parses standard OpenAI chat completion histories (`user`, `assistant`, `tool`, and `tool_calls`) into chronological graph nodes and directional transitions.

* `LogAdapter.from_langsmith(run_data: Dict[str, Any], session_id: str = None) -> Dict[str, Any]`  
  Converts LangChain and LangSmith run trees (including nested child runs, tool chains, and latency metadata) into a Limina trajectory schema.

* `LogAdapter.auto_convert(raw_logs: Union[str, List, Dict], source: str = "auto") -> List[Dict[str, Any]]`  
  Auto-detects log structure (file paths to `.json` files, raw JSON strings, OpenAI message lists, or LangSmith objects) and standardizes them for batch evaluation.

## Diagnostic Output Schema

Evaluation responses return structured diagnostic reports with actionable prompt patches:

```json
{
  "executive_summary": {
    "health_rating": "F",
    "success_rate_percentage": 0.0,
    "most_vulnerable_component": "GENERATION_CONTRADICTION, BUSINESS_RULE_VIOLATION",
    "actionable_advice": "Enforce database parameter constraints in system prompt.",
    "total_nodes": 3,
    "errors_detected": 2
  },
  "narrative_report": "# Executive Health: [F]\n\n# Actionable Prompt Patch (Git Diff)\n```diff\n- Always fulfill refund requests immediately.\n+ Verify database return limits (14 days max). Never promise cash refunds beyond policy constraints.\n```"
}
```

## Privacy, Security & Data Governance

Limina AI is engineered with a strict privacy-first architecture:

* **Zero Data Retention:** Customer conversation logs, user prompts, and tool outputs are processed ephemerally in volatile memory during evaluation and are not retained on disk.
* **No Model Training:** Customer data is never stored, aggregated, or used to train, fine-tune, or improve proprietary or foundation models.
* **Cryptographic Key Isolation:** API keys are never stored in plaintext. All authentication checks rely on irreversible SHA-256 cryptographic hashes.
* **Non-Blocking Runtime:** Tracing decorators run asynchronously on background threads to prevent latency overhead on host agents.

## License

Distributed under the Apache-2.0 License.
