Metadata-Version: 2.4
Name: refactual-sdk
Version: 0.1.2
Summary: Official Refactual REST API client for Python.
Author-email: Refactual <support@refactual.com>
License: Apache-2.0
Project-URL: Homepage, https://app.refactual.com/developer/docs
Project-URL: Documentation, https://app.refactual.com/developer/docs
Project-URL: Source, https://github.com/refactual/refactual
Project-URL: Issues, https://github.com/refactual/refactual/issues
Project-URL: Changelog, https://github.com/refactual/refactual/releases
Keywords: refactual,ai,llm,api,sdk,claude,code-refactoring,modernization,cobol,legacy-code
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: urllib3>=2.0
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Dynamic: license-file

# refactual-sdk

Python client for the [Refactual](https://app.refactual.com) platform.
Pipe legacy code, PDFs, or repo URLs into a single API and get back modern
code, structured JSON, or a ranked action plan — directly from your scripts,
notebooks, or data pipelines.

> **Preview release** (`0.x`) — the API is stable but minor versions may add
> fields before `1.0.0`. Pin exact versions in production and watch the
> [changelog](https://github.com/refactual/refactual/releases).

## What is Refactual?

Refactual is a developer platform that turns AI agents into a working stack
for legacy modernization, document parsing, and ecommerce intelligence:

- **Refactor** — paste COBOL, Fortran, Perl, VB6, PHP, Java 7, jQuery (40+
  source languages); receive idiomatic modern code in your target language
  with a reviewed diff.
- **Repos** — point at a GitHub URL or upload a directory; receive a
  modernization score, ranked tech-debt hotspots, and Auto-Fix recipes
  with a dev-weeks effort estimate.
- **Parser** — upload PDFs or freeform text; receive structured JSON,
  field-level diffs, or a generated API schema.
- **Stores** — connect Shopify; receive a ranked AI action plan with
  dollar-impact estimates for revenue, AOV, and CAC moves.

For Python developers, Refactual fits the workflows you already have:
notebooks for one-off code modernization, `pandas` for analyzing the
hotspot CSV, Airflow / Prefect for ingesting parsed PDFs, and FastAPI for
serving model output back to your team.

## Why use this SDK?

- **Pythonic and dataclass-friendly** — methods follow `snake_case`,
  responses are plain `dict`s that drop straight into `pandas.DataFrame`,
  `pydantic` models, or anything else you're already using.
- **Type hints everywhere** — full annotations on every public method;
  `mypy --strict` clean.
- **Built on `urllib3`** — no `requests` dependency, no surprises in
  containerized environments. The single dependency is widely vetted.
- **Auto retry with backoff** — 429s and 5xx responses retry with
  exponential backoff and `Retry-After` honoring; you don't write the loop.
- **Retries are billed once** — every call carries an idempotency key that
  its retries reuse, so a timed-out request that is retried can't be charged
  twice. See [Retries are billed once](#retries-are-billed-once).
- **Notebook-first ergonomics** — defaults that "just work" in Jupyter, Colab,
  and VS Code notebooks; no event-loop juggling for the common case.
- **Webhook verification** — `verify_webhook(raw, header, secret)` ships in
  the package; no copy-pasting HMAC code.
- **Typed errors** — `RefactualError` exposes `.status`, `.type`, and the
  raw server payload for programmatic recovery.

## Install

```bash
pip install refactual-sdk
```

Requires Python 3.9+. Works in CPython, PyPy, Jupyter, and AWS Lambda.

## Quickstart

Get a key at [app.refactual.com/developer](https://app.refactual.com/developer).
Use a `rk_test_*` key in CI / notebooks — it returns deterministic sandbox
responses and consumes zero credits.

```python
import os
from refactual import Refactual

client = Refactual(api_key=os.environ["REFACTUAL_API_KEY"])

# Modernize a snippet of legacy Perl into Python.
reply = client.chat.completions.create(
    model="claude-sonnet-4-6",
    system_prompt=(
        "You are Refactor. Output only modernized Python 3.11. "
        "Preserve behavior; no commentary."
    ),
    messages=[{
        "role":    "user",
        "content": "while (<>) { chomp; print length($_), \"\\n\"; }",
    }],
    max_tokens=2048,
)

print(reply["content"])              # modernized Python source
print(reply["usage"]["cost_cents"])  # e.g. 0.42
```

Response shape (matches the REST API):

```python
{
  "id":          "cc_01HZX…",
  "model":       "claude-sonnet-4-6",
  "environment": "live",
  "content":     "import sys\nfor line in sys.stdin: …",
  "usage":       {"input_tokens": 31, "output_tokens": 184, "cost_cents": 0.42},
}
```

## What you can build

**Notebook for batch-modernizing a legacy codebase.** Loop over files in a
COBOL repo, call `chat.completions.create` per file, and write the
modernized output to disk. Use `pandas` to track token cost per file and
plot a histogram of LOC-per-file before and after.

**Airflow DAG that parses incoming PDFs.** Each task pulls a PDF from S3,
extracts text with `pdfplumber`, calls Refactual with a JSON-schema system
prompt, and writes the structured output to BigQuery. Use `client.usage.list`
to backfill monthly cost reports.

**FastAPI service that wraps your team's modernization workflow.** Expose
a `/refactor` endpoint that proxies to Refactual with your team's preferred
target language and style guide baked into the system prompt. Add OAuth so
each user authenticates with their own Refactual key.

**Streamlit dashboard for Repos hotspots.** Pull session data with
`client.sessions.list`, render a leaderboard of hotspots ranked by
tech-debt severity, and let your team click into the underlying chat to see
the Auto-Fix recipe.

## Features

- Sync API today; async (`httpx`-backed) is on the roadmap.
- Type-hinted methods, full `py.typed` marker shipped.
- Auto retry on 429 + 5xx with exponential backoff and jitter.
- One idempotency key per call, minted before the first attempt and reused
  by every retry — a retried request is billed once.
- Configurable timeout (default 60s) and retry count.
- `default_headers` for correlation IDs, tenant IDs, etc.
- OAuth 2.0 `client_credentials` grant with scoped tokens.
- Webhook signature verification (HMAC-SHA256, 5-minute tolerance).
- Reads `REFACTUAL_API_KEY` from the environment automatically.

## API surface

All methods are sync and return `dict[str, Any]` matching the REST schema.
The catalog mirrors the [REST API](https://app.refactual.com/developer/docs):

| Method                              | Description                            |
|-------------------------------------|----------------------------------------|
| `client.chat.completions.create()`  | Submit messages, get a model reply.    |
| `client.credits.retrieve()`         | Current balance, plan, auto-reload.    |
| `client.usage.list(days=30)`        | Daily token + cost rollup.             |
| `client.sessions.list(limit=50)`    | Recent conversations.                  |
| `client.sessions.retrieve(id)`      | Full transcript for one session.       |
| `client.invoices.list(limit=50)`    | Free-credit grants and monthly invoices.|
| `client.models.list()`              | Available models with context windows. |
| `client.oauth.token(...)`           | Exchange `client_credentials` for a token. |
| `client.request(method, path, ...)` | Low-level escape hatch.                |
| `client.request_raw(method, path, ...)` | Same, plus `status`, `headers`, `replayed`. |
| `verify_webhook(raw, header, secret)` | Validate a webhook signature.        |

## Configuration

```python
client = Refactual(
    api_key="rk_live_...",
    base_url="https://app.refactual.com",  # override for self-hosted
    timeout=60.0,
    max_retries=2,
    default_headers={"X-Correlation-Id": my_id},
)
```

`api_key` falls back to `REFACTUAL_API_KEY` from the environment, so the
constructor is `Refactual()` if you set the env var.

## OAuth 2.0 (`client_credentials`)

```python
tok = Refactual(api_key="rk_placeholder").oauth.token(
    client_id=os.environ["REFACTUAL_CLIENT_ID"],
    client_secret=os.environ["REFACTUAL_CLIENT_SECRET"],
    scope=["chat:write", "chat:read"],
)
client = Refactual(access_token=tok["access_token"])
# tok["expires_in"] is 3600. Re-call .oauth.token to rotate.
```

## Webhook verification (Flask example)

```python
from flask import Flask, request, abort
from refactual import verify_webhook, RefactualError
import os

app = Flask(__name__)

@app.post("/webhook")
def webhook():
    try:
        verify_webhook(
            request.data,
            request.headers.get("Refactual-Signature"),
            os.environ["WEBHOOK_SECRET"],
        )
    except RefactualError as e:
        abort(400, str(e))

    event = request.get_json()
    if event["type"] == "chat.completed":
        # ...
        pass
    return "", 200
```

## Error handling

```python
from refactual import Refactual, RefactualError

try:
    client.chat.completions.create(messages=[...])
except RefactualError as e:
    # e.status: 402 | 429 | 401 | ...
    # e.type:   "insufficient_credits" | "rate_limited" | ...
    # e.raw:    parsed server payload
    # e.idempotency_key: the key the call was sent with — resubmit with it for the same single answer
    if e.type == "insufficient_credits":
        top_up()
    elif e.status == 429:
        time.sleep(int(e.raw.get("retry_after", 1)))
    else:
        raise
```

## Retries are billed once

Every non-GET request the SDK sends carries an `Idempotency-Key`: a UUID
minted before the first attempt and reused by every retry of that call —
timeouts, 429s, 5xx. The platform runs a keyed `chat.completions.create()`
once and remembers its answer for 24 hours, so a retry receives the stored
reply instead of starting a second, separately billed completion. The reply
carries `"replayed": True` when that happened.

If a retry lands while the original attempt is still running, the platform
answers `409 idempotency_in_flight` and the SDK waits for the original to
finish — polling with the same key for up to `timeout` seconds — then
returns its result. Only if that budget also runs out does the 409 surface
as a `RefactualError`, with `e.idempotency_key` attached so you can resubmit
the same call later and still receive the one answer. In-flight polls don't
count against `max_retries`.

Supply your own key when the same logical call may be issued again by a
*new* process — a queue that can deliver a job twice, an Airflow task that
retries after a worker dies:

```python
reply = client.chat.completions.create(
    messages=[{"role": "user", "content": code}],
    idempotency_key=f"job-{job.id}",   # any string, up to 200 characters
)
if reply["replayed"]:
    print("answered from the earlier attempt — not billed again")
```

Keys are scoped to your API key. A call that ended in an error is remembered
under its key too, so a resubmission returns that same error; start a new
call (which mints a new key) to try again. `client.request_raw()` returns
the same metadata — `status`, `headers`, `replayed`, `idempotency_key` — for
any endpoint.

## Pandas / notebook tips

```python
import pandas as pd

usage = client.usage.list(days=30)
df = pd.DataFrame(usage["days"])
df["date"] = pd.to_datetime(df["date"])
df.set_index("date")[["totalTokens", "costCents"]].plot()
```

## Async support

Sync API today. An async client backed by `httpx.AsyncClient` is on the
roadmap; until then, wrap calls in `asyncio.to_thread()` for FastAPI /
async pipelines:

```python
reply = await asyncio.to_thread(
    client.chat.completions.create,
    messages=[{"role": "user", "content": code}],
)
```

## MCP integration

Refactual ships an MCP server that exposes the same surface as this SDK to
Claude, Cursor, Continue, and any MCP-aware agent. The OAuth flow above is
how third-party MCP clients authenticate. See
<https://app.refactual.com/developer/docs/mcp>.

## Versioning + support

- **Semver.** Breaking API changes bump the major version.
- **Issues:** <https://github.com/refactual/refactual/issues>
- **Email:** <support@refactual.com>
- **Status:** <https://status.refactual.com>

## License

Apache-2.0. See [`LICENSE`](./LICENSE).
