# Koinelix AI API

Paid services, each one POST with an x402 payment; no account is needed.

- Image generation: POST https://api.koinelix.com/v1/images/generations, 0.005 USDC. Create or edit an image from a text prompt (section "Image generation").
- Image recognition: POST https://api.koinelix.com/v1/images/recognitions, 0.003 USDC. Describe or read an image, sent as an image URL or as Base64 (section "Image recognition").
- File upload: POST https://api.koinelix.com/v1/files, 0.004 USDC. Upload one file and receive a signed download link (section "File upload").

## Image generation

Generates or edits one image from a prompt and up to 3 reference images. Returns Base64 JSON. 0.005 USDC per x402 call. No account or API key required. A platform API key allows up to 3 attempts per payment. The default model is gpt-image-2.5. Text-to-image defaults for gpt-image-2.6-flare, gpt-image-2.6-sunburst are size=auto, quality=medium, output_format=png. These defaults assume no image parameter overrides.

- Endpoint: POST https://api.koinelix.com/v1/images/generations
- Price: 0.005 USDC per paid call (x402 v2, scheme exact)
- Networks: eip155:8453 (asset 0x833589fcd6edb6e08f4c7c32d4f71b54bda02913)
- Availability: ready
- Published model IDs (optional; the first is the default): gpt-image-2.5, gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2.6-flare, gpt-image-2.6-sunburst
- OpenAPI: https://api.koinelix.com/openapi.json

### Example bodies

text:

```json
{"prompt":"A watercolor lighthouse at sunrise"}
```

reference_url:

```json
{"image_urls":["https://example.com/photo.jpg"],"prompt":"Replace the man in the reference image with a woman; keep everything else unchanged"}
```

reference_b64:

```json
{"image_b64":["<standard Base64 of a JPEG or PNG, no data: prefix>"],"prompt":"Turn this photo into a watercolor painting"}
```

with_model:

```json
{"model":"gpt-image-2.5","prompt":"A watercolor lighthouse at sunrise"}
```

with_image_parameters:

```json
{"model":"gpt-image-2.6-flare","output_format":"png","prompt":"A watercolor lighthouse at sunrise","quality":"medium","size":"auto"}
```


Optional size, quality and output_format are enabled only for the models below. Other models retain their original request contract. Omitted values use the exact published defaults below (initial 2.6 defaults: auto/medium/png). With reference images, omitted size stays omitted; explicit size is forwarded. SVG cannot be combined with reference images.

```json
{
  "gpt-image-2.6-flare": {
    "prompt_max_bytes": 6000,
    "allow_auto_size": true,
    "allow_custom_size": true,
    "min_dimension": 10,
    "max_dimension": 3840,
    "sizes": [
      "auto",
      "1024x1024",
      "1024x1536",
      "1536x1024",
      "688x2048",
      "880x2048",
      "1024x2048",
      "1152x2048",
      "1360x2048",
      "1536x2048",
      "2048x688",
      "2048x880",
      "2048x1024",
      "2048x1152",
      "2048x1360",
      "2048x1536",
      "2048x2048",
      "2160x3840",
      "3840x2160"
    ],
    "request_parameter_fields": [
      "size",
      "quality",
      "output_format"
    ],
    "qualities": [
      "low",
      "medium",
      "high",
      "xhigh",
      "max",
      "auto"
    ],
    "formats": [
      "png",
      "jpeg",
      "webp",
      "svg",
      "gif"
    ],
    "size_constraints": {
      "multiple_of": 16,
      "max_edge": 3840,
      "max_aspect_ratio": 3,
      "min_pixels": 655360,
      "max_pixels": 8294400
    },
    "defaults": {
      "n": 1,
      "size": "auto",
      "quality": "medium",
      "output_format": "png"
    }
  },
  "gpt-image-2.6-sunburst": {
    "prompt_max_bytes": 6000,
    "allow_auto_size": true,
    "allow_custom_size": true,
    "min_dimension": 10,
    "max_dimension": 3840,
    "sizes": [
      "auto",
      "1024x1024",
      "1024x1536",
      "1536x1024",
      "688x2048",
      "880x2048",
      "1024x2048",
      "1152x2048",
      "1360x2048",
      "1536x2048",
      "2048x688",
      "2048x880",
      "2048x1024",
      "2048x1152",
      "2048x1360",
      "2048x1536",
      "2048x2048",
      "2160x3840",
      "3840x2160"
    ],
    "request_parameter_fields": [
      "size",
      "quality",
      "output_format"
    ],
    "qualities": [
      "low",
      "medium",
      "high",
      "xhigh",
      "max",
      "auto"
    ],
    "formats": [
      "png",
      "jpeg",
      "webp",
      "svg",
      "gif"
    ],
    "size_constraints": {
      "multiple_of": 16,
      "max_edge": 3840,
      "max_aspect_ratio": 3,
      "min_pixels": 655360,
      "max_pixels": 8294400
    },
    "defaults": {
      "n": 1,
      "size": "auto",
      "quality": "medium",
      "output_format": "png"
    }
  }
}
```
### Steps

