> ## Documentation Index
> Fetch the complete documentation index at: https://phaseo.app/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Phaseo Gateway base URL: https://api.phaseo.app/v1. Send `Authorization: Bearer $PHASEO_API_KEY` with every request.
> Model IDs look like `provider/model`, for example `openai/gpt-6-astra`. Do not guess IDs: list them with `GET /v1/models` or check https://phaseo.app/models. `phaseo/free` routes to an available free model and needs no wallet balance.
> For new text integrations prefer `POST /v1/responses`. `POST /v1/chat/completions` (OpenAI format) and `POST /v1/messages` (Anthropic format) suit existing code.
> The full API contract is https://phaseo.app/docs/openapi/v1/openapi.yaml. Official SDKs: `@phaseo/sdk` (TypeScript) and `phaseo` (Python), plus Go, C#, PHP, Ruby and Rust.
> Search these docs over MCP at https://phaseo.app/docs/mcp, and install Phaseo skills with `npx skills add https://phaseo.app/docs`. If a page is wrong or out of date, report it with the MCP `submit_feedback` tool.
> Manage Phaseo accounts with the `phaseo` CLI (`npm install -g @phaseo/cli`, then `phaseo login` or `phaseo login --device-code`), the `/v1` Management API or the MCP server at `https://mcp.phaseo.app/mcp?access=manage`. Do not send users to the dashboard for account tasks. A person is still needed for sign-up, approving a sign-in, paying the first top-up on the checkout link that `phaseo credits add` returns when no card is saved, confirming each saved-card top-up from the emailed link, and account security (password, MFA, passkeys). Create API keys with `phaseo keys create --name <name> --json`; never guess one. Credit top-ups need `phaseo login --scopes billing:write` first. Task map: https://phaseo.app/docs/v1/developers/manage-from-an-agent.md.

# Python SDK Overview

> Official Python client for the Phaseo Gateway API

Install the published [`phaseo`](https://pypi.org/project/phaseo/) package from PyPI.

The Phaseo Python SDK provides synchronous `Phaseo` and native async `AsyncPhaseo` clients.

## Native async requests

```python theme={null}
import asyncio
from phaseo import AsyncPhaseo

async def main():
    async with AsyncPhaseo() as client:
        response = await client.responses.create({"model": "openai/gpt-5-nano", "input": "Hello"})
        print(response.output_text, response.request_id, response.trace_url)

asyncio.run(main())
```

Use `async for event in client.responses.stream(request)` for parsed text events.
Native asyncio cancellation stops HTTP and polling. Resource namespaces cover text,
images, audio, music, video, batches, files, models, embeddings, OCR, rerank, parse,
moderations and decisions; use `await client.request(...)` for other HTTP operations.
Injected HTTPX clients remain caller-owned.

Both clients support `with_options(timeout=30, max_retries=2)` without changing the
original client. HTTPX timeouts bound network inactivity in seconds. Retries default
to zero and apply only to GET/HEAD before response consumption, never submissions.
`PhaseoHTTPError` exposes the body, code, request ID, dashboard trace URL and retry delay.

When upgrading, replace synchronous JSON request catches of `urllib.error.HTTPError`
with `PhaseoHTTPError` (or `httpx.HTTPStatusError`), and connection error catches
with `httpx.TransportError`. `error.status` is the HTTP status; `error.code` is
the API error code.

## Additional conveniences

Job resources expose `start` and `resume` handles with `result`, `events` and
`to_dict`. Await async methods and iterate async events with `async for`.
Only video and batch support remote cancellation. Stream media with
`videos.stream_content(id)` and batches with `batches.results(id)`. The synchronous
`download_to(chunks, binary_file)` helper writes without buffering the whole file.
File uploads accept bytes, `Path` objects, file objects and HTTPX file tuples.

`responses.parse(request, PydanticModel)` validates completed JSON output;
configure the server response format explicitly. `collect_stream` and
`collect_async_stream` accumulate parsed text events and usage.
`check_model_capabilities(id, input_types=..., output_types=..., endpoints=...,
parameters=..., parameter_values=...)` checks advertised capabilities and scalar
constraints together on one available provider offer. Unknown facts fail preflight.

For model selectors and parameter editors, use live endpoint metadata:

```python theme={null}
support = client.models.check_parameters(
    "openai/gpt-5",
    {"temperature": 0.7, "top_p": 0.9},
    endpoint="responses",
)
```

Each parameter is marked `supported`, `partial`, `unsupported`, or `unknown`,
with matching provider routes and constraint issues for inline highlighting.
`client.models.capabilities(model_id)` returns the complete endpoint capability
response. `AsyncPhaseo` exposes the same awaitable methods.

For local tests, inject `phaseo.testing.MockTransport` using `httpx.Client` or
`httpx.AsyncClient`. Unexpected requests fail locally; call `assert_done()` to
verify all fixtures were used. These fixtures do not verify live provider behavior.
Phaseo rooms export runnable code for the submitted request through **Get code**.

## Features

* Typed request models generated from the OpenAPI spec.
* Built-in helpers for chat, responses, messages, images, audio, embeddings, moderations, files, batches, generations, and async video jobs.
* Streaming helpers for text, responses, and messages (`stream_*` iterators).
* Control-plane helpers such as models, endpoints, organisations, pricing discovery/calculation, API-key lifecycle, workspace lifecycle, current-key inspection, health, providers, credits, activity, and analytics.

## Quick example

```python theme={null}
from phaseo import Phaseo

client = Phaseo(api_key="your-api-key")

response = client.generate_response(
    {
        "model": "openai/gpt-5-nano",
        "input": "Reply with: python sdk works",
    }
)

print(response.get("id"))
```

## Wait for music, video, or batches

```python theme={null}
import os

music = client.music.generate_and_wait(
    {"model": os.environ["PHASEO_MUSIC_MODEL"], "prompt": "Gentle instrumental piano"},
    timeout=600,
    on_poll=lambda job: print(job["id"], job["status"]),
)
```

Use `videos.generate_and_wait(request, **options)` for video and `batches.create_and_wait(request, **options)` for batches. These synchronous helpers submit once and return the full completed response, polling only when needed. `JobFailedError.response` retains failed, cancelled, or expired job details. Completed batches may still contain failed individual requests.

Each resource supports `wait(id, **options)` to resume an existing job and return any terminal response. Music also exposes direct `create(request)` and `retrieve(id)` methods.

Options are `interval` (seconds; default 5, minimum 0.25), `timeout` (seconds; default 1800), `on_poll`, and `cancel_event` (a `threading.Event`). The waiting timeout starts after submission returns. The synchronous client checks cancellation and deadlines between requests and callbacks; it cannot interrupt an HTTP call already in progress with these options.

`JobTimeoutError` and `JobCancelledError` retain `job_id` and `last_response`. Resume with `.wait(error.job_id)`. Local timeout/cancellation does not cancel the remote job, and submissions are never automatically retried. These helpers do not add background execution to the gateway.

## What's included

* `Phaseo` client
* `chat.completions.create(...)` and `responses.create(...)` compatibility helpers
* Resource helpers such as `client.batches`, `client.videos`, `client.files`, and `client.async_jobs`
* Async-job websocket URL helpers for batch and video lifecycle streams
* `client.batches.stream_results(batch_id)` for batch JSONL byte chunks
* Model lifecycle helpers such as `get_model_deprecation_info(...)` and `validate_model(...)`
* Streaming iterators for text, responses, and messages
* Generated request/response models in `phaseo.models`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.