> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qwedai.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# QWEDLocal — client-side verification

> Run QWED verification directly in your code without a backend server. Local execution, model-agnostic support, and deterministic result caching.

## Why QWEDLocal?

### No backend server needed

* Run verification directly in your application
* No infrastructure to manage
* Suitable for prototyping, scripts, and small projects

### Local execution

* Your API keys stay on your machine
* Your data does not touch QWED servers
* Useful for HIPAA, GDPR, and sensitive-data workloads

### Model agnostic

* Works with any supported LLM — OpenAI, Anthropic, Gemini
* Works with local models via Ollama
* Works with any OpenAI-compatible API

### Deterministic caching

* Cached results return without an LLM round-trip
* Repeated queries skip the LLM call
* Cache hits avoid network latency

***

## Installation

```bash theme={null}
pip install qwed
```

**Dependencies:**

```bash theme={null}
# For different LLM providers
pip install openai         # OpenAI + Ollama
pip install anthropic      # Anthropic Claude
pip install google-generativeai  # Google Gemini

# For verification engines
pip install sympy          # Math verification
pip install z3-solver      # Logic verification

# For caching and CLI
pip install colorama click
```

***

## Quick start

> [!NOTE]
>
> From v9.0.0, `QWEDLocal` needs `model=`. QWED names no default model, so pass a model ID your provider serves. Without one, `QWEDLocal` raises `ValueError`. The same applies to `verify()`.

### Option 1: Ollama (no per-call cost)

```bash theme={null}
# 1. Install Ollama
# Visit: https://ollama.com

# 2. Pull a model
ollama pull llama3

# 3. Start Ollama
ollama serve
```

```python theme={null}
from qwed_sdk import QWEDLocal

client = QWEDLocal(
    base_url="http://localhost:11434/v1",
    model="llama3"
)

result = client.verify_math("What is 2+2?")
print(result.verified)  # True
print(result.value)  # 4
```

### Option 2: OpenAI

```python theme={null}
from qwed_sdk import QWEDLocal

client = QWEDLocal(
    provider="openai",
    api_key="sk-proj-...",
    model="gpt-4o-mini",
)

result = client.verify_math("What is the derivative of x^2?")
print(result.verified)  # True
print(result.value)  # 2*x
```

### Option 3: Anthropic Claude

```python theme={null}
from qwed_sdk import QWEDLocal

client = QWEDLocal(
    provider="anthropic",
    api_key="sk-ant-...",
    model="your-claude-model"
)

result = client.verify("What is 5 factorial?")
```

***

## Verification engines

### 1. Math verification (SymPy)

```python theme={null}
result = client.verify_math("What is the integral of 2x?")
print(result.value)  # x**2
print(result.evidence)  # {"method": "sympy_eval", ...}
```

### 2. Logic verification (Z3)

```python theme={null}
result = client.verify_logic("Is (p AND NOT p) satisfiable?")
print(result.value)  # FALSE (contradiction!)
print(result.evidence)  # {"method": "z3_sat", ...}
```

### 3. Code security (CodeVerifier)