1. POST /v1/images/generations with a JSON body and no payment to receive HTTP 402 with a PAYMENT-REQUIRED x402 v2 quote. Sign only if the X-Koinelix-Availability response header (also availability in the body) is ready.
The body needs only prompt. model is optional: omit it for the default model, or set it to a published model ID (listed in agents.md and in the model enum of openapi.json).
Optional reference images (edit or combine): image_urls (http or https URLs, passed to the model unchanged) and image_b64 (standard padded Base64 without a data: prefix, at most 10 MiB decoded in total); at most 3 images, ordered image_urls first, then image_b64. The body may then be at most 15 MiB. An unreachable URL or a file that is not an image is rejected by the model after payment. Koinelix does not keep results: to edit an earlier image, send it back as image_b64 or pass its URL in image_urls.
2. Sign the exact quote (0.005 USDC) and resend the same body with PAYMENT-SIGNATURE. No account or API key is needed.
3. A new payment settles before generation. After a confirmed paid failure, the same wallet can make up to two more attempts within 24 hours through the same quote and signing flow. A free attempt returns no PAYMENT-RESPONSE. New requests follow standard payment when the retry allowance is unavailable. An attempt with an unknown outcome must be recovered using its original signature and body.
4. Generation is synchronous and usually takes tens of seconds. Set the client timeout to at least 120 seconds and keep the connection open until the response arrives; save the image as soon as you receive it. If the connection drops, times out or returns a non-JSON error, the result is unknown: resend the same PAYMENT-SIGNATURE and body, never pay again. A paid attempt that never started runs then; HTTP 409 attempt_not_started means a new quote is required for an unused free retry. HTTP 409 attempt_in_progress means it is still running, so wait and resend; HTTP 409 image_result_unavailable means it completed but the image is not kept and cannot be downloaded again, and the payment is not refunded.
5. HTTP 402 payment_invalid means the facilitator rejected the signed payment and nothing was charged. error.message ends with its reason, e.g. insufficient_funds (fund the payer wallet with USDC first) or an expired or invalid signature (sign the new quote again). Never resend the same PAYMENT-SIGNATURE after this.
6. Limits: per IP and per payer rate limits apply; HTTP 429 includes Retry-After.
7. Optional: a Koinelix platform API key (Authorization: Bearer) with Idempotency-Key uses account quota first and gives up to three attempts per payment.
### Example (curl)

```bash
# 1. Get the quote: no payment. Returns HTTP 402 with the PAYMENT-REQUIRED header.
curl -i -X POST https://api.koinelix.com/v1/images/generations \
  -H 'Content-Type: application/json' \
  -d '{"prompt":"A watercolor lighthouse at sunrise"}'

# 2. Generate with the signed payment (PAYMENT_SIGNATURE is the quote signed by your wallet or x402 client).
curl --max-time 120 -X POST https://api.koinelix.com/v1/images/generations \
  -H "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  -H 'Content-Type: application/json' \
  -d '{"prompt":"A watercolor lighthouse at sunrise"}' -o response.json

# 3. Save the image: the result is Base64 in data[0].b64_json.
jq -r '.data[0].b64_json' response.json | base64 --decode > image.png
```

