Skip to main content

Reef Python SDK

Server-side Python client for Reef. Product servers authenticate with an InkPass API key or service credential. Provider credentials remain inside Reef.

Install

pip install reef-sdk

Set up a product

A product needs three things before it can send prompts: the product itself, a provider config, and a bundle of five execution policies. The requests and responses are typed; ReefError 502 unexpected_response means Reef answered with a malformed body.

from decimal import Decimal

from reef_sdk import AlreadyExistsError, ExecutionPolicyBundleCreateRequest

bundle: ExecutionPolicyBundleCreateRequest = {
    "version": 1,
    "model_policy": {
        "policy_id": "model_default",
        "default_model": "openai/gpt-5-mini",
        "max_input_tokens": 32000,
        "max_output_tokens": 4000,
    },
    "retry_policy": {
        "policy_id": "retry_default",
        "max_attempts": 3,
        "initial_backoff_ms": 250,
        "max_backoff_ms": 4000,
    },
    "optimization_policy": {
        "policy_id": "optimization_default",
        "prompt_caching": True,
        "allow_message_compaction": False,
        "max_request_bytes": 1_000_000,
    },
    "data_policy": {
        "policy_id": "data_default",
        "allow_provider_training": False,
        "retain_provider_prompts": False,
        "retention_days": 30,
    },
    "budget_policy": {
        "policy_id": "budget_default",
        "period": "month",
        "hard_limit_usd": Decimal("25"),
        "max_request_cost_usd": Decimal("0.50"),
    },
}

try:
    reef.agents.register_product(
        {"product_id": "support-product", "name": "Support", "spec_ref": "den://specs/support"},
        "support-product-register",
    )
except AlreadyExistsError:
    pass  # registered earlier; Reef does not compare the name or spec_ref

try:
    reef.configuration.create_provider("support-product", {}, "support-product-provider")
except AlreadyExistsError:
    pass

try:
    reef.configuration.create_execution_policy_bundle(
        "support-product", bundle, "support-product-policies-v1"
    )
except AlreadyExistsError:
    pass  # version 1 exists, possibly with different policies

Budget amounts are Decimal and are sent as decimal strings; a float is refused before any request is sent. The provider config always uses the platform's provider key: Reef refuses a credential reference or source in the request, so the request type offers neither.

"Already exists" versus a refusal

AlreadyExistsError (a ReefError subclass, HTTP 409 invalid_state_transition) means Reef already holds that product ID, provider config ID, or bundle version. Reef does not compare contents, so the existing resource can differ from your request. Anything else is a real refusal and stays a plain ReefError: for example 422 validation_failed (problems listed in details["errors"]), 403, or 409 idempotency_conflict.

Idempotency keys are separate from that. Repeating a call with the same key and the same body within 24 hours returns the first answer again, and raises no AlreadyExistsError. The same key with a different body raises idempotency_conflict.

Policy bundle versions

  • A bundle version is immutable. Creating a version that exists raises AlreadyExistsError, even if the policies differ. To change a policy, create the next version.
  • Creating version N retires every active version below N for the same five policy IDs.
  • A prompt names each policy by ID and runs under that ID's highest active version. A prompt that names none uses model_default, retry_default, optimization_default, data_default and budget_default; a decision defaults its model policy to decision_model_default.
  • Create versions in increasing order. A version below the current one is stored active, but prompts keep using the higher one.
  • Keep the same five policy IDs in every version of a bundle. Reusing a version number with a different policy ID is an error (Reef currently answers 500).

Create a typed decision

The decision client accepts choice, score, and noul questions in one request. Use the rolling Jev alias to follow the latest release, or use a pinned model ID when reproducibility matters.

import os

from reef_sdk import DecisionCreateRequest, ReefClient, ReefConfig


request: DecisionCreateRequest = {
    "state": {
        "ticket": "I upgraded to Pro, still see Free, and was charged.",
    },
    "questions": {
        "route": {
            "type": "choice",
            "instructions": "Choose the team that should handle this ticket.",
            "criteria": {
                "billing": "Billing, subscription, or charge issue",
                "technical": "Technical product malfunction",
                "account": "Account access or identity issue",
            },
        },
        "urgency": {
            "type": "score",
            "instructions": "Score the urgency of this ticket.",
            "criteria": ["low", "medium", "high"],
        },
        "billing_related": {
            "type": "noul",
            "instructions": "Does this ticket concern billing?",
        },
    },
    "requested_model": "~typesafe/jev-latest",
    "model_policy_id": "decision_model_default",
}

with ReefClient(
    ReefConfig(
        "https://reef.example.com",
        os.environ["REEF_SERVICE_API_KEY"],
        credential_kind="service",
    )
) as reef:
    decision = reef.decisions.create(
        "support-product",
        request,
        idempotency_key="ticket-4821-routing-v1",
    )

if decision["status"] == "completed":
    route = decision["answers"]["route"]
    if route["type"] == "choice":
        print(route["choice"], route["confidence"])

DecisionResponse is a status-discriminated union. Completed responses require typed answers, provider metadata, and usage. The SDK rejects a malformed successful response instead of passing an untyped dictionary to application code.

Ask for a structured answer

prompts.ask_structured sends one synchronous prompt with a JSON Schema for the answer. Reef validates the model's JSON against the schema before it completes the prompt, and the SDK returns the parsed value as answer.

answer = reef.prompts.ask_structured(
    "support-product",
    "Route this ticket: I upgraded to Pro and was charged twice.",
    response_schema={
        "type": "object",
        "properties": {"team": {"enum": ["billing", "technical", "account"]}},
        "required": ["team"],
    },
    idempotency_key="ticket-4821-route-v1",
    timeout_seconds=95,
)

