Chat Completions
Full specification for Chat Completions requests, responses, SSE streaming, tool calling, structured JSON outputs, and SDK setup.
POST/v1/chat/completions
Implements OpenAI's Chat Completions API. Authenticate with Authorization: or x-api-key.
Send a request
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." }]
}'
{
"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 }
}
Request body
modelstringrequired- Catalog model ID, such as
anthropic/.claude-sonnet-5. 5 messagesarrayrequired- Conversation history. Each entry specifies a
role(system,user,assistant, ortool) andcontent(plain string or content-part array includingimage_urlfor vision). streamboolean- Stream tokens as server-sent events. Defaults to
false. stream_optionsobject- Pass
{so the final usage frame matches OpenAI's schema with an empty"include_ usage": true } choicesarray. max_tokensinteger- Output token limit that also sets the credit hold while running.
max_completion_tokensbehaves identically; if both are provided, the larger value determines the hold. HeyEly never lowers an explicit cap you provide. temperaturenumber- Sampling temperature.
top_pnumber- Nucleus sampling threshold.
stopstring | array- Stop sequences that halt generation.
toolsarray- Callable function schemas. See Tool calling.
tool_choicestring | objectauto,none,required, or a named function target.response_formatobjectjson_objectorjson_schema. See Structured outputs.reasoningobject- Controls thinking budget on reasoning models via
{or"effort": "low" | "medium" | "high" } { "max_tokens": 2000 }. modalitiesarray- Pass
["image", "text"]on multimodal chat models that generate images inline. seedinteger- 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 , 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 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.
Response
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.
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 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." }]
}'
The final frame ahead of [DONE] includes usage. Passing stream_ 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. 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: and relay events as upstream emits them.
Sequences
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]
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_, 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., response., response., response., response.reasoning.delta, response.reasoning.done, response., response., response., response., 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.completedfor a finished replyresponse.incompletewhen halted early (checkincomplete_details)response.failedfor 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_ updates, finishes with image_ (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
errorobject paired withfinish_reason: "error" - Responses:
response.failedorerrorevent - Messages:
errorevent
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 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"]
}
}
}]
}'
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.
{
"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).
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 { , read function_call items from output, and send results back inside input as function_call_output.
{
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
}
Structured outputs
Request strict schema-validated JSON via response_format with type: "json_schema", or free-form JSON objects via { . Both modes require a model advertising response_format or structured_outputs in supported_parameters.
Request a schema
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
}
}
}
}'
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.
from openai import OpenAI
client = OpenAI(
base_url="https://heyely.si/v1",
api_key="sk-df-...",
)
Supported endpoints
| Endpoint | Notes |
|---|---|
POST | 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/namecatalog IDs (such asanthropic/) to the endpoint matching the model's modality. Read Choose a model.claude-sonnet-5. 5 - Calls execute strictly on the requested model at that model's rate. Routing overrides (
models,fallbacks,route,provider) return400, as dounsupported_ parameter pluginsoutside the free allowlist (response-healing,file-parseroncloudflare-aiornative, andcontext-compressionwithenabled: false). On Images,noutside integers 1 to 10 returns400 invalid_parameter. - Chat Completions, legacy Completions, Embeddings, and Images overwrite
userwith 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 setx-astra-costin micro-dollars (provisional when carrying a generation ID, final on Images when cost is reported, or0when an image succeeds without a reported cost).
Files and server tools
- Models listing
fileinput read attachments directly. For models without native file support, Chat Completions automatically invokes the freecloudflare-aiparser, whereas Responses and Messages return400unless you passunsupported_ parameter "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_callsto lower the step ceiling from its default of 30 (ignored ifstop_server_tools_whenis set, which holds the ceiling at 30). - X search (
x_search) and audio input (input_audio) return400, and models billed per search (such asunsupported_ parameter perplexity/) returnsonar-deep-research 400 unsupported_model.
Streaming
Chat streams emit a final usage chunk ahead of [DONE]. With stream_, 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.
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
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)
client.responses and client.embeddings work identically. Because the OpenAI SDK's image helpers target OpenAI's own paths, call POST /v1/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.
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)
messages.count_tokens is unavailable. The Claude Agent SDK picks up ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN just like Claude Code.
Vercel AI SDK
Point @ai-sdk/ at https://heyely.si/v1:
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:
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
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: 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.
Want to wire up a coding editor or CLI instead? Continue to Coding tools.