> [!NOTE]
>
> Changed in v8.0.0 ([GHSA-v8qq-v427-qrqc](https://github.com/QWED-AI/qwed-verification/security/advisories/GHSA-v8qq-v427-qrqc))

`verify_code` runs QWED's [`CodeVerifier`](https://docs.qwedai.tech/engines/code#security-scanning-codeverifier) in process and admits the code with `admission_decision()`. Only admitted code is `verified=True` with `value="SAFE"`.

```python theme={null}
code = """
def safe_function():
    return 42
"""

result = client.verify_code(code)
print(result.value)                   # "SAFE"
print(result.evidence["admission"])   # "ADMIT"
```

**Dangerous code detection:**

```python theme={null}
dangerous_code = """
import os
os.system("echo hello")
"""

result = client.verify_code(dangerous_code)
print(result.verified)                # False
print(result.value)                   # "UNSAFE"
print(result.evidence["admission"])   # "BLOCKED"
print(result.evidence["issues"])      # CodeVerifier issues, e.g. process_execution
```

`result.evidence` carries the verifier's `status`, `admission`, `constraint_id`, `critical_count`, `issues`, and `proof_ref`.

From v9.1.0, `CodeVerifier` admits Python code only when the modules and module names it uses, its builtins, and its special attributes are on QWED's lists. `QWEDLocal` uses the default lists with no trusted modules, so code that imports a third-party module such as `numpy` is not admitted. See [Only listed modules, builtins and attributes are admitted](https://docs.qwedai.tech/engines/code.md#only-listed-modules-builtins-and-attributes-are-admitted). `QWEDLocal` does not serve code results it cached before v9.1.0.

`CodeVerifier` ships with the full `qwed` package. Without it, `verify_code` returns `verified=False` with `value="UNVERIFIABLE"` and an error. It never returns `SAFE`.

> [!WARNING]
>
> Before v8.0.0, `verify_code` used a local AST check that flagged only bare calls to `eval`, `exec`, `compile`, and `__import__`. Code such as `os.system(...)`, `subprocess.run(...)`, or `from os import system` came back `SAFE`. Cached code results from that check are not reused after you upgrade.

***

## Deterministic caching

Caching avoids redundant LLM calls.

```python theme={null}
# First call - hits LLM ($$$)
result = client.verify_math("2+2")
# -> 🔬 QWED Verification | Math Engine
# -> 📝 LLM Response: 4
# -> ✅ VERIFIED → 4

# Second call - from cache (FREE!)
result = client.verify_math("2+2")
# -> ⚡ Cache HIT (saved API call!)
# -> Returns instantly!
```

**Cache stats:**

```python theme={null}
stats = client.cache_stats
print(f"Hit rate: {stats.hit_rate:.1%}")
print(f"Hits: {stats.hits}, Misses: {stats.misses}")
```

**Disable caching:**

```python theme={null}
client = QWEDLocal(
    provider="openai",
    model="gpt-4o-mini",
    api_key="...",
    cache=False  # Always fresh
)
```

***

## CLI tool

### One-shot verification

```bash theme={null}
# Basic usage: the saved provider, with its model variable set
export OLLAMA_MODEL=your-model
qwed verify "What is 2+2?"

# With specific provider
qwed verify "derivative of x^2" --provider openai --model gpt-4o-mini

# With Ollama
qwed verify "5!" --base-url http://localhost:11434/v1 --model llama3

# Quiet mode (for scripts)
qwed verify "2+2" --quiet
```

### Interactive mode

```bash theme={null}
qwed interactive

# Output:
🔬 QWED Interactive Mode
Type 'exit' or 'quit' to quit

> What is 2+2?
🔬 QWED Verification | Math Engine
📝 LLM Response: 4
✅ VERIFIED → 4

> exit
```

### Cache management

```bash theme={null}
# View cache stats
qwed cache stats

# Clear cache
qwed cache clear
```

### Help

```bash theme={null}
qwed --help
qwed verify --help
qwed interactive --help
```

***

## Cost comparison

| Tier | Monthly cost | LLM options | Use cases |
| - | - | - | - |
| **Local** | **\$0** | Ollama (Llama 3, Mistral, Phi) | students, privacy, development |
| **Budget** | **\~\$5-10** | GPT-4o-mini, Gemini Flash | startups, prototypes |
| **Premium** | **\~\$50-100** | GPT-4, Claude Opus | enterprises, production |

Caching reduces repeated-query cost by skipping the LLM call.

***

## Privacy and security

### Local-only data flow

**QWEDLocal architecture:**

```text theme={null}
┌─────────────────────────────────────┐
│ Your Machine                        │
│                                     │
│  ┌──────────────┐                  │
│  │ QWEDLocal    │                  │
│  │ (Your Code)  │                  │
│  └──────┬───────┘                  │
│         │                           │
│         ├─→ LLM API (Direct)       │
│         │   (OpenAI/Anthropic/     │
│         │    Ollama)                │
│         │                           │
│         └─→ Verifiers (Local)      │
│             SymPy, Z3, AST          │
│                                     │
│  ❌ NO data sent to QWED!          │
└─────────────────────────────────────┘
```

**Use cases:**

* Healthcare (HIPAA compliance)
* Finance (PCI-DSS compliance)
* Government (classified data)
* Privacy-focused applications

***

## Advanced configuration

### Custom cache settings

```python theme={null}
client = QWEDLocal(
    provider="openai",
    model="gpt-4o-mini",
    api_key="...",
    cache=True,
    cache_ttl=3600  # 1 hour TTL (default: 24 hours)
)
```

### Environment variables

```bash theme={null}
export QWED_API_KEY="sk-..."
export QWED_QUIET=1  # Disable colorful output
```

### Quiet mode (no branding)

```python theme={null}
import os
os.environ["QWED_QUIET"] = "1"

client = QWEDLocal(...)
result = client.verify("2+2")
# No colored output, just results
```

***

## Examples

### Example 1: fact-checking pipeline

```python theme={null}
from qwed_sdk import QWEDLocal

client = QWEDLocal(base_url="http://localhost:11434/v1", model="llama3")

facts_to_check = [
    "2+2=4",
    "The derivative of x^2 is 2x",
    "Paris is the capital of France"
]

for fact in facts_to_check:
    result = client.verify(fact)
    print(f"{fact}: {'✅' if result.verified else '❌'}")
```

### Example 2: code review automation

```python theme={null}
import os
from qwed_sdk import QWEDLocal

client = QWEDLocal(provider="openai", model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY"))

code_snippets = [
    "def add(a, b): return a + b",
    "exec(user_input)",  # Dangerous!
    "import os; os.system('rm -rf /')"  # Very dangerous!
]

for code in code_snippets:
    result = client.verify_code(code)
    status = "🟢 SAFE" if result.verified else "🔴 UNSAFE"
    print(f"{status}: {code[:30]}...")
    if not result.verified:
        print(f"  Issues: {result.evidence.get('issues', [])}")
```

### Example 3: batch processing with cache

```python theme={null}
from qwed_sdk import QWEDLocal

client = QWEDLocal(provider="openai", model="gpt-4o-mini", api_key="...")

# Process 1000 math queries
queries = ["What is 2+2?"] * 500 + ["What is 3+3?"] * 500

for q in queries:
    result = client.verify_math(q)
    # First 2 calls hit LLM, rest cached!

print(client.cache_stats)
# Hit rate: 99.8%! (Saved $$$)
```

***

## Troubleshooting

### LLM not available

```python theme={null}
# Check if Ollama is running
curl http://localhost:11434/v1/models

# Start Ollama
ollama serve
```

### Missing dependencies

```bash theme={null}
# Install verification engines
pip install sympy z3-solver

# Install LLM clients
pip install openai anthropic google-generativeai
```

### Cache issues

```bash theme={null}
# Clear cache
qwed cache clear

# Or in Python
client._cache.clear()
```

***

## Learn more

* [CLI guide](https://docs.qwedai.tech/advanced/cli.md) — complete CLI reference
* [Ollama integration](https://docs.qwedai.tech/advanced/ollama.md) — local LLMs
* [LLM configuration](https://docs.qwedai.tech/getting-started/llm-configuration.md) — provider setup
* [Full documentation](https://docs.qwedai.tech)

***

## Contributing

Contributions welcome. See the [contributing guide](https://github.com/QWED-AI/qwed-verification/blob/main/CONTRIBUTING.md).

***

## License

Apache 2.0 — see [LICENSE](https://github.com/QWED-AI/qwed-verification/blob/main/LICENSE).

***

## Support

If QWEDLocal saved you time or money, give us a star! ⭐

**Made with 💜 by the QWED team**


## Related topics

- [Getting started](https://docs.qwedai.tech/integration/getting-started.md)
- [Frequently asked questions](https://docs.qwedai.tech/faq.md)
- [Python SDK](https://docs.qwedai.tech/sdks/python.md)
- [QWED CLI reference](https://docs.qwedai.tech/advanced/cli.md)
- [QWED Open Responses guards for verified AI agents](https://docs.qwedai.tech/open-responses/guards.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.