API AccessDEVELOPER GUIDE

Build with RelayCode.

Use your RelayCode API key to discover the model catalog and read your account usage.

YOUR BASE URLhttps://relaycode.site/v1
START HERE

Your first working request

You need a RelayCode account and a personal API key. Free accounts can use the API too.

  1. 1

    Get your key

    Sign in and open API Access. Create a personal key and keep it private.

  2. 2

    Set it on your computer or server

    Pick your operating system. Replace the placeholder, then run the command in your terminal.

    macOS / Linux · environment variable
    # macOS / Linux: replace the placeholder with your personal key.
    export RELAYCODE_API_KEY='YOUR_RELAYCODE_KEY'
  3. 3

    Choose a model and copy an example

    The example uses your selection below. Copying it does not run a request or use your allowance.

    Examples use the published catalog while the live list loads.

cURL · first message
curl --fail-with-body 'https://relaycode.site/v1/chat/completions' \
  -H "Authorization: Bearer $RELAYCODE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "glm-5.3-flash-current",
  "messages": [
    {
      "role": "user",
      "content": "Hello from RelayCode!"
    }
  ],
  "max_tokens": 4096
}'

cURL examples use Bash on macOS/Linux. Select PowerShell for Windows. Run Python or JavaScript examples on your server; never put a personal API key in public browser code.

Base URL & endpoints

For OpenAI-compatible applications, choose Chat Completions or stateless Responses. Text keys discover their permitted text models. A model copied from another service is not automatically a RelayCode model: fetch the current IDs with your own key.

Paste https://relaycode.site/v1 into your client’s OpenAI-compatible base URL field. Add the endpoint only when making a raw HTTP request.

Base URLhttps://relaycode.site/v1Full chat endpointhttps://relaycode.site/v1/chat/completions

Do not put /chat/completions in an SDK’s base URL field. The canonical version is /v1, with the letter v immediately followed by 1. Clients such as eGPT can choose Responses with store:false. Both protocols use the same key, model permissions and usage accounting.

TaskMethodEndpoint after the base URL
List text modelsGET/models
List all model typesGET/models?type=all
Send a messagePOST/chat/completions
Stateless ResponsesPOST/responses
Roleplay messagePOST/roleplay/chat/completions
Check usageGET/usage
Generate an imagePOST/images/generations

Open API discovery for a machine-readable list. All examples here use RelayCode’s public connection address.

Responses API

POST /v1/responses supports stateless text/image conversations and function tools using the same key and model IDs. Set store:false and send the full input history on every turn. Stored-response retrieval, previous_response_id, background mode and hosted tools are unavailable.

JavaScript · Responses
import OpenAI from "openai";

// Node.js 18+ · save as an .mjs file · keep your key on your server
const client = new OpenAI({ baseURL: "https://relaycode.site/v1", apiKey: process.env.RELAYCODE_API_KEY });

const response = await client.responses.create({
  model: "glm-5.3-flash-current",
  store: false,
  instructions: "Give concise, accurate answers.",
  input: "Explain this code.",
  max_output_tokens: 4096,
  reasoning: { effort: "low" },
  include: ["reasoning.encrypted_content"]
});
console.log(response.output_text);

Use flat function tools: {type:"function", name:"read_file", parameters:{type:"object", properties:{}, additionalProperties:false}, strict:true}. Selection accepts auto, none, required or {type:"function", name:"read_file"}; parallel_tool_calls:false requests one call at a time. Your application executes the tool with its own permission checks.

JavaScript · continue after tool results
const next = await client.responses.create({
  model: "glm-5.3-flash-current", store: false,
  input: [
    ...previousInput, ...response.output,
    { type: "function_call_output", call_id: call.call_id, output: toolResult }
  ],
  tools, max_output_tokens: 4096
});

With stream:true, read response.output_text.delta and response.function_call_arguments.delta. A successful stream ends with response.completed, including the full response and complete arguments. Check status before executing a call: interrupted/provider failures produce response.failed; output limits produce response.incomplete. Partial output is never automatically replayed.

Use the model’s advertised reasoning efforts (GPT-6.1 Sol includes low, medium and high). include:["reasoning.encrypted_content"] returns encrypted continuation only when the provider produces reasoning. This is RelayCode’s opaque continuation format, bound to your current key and model for24hours; it is not interchangeable with another provider’s ciphertext. Preserve the full reasoning item in history. When the model returns readable reasoning, it arrives as a reasoning item with summary_text (streamed as response.reasoning_summary_text.delta); opaque provider reasoning is never exposed. safety_identifier accepts an opaque identifier; never send an email or other unnecessary personal data. Responses are not saved for later retrieval; existing usage/security metadata retention still applies.

Structured output uses text.format: text, json_object or json_schema with name/schema/strict. Validate generated JSON and tool arguments in your application.

