Metadata-Version: 2.4
Name: byterover
Version: 0.2.0
Summary: The ByteRover Python SDK: search your team's drives and manage their documents through the ByteRover API.
Project-URL: Homepage, https://docs.byterover.ai
Project-URL: Documentation, https://docs.byterover.ai/api/python-sdk
Author: ByteRover, Inc.
License-Expression: MIT
License-File: LICENSE
Keywords: api,byterover,documents,rag,retrieval,sdk,search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.7
Description-Content-Type: text/markdown

# ByteRover Python SDK

The ByteRover Python SDK: search your drives and manage their documents from Python.

> **0.2.0 replaces the old `byterover` client.** The PyPI project `byterover` used to hold an older client (0.1.0 to
> 0.1.8) with another API. This SDK isn't compatible with it: code written for 0.1.x needs changes. To keep the old
> client, pin it with `pip install "byterover<0.2"`. See the [changelog](https://docs.byterover.ai/changelog).

```sh
pip install byterover
# or
uv add byterover
```

- The import name is `byterover`.
- Python 3.11 to 3.13 (see Compatibility, below). Its runtime dependencies are `httpx` and `pydantic`, whose licenses
  are under Dependencies, below.
- Sync and thread-safe: one client, one `httpx.Client`. After `os.fork()`, create a new client in the child.
- Docs: [docs.byterover.ai/api/python-sdk](https://docs.byterover.ai/api/python-sdk).

## Get an API key

A team owner or admin creates one in ByteRover: select **API keys** under **Team** in the sidebar, then **Create
key**, and choose its scope (**Search**, or **Read and write**), its drives and its expiry. The secret is shown only
once, so put it in your secret store, then in the `BYTEROVER_API_KEY` environment variable. A key starts with `brv_`.
See [Authentication and API keys](https://docs.byterover.ai/api/authentication).

## Start

```python
from byterover import ByteRover

client = ByteRover()  # reads BYTEROVER_API_KEY, and BYTEROVER_BASE_URL if set

found = client.search(
    query="How long do refunds take in the EU?",
    drive_ids=["drv_…"],
    effort="medium",  # sets the price; there is no default
)
for result in found.results:
    print(" > ".join(result.location.heading_path), result.text)
```

| Option | Default |
|---|---|
| `api_key` | `BYTEROVER_API_KEY`; the constructor raises without one |
| `base_url` | `BYTEROVER_BASE_URL`, then `https://byterover.ai/api`. It must be https, except on loopback |
| `timeout` | 60 s for each step of an attempt (waiting for a connection, connecting, each write, each read); not a total limit. A search gets 105 s at `medium` and 135 s at `high`; any call takes its own `timeout` |
| `max_retries` | 2 |
| `http_client` | one of the client's own; part uploads go through it too |
| `logger` | none: nothing is logged |

The key is never shown in full: `repr(client)`, errors and logs show `brv_` and four characters. Use the client in a
`with` block, or call `client.close()`, to close its connections.

## What it covers

| | |
|---|---|
| `client.key.retrieve()` | the key and the drives it reaches |
| `client.drives.list()`, `retrieve(drive_id)` | |
| `client.folders.list`, `create`, `move` (`from_=`, `to=`), `delete` | |
| `client.documents.list(drive_id, folder=, name=, status=, sort=, order=, limit=)` | pages, see below |
| `client.documents.retrieve`, `list_revisions`, `read`, `content` | `content` streams the original file |
| `client.documents.put_text`, `update`, `copy`, `delete` | |
| `client.uploads.create`, `list_parts`, `put_part`, `complete` | uploads in parts, straight to storage |
| `client.operations.retrieve(id)` | the work a write started |
| `client.search(query=, drive_ids=, effort=, …)` | |
| `client.request(method, path, query=, body=)` | any other `/v1/` path, with the same key and retries |

Fields keep the API's names (`drive_ids`, `next_cursor`, `apiKey`). Responses are pydantic models built without
validation: fields a newer server adds are kept (`model_extra`, `to_dict()`), and an enum value this SDK doesn't know
arrives as a string, so give a `match` over one a default case. Requests are typed with closed enums, so a type
checker catches a misspelled value.

### Pages

```python
for document in client.documents.list(drive_id, folder="/policies"):
    print(document.path)
first = client.documents.list(drive_id).first_page()  # or one page, with next_cursor
for page in client.documents.list(drive_id).pages():
    print(len(page.documents))
```

### Status, headers and the trace id

```python
answered = client.with_raw_response.documents.retrieve(document_id)
print(answered.data.path, answered.status, answered.trace_id)
```

Quote the `trace_id` (on a response or an error) when you contact support.

## Errors

Every error is a `ByteRoverError`. An error response is an `APIStatusError` with `status`, `code` (always a string),
`message` and `trace_id`, as one of: `BadRequestError` 400, `AuthenticationError` 401, `InsufficientBalanceError`
402, `PermissionDeniedError` 403, `NotFoundError` 404, `ConflictError` 409 (see `code`: `VERSION_MISMATCH`,
`UPLOAD_CLOSED`, …), `RateLimitError` 429, `InternalServerError` 500 and any other 5xx, and `ServiceUnavailableError`
503/504. On any 5xx, `from_gateway` is true when a proxy answered, not ByteRover, and the outcome is unknown. Each
error also keeps its `response` and parsed `body`. A 2xx whose body isn't JSON (a captive portal, a web page) is an
`APIStatusError` with `code` `INVALID_RESPONSE`. No response at all is an `APIConnectionError`, or an
`APITimeoutError` when the timeout ran out. A redirect is refused, not followed, so the key never leaves `base_url`.

## Retries and writes sent twice

A call is retried only when that is safe:

- anything, when the connection failed before the request went out (`error.sent == "no"`), and on a 429 from
  ByteRover;
- reads, also after a timeout, a lost connection, a 5xx or a 429 from a proxy;
- **never** a write or a search whose outcome is unknown (a timeout, a lost connection, a 5xx). The write may have
  run, and the search may have been charged.

Every write sends an `Idempotency-Key` (a new one per call, kept across its retries); a search sends one only when you
pass `idempotency_key`. After an unknown outcome, check the state first
(`documents.retrieve`, `documents.list`, `operations.retrieve`), and only then send the write again with the same
`idempotency_key`:

```python
client.documents.put_text(drive_id, path="/notes/today.txt", text=text, idempotency_key="notes-2026-11-15")
```

If your process dies, a key the SDK made dies with it: pass your own when a write must survive a crash. Keys are kept
for 24 hours.

Stopping your program (Ctrl-C) stops the client; it doesn't stop the server, which may still finish (and, for a
search, charge) what it started. There is no server-side cancel.

## Uploads

`documents.upload()` does the whole upload: it hashes the file (the API wants its size and SHA-256 first), opens the
upload, sends the parts to storage four at a time, refreshes part URLs that expired (they last 15 minutes), retries a
part that failed on the way, and completes it. The API chooses the part size (`part_size` in its upload plan, 8 MiB
today); `on_upload_created` hands you `part_count` and `part_size`.

```python
result = client.documents.upload(
    drive_id,
    "/reports/q3.pdf",
    "q3.pdf",
    tags=["finance"],
    wait="searchable",  # or "done"; by default it returns once the upload is complete
)
print(result.document.id, result.operation.status)
```

The source must be readable twice: a file path, bytes, a seekable binary file (`open(path, "rb")`), or an object with
`size` and `read(start, end)`. A one-shot stream is refused, with an error that says why. Every option is checked
before the file is read.

Ctrl-C raises at once and starts no more parts. A part already being sent can't be cut, so it finishes (or
times out under `part_timeout`) in the background, and Python waits for it before the process exits.

If your process may die mid-upload, keep what `on_upload_created` hands you (it holds no URL or key, so it can go in
a file or a database), and finish later with the same file:

```python
from byterover import UploadIncompleteError

try:
    client.documents.upload(drive_id, path, file, on_upload_created=lambda saved: store.put(path, saved))
except UploadIncompleteError:
    # Now, or after a restart: the upload is still pending.
    client.uploads.resume(store.get(path), file)
```

A resume works while the upload is pending, and sends every part again. A part that can't be sent ends the upload
with an `UploadIncompleteError`, which names the `upload_id` and `path` (the part's own error is its `__cause__`).

If completing an upload loses its response, the SDK sends the same completion again. That's safe: the server claims
the upload first, so a completed upload just answers its document again. While another completion is still running,
the SDK keeps asking, backing off, for `complete_wait` (2 minutes by default), then raises an `UploadIncompleteError`.
Each completion attempt gets `complete_timeout` (the client's timeout by default). Raise it for very large files.

Run with your own `idempotency_key`, running `documents.upload()` again with the same key and file either finishes the
earlier upload, or answers the document the earlier run already made, for as long as the API keeps the key (24
hours). It doesn't upload the file a second time.

`documents.upload_directory(drive_id, "docs", prefix="/imports")` uploads every file whose extension the API accepts.
Hidden files and folders (`.git`, `.env`), empty files, symbolic links and files that can't be read are skipped and
listed; `include_hidden` and `ignore` change that. A file swapped for a link, a folder or another file after the
folder was read is never read: it is listed in `failed`. It isn't atomic: the result lists what `succeeded`, what uploaded
but isn't ready (`uploaded_not_ready`: the document exists, its wait failed), what `failed` and what was
`skipped`. `upload={"wait": "searchable"}` passes `wait`, `wait_timeout` and `part_concurrency` to each file's
upload. Stopping it (Ctrl-C) still raises once the files in flight have settled; a file whose completion was cut off
may still be stored, so look for it with `documents.list` before uploading it again.

`operations.wait(operation.id)` polls until the operation is `done`, at the pace the API asks for. A poll that fails
on the way (a gateway's 504 while a big file is ingested, a lost connection) is asked again at the next poll, until the
deadline. It raises `OperationFailedError` when the operation fails, and `WaitTimeoutError` after `timeout` (10
minutes by default), with the last failure as its `__cause__` when the API kept failing. The operation goes on on the
server either way.

With `wait`, anything that fails after the upload completed is an `UploadWaitError`: the document exists, and the
error carries `document_id` and `operation_id` (and the original error as `__cause__`). Don't upload the file again:
wait for the operation again. `on_upload_completed` hands you the document before any wait.

The building blocks are there too: `uploads.create`, `list_parts`, `put_part` and `complete`. `put_part` sends no API
header and never logs the URL, which is itself a credential.

## Downloads

`documents.content(id)` streams the original file: `iter_bytes()`, `read()`, `text()` or `write_to_file(path)`. If
the connection is cut, or nothing arrives for the call's timeout, the SDK asks for the rest with `Range` and
`If-Range` on the file's ETag. If the file changed in between, the read fails instead of joining two versions.

## Compatibility

| | Supported | Tested in CI |
|---|---|---|
| Python | 3.11 to 3.13 (`requires-python = ">=3.11"`) | 3.11, 3.12 and 3.13 |
| Operating system | any | Linux |

The package installs on a later Python too, but only the versions above are tested.

## Versioning

The SDK is at 0.x: a new minor version (0.2 to 0.3) may break your code, and a patch version (0.2.0 to 0.2.1) fixes
bugs without breaking it. Pin a minor version, such as `byterover>=0.2,<0.3`, and read the changelog before you move
to the next one. The TypeScript SDK, `@byterover/sdk`, has the same version number. See
[Versioning and support](https://docs.byterover.ai/api/sdk-versioning).

## Dependencies

| Package | Why | License |
|---|---|---|
| `httpx` (`>=0.27,<1`) | HTTP | BSD-3-Clause |
| `pydantic` (`>=2.7,<3`) | response models | MIT |
| `certifi`, through `httpx` | the CA certificates httpx trusts | MPL-2.0 |

`httpx` and `pydantic` also bring `httpcore`, `idna` (BSD-3-Clause), `anyio`, `h11`, `pydantic-core`,
`annotated-types`, `typing-inspection` (MIT) and `typing-extensions` (PSF-2.0).

## Docs, changelog and support

- Docs: [Python SDK](https://docs.byterover.ai/api/python-sdk), and the
  [API reference](https://docs.byterover.ai/api-reference/introduction).
- Changelog: [docs.byterover.ai/changelog](https://docs.byterover.ai/changelog), and `CHANGELOG.md` in the sdist.
- Support: contact ByteRover support and quote the `trace_id` (on a response or an error). For a search, add its
  `search_id`; for a write, the `id` of its operation. See
  [Errors and retries](https://docs.byterover.ai/api/errors#get-help).

## License

MIT.
