# Chat Completions

> Full specification for Chat Completions requests, responses, SSE streaming, tool calling, structured JSON outputs, and SDK setup.

**POST** `https://heyely.si/v1/chat/completions`

Implements OpenAI's Chat Completions API. Authenticate with `Authorization: Bearer sk-df-...` or `x-api-key`.

## Send a request

**curl**

```bash
curl https://heyely.si/v1/chat/completions \
  -H "Authorization: Bearer $HEYELY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5.5",
    "messages": [{ "role": "user", "content": "Say hello in one sentence." }]
  }'
```

**Python**

```python
import os
from openai import OpenAI

client = OpenAI(base_url="https://heyely.si/v1", api_key=os.environ["HEYELY_API_KEY"])

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(response.choices[0].message.content)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://heyely.si/v1",
  apiKey: process.env.HEYELY_API_KEY,
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5.5",
  messages: [{ role: "user", content: "Say hello in one sentence." }],
});
console.log(response.choices[0].message.content);
```

## Request body

* `model` (string, required): Catalog model ID, such as `anthropic/claude-sonnet-5.5`.
* `messages` (array, required): Conversation history. Each entry specifies a `role` (`system`, `user`, `assistant`, or `tool`) and `content` (plain string or content-part array including `image_url` for vision).
* `stream` (boolean): Stream tokens as server-sent events. Defaults to `false`.
* `stream_options` (object): Pass `{ "include_usage": true }` so the final usage frame matches OpenAI's schema with an empty `choices` array.
* `max_tokens` (integer): Output token limit that also sets the credit hold while running. `max_completion_tokens` behaves identically; if both are provided, the larger value determines the hold. HeyEly never lowers an explicit cap you provide.
* `temperature` (number): Sampling temperature.
* `top_p` (number): Nucleus sampling threshold.
* `stop` (string | array): Stop sequences that halt generation.
* `tools` (array): Callable function schemas. See [Tool calling](https://heyely.si/docs/api-reference/chat-completions#tools-and-json).
* `tool_choice` (string | object): `auto`, `none`, `required`, or a named function target.
* `response_format` (object): `json_object` or `json_schema`. See [Structured outputs](https://heyely.si/docs/api-reference/chat-completions#tools-and-json).
* `reasoning` (object): Controls thinking budget on reasoning models via `{ "effort": "low" | "medium" | "high" }` or `{ "max_tokens": 2000 }`.
* `modalities` (array): Pass `["image", "text"]` on multimodal chat models that generate images inline.
* `seed` (integer): Requests deterministic sampling where supported by the model.

Additional parameters pass upstream, where providers ignore unsupported options. Routing overrides (`models`, `fallbacks`, `route`, `provider`) are rejected with `400 unsupported_parameter`, along with any `plugins` entry outside `response-healing`, `file-parser` on `cloudflare-ai` or `native`, or `context-compression` with `enabled: false`. Unsupported tool types (anything outside `function`, `custom`, and supported web search), X search, and audio input return `400 unsupported_parameter` as well. HeyEly replaces `user` with a non-reversible account tag.

Use `max_tokens` or `max_completion_tokens` to control both output length and credit holds. Explicit caps are always honored verbatim, failing upfront if your available credit cannot cover the hold. When you omit an output cap and invoke no server tools, HeyEly can reduce its default cap so the hold fits your remaining account credit or key limit; requests invoking server tools must fit their entire hold. See [Credit](https://heyely.si/docs/concepts/credit-and-activation).

## Response

```json
{
  "id": "gen-1760000000-Ab3xQz9k",
  "object": "chat.completion",
  "created": 1760000000,
  "model": "anthropic/claude-sonnet-5.5",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "Hello, nice to meet you." },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 14, "completion_tokens": 7, "total_tokens": 21 }
}
```

`finish_reason` reports `stop`, `length`, `tool_calls`, `content_filter`, or `error`.

`usage` forwards provider-specific counters including cached tokens, reasoning tokens, and raw cost. Open models bill OpenRouter's price plus OpenRouter's 5% platform fee; Private models bill the confidential provider's price (Phala or NEAR AI) plus a 5% routing fee. HeyEly adds zero markup, reporting your charge in `x-astra-cost` and [Credit and usage](https://heyely.si/docs/concepts/credit-and-activation#usage).

## Response headers

| Header         | Meaning                                                                                                                   |
| -------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `x-request-id` | Unique request ID attached to every response (including errors), visible in Credit and usage once dispatched upstream     |
| `x-astra-cost` | Billed amount in micro-dollars on completed non-streamed calls (provisional whenever the payload carries a generation ID) |

## Streaming

Enable `stream: true` to receive token-by-token server-sent events ending with `data: [DONE]` (preceded by a final `usage` chunk). HeyEly forwards chunks immediately without buffering so first-token latency stays minimal.

### Chat Completions

**curl**

```bash
curl https://heyely.si/v1/chat/completions \
  -H "Authorization: Bearer $HEYELY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5.5",
    "stream": true,
    "stream_options": { "include_usage": true },
    "messages": [{ "role": "user", "content": "Write a haiku about ledgers." }]
  }'
```

**Python**

```python
import os
from openai import OpenAI

client = OpenAI(base_url="https://heyely.si/v1", api_key=os.environ["HEYELY_API_KEY"])

stream = client.chat.completions.create(
    model="anthropic/claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Write a haiku about ledgers."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="")
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://heyely.si/v1",
  apiKey: process.env.HEYELY_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5.5",
  messages: [{ role: "user", content: "Write a haiku about ledgers." }],
  stream: true,
  stream_options: { include_usage: true },
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
```

The final frame ahead of `[DONE]` includes `usage`. Passing `stream_options.include_usage: true` emits an empty `choices` array matching OpenAI's convention; omitting it leaves a single choice with an empty delta, so guard `choices[0]` before reading `delta`.

### Messages and Responses

`POST /v1/messages` streams `message_start`, content block lifecycle events, `message_delta`, and `message_stop`. `POST /v1/responses` streams delta events such as `response.output_text.delta` and finishes on `response.completed`, `response.incomplete`, or `response.failed`. HeyEly relays both event streams verbatim.

### Keepalives

During slow reasoning or long pauses, streams may emit SSE comment lines beginning with `:` or `ping` events. Standard SSE clients skip comments automatically; custom line parsers should ignore any line that does not begin with `data:`.

### Cancelling

Aborting the client socket stops local token delivery, though HeyEly drains the upstream response to completion and bills for tokens produced by the model.

### Errors in a stream

Once response headers flush with HTTP `200`, mid-stream failures arrive inside the event stream itself. Inspect incoming chunks for an `error` event or `finish_reason: "error"` before accepting generated output.

If the upstream socket drops abruptly, the stream closes without an error frame. Treat any stream terminating without its expected closing marker (`[DONE]`, `message_stop`, or a terminal `response.*` event) as incomplete.

### Streaming events

All streams use `content-type: text/event-stream` and relay events as upstream emits them.

#### Sequences

**Chat Completions**

```text
data: {"id":"gen-...","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}

data: {"id":"gen-...","choices":[{"index":0,"delta":{"content":"Hello"}}]}

data: {"id":"gen-...","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

# with stream_options.include_usage
data: {"id":"gen-...","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":7,"total_tokens":21}}

data: [DONE]
```

**Responses**

```text
event: response.created
event: response.in_progress
event: response.output_item.added
event: response.content_part.added
event: response.output_text.delta
event: response.output_text.done
event: response.content_part.done
event: response.output_item.done
event: response.completed
```

**Messages**

```text
event: message_start
event: content_block_start
event: content_block_delta
event: content_block_stop
event: message_delta
event: message_stop
```

#### Chat Completions

Incremental frames deliver token deltas inside `choices[].delta`, with `finish_reason` arriving on the final content chunk and `usage` arriving immediately prior to `data: [DONE]`.

With `stream_options.include_usage`, the usage chunk sends an empty `choices` array; without it, `choices` retains one entry containing an empty delta. Comment lines prefixed with `:` may appear between chunks and should be ignored.

#### Responses

Common event names include `response.created`, `response.in_progress`, `response.output_item.added`, `response.content_part.added`, `response.output_text.delta`, `response.output_text.done`, `response.reasoning.delta`, `response.reasoning.done`, `response.content_part.done`, `response.function_call_arguments.delta`, `response.function_call_arguments.done`, `response.output_item.done`, `response.completed`, `response.incomplete`, `response.failed`, and `error` (any additional upstream event names pass straight through). Streams end with an `error` event or one of three terminal states carrying the final response object and usage:

* `response.completed` for a finished reply
* `response.incomplete` when halted early (check `incomplete_details`)
* `response.failed` for a generation failure

#### Messages

`message_start` reports initial input token counts. Each content block emits `content_block_start`, one or more `content_block_delta` frames (`text_delta`, `input_json_delta`, `thinking_delta`, or `signature_delta`), and `content_block_stop`.

`message_delta` reports `stop_reason` and cumulative `usage.output_tokens`, followed by `message_stop`. `ping` keepalives and mid-stream `error` events can appear at any point; ignore unfamiliar event types.

#### Images

On image models that support streaming, `POST /v1/images` streams `image_generation.partial_image` updates, finishes with `image_generation.completed` (final image plus usage), and closes on `data: [DONE]`. An `error` event can short-circuit either stage.

#### Errors

Mid-stream errors stay on HTTP `200` and signal failure through the stream payload:

* Chat Completions: top-level `error` object paired with `finish_reason: "error"`
* Responses: `response.failed` or `error` event
* Messages: `error` event

## Tools and JSON

### Tool calling

Function calling works on every model listing `tools` in `supported_parameters`. Confirm support on `GET /v1/models` or the model's catalog entry before wiring tools into production.

#### Define a tool

**curl**

```bash
curl https://heyely.si/v1/chat/completions \
  -H "Authorization: Bearer $HEYELY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5.5",
    "messages": [{ "role": "user", "content": "What is the weather in Lisbon?" }],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": { "city": { "type": "string" } },
          "required": ["city"]
        }
      }
    }]
  }'
```

**Python**

```python
import json, os
from openai import OpenAI

client = OpenAI(base_url="https://heyely.si/v1", api_key=os.environ["HEYELY_API_KEY"])

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "What is the weather in Lisbon?"}]
response = client.chat.completions.create(model="anthropic/claude-sonnet-5.5", messages=messages, tools=tools)
call = response.choices[0].message.tool_calls[0]
print(call.function.name, json.loads(call.function.arguments))
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://heyely.si/v1",
  apiKey: process.env.HEYELY_API_KEY,
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5.5",
  messages: [{ role: "user", content: "What is the weather in Lisbon?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the current weather for a city.",
        parameters: {
          type: "object",
          properties: { city: { type: "string" } },
          required: ["city"],
        },
      },
    },
  ],
});
console.log(response.choices[0].message.tool_calls);
```

#### Read the call

When the model requests a function call, `finish_reason` reads `tool_calls` and `message.tool_calls` contains each requested function name alongside its serialized JSON argument string.

#### Return the result

Append the assistant message to `messages`, add one `role: "tool"` message per tool call matching its `tool_call_id`, and send the updated history back to the model.

```json
{
  "role": "tool",
  "tool_call_id": "call_abc123",
  "content": "{\"temperature_c\": 21, \"sky\": \"clear\"}"
}
```

#### Control the choice

Set `tool_choice` to `"auto"` (default), `"none"`, `"required"`, or a specific function selector.

#### On Messages and Responses

`POST /v1/messages` expects Anthropic's native `tools` and `tool_use` block syntax, forwarding the body intact except for catalog model-ID normalization and capping `web_search` `max_uses` to the tool-step allowance (see [Messages](https://heyely.si/docs/api-reference#credit-held)).

`POST /v1/responses` preserves everything except catalog model-ID normalization, so supply OpenAI's Responses tool shapes rather than the nested `function` wrapper and `role: "tool"` messages used by Chat Completions: define tools flat, target a specific function with `{ "type": "function", "name": "get_weather" }`, read `function_call` items from `output`, and send results back inside `input` as `function_call_output`.

**Tool**

```json
{
  "type": "function",
  "name": "get_weather",
  "description": "Get the current weather for a city.",
  "parameters": {
    "type": "object",
    "properties": { "city": { "type": "string" } },
    "required": ["city"]
  }
}
```

**Call**

```json
{
  "type": "function_call",
  "call_id": "call_abc123",
  "name": "get_weather",
  "arguments": "{\"city\": \"Lisbon\"}"
}
```

**Result**

```json
{
  "type": "function_call_output",
  "call_id": "call_abc123",
  "output": "{\"temperature_c\": 21, \"sky\": \"clear\"}"
}
```

### Structured outputs

Request strict schema-validated JSON via `response_format` with `type: "json_schema"`, or free-form JSON objects via `{ "type": "json_object" }`. Both modes require a model advertising `response_format` or `structured_outputs` in `supported_parameters`.

#### Request a schema

**curl**

```bash
curl https://heyely.si/v1/chat/completions \
  -H "Authorization: Bearer $HEYELY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5.5",
    "messages": [{ "role": "user", "content": "Extract: Ada paid $12.40 on Oct 8." }],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "payment",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": { "type": "string" },
            "amount_usd": { "type": "number" },
            "date": { "type": "string" }
          },
          "required": ["name", "amount_usd", "date"],
          "additionalProperties": false
        }
      }
    }
  }'
```

**Python**

```python
import json, os
from openai import OpenAI

client = OpenAI(base_url="https://heyely.si/v1", api_key=os.environ["HEYELY_API_KEY"])

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Extract: Ada paid $12.40 on Oct 8."}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "payment",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "amount_usd": {"type": "number"},
                    "date": {"type": "string"},
                },
                "required": ["name", "amount_usd", "date"],
                "additionalProperties": False,
            },
        },
    },
)
print(json.loads(response.choices[0].message.content))
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://heyely.si/v1",
  apiKey: process.env.HEYELY_API_KEY,
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5.5",
  messages: [{ role: "user", content: "Extract: Ada paid $12.40 on Oct 8." }],
  response_format: {
    type: "json_schema",
    json_schema: {
      name: "payment",
      strict: true,
      schema: {
        type: "object",
        properties: {
          name: { type: "string" },
          amount_usd: { type: "number" },
          date: { type: "string" },
        },
        required: ["name", "amount_usd", "date"],
        additionalProperties: false,
      },
    },
  },
});
console.log(JSON.parse(response.choices[0].message.content ?? "{}"));
```

#### Check the result

`message.content` arrives as a JSON string: parse it and validate it with your application schema. If `finish_reason` reads `length`, the JSON may be truncated, so increase `max_tokens` and retry.

#### Models without support

Sending `response_format` to an unsupported model (or submitting an invalid JSON schema) surfaces the provider's error, typically HTTP `400`. Check `supported_parameters` beforehand; because `provider` overrides are disallowed, you cannot force an alternate endpoint. For models without schema enforcement, describe the JSON structure in your prompt and validate client-side.

## OpenAI compatibility

HeyEly implements OpenAI's Chat Completions, legacy text Completions, Responses, and Embeddings protocols. Point your existing OpenAI client at `https://heyely.si/v1` with your HeyEly API key and keep the rest of your code unchanged.

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://heyely.si/v1",
    api_key="sk-df-...",
)
```

### Supported endpoints

| Endpoint                    | Notes                                                                                                     |
| --------------------------- | --------------------------------------------------------------------------------------------------------- |
| `POST /v1/chat/completions` | Supports streaming, tools, structured JSON outputs, and inline images where supported by the model        |
| `POST /v1/completions`      | Legacy text completions with streaming support. Requires `prompt` and a compatible model                  |
| `POST /v1/responses`        | Stateless endpoint; pass the complete conversation in `input` on every call                               |
| `POST /v1/embeddings`       | Embedding models only                                                                                     |
| `POST /v1/images`           | HeyEly's image generation route; call directly because OpenAI SDK `images.generate` hits a different path |
| `GET /v1/models`            | Public catalog listing (no API key needed)                                                                |
| `GET /v1/models/{id}`       | Single model record                                                                                       |
| `GET /v1/key`               | Active key cap, cumulative spend, and available credit                                                    |

For legacy completions, pass `prompt` as a string or array and bound reply length with `max_tokens`. Not every chat model accepts legacy text completions.

### How requests are handled

* Unrecognized parameters forward upstream so providers can ignore anything a model does not implement. Chat Completions and legacy Completions without an explicit output cap and without server tools can have their default cap lowered to fit spendable balance; explicit caps are kept untouched.
* Always pass `author/name` catalog IDs (such as `anthropic/claude-sonnet-5.5`) to the endpoint matching the model's modality. Read [Choose a model](https://heyely.si/docs/models).
* Calls execute strictly on the requested model at that model's rate. Routing overrides (`models`, `fallbacks`, `route`, `provider`) return `400 unsupported_parameter`, as do `plugins` outside the free allowlist (`response-healing`, `file-parser` on `cloudflare-ai` or `native`, and `context-compression` with `enabled: false`). On Images, `n` outside integers 1 to 10 returns `400 invalid_parameter`.
* Chat Completions, legacy Completions, Embeddings, and Images overwrite `user` with an irreversible account tag, and every endpoint normalizes non-catalog model IDs (including stripping trailing `[1m]`). Responses leaves the rest of the body intact.
* Every response includes `x-request-id` (errors included). Completed non-streamed responses also set `x-astra-cost` in micro-dollars (provisional when carrying a generation ID, final on Images when cost is reported, or `0` when an image succeeds without a reported cost).

### Files and server tools

* Models listing `file` input read attachments directly. For models without native file support, Chat Completions automatically invokes the free `cloudflare-ai` parser, whereas Responses and Messages return `400 unsupported_parameter` unless you pass `"plugins": [{ "id": "file-parser", "pdf": { "engine": "cloudflare-ai" } }]`.
* Every inline or URL file attachment and URL-referenced image or video reserves the larger of the text estimate and the model's context window (or 1,000,000 tokens if unknown).
* Server-run tools like web search reserve credit step-by-step. Pass `max_tool_calls` to lower the step ceiling from its default of 30 (ignored if `stop_server_tools_when` is set, which holds the ceiling at 30).
* X search (`x_search`) and audio input (`input_audio`) return `400 unsupported_parameter`, and models billed per search (such as `perplexity/sonar-deep-research`) return `400 unsupported_model`.

### Streaming

Chat streams emit a final `usage` chunk ahead of `[DONE]`. With `stream_options.include_usage`, `choices` is empty (`[]`); otherwise `choices` contains one empty-delta item.

### Not available

HeyEly does not expose OpenAI's audio, files, batches, assistants, fine-tuning, moderation, or image paths (`/v1/images/generations`, edits, and variations); requests to those routes answer `404`.

### Errors

Errors use OpenAI's standard JSON envelope containing `error.message`, `error.type`, `error.code`, and `error.param`. See [Errors](https://heyely.si/docs/api-reference/errors).

## SDKs and clients

You do not need a proprietary SDK to use HeyEly. Configure the base URL and API key in whichever library you already maintain.

| Client                             | Base URL               |
| ---------------------------------- | ---------------------- |
| OpenAI SDK (Python, TypeScript)    | `https://heyely.si/v1` |
| Anthropic SDK (Python, TypeScript) | `https://heyely.si`    |
| Vercel AI SDK, LiteLLM, LangChain  | `https://heyely.si/v1` |

Each snippet below reads your secret from `HEYELY_API_KEY`.

### OpenAI SDK

**Python**

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://heyely.si/v1",
    api_key=os.environ["HEYELY_API_KEY"],
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(response.choices[0].message.content)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://heyely.si/v1",
  apiKey: process.env.HEYELY_API_KEY,
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5.5",
  messages: [{ role: "user", content: "Say hello in one sentence." }],
});
console.log(response.choices[0].message.content);
```

`client.responses` and `client.embeddings` work identically. Because the OpenAI SDK's image helpers target OpenAI's own paths, call [`POST /v1/images`](https://heyely.si/docs/api-reference#images) directly for image generation.

### Anthropic SDK

Omit `/v1` from the base URL because the Anthropic SDK appends `/v1/messages` automatically and sends credentials via `x-api-key`.

**Python**

```python
import os
import anthropic

