# JavaScript / TypeScript SDK

> The @lykia/sdk client for Node.js, browsers and edge runtimes: setup, chat and streaming, errors, request tags, the Vercel AI SDK helper, a single-file build and a fake server for tests.

`@lykia/sdk` is a small TypeScript client for the Lykia API. It has no runtime dependencies and uses the global `fetch`, so it runs on Node.js 20 or newer, in modern browsers and on edge runtimes. It ships ESM and CommonJS builds with type declarations.

You do not need it to use Lykia: the [OpenAI SDK works with Lykia](https://www.getlykia.com/en/docs/guides/migrate-from-openai) by changing the base address and the key. The Lykia SDK adds what the OpenAI SDK has no place for: the request cost, the request id, Lykia's error classes and request tags.

> **Not on npm yet:** `@lykia/sdk` is being published to npm. Until it is, `npm install @lykia/sdk` will not find the package; call the API with the OpenAI SDK as shown in the [Quickstart](https://www.getlykia.com/en/docs/quickstart).

## Install

```bash
npm install @lykia/sdk
```

## First request

```typescript
import { Lykia } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

const res = await lykia.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Write a haiku about the sea." }],
});

console.log(res.choices[0].message.content);
console.log(res.usage?.cost, res._meta.generationId); // USD cost and the request id
```

`res.usage.cost` is what the request cost in USD, and `res._meta.generationId` is its request id (the `X-Generation-Id` header); look the record up later with `lykia.generations.get(id)`.

## Client options

```typescript
import { Lykia } from "@lykia/sdk";

const lykia = new Lykia({
  apiKey: process.env.LYKIA_API_KEY,
  baseURL: "https://api.getlykia.com/v1", // the default
  timeoutMs: 60_000, // the default
  maxRetries: 0, // the default: no automatic retries
  defaultHeaders: { "HTTP-Referer": "https://example.com", "X-Title": "Support bot" },
});

// Every method takes per-call options as its last argument
const controller = new AbortController();
const models = await lykia.models.list({}, { timeoutMs: 10_000, signal: controller.signal });
console.log(models.data.length);
```

- `apiKey` (string, required) — A project API key. Read it from an environment variable.
- `baseURL` (string) — Defaults to `https://api.getlykia.com/v1`.
- `timeoutMs` (number) — Time limit for one request. Defaults to 60 seconds.
- `maxRetries` (number) — Defaults to `0`. See [Errors](#errors).
- `fetch` (function) — A custom `fetch` implementation.
- `defaultHeaders` (object) — Headers sent with every request, for example the attribution headers `HTTP-Referer` and `X-Title`. An `Authorization` entry here is ignored.

Every method also takes per-call options `{ timeoutMs, signal, headers }` as its last argument.

## Streaming

`chat.completions.stream()` returns an async iterable of simple events:

```typescript
import { Lykia } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

const stream = lykia.chat.completions.stream({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Explain streaming in two sentences." }],
});

for await (const event of stream) {
  if (event.type === "text") process.stdout.write(event.delta);
  if (event.type === "tool_call") {
    // event.index, event.id, event.name, event.argumentsDelta
  }
  if (event.type === "done") {
    console.log("\n", event.finishReason, event.usage?.cost, event.generationId);
  }
}
```

| Event       | Fields                                                                                    |
| ----------- | ----------------------------------------------------------------------------------------- |
| `text`      | `delta`: the next piece of the answer.                                                    |
| `reasoning` | `delta`: thinking text, for models that return it.                                        |
| `tool_call` | `index`, `id`, `name`, `argumentsDelta`.                                                  |
| `done`      | `message` (the assembled message), `usage` (with `cost`), `finishReason`, `generationId`. |

If you only need the result, call `.final()`:

```typescript
import { Lykia } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

// Without iterating: wait for the assembled message
const { message, usage, finishReason } = await lykia.chat.completions
  .stream({ model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }] })
  .final();

console.log(message.content, usage?.cost, finishReason);
```

`message.tool_calls` carries complete argument strings. When a model returns `reasoning_details`, send the assistant message back unchanged in the next turn of a tool loop so the provider can continue its thinking. How streaming works on the wire is covered in [Streaming](https://www.getlykia.com/en/docs/guides/streaming).

## Other endpoints

```typescript
import { Lykia } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

await lykia.models.list({ supported_parameters: ["tools"] });
await lykia.models.get("openai/gpt-4o-mini");
await lykia.providers.list();
await lykia.key.get(); // label, limit, usage, company, project
await lykia.credits.get(); // balance, total_usage, reserved, available, billing_mode
await lykia.generations.get("gen-1732350000-AbCdEf0123456789");
await lykia.generations.list({ limit: 50 }); // newest first; pass next_cursor as `after` for the next page
```

These map to [`GET /models`](https://www.getlykia.com/en/docs/api-reference/models), [`GET /providers`](https://www.getlykia.com/en/docs/api-reference/providers), [`GET /key`](https://www.getlykia.com/en/docs/api-reference/key), [`GET /credits`](https://www.getlykia.com/en/docs/api-reference/credits) and [`GET /generation`](https://www.getlykia.com/en/docs/api-reference/generation).

## Presets, embeddings and request records

```typescript
import { Lykia, PRESETS, preset } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

// A preset in place of a model id; preset() checks the name, PRESETS lists the suggested names
const res = await lykia.chat.completions.create({
  model: preset("text"),
  messages: [{ role: "user", content: "Write a one-line welcome message." }],
  user: "tenant-42",
  metadata: { feature: "onboarding" },
});
console.log(res.model, res._meta.preset, PRESETS);

// Embeddings, and the request records of one end user
const vectors = await lykia.embeddings.create({ model: "@embedding", input: ["first text", "second text"] });
console.log(vectors.data.length, vectors.usage?.cost);

const page = await lykia.generations.list({ limit: 50, user: "tenant-42", metadata: { feature: "onboarding" } });
console.log(page.data.length, page.next_cursor);
```

- `model: "@text"` calls a [model preset](https://www.getlykia.com/en/docs/guides/model-presets); `preset("text")` builds the same string and checks the name. `PRESETS` lists the suggested names. The response's `model` is the real model, and `res._meta.preset` is the preset name from the `X-Lykia-Preset` header.
- `embeddings.create()` calls [`POST /embeddings`](https://www.getlykia.com/en/docs/api-reference/embeddings).
- `generations.list()` calls [`GET /generations`](https://www.getlykia.com/en/docs/api-reference/generations) with `user`, `preset`, `model`, `metadata`, `from`, `to`, `limit` and `after`; pass the returned `next_cursor` as `after` for the next page.
- `res._meta.reasoningDropped` is `true` when Lykia turned thinking off for a request (`X-Lykia-Reasoning: dropped`; see [Reasoning and prompt caching](https://www.getlykia.com/en/docs/guides/reasoning-and-caching)).

## Images, video, speech and transcription

```typescript
import { writeFile } from "node:fs/promises";
import { Lykia } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

// Images: a signed link (about one hour) per image, the cost in usage
const img = await lykia.images.generate({ model: "recraft/recraftv4_1", prompt: "a red bicycle on a cobbled street", n: 2 });
console.log(img.data[0].url, img.data[0].expires_at, img.usage.cost);

// Edit with a reference image; or ask for the bytes with response_format: "b64_json"
await lykia.images.generate({ model: "recraft/recraftv4_1", prompt: "the same street at night", images: [img.data[0].url] });

// Video: start a job, wait for it, then download the file
const job = await lykia.videos.create({ model: "bytedance/seedance-1.0-pro", prompt: "waves at dusk", duration: 5 });
const done = await lykia.videos.wait(job.id, { intervalMs: 5000 });
console.log(done.status, done.output?.url, done.usage?.cost);
const file = await lykia.videos.content(job.id);
await writeFile("waves.mp4", file.data);

// Speech: the audio bytes and the cost from X-Lykia-Cost
const speech = await lykia.audio.speech({ model: "elevenlabs/eleven_multilingual_v2", input: "Hello from Lykia.", voice: "JBFqnCBsd6RMkjVDRZzb" });
await writeFile("hello.mp3", speech.data);
console.log(speech.contentType, speech.cost);

// Voices: ready-made voices and your project's clones; cloning needs the speaker's consent
const voices = await lykia.audio.voices.list({ model: "elevenlabs/eleven_multilingual_v2" });
console.log(voices.data.map((v) => `${v.id} ${v.category}`));

// Transcription: the SDK always sends the file last, so the upload is streamed
const text = await lykia.audio.transcriptions.create({ model: "elevenlabs/scribe_v2", file: { path: "call.mp3" } });
console.log(text.text, text.usage?.cost);
```

Media methods take a media model id or a preset of the matching kind (`@image`, `@video`, `@tts`, `@stt`), and the same `user` and `metadata` tags as chat.

- `images.generate()` calls [`POST /images/generations`](https://www.getlykia.com/en/docs/api-reference/images-generations). `images` takes source images for editing; `response_format: "b64_json"` returns the bytes instead of a link.
- `videos.create()` starts a job ([`POST /videos`](https://www.getlykia.com/en/docs/api-reference/videos-create)); `videos.get()`, `videos.list()` and `videos.cancel()` map to the job endpoints. `videos.wait()` polls until the job ends and throws a `LykiaError` with the code `video_failed` or `video_cancelled` when it did not complete, or `timeout` when your own wait ran out (the job keeps running; call `wait` again). `videos.content()` downloads the file, `videos.contentUrl()` returns a fresh signed link ([`GET /videos/{id}/content`](https://www.getlykia.com/en/docs/api-reference/videos-content)).
- `audio.speech()` returns the audio as bytes with `contentType` and `cost` ([`POST /audio/speech`](https://www.getlykia.com/en/docs/api-reference/audio-speech)).
- `audio.voices.list()`, `audio.voices.create()` and `audio.voices.delete()` map to the [voice endpoints](https://www.getlykia.com/en/docs/api-reference/audio-voices-list). `create` needs `consent: true`, your statement that the speaker allowed the clone.
- `audio.transcriptions.create()` calls [`POST /audio/transcriptions`](https://www.getlykia.com/en/docs/api-reference/audio-transcriptions). The SDK always sends the file as the last form field, so the gateway streams the upload to the provider.

Links to stored files are signed for about an hour and re-signed on every read. Lykia keeps stored files for a limited time that the platform sets; a video job's `expires_at` says when. Download what you want to keep. Walkthroughs: [Image generation](https://www.getlykia.com/en/docs/guides/image-generation), [Video generation](https://www.getlykia.com/en/docs/guides/video-generation), [Speech and voices](https://www.getlykia.com/en/docs/guides/speech-and-voices), [Transcription](https://www.getlykia.com/en/docs/guides/transcription).

## Errors

Every failure is a `LykiaError`:

```typescript
import { Lykia, LykiaError } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

try {
  await lykia.chat.completions.create({
    model: "openai/gpt-4o-mini",
    messages: [{ role: "user", content: "Hello!" }],
  });
} catch (error) {
  if (error instanceof LykiaError) {
    console.error(error.status, error.code, error.reason, error.generationId);
    if (error.reason === "insufficient_credits") {
      // top up credits or raise the key's spending limit
    } else if (error.retryable) {
      // rate_limited, overloaded, timeout, provider_error or a network error: retry after error.retryAfter seconds
    }
  } else {
    throw error;
  }
}
```

| Field                  | Meaning                                                                                                                                                                                                     |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`               | The HTTP status. For an error in the middle of a stream it is the error's own `status`; `0` when there was no response.                                                                                     |
| `code`                 | A string code from the error body; `network_error`, `timeout` or `aborted` when there was no response.                                                                                                      |
| `reason`               | The stable error class, as in [Errors](https://www.getlykia.com/en/docs/guides/errors): `invalid_request`, `unauthorized`, `forbidden`, `insufficient_credits`, `limit_exceeded`, `rate_limited` and so on. |
| `retryable`            | `true` for `rate_limited`, `overloaded`, `timeout`, `provider_error` and network errors.                                                                                                                    |
| `retryAfter`           | Seconds to wait, from the error body or the `Retry-After` header.                                                                                                                                           |
| `generationId`, `body` | The request id and the parsed error body.                                                                                                                                                                   |

A provider failure after a stream has started is thrown from the iteration as a `LykiaError`, although the HTTP status stays `200`.

The SDK does not retry by default. With `maxRetries` above zero it retries read-only requests after network errors, `408`, `429` and `5xx`, and any request whose `429` carries `Retry-After` (Lykia rejected it before doing any work, so nothing was billed). It never resends a request that may already have run, and it does not wait longer than a minute on its own.

## Request tags

Chat and embedding requests accept `user` (your end user or tenant id) and `metadata` (string key-value pairs). Lykia stores them with the request record so you can break usage down by them ([Tags and usage breakdown](https://www.getlykia.com/en/docs/guides/tags-and-usage)); they are never sent to the provider. `sanitizeTags()` trims any input to the limits Lykia accepts, without throwing:

```typescript
import { Lykia, sanitizeTags } from "@lykia/sdk";

const lykia = new Lykia({ apiKey: process.env.LYKIA_API_KEY });

// Fit any input to the tag limits without throwing; warnings lists what was trimmed
const { user, metadata, warnings } = sanitizeTags({ user: "tenant-42", metadata: { product: "support-bot", plan: "pro" } });
if (warnings.length) console.warn(warnings);

const res = await lykia.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Summarize this ticket." }],
  user,
  metadata,
});
console.log(res._meta.generationId);
```

## Vercel AI SDK

Lykia works with the Vercel AI SDK's OpenAI-compatible provider. Always use the Chat Completions model (`provider.chatModel(...)` with `@ai-sdk/openai-compatible`, `provider.chat(...)` with `@ai-sdk/openai`), and pass `maxRetries: 0` so the AI SDK does not resend a request that was already billed.

The AI SDK drops the request cost, has no place for Lykia's tags, and can make a stream that failed halfway look like a normal finish. `createAiSdkFetch()` fixes this; pass it as the provider's `fetch`:

```typescript
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { streamText } from "ai";
import { createAiSdkFetch, type LykiaError } from "@lykia/sdk";

let streamError: LykiaError | undefined;

const lykia = createOpenAICompatible({
  name: "lykia",
  baseURL: "https://api.getlykia.com/v1",
  apiKey: process.env.LYKIA_API_KEY,
  includeUsage: true,
  fetch: createAiSdkFetch({
    tags: { user: "tenant-42", metadata: { product: "support-bot" } },
    onResult: (r) => console.log(r.generationId, r.cost, r.usage),
    onError: (e) => {
      streamError = e;
    },
    streamErrors: "part", // the default; or "throw"
  }),
});

const result = streamText({ model: lykia.chatModel("openai/gpt-4o-mini"), prompt: "Hello!", maxRetries: 0 });
for await (const part of result.fullStream) {
  if (part.type === "text-delta") process.stdout.write(part.text);
  if (part.type === "error") console.error(streamError?.status, streamError?.code, streamError?.reason);
}
```

- `tags`: an object or a function returning one; merged into every chat request body (tags already in the body win).
- `onResult`: called once per request with `generationId`, `cost`, `usage` and, for a cancelled request, `aborted: true`.
- `onError`: called with the full `LykiaError` for HTTP errors and for errors in the middle of a stream.
- `streamErrors`: `"part"` (default) hands a mid-stream error to the AI SDK as an `error` part after the partial text; `"throw"` makes reading the stream fail with the `LykiaError`.

Responses otherwise reach the AI SDK unchanged. The helper does not retry and does not log.

## Without npm: a single file

`dist/lykia-client.cjs` in the package is the whole client in one CommonJS file without dependencies (Node.js 18 or newer). Copy it into a plain JavaScript project and load it:

```text
const { Lykia, LykiaError } = require("./lykia-client.cjs");
```

Copy `dist/lykia-client.d.cts` next to it for TypeScript types. The file is generated by the package build; do not edit it.

## Testing with the fake server

`@lykia/sdk/testing` starts a local fake of the Lykia API for your tests, so they need no key and spend nothing:

```typescript
import { Lykia } from "@lykia/sdk";
import { chatChunks, createFakeLykia, fakeError } from "@lykia/sdk/testing";

const fake = await createFakeLykia();
const lykia = new Lykia({ apiKey: "lyk-v1-test", baseURL: fake.url });

// The next chat request fails with 429, the one after it streams "Hi"
fake.enqueue("POST /chat/completions", fakeError(429, { reason: "rate_limited", retry_after: 2 }));
fake.enqueue("POST /chat/completions", { stream: chatChunks({ text: "Hi" }) });

const body = { model: "openai/gpt-4o-mini", messages: [{ role: "user" as const, content: "Hello" }] };
try {
    await lykia.chat.completions.create(body);
} catch (error) {
    console.log("first call failed:", error); // LykiaError: status 429, reason "rate_limited", retryAfter 2
}
const { message } = await lykia.chat.completions.stream(body).final();
console.log(message.content, fake.requests.length); // "Hi", 2

await fake.close();
```

The fake checks what the real API checks: a bearer key on every request, tag limits and body fields. Without a queued answer every endpoint replies with a realistic default (usage with cost, request records you can look up by id). Queued answers can also simulate failures such as a dropped connection, a slow first byte or an error in the middle of a stream. `createFakeLykia({ strict: false })` accepts anything.

## Security

- Keep API keys on your server. The SDK refuses to run in a browser page unless you pass `dangerouslyAllowBrowser: true`.
- The key is kept in private fields: `JSON.stringify` and `console.log` of the client never show it.
- The key is only sent to `baseURL`; redirects to another origin never carry it.
- The SDK sends no telemetry.

## Related

- [MCP: connect Lykia to your AI client](https://www.getlykia.com/en/docs/guides/mcp): use Lykia from Claude, Cursor or VS Code.
- [Errors](https://www.getlykia.com/en/docs/guides/errors): status codes and error classes.
- [Streaming](https://www.getlykia.com/en/docs/guides/streaming): the stream format.
