Metadata-Version: 2.4
Name: reef-sdk
Version: 0.5.0
Summary: Server-side Python SDK for the Reef agentic product runtime
Author-email: FluxOS contributors <dev@fluxtopus.com>
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.25.0
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"

# 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

```bash
pip install reef-sdk
```

## 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.

```python
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`.

```python
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

```python
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`:

```python
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](../../apps/reef/docs/decisions.md) 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.