client = anthropic.Anthropic(
    base_url="https://heyely.si",
    api_key=os.environ["HEYELY_API_KEY"],
)

message = client.messages.create(
    model="anthropic/claude-sonnet-5.5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(message.content[0].text)
```

**TypeScript**

```typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  baseURL: "https://heyely.si",
  apiKey: process.env.HEYELY_API_KEY,
});

const message = await client.messages.create({
  model: "anthropic/claude-sonnet-5.5",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Say hello in one sentence." }],
});
console.log(message.content);
```

`messages.count_tokens` is unavailable. The Claude Agent SDK picks up `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN` just like [Claude Code](https://heyely.si/docs/coding-tools/claude-code).

### Vercel AI SDK

Point `@ai-sdk/openai-compatible` at `https://heyely.si/v1`:

```typescript
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { generateText } from "ai";

const heyely = createOpenAICompatible({
  name: "heyely",
  baseURL: "https://heyely.si/v1",
  apiKey: process.env.HEYELY_API_KEY,
});

const { text } = await generateText({
  model: heyely("anthropic/claude-sonnet-5.5"),
  prompt: "Say hello in one sentence.",
});
console.log(text);
```

### LiteLLM

Prepend `openai/` to HeyEly's catalog ID so LiteLLM routes via its OpenAI-compatible adapter:

```python
import os
import litellm

response = litellm.completion(
    model="openai/anthropic/claude-sonnet-5.5",
    api_base="https://heyely.si/v1",
    api_key=os.environ["HEYELY_API_KEY"],
    messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(response.choices[0].message.content)
```

### LangChain

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="anthropic/claude-sonnet-5.5",
    base_url="https://heyely.si/v1",
    api_key=os.environ["HEYELY_API_KEY"],
)
print(llm.invoke("Say hello in one sentence.").content)
```

### Plain HTTP

Plain HTTP works from any language or shell: send a JSON body with `Authorization: Bearer sk-df-...` or `x-api-key` to any inference `POST` endpoint, call `GET /v1/models` publicly, or inspect credit with `GET /v1/key`. Refer to the curl snippet at the top of [Chat Completions](https://heyely.si/docs/api-reference/chat-completions).

Want to wire up a coding editor or CLI instead? Continue to [Coding tools](https://heyely.si/docs/coding-tools).