## Image recognition

Image recognition and description with a multimodal model. Use when an agent needs to understand a picture: describe it, answer a question about it, read visible text or inspect details. One image goes in as an image URL or as Base64 (up to 10 MiB decoded) with an optional prompt; the answer returns as plain text or Markdown. Price: 0.003 USDC per call, paid with x402; no account or API key is needed.

- Endpoint: POST https://api.koinelix.com/v1/images/recognitions
- Price: 0.003 USDC per call (x402 v2, scheme exact)
- Networks: eip155:8453 (asset 0x833589fcd6edb6e08f4c7c32d4f71b54bda02913)
- Availability: ready
- Client code for x402 libraries: https://koinelix.com/docs/image-recognition

### Example bodies

url_text:

```json
{"image_url":"https://example.com/photo.jpg"}
```

base64_markdown:

```json
{"image_b64":"<standard Base64 of a PNG, JPEG, WebP or GIF, no data: prefix>","prompt":"List the items on this receipt","output_format":"markdown"}
```

### Steps

1. Choose the image input. Send exactly one image: image_url (an http or https URL) or image_b64 (one standard padded Base64 string on a single line without a data: prefix; png, jpeg, webp or gif, at most 10 MiB decoded). image_b64 is a single string, not an array. Both inputs are fully supported: use image_url when the image is online, image_b64 when you have the file. To produce image_b64, read and encode the file in code and put the result into the request body (shell: base64 < photo.png | tr -d '\n'; Python: base64.b64encode(data).decode()); images up to the limit work this way, with no resizing or upload step. Tip for clients that must write the Base64 into a tool call by hand, token by token: a long string is easily corrupted, so for such clients prefer image_url or a code-built request, or send a small thumbnail (a few thousand characters). Do not upload the file to a file host only to get a URL. Optional prompt (up to 4000 UTF-8 bytes) is what you want to know about the image; optional output_format is text (default) or markdown. The body may be at most 15 MiB.
2. POST /v1/images/recognitions with no payment to receive HTTP 402 with a PAYMENT-REQUIRED x402 v2 quote. The quote does not depend on the body, so when you handle the 402 yourself an empty {} is enough for this first request; an x402 client library that resends your full body works too. Sign only if the X-Koinelix-Availability response header (also availability in the body) is ready.
3. Sign the exact quote (0.003 USDC) and resend the request with PAYMENT-SIGNATURE and the real body. No account or API key is needed.
4. Success is HTTP 200 JSON: {"id":"c_0123456789abcdef","created":1767225600,"format":"markdown","content":"<the answer>","truncated":false}. content is the final answer; one call is enough. Set the client timeout to at least 120 seconds and keep the connection open until the response arrives. If the connection drops or times out, resend the same PAYMENT-SIGNATURE and body instead of paying again. If the answer was already delivered, the response has status succeeded, content null and result_stored false.
5. HTTP 400 validation_failed names the field in error.param and says what to fix (for example a line break or a truncated Base64 string, with the character position). Fix the body, request a new quote and sign it again.
6. HTTP 402 payment_invalid means the facilitator rejected the signed payment; error.message ends with its reason, e.g. insufficient_funds (fund the payer wallet with USDC first). Sign the new quote and never resend the same PAYMENT-SIGNATURE after this.
7. HTTP 429 includes Retry-After.
8. Optional: a Koinelix platform API key (Authorization: Bearer) uses account quota first; Idempotency-Key is optional.

### Example (curl)

