Skip to main content

Lebrel encrypted Python client

Questions are encrypted locally for the verified runtime. Answers are decrypted locally. This client serves DeepSeek V4.1 Flash · Lebrel Uncensored (lebrel/deepseek-v4.1-flash-uncensored) and verifies Lebrel's pinned Ed25519 signature before encrypting anything for a runtime key.

Requires Python 3.9 or newer.

python -m pip install lebrel-encrypted
export LEBREL_API_KEY='your-Lebrel-API-key'

The package is published on PyPI as lebrel-encrypted; the same source is at https://github.com/LEBREL-AI/lebrel-encrypted-python and, as a reviewable archive, at https://lebrel.ai/sdk/lebrel-encrypted-python.zip (python -m pip install <archive>). The import is lebrel_encrypted; there is no need for the OpenAI package. The interface accepts OpenAI chat-completion parameters and returns dictionaries.

from lebrel_encrypted import Lebrel

with Lebrel() as client:  # reads LEBREL_API_KEY
    response = client.chat.completions.create(
        messages=[{"role": "user", "content": "Write the opening of a story."}],
        max_tokens=256,
    )
    print(response["choices"][0]["message"]["content"])

The model defaults to the exact DeepSeek V4.1 Flash edition above. Another model ID is rejected locally. You can also pass Lebrel(api_key="...") or use the shorter client.create(...) interface.

OpenCode and other OpenAI-compatible applications

Run the local adapter in a terminal:

python -m lebrel_encrypted.proxy --port 11437

Configure your application with:

  • Base URL: http://127.0.0.1:11437/v1
  • API key: your usual Lebrel API key
  • Model: lebrel/deepseek-v4.1-flash-uncensored

The adapter receives normal OpenAI JSON and SSE on loopback, then uses this SDK to encrypt requests to the public API and decrypt responses. It binds only to 127.0.0.1; there is no network-bind option. The hop between your application and the adapter is plaintext on loopback: any process on your computer that can reach it is inside your trust boundary. Requests require Authorization: Bearer ... and JSON bodies with Content-Length. Browser-origin requests are rejected.

The adapter does not persist API keys or conversations. By default the key comes from each application's request. Optional standalone use can read the key from --api-key-file /private/path/to/key; an incoming Bearer key takes precedence. The file must contain exactly one key. Do not put the key itself on the command line. The authenticated /v1/models route forwards metadata only for the exact DeepSeek V4.1 Flash Uncensored model. Stream disconnects close the encrypted upstream response.

GET http://127.0.0.1:11437/healthz requires no key and identifies the local adapter, SDK version, upstream, signing-key ID and loaded proxy source hash. Startup emits one status line; request bodies and credentials are never logged. The proxy runs in the foreground until stopped. Installing this package does not automatically start it or modify application configuration.

The console entry point lebrel-encrypted proxy --port 11437 is equivalent.

Reasoning

DeepSeek V4.1 Flash thinks only when asked. Through the proxy the edition gets thinking: true unless your request names thinking (true/false), profile (chat or thinking_50), chat_template_kwargs, reasoning_effort or custom_params, which are forwarded as they are. With the client, pass thinking=True to create().

Terminal requests

Put a normal OpenAI completion request in a local JSON file, then:

export LEBREL_API_KEY='your-Lebrel-API-key'
lebrel-encrypted infer < request.json

Equivalent: python -m lebrel_encrypted infer < request.json. The command reads JSON from stdin and the key from the environment. It writes a JSON response, or SSE when the input sets "stream": true. On failure it exits nonzero and prints a JSON error to stderr with the platform's reason when there is one (see below).

Streaming and cancellation

from lebrel_encrypted import Lebrel

with Lebrel() as client:
    with client.chat.completions.create(
        messages=[{"role": "user", "content": "Explain how HPKE works."}],
        max_tokens=512,
        stream=True,
    ) as stream:
        for chunk in stream:
            for choice in chunk.get("choices", []):
                delta = choice.get("delta", {})
                print(delta.get("content") or "", end="", flush=True)
        assert stream.completed

Read the stream to its end to verify completion. It requires a final finish_reason for every observed choice, then an authenticated [DONE], and rejects subsequent data or truncated encrypted frames. Partial output may have been displayed before a later error: do not treat it as a completed answer. stream.close() or leaving the context closes the HTTP response and propagates cancellation. Closing early leaves stream.completed false.

Receipts: proof of what answered

