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

# TypeScript SDK Overview

> Official TypeScript client for the Phaseo Gateway API

Install the published [`@phaseo/sdk`](https://www.npmjs.com/package/@phaseo/sdk) package from npm.

The Phaseo TypeScript SDK provides a type-safe, convenient way to interact with the Phaseo Gateway API. Built on top of the OpenAPI specification, it offers full TypeScript support with generated types and a simple client interface.

## Features

* **Type-safe**: Full TypeScript support with generated types from the OpenAPI spec
* **Simple API**: Easy-to-use client with a clean interface
* **Generated code**: Automatically generated from the canonical API specification
* **Comprehensive**: Covers all Gateway API endpoints

## Quick Example

```typescript theme={null}
import Phaseo from "@phaseo/sdk";

const client = new Phaseo({ apiKey: process.env.PHASEO_API_KEY! });

const response = await client.generateText({
	model: "openai/gpt-4o-mini",
	messages: [{ role: "user", content: "Hello, how are you?" }],
});

console.log(response.choices[0].message.content);
```

## Wait for music, video, or batches

```typescript theme={null}
const music = await client.music.generateAndWait(
  { model: process.env.PHASEO_MUSIC_MODEL!, prompt: "Gentle instrumental piano" },
  { timeoutMs: 600_000, onPoll: (job) => console.log(job.id, job.status) },
);
```

Use `videos.generateAndWait(request, options)` for video and `batches.createAndWait(request, options)` for batches. These helpers submit once, return an immediate completed response without polling, or poll the same job until completion. They return the full response and throw `JobFailedError` with `response` for failed, cancelled, or expired jobs. Completed batches can still have failed individual requests.

Each resource also has `wait(id, options)`, which returns any terminal response, including failures. Options include `intervalMs` (default 5,000; minimum 250), `timeoutMs` (default 1,800,000), `signal`, and `onPoll`. The waiting timeout starts after submission returns; the initial HTTP request keeps its own timeout. Progress callbacks receive the initial response and each poll.

`JobTimeoutError` and `JobCancelledError` retain `jobId` and `lastResponse`, allowing `.wait(error.jobId)` to resume. Stopping a wait cancels its in-flight polling request but does not cancel remote work. HTTP failures propagate without automatically resubmitting. These SDK helpers do not add background execution to the gateway.

## Request controls and diagnostics

Use `client.withOptions({ timeoutMs: 30_000, signal, maxRetries: 2 })` for an
immutable client with controls applied to all resources, streams and media.
Timeouts include reading the response body. Retries default to zero and apply
only to GET/HEAD, with `Retry-After` respected. Paid submissions are never retried.

`responseMetadata(result)` exposes the gateway request ID and dashboard trace URL.
HTTP errors expose `code`, `requestId`, `traceUrl`, `retryAfterMs`, body and headers.

## Workflow helpers

`music.start`, `videos.start` and `batches.start` return handles with `result()`,
`events()` and `toJSON()`. Persist kind and ID and reconstruct using `resume(id)`.
`result()` rejects terminal failures. Only video and batch support remote cancellation.

`videos.streamContent(id)` with `downloadTo(stream, writable)` streams large
outputs. `toFile(bytes, filename, contentType)` prepares uploads.
`batchResults(await client.batches.streamResults(id))` incrementally parses JSONL;
`matchBatchResult(row, inputsByCustomId)` retains individual errors and input identity.

`responses.parse(request, schema)` accepts a Zod-compatible parser and returns
validated output. Set the server structured-output format in the request too.
`collectStream(client.streamResponses(request))` accumulates text and usage.

`checkModelCapabilities(id, { inputTypes, outputTypes, endpoints, parameters,
parameterValues })` checks advertised capabilities and scalar constraints on one
active provider offer. Missing metadata is reported as unknown. It never changes
the model or drops parameters, and cannot guarantee a live provider will accept a request.

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

```typescript theme={null}
const support = await client.models.checkParameters(
  "openai/gpt-5",
  { temperature: 0.7, top_p: 0.9 },
  { endpoint: "responses" },
);
```

Each parameter is marked `supported`, `partial`, `unsupported`, or `unknown`,
with provider routes and constraint issues suitable for inline highlighting.
`client.models.capabilities(modelId)` returns the complete endpoint capability
response. These explicit checks do not add a discovery request to generation calls.

## Local testing and website exports

Import `createMockTransport` and `jobFixtures` from `@phaseo/sdk/testing` to inject
strict, ordered fixtures through `fetchImpl`. Call `mock.assertDone()` to check all
expected requests happened. Unexpected calls fail locally with no network fallback.

After submitting a request in a Phaseo room, **Get code** exports its model and
settings as TypeScript or Python. **View request** opens its dashboard trace when
a request ID is available. Run exported code on your server with `PHASEO_API_KEY`.

## What's Included

* `Phaseo` client class for all API interactions
* Resource-style helpers such as `client.models`, `client.batches`, `client.videos`, and `client.asyncJobs`
* Discovery and pricing helpers such as `client.getModels()`, `client.listProviders()`, `client.getCredits()`, `client.getActivity()`, `client.getAnalytics()`, `client.listEndpoints()`, `client.listOrganisations()`, `client.listPricingModels()`, `client.calculatePricing()`, `client.listApiKeys()`, `client.createApiKey()`, `client.getApiKey(id)`, `client.updateApiKey(id, ...)`, `client.deleteApiKey(id)`, `client.listWorkspaces()`, `client.getWorkspace(id)`, `client.createWorkspace(...)`, `client.updateWorkspace(id, ...)`, `client.deleteWorkspace(id)`, and `client.getCurrentApiKey()`
* Async-job websocket URL helpers for batch and video lifecycle streams
* `client.batches.streamResults(batchId, { signal })` for streaming Anthropic JSONL downloads
* Generated types for all request/response objects
* Full API coverage including chat completions, models, credits, and more
* TypeScript definitions for better development experience


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