Skip to content

Codeines API documentation

Use the Codeines AI API with OpenAI or Anthropic SDKs. Find the base URLs, project API key examples, supported endpoints, and setup guides for coding agents.

SDK base URLs

Production
OpenAI
https://api.codeines.com/v1
Anthropic
https://api.codeines.com

Make your first request

Start with a plain text request and check the result before adding streaming.

  1. Create a key and fund your wallet

    In the Console, select a project and create a project API key. Store it privately when it appears. Check that the organization that owns the project has a USD wallet balance before calling a text or image endpoint.

    Set CODEINES_API_KEY in your server environment. For a local test in Bash or Zsh, enter the key at the hidden prompt, then run the examples in that same terminal.

    Set the API key
    printf 'Codeines API key: '
    read -rs CODEINES_API_KEY
    printf '\n'
    export CODEINES_API_KEY
  2. Check which models your key can use

    List models with your project key. Copy an ID from data[].id and check its supported APIs in the catalog before using it below. Discovery works without wallet credit.

    Model catalog
    List models with cURL
    curl --fail-with-body https://api.codeines.com/v1/models \
      -H "Authorization: Bearer $CODEINES_API_KEY"
  3. Send a text request

    Replace the example model ID if your key uses a different Chat Completions model. The reply is in choices[0].message.content. The JSON tab shows the relevant fields from a successful response.

    For JavaScript, save the example as example.mjs and run node example.mjs. For Python, save it as example.py and run python example.py.

    Chat Completions reference
    cURL example
    curl --fail-with-body https://api.codeines.com/v1/chat/completions \
      -H "Authorization: Bearer $CODEINES_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-6.1-terra",
        "max_completion_tokens": 512,
        "messages": [{"role": "user", "content": "Explain what an API gateway does in one sentence."}]
      }'

Set up with an AI agent

Use a prompt to let your current agent call Codeines from its terminal or integrate the API into your project. Give the agent access to CODEINES_API_KEY through its environment or private secret store.

Coding agent guides

Start with a project key and wallet credit. Set CODEINES_API_KEY in the terminal for CLI setups, then check model access with the same key. Use a returned model ID that supports the API shown in your guide. For coding sessions, choose a route with streaming and tool calling.

Tool calls, image inputs, and prompt cache keys depend on the model and API route. OpenCode and Droid examples use the capabilities published for the example model. You can also keep your current agent provider and use the Run a text request prompt to call Codeines from the agent's terminal.

OpenCodeChat CompletionsProvider setup
  1. Open opencode.jsonc or opencode.json at the project root. If neither exists, create opencode.jsonc. For OpenCode 2.0.22 or later, add the codeines entry to the providers map. Use the whole example for a new file.

    OpenCode provider configuration
    {
      "$schema": "https://opencode.ai/config.json",
      "providers": {
        "codeines": {
          "name": "Codeines",
          "env": [
            "CODEINES_API_KEY"
          ],
          "package": "@opencode/ai/providers/openai-compatible",
          "settings": {
            "baseURL": "https://api.codeines.com/v1"
          },
          "compatibility": {
            "supportsPromptCacheKey": false
          },
          "models": {
            "gpt-6.1-terra": {
              "name": "gpt-6.1-terra (Codeines)",
              "capabilities": {
                "tools": false,
                "input": [
                  "text"
                ],
                "output": [
                  "text"
                ]
              }
            }
          }
        }
      }
    }

    The example uses the model catalog's Chat Completions capabilities. OpenCode defaults to tool support when tools is omitted. supportsPromptCacheKey controls whether OpenCode sends the optional cache key. Automatic caching can still apply without that key.

  2. In the terminal with your project key, run the command below. Expect to see codeines/gpt-6.1-terra if you kept the example ID. This checks that OpenCode loaded the configuration.

    List configured OpenCode models
    opencode models --standalone
  3. Run the Chat Completions example to verify the key and model, then try the request below. For an interactive session, run opencode and choose codeines/gpt-6.1-terra in the model picker. Coding turns require tool calling. Paste an image when the config lists image under input.

    Send a test request from OpenCode
    opencode run --standalone --model codeines/gpt-6.1-terra "Reply with hello."
Factory DroidChat CompletionsProvider setup
  1. Open ~/.factory/settings.json. Add the example model object to the customModels array, or paste the full example into a new file. Leave the key reference as written so Droid reads it from the terminal environment.

    Droid custom model configuration
    {
      "customModels": [
        {
          "model": "gpt-6.1-terra",
          "displayName": "Codeines (Chat Completions)",
          "baseUrl": "https://api.codeines.com/v1",
          "apiKey": "${CODEINES_API_KEY}",
          "provider": "generic-chat-completion-api",
          "maxOutputTokens": 512,
          "noImageSupport": true
        }
      ]
    }
  2. Start droid from that terminal. Open /model and look under Custom Models for Codeines (Chat Completions).

  3. Verify the key and model with the Chat Completions example. A listed model confirms Droid loaded the entry. Use a route that has tool calling enabled for coding turns.