```bash
# 1. Get the quote: no payment. Returns HTTP 402 with the PAYMENT-REQUIRED header.
curl -i -X POST https://api.koinelix.com/v1/images/recognitions \
  -H 'Content-Type: application/json' \
  -d '{"image_url":"https://example.com/photo.jpg"}'

# 2. Recognize with the signed payment (PAYMENT_SIGNATURE is the quote signed by your wallet or x402 client).
curl --max-time 120 -X POST https://api.koinelix.com/v1/images/recognitions \
  -H "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  -H 'Content-Type: application/json' \
  -d '{"image_url":"https://example.com/photo.jpg","prompt":"What is in this image?"}'
# The answer is in the content field of the JSON response.

# Or send a local image as one-line standard Base64 (image_b64) from a body file.
printf '{"image_b64":"%s"}' "$(base64 < photo.png | tr -d '\n')" > body.json
curl --max-time 120 -X POST https://api.koinelix.com/v1/images/recognitions \
  -H "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  -H 'Content-Type: application/json' \
  --data-binary @body.json
```

## File upload

Upload one file (up to 10 MiB) and receive a signed download link directly in the response. Price: 0.004 USDC per file. No account or API key is needed: pay with x402. The link works for 10 days.

- Endpoint: POST https://api.koinelix.com/v1/files
- Price: 0.004 USDC per file (x402 v2, scheme exact)
- Networks: eip155:8453 (asset 0x833589fcd6edb6e08f4c7c32d4f71b54bda02913)
- Request: multipart/form-data with exactly one part named file, or JSON with the file as base64 (up to 8 MiB); header PAYMENT-SIGNATURE; Idempotency-Key optional
- Guide with curl examples: https://koinelix.com/docs/files

### Steps

1. POST https://api.koinelix.com/v1/files with an empty body and no payment to receive HTTP 402 with a PAYMENT-REQUIRED x402 v2 quote.
2. Keep the signed payment and the file bytes until you have the link. An Idempotency-Key header is optional: when you send one it must be 32 lowercase hex characters (128 random bits) created once per upload and reused unchanged on every retry; without one the upload is identified by the payment itself.
3. Sign the exact quote (0.004 USDC) and POST the file with PAYMENT-SIGNATURE, in one of two forms. Multipart: Content-Type multipart/form-data with exactly one part named file (no other fields; let your HTTP library build the body), up to 10 MiB. JSON: Content-Type application/json with {"filename": "report.pdf", "content_type": "application/pdf", "content_base64": "<standard padded Base64>"}, up to 8 MiB decoded; filename and content_type are optional and no other fields are accepted. Do not send an Authorization header. Use a client timeout of at least 120 seconds.
4. HTTP 201 returns data.url, a ready-to-use GET download link, plus file_id, filename, content_type, size_bytes, sha256 and expires_at. Anyone with the link can download the file until expires_at, so share it only where intended.
5. HTTP 202 (payment_pending or storage_pending, with Retry-After) means the request is still being completed: after the delay resend the identical request (same PAYMENT-SIGNATURE, same Idempotency-Key if you sent one, same file bytes; the multipart and JSON forms of the same file are interchangeable). Never pay again for the same file; one payment buys exactly one file. A different file or key with the same payment returns HTTP 409.
6. HTTP 402 payment_invalid, 413 file_too_large and 503 file_service_unavailable mean nothing was charged. HTTP 429 includes Retry-After.
7. With an x402 client library (for example @x402/fetch) pass the body as FormData or a Blob: the library resends the same request after signing, which a one-shot stream cannot do. The library does not retry a 202 for you: keep the PAYMENT-SIGNATURE it sent and resend the identical request yourself.
8. Download the file with a plain GET of data.url, unchanged and without credentials. HEAD is also accepted. After expires_at the link stops working.

### Example (curl)

```bash
# 1. Get the quote: no payment, no body. Returns HTTP 402 with the PAYMENT-REQUIRED header.
curl -i -X POST https://api.koinelix.com/v1/files

# 2. Upload with the signed payment (PAYMENT_SIGNATURE is the quote signed by your wallet or x402 client).
curl -X POST https://api.koinelix.com/v1/files \
  -H "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  -F "file=@photo.png"

# Or send the file as JSON with one-line standard Base64.
printf '{"filename":"photo.png","content_base64":"%s"}' "$(base64 < photo.png | tr -d '\n')" > body.json
curl -X POST https://api.koinelix.com/v1/files \
  -H "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  -H 'Content-Type: application/json' \
  --data-binary @body.json
```

