Metadata-Version: 2.4
Name: privysha
Version: 0.3.0
Summary: PrivySHA (privacy focused secure hashing library) — drop-in security + optimization layer for LLM apps (developer preview)
Author-email: Ajay Rajan A <ajayrajan727@gmail.com>
Maintainer-email: Ajay Rajan A <ajayrajan727@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Ajay Rajan A
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/AjayRajan05/privySHA
Project-URL: Issues, https://github.com/AjayRajan05/privySHA/issues
Project-URL: Changelog, https://github.com/AjayRajan05/privySHA/blob/main/CHANGELOG.md
Keywords: llm,security,optimization,privacy,pii-detection,openai,anthropic,gemini,prompt-engineering
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Classifier: Topic :: Text Processing
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic<3.0.0,>=2.0.0
Requires-Dist: tiktoken<2.0.0,>=0.5.0
Requires-Dist: requests<3.0.0,>=2.28.0
Requires-Dist: python-dotenv<2.0.0,>=1.0.0
Requires-Dist: click<9.0.0,>=8.0.0
Provides-Extra: dev
Requires-Dist: pytest<10.0.0,>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov<8.0.0,>=4.0.0; extra == "dev"
Requires-Dist: pytest-asyncio<2.0.0,>=0.21.0; extra == "dev"
Requires-Dist: black<26.0.0,>=22.0.0; extra == "dev"
Requires-Dist: flake8<8.0.0,>=5.0.0; extra == "dev"
Requires-Dist: mypy<3.0.0,>=1.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs<3.0.0,>=1.4.0; extra == "docs"
Requires-Dist: mkdocs-material<10.0.0,>=8.5.0; extra == "docs"
Requires-Dist: mkdocstrings[python]<1.0.0,>=0.19.0; extra == "docs"
Provides-Extra: openai
Requires-Dist: openai<3.0.0,>=1.0.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: anthropic<1.0.0,>=0.5.0; extra == "anthropic"
Provides-Extra: gemini
Requires-Dist: google-generativeai<1.0.0,>=0.3.0; extra == "gemini"
Provides-Extra: transformers
Requires-Dist: transformers<6.0.0,>=4.20.0; extra == "transformers"
Requires-Dist: torch<3.0.0,>=1.12.0; extra == "transformers"
Requires-Dist: accelerate<2.0.0,>=0.20.0; extra == "transformers"
Provides-Extra: ml
Requires-Dist: spacy<4.0.0,>=3.4.0; extra == "ml"
Requires-Dist: transformers<6.0.0,>=4.20.0; extra == "ml"
Requires-Dist: torch<3.0.0,>=1.12.0; extra == "ml"
Requires-Dist: accelerate<2.0.0,>=0.20.0; extra == "ml"
Provides-Extra: fastapi
Requires-Dist: fastapi<1.0.0,>=0.100.0; extra == "fastapi"
Requires-Dist: starlette<1.0.0,>=0.27.0; extra == "fastapi"
Requires-Dist: uvicorn<1.0.0,>=0.23.0; extra == "fastapi"
Provides-Extra: flask
Requires-Dist: flask<4.0.0,>=2.0.0; extra == "flask"
Provides-Extra: django
Requires-Dist: django<6.0.0,>=4.0.0; extra == "django"
Provides-Extra: langchain
Requires-Dist: langchain-core<2.0.0,>=0.1.0; extra == "langchain"
Requires-Dist: langchain-openai<2.0.0,>=0.1.0; extra == "langchain"
Provides-Extra: instructor
Requires-Dist: instructor<2.0.0,>=0.4.0; extra == "instructor"
Requires-Dist: openai<3.0.0,>=1.0.0; extra == "instructor"
Provides-Extra: guardrails
Requires-Dist: guardrails-ai<1.0.0,>=0.4.0; extra == "guardrails"
Provides-Extra: integrations
Requires-Dist: fastapi<1.0.0,>=0.100.0; extra == "integrations"
Requires-Dist: starlette<1.0.0,>=0.27.0; extra == "integrations"
Requires-Dist: uvicorn<1.0.0,>=0.23.0; extra == "integrations"
Requires-Dist: langchain-core<2.0.0,>=0.1.0; extra == "integrations"
Requires-Dist: langchain-openai<2.0.0,>=0.1.0; extra == "integrations"
Requires-Dist: instructor<2.0.0,>=0.4.0; extra == "integrations"
Requires-Dist: openai<3.0.0,>=1.0.0; extra == "integrations"
Provides-Extra: llamaindex
Requires-Dist: llama-index-core<1.0.0,>=0.10.0; extra == "llamaindex"
Provides-Extra: otel
Requires-Dist: opentelemetry-api<3.0.0,>=1.20.0; extra == "otel"
Requires-Dist: opentelemetry-sdk<3.0.0,>=1.20.0; extra == "otel"
Provides-Extra: local-advisor
Requires-Dist: huggingface_hub<1.0.0,>=0.20.0; extra == "local-advisor"
Provides-Extra: local-advisor-gpu
Requires-Dist: privysha[local-advisor]; extra == "local-advisor-gpu"
Requires-Dist: nvidia-ml-py<14.0.0,>=12.0.0; extra == "local-advisor-gpu"
Provides-Extra: all
Requires-Dist: openai<3.0.0,>=1.0.0; extra == "all"
Requires-Dist: anthropic<1.0.0,>=0.5.0; extra == "all"
Requires-Dist: google-generativeai<1.0.0,>=0.3.0; extra == "all"
Requires-Dist: transformers<6.0.0,>=4.20.0; extra == "all"
Requires-Dist: torch<3.0.0,>=1.12.0; extra == "all"
Requires-Dist: accelerate<2.0.0,>=0.20.0; extra == "all"
Requires-Dist: spacy<4.0.0,>=3.4.0; extra == "all"
Requires-Dist: fastapi<1.0.0,>=0.100.0; extra == "all"
Requires-Dist: starlette<1.0.0,>=0.27.0; extra == "all"
Requires-Dist: uvicorn<1.0.0,>=0.23.0; extra == "all"
Requires-Dist: langchain-core<2.0.0,>=0.1.0; extra == "all"
Requires-Dist: langchain-openai<2.0.0,>=0.1.0; extra == "all"
Requires-Dist: instructor<2.0.0,>=0.4.0; extra == "all"
Requires-Dist: flask<4.0.0,>=2.0.0; extra == "all"
Requires-Dist: django<6.0.0,>=4.0.0; extra == "all"
Requires-Dist: guardrails-ai<1.0.0,>=0.4.0; extra == "all"
Requires-Dist: opentelemetry-api<3.0.0,>=1.20.0; extra == "all"
Requires-Dist: opentelemetry-sdk<3.0.0,>=1.20.0; extra == "all"
Requires-Dist: llama-index-core<1.0.0,>=0.10.0; extra == "all"
Dynamic: license-file

