# The-Code API integration guide

The-Code API provides one OpenAI-compatible gateway for approved AI models. Applications use a named The-Code user key; platform provider credentials remain hidden and centrally managed.

## Connection

```text
Base URL:    https://api.thecodeapi.com/v1
API key:     <tca_test_... or tca_live_...>
Auth header: Authorization: Bearer <THE_CODE_API_KEY>
```

Store the key in a server-side secret manager. Never expose it in browser code, source control, logs, prompts, screenshots, or URLs.

## Start with model discovery

```http
GET /v1/models
Authorization: Bearer <THE_CODE_API_KEY>
```

Use only models returned for the calling key. The live response applies platform approval, active providers, the user's enabled models, aliases, and capability policy.

## OpenAI SDK examples

Python:

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["THE_CODE_API_KEY"],
    base_url="https://api.thecodeapi.com/v1",
)
models = client.models.list()
response = client.chat.completions.create(
    model=models.data[0].id,
    messages=[{"role": "user", "content": "Hello"}],
)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.THE_CODE_API_KEY,
  baseURL: "https://api.thecodeapi.com/v1",
});
const models = await client.models.list();
const response = await client.chat.completions.create({
  model: models.data[0].id,
  messages: [{ role: "user", content: "Hello" }],
});
```

## Core endpoints

- `GET /v1/models`: approved exact models and aliases visible to the user key.
- `POST /v1/chat/completions`: non-streaming and SSE streaming chat.
- `POST /v1/responses`: documented non-streaming Responses subset.
- `POST /v1/embeddings`: embeddings for models advertising that capability.

Inspect `https://api.thecodeapi.com/api/openapi.json` for exact deployed schemas.

Kimi.ai models use IDs beginning with `kimi/`. Discover the exact IDs and their
capabilities through `GET /v1/models`, then call the gateway with the same
The-Code API key. Platform administrators manage the Moonshot API credential.

Amazon Bedrock models use IDs beginning with `aws/`. For Cohere Embed models on
Bedrock, `/v1/embeddings` additionally requires `input_type` with one of
`search_document`, `search_query`, `classification`, or `clustering`. It accepts
optional `truncate` values `NONE`, `START`, or `END`. Titan Text Embeddings does
not accept those Cohere-only fields. Always use the request contract returned by
`GET /v1/models` for the selected exact model.

## Request controls

### Function tools

Chat Completions and the non-streaming Responses subset accept optional
`tool_choice` and `parallel_tool_calls`. Read the selected model's
`request_contract.parameters` in `GET /v1/models`: `supported` and `values`
describe the settings available on that exact model. Alias contracts contain
only the settings supported by every target. Omission preserves provider defaults.

- `tool_choice`: `auto`, `none`, `required`, or a named function. `required`
  requires at least one call; choosing a function does not universally limit
  the number of invocations.
- Chat named choice: `{"type":"function","function":{"name":"weather"}}`.
- Responses named choice: `{"type":"function","name":"weather"}`.
- `parallel_tool_calls: true` permits multiple calls in one model response;
  `false` requires at most one. Your application controls actual execution.

OpenAI and Anthropic support the parallel switch. Gemini, Kimi, Ollama, and
Bedrock Converse currently accept only `true`; their adapters do not advertise
an enforceable single-call setting. Unsupported values return HTTP 400 with
`unsupported_parameter`. Anthropic Fable/Mythos 5.1 support `auto` and `none`
only. Bedrock Converse supports `auto` and `required`; named selection is
advertised for Claude 3 and Nova. Its `none` mode is not exposed.
Anthropic's generic `json_object` mode uses an internal forced tool, so it
cannot be combined with explicit `tool_choice` or `parallel_tool_calls: true`.
Ollama supports only `tool_choice: "auto"` in this gateway: its current
OpenAI-compatible server implementation does not enforce the other choices.

For a tool loop, append the complete returned assistant message, execute each
`tool_calls` function in your application, then append one `role: "tool"`
message per call with its exact `tool_call_id` and string result. Return all
results before continuing. Anthropic and Gemini accept these histories,
including multiple calls to the same function and calls received through SSE.
Accumulate streamed arguments by tool-call `index`; retain the final metadata
delta as part of the assistant message.

Preserve returned `reasoning_content` and `extra_content` unchanged. Gemini
uses `tool_calls[].extra_content.google.thought_signature` and, when needed,
`message.extra_content.google.parts`; Anthropic uses
`message.extra_content.anthropic.content` for signed thinking blocks.
These opaque fields must survive SDK serialization and replay to the same
provider/model. For Responses, append returned output items (including their
metadata), followed by `function_call_output` items with matching `call_id`.
Responses streaming remains unavailable; use Chat Completions for SSE.

Provider references reviewed for these controls:
[OpenAI](https://developers.openai.com/api/docs/guides/function-calling),
[Anthropic](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools),
[Gemini](https://ai.google.dev/api/caching#FunctionCallingConfig),
[Kimi](https://platform.kimi.ai/docs/api/chat),
[Ollama](https://docs.ollama.com/api/openai-compatibility), and
[Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ToolChoice.html).

### Output limits and headers

Omitting an output-token maximum selects The-Code's managed output policy. The
default managed ceiling is 16,384 tokens and is caller-policy aware; The-Code
still clamps it to the current model and context limits before reserving credits
or dispatching upstream.

| Header | Purpose |
|---|---|
| `Idempotency-Key` | Makes retry of the same logical operation safe |
| `Prefer: respond-async` | Accepts non-streaming Chat Completions or Responses inference and returns a pollable handle |
| `X-The-Code-Max-Credits` | Rejects an estimate above the caller's ceiling |
| `X-Request-ID` | Carries a safe caller correlation ID |

Successful responses identify the actual route through `X-The-Code-Provider` and `X-The-Code-Model` and return the request ID. Streaming clients must ignore SSE comments and wait for `data: [DONE]`.
They also return `X-The-Code-Output-Policy` and
`X-The-Code-Effective-Max-Tokens` so callers can audit how an omitted or explicit
ceiling was compiled.

## Errors and retrying

Errors use an OpenAI-style envelope. Correct `400`, authentication, credit, policy, not-found, and idempotency-conflict failures before retrying. Retry eligible `429`, `502`, `503`, and `504` failures with bounded exponential backoff, jitter, and the same idempotency key. Honor `Retry-After`.

For `respond-async`, poll the returned `status_url` with the same API key and
honor `Retry-After`. A poll returns `202` while work is active, then the original
validated completion or typed terminal error. Do not resubmit with a different
model, payload, schema, catalog revision, or idempotency key.

## Credits

Paid platform traffic reserves and settles against the key owner's single user wallet. Only platform administrators grant or revoke unspent credits. Users can view available, reserved, granted, and consumed credits but cannot transfer or allocate them.

## Videos

Video generation and media retrieval are managed platform capabilities. Use the routes and schemas published by the deployed OpenAPI document, send stable idempotency keys for submissions, and download completed files only through authenticated content URLs. Treat prompts and media as sensitive tenant data.

## More documentation

- Human and administrator guide: `https://api.thecodeapi.com/docs/human-guide.md`
- AI-agent contract: `https://api.thecodeapi.com/docs/ai-agent-guide.md`
- Machine index: `https://api.thecodeapi.com/llms.txt`
- Swagger: `https://api.thecodeapi.com/api/docs`