### Example (TypeScript: @x402/fetch, @x402/evm, viem)

```ts
import { wrapFetchWithPaymentFromConfig } from '@x402/fetch';
import { ExactEvmScheme } from '@x402/evm';
import { privateKeyToAccount } from 'viem/accounts';
import type { Hex } from 'viem';
import { openAsBlob } from 'node:fs';
import { randomBytes } from 'node:crypto';

const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as Hex);

// Keep the exact signature the library sends: a retry after a lost response or a 202 must reuse it.
let paymentSignature = '';
const recordingFetch: typeof fetch = (input, init) => {
  const signature = new Headers(input instanceof Request ? input.headers : init?.headers).get('PAYMENT-SIGNATURE');
  if (signature) paymentSignature = signature;
  return fetch(input, init);
};
const fetchWithPayment = wrapFetchWithPaymentFromConfig(recordingFetch, {
  schemes: [{ network: 'eip155:8453', client: new ExactEvmScheme(account) }],
});

const idempotencyKey = randomBytes(16).toString('hex'); // once per upload; keep it with the signature and the file
const form = new FormData();
form.append('file', await openAsBlob(process.env.FILE_PATH!), 'upload.bin'); // exactly one part named "file"

const response = await fetchWithPayment('https://api.koinelix.com/v1/files', {
  method: 'POST',
  headers: { 'Idempotency-Key': idempotencyKey },
  body: form,
});
if (response.status === 202) {
  // Wait Retry-After, then resend the same request WITHOUT paying again:
  // fetch('https://api.koinelix.com/v1/files', { method: 'POST', headers: { 'Idempotency-Key': idempotencyKey, 'PAYMENT-SIGNATURE': paymentSignature }, body: sameForm })
} else if (!response.ok) {
  throw new Error('HTTP ' + response.status + ': ' + (await response.text()));
}
const { data } = await response.json();
console.log(data.url); // plain GET download link, valid until data.expires_at
```
GET /v1/models returns final billable token rates; do not apply another discount. Billing uses actual token usage at the quoted rates, subject to each model's minimum_charge_usdc. There is no additional per-request platform fee.

## Language models — actual token settlement

Use LLM for conversation, writing, code and local function definitions. Receive streaming or non-streaming responses. Discover available models, supported_protocols endpoints, pricing, context_window and max_output_tokens with GET https://api.koinelix.com/v1/models. Keep the input within the model's context_window and the output budget within its max_output_tokens; larger requests are rejected before payment.

Payment: x402 v2 upto / Permit2; network eip155:8453; asset 0x833589fcd6edb6e08f4c7c32d4f71b54bda02913. Prices are USD per million tokens, settled at the same numeric USDC amount. Minimum charge: 0.002000 USDC per call. Final billing uses actual input, cached input, cache writes and output at the applicable quoted rates.