# PrivySHA

> **Status: Developer Preview (v0.3.0)** — Early development. APIs and features may change before 1.0.0. See [Developer Preview](docs/developer-preview.md) for scope, limitations, and how to give feedback.

<p align="center">
<strong>PrivySHA — privacy focused secure hashing library</strong><br/>
<em>Privacy-first prompt compilation for AI systems</em>
</p>

<p align="center">
Transform raw prompts into optimized, structured, privacy-safe prompts before they reach LLMs.
</p>

<p align="center">

![PyPI](https://img.shields.io/badge/pypi-v0.3.0-orange)
![Python](https://img.shields.io/badge/python-3.10+-blue)
![License](https://img.shields.io/badge/license-Apache%202.0-blue)
![Status](https://img.shields.io/badge/status-developer%20preview-orange)
![Tests](https://img.shields.io/badge/tests-pytest-green)

</p>

---

## Quick try (60 seconds)

```bash
pip install -e .
python examples/developer_preview_demo.py
```

```python
from privysha import process

result = process(
    "My email is alex@company.com — analyze this dataset.",
    return_metrics=True,
)
print(result["optimized"])
```

---

## Scope (what to expect in 0.x)

| Included now | Preview / evolving | Not yet |
|--------------|-------------------|---------|
| `process()`, `wrap_llm()`, `optimize()`, `sanitize()` | PrivyFit (`recommend_local_model`) | Stable 1.0 API guarantee |
| PII masking, token compression | Agent, routing, pipeline stages | Enterprise compliance reports |
| CLI demo & benchmarks | Multi-provider routing at scale | Full HF catalog tooling |

Full details: [Developer Preview](docs/developer-preview.md) · [Roadmap](docs/roadmap.md)

---

# Overview

PrivySHA is an **open-source prompt optimization and compilation framework** designed for modern AI applications.

Instead of sending **raw user prompts** directly to Large Language Models, PrivySHA introduces a **compiler-style processing pipeline** that transforms prompts into structured, optimized instructions.

This improves:

• privacy
• token efficiency
• prompt reliability
• system observability

PrivySHA acts as a **prompt compiler layer** between your application and any LLM.

> **Release track:** `0.3.0` developer preview — use for feedback and experiments. Requires Python 3.10+. Install with `pip install privysha` (or `pip install -e .` from source). Primary APIs: `process()` and `wrap_llm()`.

---

# Motivation

Most LLM applications look like this:

```
User Prompt → LLM
```

This causes problems:

| Problem              | Result                 |
| -------------------- | ---------------------- |
| Unstructured prompts | inconsistent responses |
| Excess tokens        | higher API costs       |
| PII leakage          | privacy risk           |
| Prompt drift         | unreliable outputs     |
| No observability     | hard debugging         |

PrivySHA introduces a structured pipeline:

```
User Prompt → PrivySHA → Optimized Prompt → LLM
```

---

# Key Features

### Privacy-First Processing

PrivySHA detects and masks sensitive information such as:

* email addresses
* phone numbers
* personal identifiers

Example:

Input

```
John's email is john@email.com analyze this dataset
```

Output

```
<PERSON_HASH> email <EMAIL_HASH> analyze dataset
```

---

### PrivyFit — Local Model Advisor

Recommend local LLMs for **your app's compiled workload** on **your hardware**:

```python
from privysha import recommend_local_model

report = recommend_local_model(
    prompts=["My email is john@x.com — analyze this dataset."],
    mode="strict",
    top=3,
)
print(report.top_pick.ollama_pull_name)
```

CLI: `privysha recommend --prompts ./samples.json --gpu "RTX 4090"`

See [docs/local-advisor.md](docs/local-advisor.md).

---

### Prompt Sanitization

Removes conversational filler.

Example

```
Hey bro can you analyze this dataset for anomalies?
```

becomes

```
analyze dataset for anomalies
```

---

### Prompt AST

PrivySHA converts prompts into structured representations.

Example

```
intent: analyze
object: dataset
task: anomaly_detection
```

This allows the system to perform **compiler-style optimizations**.

---

### Token Optimization

Prompts are compressed to reduce token usage.

Example

```
Analyze this dataset for anomalies and patterns
```

becomes

```
@analyze(dataset)
```

---

### Modular Prompt Pipeline

PrivySHA processes prompts through multiple stages.

```
User Prompt
   │
   ▼
Parser
   │
   ▼
Sanitizer
   │
   ▼
PII Detection
   │
   ▼
Optimizer
   │
   ▼
Context Injector
   │
   ▼
Prompt Compiler
   │
   ▼
Model Adapter
   │
   ▼
LLM Response
```

Each stage can be customized or replaced.

---

# Installation

## Basic Installation (Lightweight)

```bash
pip install privysha
```

**Instant setup** - No downloads, works immediately with rule-based PII detection.

## Advanced Features (Optional)

For ML-enhanced PII detection and advanced features:

```bash
pip install privysha[ml]
```

**ML features include:**
- Enhanced PII detection with transformer models
- Higher accuracy for complex PII patterns
- Context-aware entity recognition

## Provider-Specific

```bash
# OpenAI support
pip install privysha[openai]

# Anthropic Claude support  
pip install privysha[anthropic]

# Google Gemini support
pip install privysha[gemini]

# All providers + ML features
pip install privysha[all]
```

Requirements:

* Python 3.10+

---

# Quick Start

## Drop-in Functions (Easiest)

```python
from privysha import process

# Simple processing
result = process("Hey bro analyze my dataset with john@example.com")
print(result)  # "analyze dataset with <EMAIL_HASH>"

# With ML-enhanced PII detection (requires pip install privysha[ml])
result = process("Contact john@example.com for details", pii_mode="hybrid")
print(result)  # Enhanced PII detection with transformer models
```

## Agent Class (Full Control)

```python
from privysha import Agent

agent = Agent(
    model="mock",  # Use "gpt-4o-mini" for OpenAI, "llama3" for Ollama
    privacy=True,
    token_budget=1200
)

response = agent.run(
    "Hey bro can you analyze this dataset for anomalies?"
)

print(response)
```

PrivySHA automatically:

1. sanitizes the prompt
2. removes personal language
3. masks sensitive data
4. optimizes token usage
5. compiles a structured prompt

## Progressive Enhancement

Choose your PII detection level:

```python
# Rule-based only (lightweight, default)
process("Contact john@example.com", pii_mode="rule")

# Hybrid: Rules + ML (requires pip install privysha[ml])
process("Contact john@example.com", pii_mode="hybrid")

# ML-only (experimental, requires pip install privysha[ml])
process("Contact john@example.com", pii_mode="ml_only")
```

---

# Usage Examples

## Model Providers

### OpenAI (Requires API Key)

```python
import os
from privysha import Agent

os.environ["OPENAI_API_KEY"] = "your-api-key"

agent = Agent(model="gpt-4o-mini")
response = agent.run("Analyze this data")
```

### Ollama (Requires Local Server)

```bash
# Install and start Ollama
curl -fsSL https://ollama.ai/install.sh | sh
ollama serve
ollama pull llama3
```

```python
from privysha import Agent

agent = Agent(model="llama3")
response = agent.run("Analyze this data")
```

### HuggingFace (Requires Transformers)

```python
from privysha import Agent

agent = Agent(model="microsoft/DialoGPT-medium")
response = agent.run("Analyze this data")
```

## Real-World Applications

### Data Analysis Pipeline

```python
from privysha import Agent

agent = Agent(model="gpt-4o-mini", privacy=True)

def analyze_data(data_description):
    prompt = f"Analyze this dataset for patterns: {data_description}"
    return agent.run(prompt)

# Usage
result = analyze_data("Sales data from Q1 2024 with customer emails")
```

### Customer Support

```python
from privysha import Agent

agent = Agent(model="gpt-4o-mini", privacy=True)

def support_query(customer_message):
    # PII will be automatically masked
    return agent.run(customer_message)

# Usage
response = support_query("Help me with order #12345, email john@example.com")
```

### Content Moderation

```python
from privysha import Agent

agent = Agent(model="gpt-4o-mini", privacy=True)

def moderate_content(user_content):
    return agent.run(f"Review this content for policy violations: {user_content}")

# Usage
moderation_result = moderate_content("Check this post from user@social.com")
```

---

# Debugging Prompt Transformations

PrivySHA exposes the full pipeline trace.

```python
result = agent.run(prompt, trace=True)

print(result)
```

Example output

```
RAW PROMPT
Hey bro analyze this dataset

SANITIZED
analyze dataset

OPTIMIZED
@analyze(dataset)

COMPILED
SYSTEM:
You are a data scientist

TASK:
analyze dataset
```

This allows developers to **debug prompt engineering systematically**.

---

# Production Deployment

## Security Best Practices

```python
import os
from privysha import Agent

# Always use environment variables for API keys
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")

# Production configuration
agent = Agent(
    model="gpt-4o-mini",
    privacy=True,  # Always enable in production
    token_budget=2000  # Adjust based on your needs
)

def process_prompt(user_input):
    """Process user input with privacy protection"""
    try:
        response = agent.run(user_input)
        return response
    except Exception as e:
        return f"Error processing prompt: {e}"
```

## Monitoring & Debugging

```python
import time
from privysha import Agent

agent = Agent(model="gpt-4o-mini", privacy=True)

def monitored_process(prompt):
    start_time = time.time()
    
    result = agent.run(prompt, trace=True)
    
    processing_time = time.time() - start_time
    
    # Log metrics (without sensitive data)
    print(f"Processing time: {processing_time:.2f}s")
    print(f"Token optimization: {len(result['raw_prompt'])} -> {len(result['optimized'])}")
    
    return result["response"]
```

## Testing Your Setup

```python
from privysha import Agent

# Test without external services
agent = Agent(model="mock", privacy=True)
response = agent.run("Test prompt with email@example.com")
print(response)

# Test pipeline stages
result = agent.run("Hey bro analyze my dataset john@example.com", trace=True)

# Verify PII masking
assert "john@example.com" not in result["sanitized"]
assert "<EMAIL_HASH>" in result["sanitized"]

# Verify sanitization
assert "bro" not in result["sanitized"]
```

---

# Supported Model Providers

PrivySHA integrates with multiple model providers.

| Provider    | Type               |
| ----------- | ------------------ |
| OpenAI      | hosted APIs        |
| Ollama      | local LLM runtime  |
| HuggingFace | transformer models |

Example:

```python
Agent(model="gpt-4o-mini")
```

or

```python
Agent(model="llama3")
```

---

# Architecture

PrivySHA follows a **compiler-inspired, modular pipeline architecture**.

```mermaid
flowchart LR
    UserInput[User Input] --> Security[Security Stage]
    Security --> IR[IR Generation]
    IR --> Routing[Model Routing]
    Routing --> Compile[Compilation]
    Compile --> Optimize[Optimization]
    Optimize --> LLM[LLM Provider]
    LLM --> Result[Result Assembly]
```

```
privysha/
├── agent.py                 # High-level Agent API
├── utils/
│   ├── dropin.py            # process(), wrap_llm(), optimize(), sanitize()
│   └── pii_detector.py      # Rule-based PII detection
├── pipeline/
│   ├── pipeline.py          # 7-stage orchestrator
│   └── stages/              # Security, IR, Routing, Compilation, Optimization, Generation, Result
├── core/
│   └── pii_pipeline/        # Multi-stage PII detection pipeline
├── compiler/
│   └── msdpc/               # Token optimization engine
├── security/                # Threat detection and masking
├── adapters/                # OpenAI, Claude, Gemini, Grok, Ollama, HuggingFace, Mock
├── integrations/            # FastAPI, Flask, Django, LangChain, LlamaIndex
├── cli/                     # privysha command-line tool
└── ir/                      # Prompt intermediate representation
```

---

# Documentation

- [📖 Quickstart Guide](docs/quickstart.md) - 5-minute walkthrough
- [🔧 Troubleshooting Guide](docs/troubleshooting.md) - Common issues & solutions
- [⚡ Performance Tuning](docs/performance-tuning.md) - Optimization guide
- [🔄 Migration Guide](docs/migration.md) - From other solutions
- [📚 API Reference](docs/api-reference.md) - Complete documentation
- [🏗️ Architecture](docs/architecture.md) - System design
- [🤝 Contributing](docs/contributing.md) - Development guide

Build the docs site locally:

```bash
pip install -e ".[docs]"
mkdocs serve
```

Optional integrations: `pip install privysha[integrations]` or `pip install privysha[fastapi,langchain,instructor]`

See [docs/publishing.md](docs/publishing.md) for PyPI trusted publishing setup.

---

# Running Tests

```bash
# Unit tests (no API keys required)
pytest -m "not integration"

# Full suite including integration tests (requires GEMINI_API_KEY)
pytest
```

Or run the readiness check:

```bash
pytest tests/comprehensive_test.py -v
```

Tests validate:

* prompt sanitization
* token optimization
* pipeline execution
* PII masking
* adapter functionality

---

# Troubleshooting

## Common Issues

1. **Import Error**: `pip install -e .` in development
2. **Connection Refused**: Start Ollama server or check API keys
3. **Memory Issues**: Reduce `token_budget` or use smaller models
4. **PII Not Masked**: Ensure `privacy=True`

## Debug Mode

```python
# Enable full debugging
result = agent.run(prompt, trace=True)

# Print all stages
for stage, output in result.items():
    if stage != "response":
        print(f"{stage.upper()}:")
        print(f"  {output}")
        print()
```

---

# Comparison

| Feature             | PrivySHA | Traditional Prompting |
| ------------------- | -------- | --------------------- |
| Prompt Sanitization | ✓        | ✗                     |
| PII Protection      | ✓        | ✗                     |
| Token Optimization  | ✓        | ✗                     |
| Pipeline Debugging  | ✓        | ✗                     |

PrivySHA introduces a **structured prompt lifecycle** rather than raw prompt usage.

---

# Performance Benchmarks

Reproducible benchmarks are included in the repo. Typical results (rule-based PII, no ML):

| Metric | Typical range |
|--------|---------------|
| Token reduction | 5–15% on verbose prompts |
| Processing latency | 20–80 ms |
| Fail-safe rate | ~100% |

```bash
pip install -e .
python benchmarks/run_benchmarks.py --save
```

Results are written to `benchmarks/output/`. See [benchmarks/results.md](benchmarks/results.md) for methodology and reference numbers. Benchmarks also run in CI on every push.

---

# Contributing

Contributions are welcome.

Steps:

1. Fork the repository
2. Create a feature branch
3. Write tests for your changes
4. Submit a pull request

Before submitting:

```
pytest
```

---

# Roadmap

Future versions will include:

* advanced prompt AST analysis
* prompt caching engine
* cost-aware optimization
* multi-model routing

---

# License

This project is licensed under the **Apache 2.0 License**.

See the LICENSE file for details.

---

# Acknowledgements

PrivySHA is inspired by ideas from modern AI tooling ecosystems and compiler design.

It explores the idea of treating prompts as **structured programs** rather than raw text.

---

# Support the Project

If you find this project useful:

⭐ Star the repository
🐛 Report issues
💡 Suggest improvements