The runtime signs a receipt for every answer: the SHA-256 of your request exactly as sent, the SHA-256 of the answer, the serving manifest it ran under (which weights, precision, engine and tokenizer) and the token counts. The client checks it for you, with the same checks as https://lebrel.ai/verify:

from lebrel_encrypted import Lebrel

with Lebrel() as client:
    answer = client.chat.completions.create(messages=[{"role": "user", "content": "Name one color."}])
    receipt = client.receipt(answer)
    assert receipt.verified
    print(receipt.request_id, receipt.manifest.payload["weights"]["revision"])

receipt.checks lists every step: the pinned signing key, the signature, the request id, the digest of your request, the digest of the answer and the serving manifest the receipt names, fetched and checked at the same time (manifest=False skips that fetch). A stream is checked the same way once fully consumed: client.receipt(stream). Any receipt can be looked up later by its request id while the API keeps it: client.receipt("…"); client.manifest() returns the current serving manifest, checked. Every completion carries request_id, request_sha256 and response_sha256; the dictionary itself is unchanged.

The local proxy sends X-Lebrel-Request-Id on every answer and, on non-streaming answers, Proof-Of-Edition-Receipt (the signed receipt, base64) as the API sent it. GET /v1/receipts/{id} on the proxy returns the receipt with X-Lebrel-Receipt-Check: verified once the proxy has checked its signature and the serving manifest; the digests are yours to check against your text.

Errors and retries

from lebrel_encrypted import APIError, EncryptionError, Lebrel, StreamError, TransportError

try:
    with Lebrel() as client:
        response = client.create(messages=[{"role": "user", "content": "Hello"}])
except APIError as error:
    print(error.status_code, error.code)
except (EncryptionError, StreamError, TransportError) as error:
    print(str(error))

The client never retries inference on its own. A connection failure may occur after execution has begun, so a fresh retry by your application can incur a new charge. Each request gets a new UUID in X-Lebrel-Request-Id and a fresh HPKE encapsulation. The client never follows redirects, never accepts a plaintext success response and never falls back to the unencrypted API. Error messages omit conversation content and ignore untrusted plaintext error bodies.

When a request cannot be served

APIError.code carries the platform's reason, and the proxy and the command line put the same code and a plain message in the JSON error they answer with:

code What it means
queue_wait_timeout You were in line for the model and the wait ran out (two minutes). Retry; the line moves as answers finish.
queue_full The line for the model is full right now. Try again in a minute.
queue_lapsed Your place in line lapsed. Send the request again.
model_paused The model is paused until the next drop.
rate_limit_exceeded Too many requests at once for this account.
insufficient_quota Not enough balance for this request.
priority_unavailable Priority is not available for this key.
context_length_exceeded The prompt and the output limit exceed the model's context window.
inference_unavailable, billing_unavailable, authentication_unavailable, database_unavailable, encrypted_inference_unavailable The platform or the model's node could not be reached just now. Try again in a moment.

Priority

answer = client.create(messages=[...], service_tier="priority")

Priority is a setting of your account (Dashboard → Billing): with it on, every request goes ahead of the line at the priority price. The OpenAI service_tier parameter is accepted as well, in Python and through the proxy, and sends X-Lebrel-Service-Tier: priority. The response header X-Lebrel-Price-Multiplier names the price the request was admitted at, as a percentage of the list price, and X-Lebrel-Queue-Wait-Ms the time it waited in line.

The default timeout is 900 seconds for cold starts; configure Lebrel(timeout=...) when needed. Environment HTTP proxy settings are disabled. HTTPS certificate verification remains enabled.

Routed models, encrypted to the attested router

The models Lebrel routes to their labs (deepseek/deepseek-v4.1-flash, deepseek/deepseek-v4-pro, z-ai/glm-5.3, z-ai/glm-5.3-flash, moonshotai/kimi-k3, qwen/qwen3.8-max, qwen/qwen3.8-flash) are served by Lebrel's router inside an Intel TDX confidential VM. The client asks that machine for a quote with a fresh nonce, verifies it in your process (see lebrel_encrypted.attestation), checks that the route's key document is signed by the receipt key the quote binds and names the encryption key the quote binds, and only then encrypts your request to it. Nothing between you and the router reads the prompt or the answer: not Lebrel's edge, not Cloudflare, not the machine's host. The router sends the plaintext to the lab over the lab's own API; what the lab does with it is the lab's policy.

from lebrel_encrypted import Lebrel

