Metadata-Version: 2.5
Name: uprelic
Version: 0.7.0
Summary: Python client for the Uprelic API
Project-URL: Documentation, https://api.uprelic.com/v1/docs
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2
Description-Content-Type: text/markdown

# Uprelic Python SDK

```sh
pip install uprelic
```

Set `UPRELIC_API_KEY` (create a key at https://platform.uprelic.com), or pass `api_key=` to the client.

```python
from uprelic import Uprelic, Noul, Choice, Score

client = Uprelic()
response = client.system_one(
    model="strom-1.0.7",
    state="I was charged twice for my subscription. Please fix this today.",
    questions={
        "billing": Noul("Is this message about billing?"),
        "tone": Choice("What is the tone?", criteria={"angry": "Upset or hostile", "calm": "Neutral or polite"}),
        "urgency": Score("How urgent is this?", criteria=["Can wait", "This week", "Today"]),
    },
)

response.nouls["billing"].noul        # 0.98
response.choices["tone"].choice       # "angry"
response.scores["urgency"].score      # 1.8
response.usage.input_tokens
response.usage.cost                   # in response.usage.currency
response.metadata.server_processing_time_ms
```

Images go in `images=` as http(s) or `data:image/...` URLs. `Box("the white SUV", image=0)` (beta) finds an object
in an image: `response.boxes["suv"].box` has its `left`, `top`, `right` and `bottom` edges as fractions of the
image's width and height. With `multiple=True` it finds every match instead: `response.boxes["cars"].boxes` lists
each one's `box` and `probability`, most likely first. `client.models()` lists the available models:
`strom-1.0.7` (alias `strom-fast`) and `strom-base-1.0` (alias `strom-base`, in beta).

## Document extraction

`client.extract()` takes one PDF (at most 8 pages) or image and a JSON Schema whose properties are the fields to
extract: strings (`format: date`), numbers (`format: amount` or `percent`), booleans or string enums.

```python
from pathlib import Path

response = client.extract(
    model="strom-1.0.7",
    document=Path("invoice.pdf"),  # or bytes, or an http(s) or data: URL
    schema={"properties": {
        "invoice_date": {"type": "string", "format": "date"},
        "total": {"type": "number", "format": "amount", "description": "The total including tax"},
    }},
)

response.fields["total"].value        # 1234.5
response.fields["total"].text         # "Total EUR 1.234,50", the line it came from
response.fields["total"].confidence   # 0.94
response.fields["total"].page, response.fields["total"].box
```

A field the document doesn't give is `None`. When the line holds more than one value of the field's type, `value` is
the whole line.

With `model="strom-extract-1.0.1"`, you can send plain text as `text=` instead of a document. Each field then has
`start` and `end` instead of `page` and `box`: its position in your text, counted in Unicode characters, so
`text[start:end]` is the field's `text`.

```python
text = "Invoice no. 17795\nDate: 16 Dec 2026\nTotal EUR 428.40"
response = client.extract(model="strom-extract-1.0.1", text=text, schema=schema)
total = response.fields["total"]
text[total.start:total.end]           # "EUR 428.40"
```

## Zero data retention

`private=True` sends `client.system_one()` or `client.extract()` to the private endpoint, which stores no request or
response content. It costs 20% more and needs a paid plan or the zero data retention subscription. See
https://platform.uprelic.com/docs/zero-data-retention.

```python
response = client.extract(model="strom-1.0.7", document=Path("payslip.pdf"), schema=schema, private=True)
```

## Agent guard

Rules in plain words, checked at one of three stages: a tool call before it runs (`before_tool`, the default), a
tool's result before the agent sees it (`after_tool`), or a reply before the user sees it (`before_reply`):

```python
client.create_guard_rule("refund-limit", text="Block refunds above 500 unless the user's role is manager.",
                         tools=["refund"], mode="enforce", threshold=0.9)
client.create_guard_rule("no-secrets", text="Block file contents that contain passwords or API keys.",
                         stage="after_tool", tools=["read_file"], mode="enforce")
```

`create_guard_rule` raises `APIError` (409) when the id is taken. Change a rule with `update_guard_rule()`, which takes
the same arguments and saves a new version.

Decorate a tool with `client.guard()`. Each call is checked first, with the function's arguments as `params`:

```python
@client.guard("refund", context=lambda: {"role": current_user.role})
def refund(order_id, amount):
    ...

try:
    refund("A1", amount=800)
except uprelic.Blocked as blocked:
    str(blocked)   # "refund blocked by refund-limit: Refunds over 500 need a manager." Return it to the model.
```

`Blocked` is raised when an enforced rule matches, and also when the check itself fails (no balance, network down),
so an unchecked action never runs. With `@client.guard("read_file", check_result=True)` the return value is checked
as well, and `Blocked` (with `.stage == "after_tool"`) is raised instead of returning it. A rule in `observe` mode only reports `would_block`; the function runs.

To check without the decorator, call `client.check(action="refund", params={...})`, add `result=...` for a
tool's result, or `client.check(response="...", request="...")` for a reply. Each rule that applies costs $0.01 per 1,000 checks.

Before enforcing a rule, see what it would have blocked: `client.guard_checks(decision="would_block")` returns your
checks of the last 90 days, newest first (`.checks`, `.total`; page with `page=` and `page_size=`).

## Video detection

`client.video_detection()` finds the object you describe in every frame of a video at a public http(s) URL (at most
10 minutes and 500 MB). It waits for the job, about 30 seconds per video minute, and costs 0.10 USD per video minute.

```python
job = client.video_detection(description="Player with the ball", video="https://example.com/match.mp4")

for frame in job.frames:  # 5 a second
    if frame.box:         # None when the object isn't in the frame
        print(frame.t, frame.box.left, frame.box.top, frame.box.right, frame.box.bottom, frame.confidence)
```

A job that fails raises `uprelic.VideoDetectionFailed`, with the job as `.job` and the reason as `.job.error`.

## Async

```python
from uprelic import AsyncUprelic

async with AsyncUprelic() as client:
    response = await client.system_one(model="strom-1.0.7", state="...", questions={...})
```

## Errors and retries

Failed requests raise `uprelic.APIError` subclasses: `AuthenticationError` (401), `InsufficientBalanceError` (402),
`InvalidRequestError` (400, 413, 422), `RateLimitError` (429) and `ServerError` (5xx). Each has `status_code` and `detail`.

Rate limits (429), 502/503/504 responses and connection failures are retried twice with backoff. Change this with
`Uprelic(max_retries=...)`.

API reference: https://api.uprelic.com/v1/docs