if answer["status"] == "completed":
    print(answer["answer"]["team"])
elif answer["status"] in ("failed", "cancelled"):
    print("no answer:", answer["error_code"])  # e.g. invalid_structured_output
else:
    # queued or streaming: the first request under this key is still running.
    answer = reef.prompts.get_answer(answer["prompt_request_id"])

StructuredAnswer is a status-discriminated union. A string is sent as one user message; pass a list of PromptMessage for system or multi-turn input, and options (StructuredAskOptions) to choose the model or the execution policies.

The idempotency key makes the ask safe to retry. A retry under the same key with the same arguments returns the stored result without calling or billing the model again. The same key with different arguments fails with idempotency_conflict. When you leave out input_message_refs, the SDK derives them from the key, so a retry sends the same request.

Reef answers when the prompt ends, which can outlast the client's 30 second default timeout. Pass timeout_seconds of about 95 for slow models. A client timeout does not cancel the prompt: retry under the same key, or read it later with get_answer.

Read the cost of one prompt

cost = reef.usage.get_prompt_cost("support-product", answer["prompt_request_id"])
if not cost["cost_pending"] and cost["cost_usd"] is not None:
    print(cost["cost_usd"], cost["currency"])  # Decimal, USD

PromptCost holds the prompt's usage rows (items) and their total as a Decimal. The total is None while it is not known: before a queued prompt records usage, or while a row's cost awaits reconciliation with the provider (cost_pending). is_estimate marks a cost Reef estimated rather than read from the provider. The principal needs agent_budget:read. A prompt in another product or organization is not found.

To wait until the cost is final, use wait_for_prompt_cost:

from reef_sdk import PromptCostTimeoutError

try:
    cost = reef.usage.wait_for_prompt_cost(
        "support-product",
        answer["prompt_request_id"],
        timeout_seconds=300,  # default
        poll_interval_seconds=1,  # first wait; doubles after each read
        max_poll_interval_seconds=15,  # longest wait between reads
    )
    print(cost["cost_usd"])  # a Decimal, never None here
except PromptCostTimeoutError as error:
    print(error.last_cost["prompt_status"], error.last_cost["cost_pending"])

It reads at once and returns as soon as the cost is final: the prompt has ended (completed, failed or cancelled) and cost_usd is known. A prompt that ended without usage costs Decimal(0). Otherwise it waits, doubling the wait up to the maximum, and never past timeout_seconds; then it raises PromptCostTimeoutError (a TimeoutError) whose last_cost is the last answer. A ReefError, such as 404, is raised at once. Reef reconciles pending costs with the provider about once a minute, so allow a few minutes; a row with no provider request ID can stay pending, and the wait then times out.

Reef has no field that says a cost is final, so the SDK reads it from prompt_status and cost_usd (is_final_cost(cost) gives the same answer for one read). For a completed or failed prompt a known total does not change. A cancelled prompt's total can: a provider call that answers after the cancel turns it back to pending, then to the provider's amount.

Reef does not offer a per-request cost ceiling. A budget policy's hard_limit_usd refuses new prompts once the period's spend plus one reservation would pass it, but max_request_cost_usd is only the amount each prompt reserves: Reef does not stop a prompt that costs more.

Runtime requirements

  • Call the SDK from a product backend. Do not expose Reef credentials to browser code.
  • The principal needs agent_decision:execute for decisions and agent_prompt:send for structured asks.
  • The product needs an active OpenRouter provider configuration and an execution policy whose model policy requires the decisions capability.
  • Reuse an idempotency key only for the same request. Reef returns the stored result without a second provider call.

See Reef decision requests for policy setup, the HTTP contract, errors, accounting, and production verification evidence.

The client also exposes configuration, prompts, conversations, files, runs, approvals, tools, usage, memory, and evidence. Mutations require caller-owned idempotency keys. The SDK never accepts provider credentials and does not retry mutations outside Reef.

Metadata

Release files for reef-sdk 0.6.0

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

Source distribution (sdist)

Source distribution for reef-sdk 0.6.0
File Size Uploaded Provenance Actions
reef_sdk-0.6.0.tar.gz 33.1 kB Without provenance Details for reef_sdk-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for reef-sdk 0.6.0
File Interpreter ABI Platform Actions
reef_sdk-0.6.0-py3-none-any.whl Python 3 none any Details for reef_sdk-0.6.0-py3-none-any.whl

Total release size: 57.1 kB

Release files / reef_sdk-0.6.0.tar.gz

Download URL reef_sdk-0.6.0.tar.gz
Size 33.1 kB
Tags Source
SHA-256 checksum
How to use checksums
28a639fcd63de5b000d591901807b74eb4722aa6b886bed03e17a71538566d45
BLAKE2b-256 checksum
How to use checksums
69c497ae360607dad5046bde641df405e705aa784a7fb13e09717d20d6f4a708
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.3 {"installer":{"name":"uv","version":"0.10.3","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 / reef_sdk-0.6.0-py3-none-any.whl

Download URL reef_sdk-0.6.0-py3-none-any.whl
Size 24.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b49eedd58f686e1f3ae48c468b3923dbef7487960ef84db65fed8f3833e4f64b
BLAKE2b-256 checksum
How to use checksums
2eb0f26428c0c1a2a7bd8d349b8dc10277b8d6a1534f3976b9a20454283e6fa6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.3 {"installer":{"name":"uv","version":"0.10.3","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 reef-sdk 0.6.0

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