client = Lebrel()  # LEBREL_API_KEY
answer = client.chat.completions.create(
    model="deepseek/deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Hello"}],
)

Intel's signature chain over the quote is checked with dcap-qvl: pip install 'lebrel-encrypted[attestation]'. Without it the client refuses routed models; Lebrel(allow_unverified_chain=True) proceeds on the binding checks alone, a weaker guarantee you should choose knowingly. The router's code, its reproducible build and the ledger of what each version measures are public at https://github.com/LEBREL-AI/router.

What is verified

The client retrieves https://api.lebrel.ai/.well-known/lebrel-encryption without sending the API key, verifies the Ed25519 signature on the original decoded payload bytes and checks the schema, exact model, signing-key digest, HPKE configuration digest, freshness and validity interval (at most ten minutes). The request body is encrypted using the verified HPKE configuration. API credentials and routing metadata are still HTTP headers protected by HTTPS.

Pinned Ed25519 public key (raw bytes, base64):

beFZtSwt6FnlhIYbX636n7w3/gpaASIkRnIMx52XJwk=

SHA-256:

8f72beb9680a0f1911dce59d1fc103a0a89039998003715d35422d3020e5292d

The runtime signature authenticates Lebrel's encryption key. Hardware attestation, which proves that the operator cannot access the model process's memory, is the layer that arrives with the public launch. Until then, questions and answers are decrypted inside an inference runtime administered by Lebrel.

Reused implementation and dependencies

The EHBP Python source is vendored without changes from the official Tinfoil repository at commit 6ae53f8b6270834ca1cb8c29f8d2a79e372bc4b0, under src/lebrel_encrypted/_vendor/ehbp. Relative imports remain unchanged. Its MIT license accompanies the source. The wrapper supplies application checks; HPKE, HKDF and response encryption/decryption use upstream EHBP and its dependencies.

Exact direct dependency versions:

  • pyhpke==0.6.3
  • cryptography==46.0.7 (latest compatible 46.x patch selected for pyhpke's <47 bound)
  • httpx==0.28.1

Tests use pytest==8.4.2; builds use hatchling==1.27.0. The archive includes VENDORED_SHA256.json so reviewers can compare vendored files to the pinned upstream revision.

Offline verification

python -m pip install '.[test]'
python -m pytest

The interoperability fixture builds a local Go EHBP server with the same pinned upstream revision (GOTOOLCHAIN=go1.26.0) and verifies real Python-to-Go encrypted requests, JSON responses, streaming, truncation and failure handling. No GPU, production credentials or production API calls are used. Dependency and Go toolchain downloads are needed once unless already cached.

Changelog and license

Changes by version are in CHANGELOG.md. The package is released under the MIT license; the vendored EHBP module keeps its own MIT license (see THIRD_PARTY_NOTICES.md). Questions and security reports: contact@lebrel.ai.

Metadata

Release files for lebrel-encrypted 0.5.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lebrel-encrypted 0.5.2
File Size Uploaded Provenance Actions
lebrel_encrypted-0.5.2.tar.gz 89.3 kB Without provenance Details for lebrel_encrypted-0.5.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lebrel-encrypted 0.5.2
File Interpreter ABI Platform Actions
lebrel_encrypted-0.5.2-py3-none-any.whl Python 3 none any Details for lebrel_encrypted-0.5.2-py3-none-any.whl

Total release size: 149.8 kB

Release files / lebrel_encrypted-0.5.2.tar.gz

Download URL lebrel_encrypted-0.5.2.tar.gz
Size 89.3 kB
Tags Source
SHA-256 checksum
How to use checksums
cfd1de4e8cfc9eb78ed7b8089ec884ce8119ae642b0713c01c019d18b4a6830e
BLAKE2b-256 checksum
How to use checksums
79c9de2d8135063593dbd11c3e0aa212a9a91f5a08a5ccf108d405da0b82b775
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.25 {"installer":{"name":"uv","version":"0.11.25","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / lebrel_encrypted-0.5.2-py3-none-any.whl

Download URL lebrel_encrypted-0.5.2-py3-none-any.whl
Size 60.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a06ff8f6c5fad1e33b6b8489cce90d5506bbcf45bbff5aadd29e9fd862d9ef01
BLAKE2b-256 checksum
How to use checksums
e63d877b32fa66b0882786da1846e18fa5a61b6302f67d4b21d255660d495fa0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.25 {"installer":{"name":"uv","version":"0.11.25","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for lebrel-encrypted 0.5.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page