1. Select a model id and an endpoint from its supported_protocols. Set a maximum output budget. For Chat Completions send messages and max_completion_tokens; max_tokens and max_output_tokens are rejected with HTTP 400, with no alias conversion. Omitting the Chat output limit uses the service default as max_completion_tokens. For Responses send input and max_output_tokens. Set stream=true for SSE.
2. POST the request as application/json with a unique Idempotency-Key. HTTP 402 and PAYMENT-REQUIRED contain the request-specific quote. Decode the base64 JSON and select scheme=upto. Verify x402Version, network, asset, trusted payTo, amount, expiry, resource URL and your spending policy.
3. Use an x402 v2 upto / Permit2 client to prepare a bounded token allowance within your spending policy and sign the quoted authorization. Token allowance and this call's signed limit are separate. Signing authorizes a maximum; funds transfer at settlement after generation.
4. Resend the identical body and path with PAYMENT-SIGNATURE, the same Idempotency-Key and the same authentication identity. Changing input, model, protocol or output budget requires a new quote and signature. The gateway binds payment to the original request.
5. Save the response on the client. The final bill is calculated after final usage, subject to the signed limit and minimum charge. Non-streaming completes settlement before returning the full response. Streaming emits text first and settles after final usage.
6. For SSE or a lost/interrupted response, POST the original endpoint/body with the original PAYMENT-SIGNATURE, Idempotency-Key and identity plus X-Koinelix-Recover-Only: true. Record X-Request-ID (HTTP trace) and X-Koinelix-Request-Id (invocation ID) separately. Read request_id, execution, usage, payment, delivery, amount, tx_hash, result_stored and authorization_released. authorization_released=true means the gateway will never request settlement for that invocation; it is not on-chain proof that the signature is unusable. amount is a nullable integer string in atomic USDC units (6 decimals). result_stored=false means response text is retained by the caller only. payment=settled means the gateway verified settlement. Use bounded backoff while processing, for example 2, 4, 8, 16 and 30 seconds, stopping after five attempts and retaining the pending state. Keep unknown outcomes on the original authorization; do not create another payment to resolve an unknown one. Recovery reports state, not retained response text.
7. For 409 payer_exposure_exceeded, the payer's funds or authorization are reserved by other requests. Respect Retry-After and reconcile original payments; rejection does not revoke a signature and must not automatically create a new authorization. For 429 respect Retry-After. A 429 without X-Koinelix-Request-Id was rejected before admission: retain the same intent and retry, except daily_cap_exceeded, which does not succeed again until the next day. A 429 capacity_exhausted with X-Koinelix-Request-Id was rejected after admission: recover it (expect execution=failed, payment=not_required), then request a new quote for a new intent; the original authorization cannot be reused. For configuration_changed or intent_mismatch, recover any existing call first, then request a new quote for a new unexecuted intent. For quote_estimation_unsupported adjust the request to a supported shape; for quote_estimation_unavailable retry with bounded backoff. Inspect the returned error code and request ID.
8. An expired unexecuted quote may be replaced after checking the original call. intent_mismatch requires restoring the original request for recovery or getting a new quote for a new intent. Missing usage, over-budget usage and unknown settlement are distinct errors: retain the request identifier for investigation.

Reference client: https://koinelix.com/examples/llm-upto-client.mjs (v1.0.0, no external dependencies, EIP-1193 wallet adapter). Use prepareLLM with a trusted network/asset/payee/account/maxAtomic policy; approve only under your allowance policy, wait for its receipt, execute once, consume the JSON or SSE body, then recover the original session. Keep that session in protected memory.

Example quote request (replace <model-id> with a catalog id):

POST https://api.koinelix.com/v1/chat/completions
Content-Type: application/json
Idempotency-Key: <unique-request-id>

{"model":"<model-id>","messages":[{"role":"user","content":"Explain your capabilities in two sentences."}],"max_completion_tokens":256,"stream":false}

Responses alternative:
POST https://api.koinelix.com/v1/responses
{"model":"<model-id>","input":"Explain your capabilities in two sentences.","max_output_tokens":256,"stream":true}


## Web search

GET https://api.koinelix.com/v1/search?q=how+solar+panels+work&count=10. Supply q with up to 400 Unicode characters. count is optional (1–20, default 10). The response includes query, the actual count, results, and untrustedContent=true. Each result has title, url, description, age and publishedAt. Publication fields are null when unavailable. An empty result set is valid. The X-Koinelix-Search-Partial header is true when an upstream search engine reports a warning.

Pay 0.002 USDC per search via x402 exact. An unsigned request returns PAYMENT-REQUIRED. A signed request is settled before execution. A provider failure after settlement remains a settled payment. Check PAYMENT-RESPONSE on failure as well as success.

For recovery, generate 32 random bytes, encode as unpadded base64url and send the private value in X-Koinelix-Search-Recovery on the first signed request. Replay the original search parameters and payment with the same token and set X-Koinelix-Recover-Only to true. Search results are delivered once.