Your API key

Send your personal tn-live- key in the Authorization header:

Request header
Authorization: Bearer YOUR_RELAYCODE_KEY
  • Your primary key works across your trusted clients. For separate tools, create named keys on the API page: up to 3 on Free, 5 on Basic, 10 on Plus and 20 on Max. Every key on your account shares the same plan limits and Text allowance; creating, rotating or revoking a key never resets usage.
  • Rotating your key stops new requests with the old key. It does not reset usage or cancel already running work.
  • Keep the key out of screenshots, public code and browser JavaScript. If exposed, rotate it on API Access.
What about a Custom API key?

Custom API keys are admin-issued or purchased on the Pricing page. A tn-custom- key is text-only and works with the chat and Responses endpoints; a tn-video- key is video-only and works with the /v1/video endpoints. Each key has its own balance and model restrictions and does not inherit an account’s monthly allowances. Revoked or disabled keys cannot be used. The examples in this guide use personal account keys.

Choose a model

Use the exact public id from GET /v1/models. Display names are for reading; IDs go into requests. Your selected example ID is glm-5.3-flash-current.

cURL · list available models
curl --fail-with-body 'https://relaycode.site/v1/models?type=all' \
  -H "Authorization: Bearer $RELAYCODE_API_KEY"
FieldHow to use it
idCopy it into the model field.
capabilitiesCheck tool_calling, vision, streaming, web_search and reasoning_efforts.
context_lengthThe advertised context size, where reported. It is not a guarantee every request size is accepted.
max_output_tokensRelayCode’s current output cap. Reasoning tokens also consume this budget.
healthAvailable, checking, degraded or unavailable. Try another model if a route is unavailable.
usage_policyThe shared text, monthly USD allowances and model-specific input/output rates.

Browse the model directory . Retired IDs are rejected; an old saved conversation remains readable.

Client format

For the models in this guide, start with OpenAI-compatible Chat Completions. A client’s protocol and requested model ID must both be supported; changing only its base URL cannot add an unsupported model or protocol.

Send a message

POST /v1/chat/completions accepts a model ID and conversation history. Include earlier user and assistant messages when you want the model to remember the conversation.

JSON · request body
{
  "model": "glm-5.3-flash-current",
  "messages": [
    {
      "role": "user",
      "content": "Hello from RelayCode!"
    }
  ],
  "max_tokens": 4096
}
ParameterUse it for
modelRequired. A current public model ID.
messagesRequired. User, assistant, system and tool messages; at most 10,000.
max_tokensOutput budget. max_completion_tokens is also accepted. Start with 4,096 for reasoning tasks; the live model cap and your remaining allowance still apply.
streamtrue for a stream; false or omitted for one JSON response.
reasoning_effortUse only an effort listed by the chosen model. Unsupported values return 400.
tools / tool_choiceFunction calling, where advertised.
temperature / top_p / stopSampling controls. Support varies by model.
response_formatJSON output where supported. Always validate the generated result.
What does a JSON response look like?
JSON · illustrative response
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "model": "glm-5.3-flash-current",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello!"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 8,
    "total_tokens": 33
  }
}

stop means the answer ended. length means the output budget was reached. Check message.tool_calls when using tools; do not rely only on the finish reason.

Streaming

Use stream: true to show an answer as it arrives. The format is Server-Sent Events (SSE), ending with data: [DONE].

cURL · stream an answer
curl -N 'https://relaycode.site/v1/chat/completions' \
  -H "Authorization: Bearer $RELAYCODE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "glm-5.3-flash-current",
  "messages": [
    {
      "role": "user",
      "content": "Write a short greeting."
    }
  ],
  "stream": true,
  "max_tokens": 4096,
  "stream_options": {
    "include_usage": true
  }
}'
SSE · illustrative events
data: {"choices":[{"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"choices":[],"usage":{"prompt_tokens":25,"completion_tokens":8,"total_tokens":33}}

data: [DONE]
  • Read choices[].delta.content for answer text. A model may also send reasoning or tool-call deltas.
  • Usage-only chunks have an empty choices array. Check the array before accessing its first element.
  • A stream can contain an error event after HTTP headers were sent. HTTP 200 alone does not prove success.
  • Preserve partial output on disconnect. Do not automatically replay a request that may already have run.

Tool calling

Choose a model reporting capabilities.tool_calling: true. Your application defines the functions and executes approved calls; a model response alone does not execute code.

  1. Send your function definitions in tools.
  2. Read message.tool_calls. Validate the function name and JSON arguments against your allowlist.
  3. Run the permitted function, then append the original assistant message and a role: "tool" result with the same tool_call_id.
  4. Send the updated history to get the final answer.
JSON · one tool definition
{
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string"
            }
          },
          "required": [
            "city"
          ]
        }
      }
    }
  ],
  "tool_choice": "auto"
}