OpenAI CodexResponsesRequires tools and cache-key support
  1. Pick a model with Responses support and run the Responses example. The example uses gpt-6.2-sol.

  2. Codex CLI registers custom providers in ~/.codex/config.toml. This entry shows the Codeines connection fields. It can sit alongside your current provider without changing the default.

    Codex provider configuration
    [model_providers.codeines]
    name = "Codeines"
    base_url = "https://api.codeines.com/v1"
    env_key = "CODEINES_API_KEY"
    wire_api = "responses"
    supports_websockets = false
    capabilities.remote_compaction = "unsupported"
  3. Choose a Responses route that supports tool calling and prompt_cache_key. Codex sends a cache key with its requests. This command selects Codeines for one session, sets reasoning effort to low for the example model, and disables built-in web search. Add --image ./screenshot.png when the route supports image input.

    Start a Codeines Codex CLI session
    codex -c 'model_provider="codeines"' -c 'model_reasoning_effort="low"' -c 'web_search="disabled"' -m gpt-6.2-sol
Claude CodeAnthropic MessagesRequires a tool-capable route
  1. Pick a model with Messages support and run the Messages example. The example uses claude-sonnet-5-5.

  2. Claude Code uses the gateway origin for ANTHROPIC_BASE_URL and reads ANTHROPIC_API_KEY for the x-api-key header. These are the Codeines values for a gateway connection.

    Start a Codeines Claude Code CLI session
    export ANTHROPIC_BASE_URL="https://api.codeines.com"
    export ANTHROPIC_API_KEY="$CODEINES_API_KEY"
    export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-sonnet-5-5"
    export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1
    export ENABLE_TOOL_SEARCH=false
    claude --model "claude-sonnet-5-5"
  3. Use an enabled Messages route with tool calling. These settings use client-side tools and plain Messages requests with cache writes disabled. Inline image attachments require image input on the same route.

CursorOpenAI-compatible chatChat setup
  1. Verify the model first with the Chat Completions example. Use a public API URL for Cursor because its backend sends the model request.

  2. Open Cursor Settings → Models → API Keys. Under OpenAI API Key, enable the key and Override OpenAI Base URL. Enter the URL below before saving your Codeines key in the OpenAI key field.

    Base URL
    https://api.codeines.com/v1
    Example model ID
    gpt-6.1-terra
  3. Add or enable the exact model ID under Models. Select it in a new chat and try a short text question. Cursor chat with Codeines has yet to be verified. Agent mode requires a route with tools enabled and a compatible request format. Turn off the URL override when switching back to your usual OpenAI endpoint.

API reference

Choose an endpoint your model supports. Text examples use JSON by default. Set stream: true on a model that supports streaming to receive server-sent events (SSE).

Use a route with the corresponding capability for the tool and image examples. Your application or agent runs client tools and sends their results back to Codeines. Use inline base64 PNG, JPEG, WebP, or GIF for vision requests.

List models

GET/v1/models

Send either OpenAI Bearer authentication or the Anthropic x-api-key header. Both return data[].id. The OpenAI list includes models for Chat Completions, Responses, and images. The Anthropic list includes Messages models. Use the supported APIs in the model catalog to choose an endpoint.

If data is empty, check the models allowed by your key and the catalog for this environment.

OpenAI example
curl --fail-with-body https://api.codeines.com/v1/models \
  -H "Authorization: Bearer $CODEINES_API_KEY"

OpenAI Chat Completions

POST/v1/chat/completions

Send model and an array of text messages with role and content. Use max_completion_tokens to bound output. With streaming enabled, read text from choices[0].delta.content when present and keep reading through [DONE]. Request final usage with stream_options.include_usage.

Set reasoning_effort to choose the reasoning level on a model that supports it. Leave room in max_completion_tokens for reasoning and the reply. Use response_format for JSON or schema-constrained output. On models that support multiple choices, use n. The output limit applies to each choice and billing uses the total token count.

Read choices[0].message.tool_calls for a tool call. Replay the assistant message and add a tool message with the matching tool_call_id. Send an inline image as a user image_url content block.

cURL example
curl --fail-with-body https://api.codeines.com/v1/chat/completions \
  -H "Authorization: Bearer $CODEINES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6.1-terra",
    "max_completion_tokens": 512,
    "messages": [{"role": "user", "content": "Explain what an API gateway does in one sentence."}]
  }'

OpenAI Responses

POST/v1/responses

Send model and input as text or a list of messages. You can also pass instructions. If supplied, max_output_tokens must be at least 16 and within the model limit.

Set reasoning.effort to a level supported by the model. max_output_tokens covers reasoning and the visible reply.

Read the SDK's output_text helper or collect output_text blocks from output[].content in raw JSON. For SSE, read response.output_text.delta events and check the final response.completed or response.incomplete event.

Responses run with store: false. Send earlier turns in input. Replay encrypted reasoning or compaction items when the model provides them. To constrain JSON output, set text.format.

Replay the function_call item and append a function_call_output with the same call_id. Use input_image to attach an inline image.

cURL example
curl --fail-with-body https://api.codeines.com/v1/responses \
  -H "Authorization: Bearer $CODEINES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6.2-sol",
    "max_output_tokens": 512,
    "input": "Explain what an API gateway does in one sentence."
  }'

Anthropic Messages

POST/v1/messages

Send x-api-key and anthropic-version: 2023-06-01. Include model, max_tokens, and text messages with user or assistant roles. Set system instructions in the top-level system field.

Set output_config.effort to a level supported by the model. For models with adaptive thinking, you can request a thinking summary with thinking: { "type": "adaptive", "display": "summarized" }. Use output_config.format to request schema-constrained JSON on models that support it.

Read content blocks of type text. For SSE, read text from content_block_delta events and continue through message_stop.

For a tool turn, replay the assistant tool_use block, then send a user tool_result block with the matching tool_use_id. Attach images in user image blocks with a base64 source.

cURL example
curl --fail-with-body https://api.codeines.com/v1/messages \
  -H "x-api-key: $CODEINES_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 512,
    "messages": [{"role": "user", "content": "Explain what an API gateway does in one sentence."}]
  }'

Generate an image

POST/v1/images/generations

Send a JSON body with an image model and a prompt. Start with n: 1 and use the model's supported dimensions when setting size. Per-image models accept one image per request.

Generate an image with cURL
curl --fail-with-body https://api.codeines.com/v1/images/generations \
  -H "Authorization: Bearer $CODEINES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2.5-sunburst",
    "prompt": "An editorial watercolor of a coffee branch on cream paper.",
    "n": 1,
    "response_format": "b64_json"
  }' \
  -o image.json
Save the returned image

Edit an image

POST/v1/images/edits

Choose a model with image-edit support. Send multipart/form-data with model, prompt, and one PNG, JPEG, or WebP image up to 8 MiB. Put input.png in your terminal's working directory or substitute your own file path and MIME type.

Edit an image with cURL
curl --fail-with-body https://api.codeines.com/v1/images/edits \
  -H "Authorization: Bearer $CODEINES_API_KEY" \
  -F "model=gpt-image-2.5-sunburst" \
  -F "prompt=Turn this photo into a watercolor illustration." \
  -F "image=@input.png;type=image/png" \
  -F "n=1" -F "response_format=b64_json" \
  -o image.json

Save the returned image

After either request succeeds, run this Python example in the same directory as image.json. It saves the decoded bytes using the actual image format or prints the URL returned by the API.

Save the image with Python
import base64
import json
from pathlib import Path

result = json.loads(Path("image.json").read_text())
image = result["data"][0]

if "b64_json" not in image:
    print(image["url"])
else:
    data = base64.b64decode(image["b64_json"])
    if data.startswith(b"\x89PNG\r\n\x1a\n"):
        suffix = "png"
    elif data.startswith(b"\xff\xd8\xff"):
        suffix = "jpg"
    elif data.startswith(b"RIFF") and data[8:12] == b"WEBP":
        suffix = "webp"
    else:
        raise ValueError("Unexpected image format")
    path = Path(f"codeines-output.{suffix}")
    path.write_bytes(data)
    print(path)

Limits and billing

Codeines reserves funds from your organization wallet before sending an inference request. The final charge uses the rates fixed at request time and the verified token usage or per-image price. Unused funds return to the available balance.

Request typeBody limitModel response timeout
Text8 MiB total, 256 KiB for options and non-image content120 seconds
Image generation256 KiB120 seconds
Image edit12 MiB total, 8 MiB per upload120 seconds

Codeines can reduce the text output budget to fit the available balance. View settled charges in Usage and available or reserved funds in Billing.

Vision requests accept up to eight inline images, each up to 4 MiB decoded, within the total body limit. The wallet reserves the configured input cap for vision. The final charge uses the recorded usage. OpenAI-compatible routes with prompt cache keys enabled scope each prompt_cache_key to the project.

Errors and retries

Read the HTTP status and error.message. Keep the X-Request-ID response header when present so you can find the request in Usage.

400 Invalid request
Check required fields, model limits, and route capabilities. Use tools you run on your side and features supported by the route.
401 Unauthorized
Check that the project key is active and that the authentication header matches the endpoint.
402 Insufficient balance
Check the project's organization wallet in Billing and add credit if needed.
404 Model unavailable
Confirm the key can discover the model and that the catalog lists the exact API you are calling.
413 Request too large
Reduce the body size or use a smaller image upload.
429 Rate limited
Wait before retrying and use exponential backoff.
5xx Server error
Check Usage before retrying a timed-out or incomplete request. A new request can incur a separate charge.