Use tool_choice: "auto" to start. Forced tool selection is model-dependent. In streams, assemble tool arguments across chunks before parsing them. Tool calls and reasoning use the model’s normal token rates; validate side effects in your own application.

Understand attached images

Vision means a chat model can read an image. It is separate from generating a new image. Select a model reporting capabilities.vision: true.

Python · ask about a local PNG
import base64
import json
import os
from urllib.request import Request, urlopen

with open("photo.png", "rb") as file:
    image = base64.b64encode(file.read()).decode()

body = {
    "model": "glm-5.3-flash-current",
    "max_tokens": 4096,
    "messages": [{"role": "user", "content": [
        {"type": "text", "text": "Describe this image."},
        {"type": "image_url", "image_url": {"url": "data:image/png;base64," + image}}
    ]}]
}
request = Request("https://relaycode.site/v1/chat/completions",
    data=json.dumps(body).encode(),
    headers={"Authorization": "Bearer " + os.environ["RELAYCODE_API_KEY"],
             "Content-Type": "application/json"})
with urlopen(request) as response:
    result = json.load(response)
if result.get("error"):
    raise RuntimeError(result["error"])
print(result["choices"][0]["message"]["content"])

Send validated image data URLs. Keep each image within the API’s size limit and the complete request under 24 MB. A public URL is not a substitute for a supported data URL.

Reasoning & web search

Reasoning levels vary by model. Use the chosen model’s live capabilities.reasoning_efforts and default_reasoning_effort. There is no universal Low-to-Max scale.

GLM 5.3 Flash

Currently listed efforts: low, high, max.

Where capabilities.reasoning_effort_mapping is listed, the selected effort is a gateway target. For example, Muse Spark’s Max target currently uses High upstream, including coding mode. Read x-talknova-requested-effort separately from the applied x-talknova-reasoning-effort header. A target is not proof of provider-native Max. No verified Nova thinking-off mode is offered.

Some models require a minimum output budget to finish reasoning before answering. RelayCode applies a floor where needed; a request can still be capped by your remaining USD allowance. Reasoning tokens count toward output usage.

Use web_search: true only if the model reports capabilities.web_search: true. A model without that capability returns 400 search_not_supported. Search being enabled does not mean the model used it: the search fee is charged only for searches the provider reports it executed, and usage.search_calls shows how many were billed (0 when the model answered without searching). If usage.search_status is pending_reconciliation, keep the completed answer; an unconfirmed search fee is held briefly and never charged without evidence. Do not retry generation to settle a search hold.

Search failures name their cause. search_verification_unavailable means RelayCode could not record the search authorization, so nothing was sent or charged; retry shortly. search_receipts_unreliable means Search is briefly paused on that model because the provider's usage reports are failing verification. search_provider_unavailable means the web search tool failed, and Search was not charged. All three carry retry_without_search: true: the same request without web_search still works. A default Search that was skipped returns the header x-talknova-search: paused, and the answer has no live results.

Generate an image

Use a personal key and a model from /models?type=image. One image per request; the monthly image count is shared with the site and apps.

cURL · generate an image
curl --fail-with-body 'https://relaycode.site/v1/images/generations' \
  -H "Authorization: Bearer $RELAYCODE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "flux-2-pro",
  "prompt": "A watercolor fox in a snowy forest"
}'

Check the JSON body for an error even if HTTP 200 was sent as a keep-alive. Save the returned data[0].b64_json image locally.

Roleplay apps

Use the same key, model IDs and monthly allowance. The roleplay endpoint preserves the caller’s character/system messages and skips RelayCode’s optional formatting prompt.

Your client asks forPaste this
OpenAI-compatible base URLhttps://relaycode.site/v1
Full roleplay/proxy endpointhttps://relaycode.site/v1/roleplay/chat/completions
API keyYour personal RelayCode key
ModelAn exact ID from GET /v1/models

For Janitor AI, choose its proxy option and use the full roleplay endpoint. Other compatible clients can use the public X-TalkNova-Plain: 1 header. Plain mode omits RelayCode’s formatting instructions; it does not change key permissions, model access, rate limits, accounting or the model provider’s policies. Usage reflects the input actually sent and generated output, with estimates identified when exact usage is unavailable.

Usage & limits

Your plan has one monthly text USD allowance you can spend on any text model, shared across the website, Mac, Windows, Android and your personal API key. Available media models have separate generation counts.

Monthly usageFreeBasicPlusMax
Text$10 / month$300 / month$600 / month$1000 / month
Images2 / month50 / month200 / month400 / month

Monthly allowances reset on the 1st of each month, UTC. Switching devices/models, rotating a key or opening more terminals does not reset usage. Check GET /v1/usage for used, remaining, reserved, reset time and max_concurrent_generations.

usage_policy on each model lists its input/output USD rate and shared text. RelayCode internal USD rates are usage-metering amounts, not a statement of upstream expenditure. Account-issued personal keys use this shared text allowance; standalone admin-issued custom keys use their independent balance.

Usage marked source: upstream comes from a verified provider receipt. A response marked source: local_tokenizer uses a local count and can differ from the provider. An uncertain receipt can leave a temporary hold for reconciliation. max_tokens bounds output and reserves spending capacity while a request runs. Settled usage uses accepted token counts. Tool-call rounds and their follow-up answers are metered separately.

When the model reports prompt caching, input usage includes uncached tokens, cache reads (prompt_tokens_details.cached_tokens) and cache writes (prompt_tokens_details.cache_write_tokens). The configured model rates apply to each reported portion: only models with a listed cache rate bill cached tokens differently, and every other model bills prompt tokens at its normal input rate. RelayCode enables provider prompt caching automatically on supported Claude and GPT-6.2 routes for conversations and agent loops (on Claude, only for requests with Search off); keep earlier messages unchanged and append new ones to benefit. Your own cache_control markers or prompt_cache_key are respected. Output usage already includes any reported reasoning. For search, RelayCode adds the search fee only for verified executions. If verification is unavailable, follow the retry guidance and keep your request ID.

Requests, concurrent work and reserved usage
LimitWhat it means
Concurrent generationsTwo active generations per personal account across the website, apps, CLI, every personal and named API key, and models. Extra calls may queue before inference starts. Creating more keys does not add capacity. Admin-issued standalone keys have no per-key limit unless one was configured for the key; provider and platform capacity still apply (503 capacity_exhausted).
Relay Spectrum requests/minuteFree: 5 · Basic: 15 · Plus: 30 · Max: 60
Other request limitsModel, endpoint and account rate limits also apply. Follow Retry-After and the structured error.
Output sizeRead the live max_output_tokens. The remaining allowance may lower your request cap.
Conversation sizeAt most 10,000 supplied messages. Long contexts may be trimmed; x-talknova-context-truncated reports omitted messages.
Reserved USDRunning or uncertain requests hold part of the allowance. It is already excluded from remaining USD; do not subtract it twice.

When your shared text allowance is exhausted, a new request is refused before model generation. If a previous request has an uncertain outcome, its hold may remain until reconciliation. A confirmed partial response can still incur usage.

Troubleshooting

Check the HTTP status, error code and RelayCode request ID. Use streaming for long generations. SSE may send heartbeat comments while queued or reasoning, and a later failure can arrive as an error event after HTTP 200. A response with cf-mitigated: challenge is an edge challenge.

JSON · illustrative error
{"error":{"message":"Your monthly allowance is used.","type":"insufficient_quota","code":"allowance_exhausted"}}
StatusMeaningNext step
400Invalid parameters, unsupported effort/tools/images or model ID.Read the message and model capabilities; change the request before retrying.
401Missing, invalid or revoked key.Check your personal key in API Access. Repeated failed attempts are throttled (429).
402Your account shared text allowance or standalone key balance cannot cover the request.Read shared text, remaining/held amounts and resets_at. Use a smaller request, upgrade or wait for reset.
429Rate limit, busy account or model capacity.Respect Retry-After. Do not open parallel clients to bypass it.
502 / 503 / 504Unavailable service, interrupted connection or uncertain generation.Read error.code and usage.status. Avoid replaying uncertain work automatically.

RelayCode retries definite transient rejections within a bounded budget. If the provider fails mid-stream before any text reaches you (for example while a tool call is still being generated, because tool calls are sent only once complete), RelayCode re-sends the request once automatically; you see one normal response and only that response is charged. If that also fails, the error event says nothing reached your app, usage.status is not_charged, and interrupted_tool names the tool call it was writing (name and argument size only). Agents should resume from their last completed step and split very large file writes into smaller edits. If autoRetryExhausted is true, wait or choose another model. A request marked pending_reconciliation may already have started; it is not safe to assume nothing happened. Keep your request ID when contacting support, and never send your key.

Connected tools (MCP)

MCP lets RelayCode web chat call external tools you connect. Add a server in chat’s tool settings, test the connection, and choose a model with tool support.

Use a reachable, authenticated HTTPS endpoint.

The website blocks localhost, private networks and internal addresses. A local stdio server cannot be reached directly by the website. If you bridge it to HTTP, expose it through a secure authenticated public endpoint and connect that URL.

Only connect tools you trust. Your configured server receives the requests and authentication needed to use it. Review permissions and tool arguments before granting access to files, accounts or actions. Tool-loop limits and network protections still apply.

Ready to connect?

Your key, live model list and remaining usage are together on API Access.

Open API Access