# Introduction

AlphaNeural provides a single, OpenAI-compatible API for chatting, vision, embeddings, and image generation. If you have already integrated the OpenAI API, you can usually switch by updating the base

{% hint style="info" %}
AlphaNeural is using an LLM proxy, so one endpoint can route to many underlying LLM providers while keeping OpenAI-style request and response formats.
{% endhint %}

All OpenAI-style endpoints are served under:

```
https://proxy.alfnrl.io/v1
```

Example. Chat completions:

```
POST https://proxy.alfnrl.io/v1/chat/completions
```

### Authentication

Authenticate with a bearer token:

* Header: `Authorization: Bearer <YOUR_API_KEY>`

### Compatibility

AlphaNeural follows the OpenAI API surface for the endpoints we expose. For example:

* Chat Completions: `POST /v1/chat/completions`
* Embeddings: `POST /v1/embeddings`
* Image generation: `POST /v1/images/generations`
* List models: `GET /v1/models`

That means you can typically keep the same payloads, streaming behaviour, and error handling you already use with OpenAI.

***

### Quickstart

#### cURL

```bash
curl https://proxy.alfnrl.io/v1/chat/completions \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3",
    "messages": [
      { "role": "user", "content": "Hello AlphaNeural" }
    ]
  }'
```

#### Python (OpenAI SDK)

```python
from openai import OpenAI
client = OpenAI(api_key=os.environ["ALPHANEURAL_API_KEY"], base_url="https://proxy.alfnrl.io/v1")
resp = client.chat.completions.create(model="qwen3", messages=[{"role":"user","content":"Hello AlphaNeural"}])
print(resp.choices[0].message.content)
```

#### JavaScript/TypeScript (OpenAI SDK)

```js
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.ALPHANEURAL_API_KEY, baseURL: "https://proxy.alfnrl.io/v1" });
const resp = await client.chat.completions.create({ model: "qwen3", messages: [{ role: "user", content: "Hello AlphaNeural" }] });
console.log(resp.choices[0].message.content);
```

### Models

Use the models endpoint to see what is available to your API key:

```bash
curl https://proxy.alfnrl.io/v1/models \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

Your `model` string in requests should match one of the returned model IDs.

### What you can build

* **Chat and agents** with tool calling and streaming (Chat Completions)
* **Embeddings** for search and RAG (Embeddings)
* **Image generation** (Images)&#x20;

### Next steps

* Chat Completions
* Embeddings
* Images
* Models


# Getting Started

This guide gets you from zero to first successful request in a couple of minutes using the OpenAI-compatible endpoints.

***

### 1. Create an API Key

1. Log in to your AlphaNeural Dashboard
2. Navigate to **API Keys**
3. Click **Create Key**
4. Copy your key (starts with `sk-...`)

> Treat your API key like a password. Never expose it publicly.

***

### 2. Set your environment variables

```bash
export ALPHANEURAL_API_KEY="YOUR_API_KEY"
export ALPHANEURAL_BASE_URL="https://proxy.alfnrl.io/v1"
```

### 3. Make your first request (Chat Completions)

Chat Completions is the quickest end-to-end smoke test.

### &#x20;<sup>cURL Example</sup>

```bash
curl "$ALPHANEURAL_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3",
    "messages": [{"role":"user","content":"Hello AlphaNeural"}]
  }'
```

This endpoint follows the OpenAI Chat Completions shape.

* ### Use the OpenAI SDK (Python)

AlphaNeural is OpenAI-compatible, so you can point the OpenAI SDK at AlphaNeural by setting the base URL.

```python
from openai import OpenAI
import os

client = OpenAI(
  api_key=os.environ["ALPHANEURAL_API_KEY"],
  base_url=os.environ["ALPHANEURAL_BASE_URL"],
)

resp = client.chat.completions.create(
  model="qwen3",
  messages=[{"role":"user","content":"Write a haiku about routers"}],
)
print(resp.choices[0].message.content)

```

* ### <sup>Discover available models</sup>

List models exposed by the proxy:

```bash
curl "$ALPHANEURAL_BASE_URL/models" \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

Model listing is available at `GET /v1/models`


# Authentication

AlphaNeural uses API keys for all requests. Send your key in an HTTP header over HTTPS.

### Where to put the API key

#### Option A. OpenAI-style (recommended for OpenAI SDK compatibility)

Send the key as a Bearer token:

```bash
-H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

This is the style used throughout the proxy examples in the OpenAPI spec.

#### Option B. Proxy-native header style

Send the key in `x-alphaneural-api-key`:

```bash
-H "x-alphaneural-api-key: $ALPHANEURAL_API_KEY"
```

This header is defined as the security scheme in the OpenAPI spec (source of truth).

### Quick test

List models (any authenticated endpoint works):

```bash
curl https://proxy.alfnrl.io/v1/models \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

### Using the OpenAI SDKs

Because AlphaNeural is OpenAI-compatible, you can point the OpenAI SDKs at the AlphaNeural base URL and keep the rest of your code the same.

#### Python

```python
from openai import OpenAI
import os

client = OpenAI(
  api_key=os.environ["ALPHANEURAL_API_KEY"],
  base_url="https://proxy.alfnrl.io/v1",
)

resp = client.chat.completions.create(
  model="qwen3",
  messages=[{"role":"user","content":"Hello AlphaNeural"}],
)
print(resp.choices[0].message.content)
```

#### Node.js / Javascript

```js
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.ALPHANEURAL_API_KEY,
  baseURL: "https://proxy.alfnrl.io/v1",
});

const resp = await client.chat.completions.create({
  model: "qwen3",
  messages: [{ role: "user", content: "Hello AlphaNeural" }],
});

console.log(resp.choices[0].message.content);
```

### Security notes

* Treat API keys like passwords. Keep them server-side and load them from environment variables or a secrets manager.
* Rotate keys if they are ever exposed. Admin endpoints and usage reporting are also protected by the same API key mechanism in the spec.


# Core Concepts

## 1. Models

Models represent the AI capabilities (chat, image generation, embeddings).

### List All Models

```bash
curl https://proxy.alfnrl.io/v1/models \
  -H "Authorization: Bearer YOUR_API_KEY"
```

Example response:

**json**

```json
{
  "object": "list",
  "data": [
    {"id": "qwen3"},
    {"id": "gemini-3-pro-preview"},
    {"id": "gemini/imagen-4.0"}
  ]
}
```

### 2. Tokens

Every request returns:

* prompt\_tokens
* completion\_tokens
* total\_tokens

### 3. Pricing

You are billed based on tokens used.

See your AlphaNeural Dashboard for pricing.

### 4. Rate Limits

Example rate limit error:

```json
{
  "error": {
    "message": "Rate limit exceeded",
    "type": "rate_limit_error",
    "code": 429
  }
}
```


# Chat Completions

Create a model response for a conversation. This endpoint is OpenAI-compatible, including message roles, tool calling, and streaming.

### Create a chat completion

`POST /v1/chat/completions`

#### Request body

**Required**

* `model` (string). The model ID to use.
* `messages` (array). A list of messages that make up the conversation so far.

**Messages**

Each message has a `role` plus `content`. Supported roles include `system`, `developer`, `user`, `assistant`, `tool`, and `function`.&#x20;

`content` can be either a simple string or a structured array for multimodal inputs. For example, `user` content can include typed blocks like `text`, `image_url`, `input_audio`, `document`, `video_url`, or `file`.&#x20;

#### Basic example

```bash
curl https://proxy.alfnrl.io/v1/chat/completions \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3",
    "messages": [
      { "role": "user", "content": "Write a haiku about routers." }
    ]
  }'
```

#### Multimodal example (text + image)

```bash
curl https://proxy.alfnrl.io/v1/chat/completions \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3",
    "messages": [
      {
        "role": "user",
        "content": [
          { "type": "text", "text": "What is in this image?" },
          { "type": "image_url", "image_url": { "url": "https://example.com/cat.png" } }
        ]
      }
    ]
  }'
```

Multimodal content blocks are part of the message schema supported by the proxy.

### Common parameters

These follow the OpenAI Chat Completions shape.

* Sampling and length: `temperature`, `top_p`, `max_tokens`, `stop`, `n`, `seed`
* Penalties and biasing: `presence_penalty`, `frequency_penalty`, `logit_bias`&#x20;
* Structured outputs: `response_format`
* Logging: `logprobs`, `top_logprobs`
* Streaming: `stream`, `stream_options`&#x20;
* Tool calling: `tools`, `tool_choice`, `parallel_tool_calls`
* Legacy function calling: `functions`, `function_call`
* Metadata: `metadata`, `user`

### Tool calling

Provide tool definitions in `tools`. When the model decides to call a tool, it will return `tool_calls` on the assistant message, and you should respond by sending a `tool` role message referencing the matching `tool_call_id`.

#### Tool calling example

```bash
curl https://proxy.alfnrl.io/v1/chat/completions \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3",
    "messages": [
      { "role": "user", "content": "What is the weather in Paris right now?" }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get the current weather for a city",
          "parameters": {
            "type": "object",
            "properties": { "city": { "type": "string" } },
            "required": ["city"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'
```

### Streaming

Set `stream: true` to receive server-sent events (SSE). Each event contains a delta. The stream ends with a final event.

```bash
curl https://proxy.alfnrl.io/v1/chat/completions \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3",
    "stream": true,
    "messages": [{ "role": "user", "content": "Explain TCP slow start in one paragraph." }]
  }'
```

### Response

The response follows the OpenAI Chat Completions format (for example, `choices` with an assistant message, plus token `usage`).

### AlphaNeural proxy extensions

The proxy accepts a few optional routing and reliability fields that do not exist in the upstream OpenAI API, such as `guardrails`, `caching`, `num_retries`, `fallbacks`, and `context_window_fallback_dict`. Use these only if you need proxy-level behaviour controls.


# Image Generation

AlphaNeural supports OpenAI-compatible image generation for GPT-style image models (and any provider-backed image model you expose through the OpenAI Images interface). The API shape matches OpenAI’s

### Create an image

`POST /v1/images/generations`

You can also find an Azure-style compatibility route in the proxy (`/openai/deployments/{model}/images/generations`). This docs page focuses on `/v1/images/generations`.

#### Request body

AlphaNeural follows the OpenAI Images API request shape. The most commonly used fields are:

* `model` (string). Image model ID to use.
* `prompt` (string). Text description of the image you want.
* `n` (integer). Number of images to generate.
* `size` (string). Output dimensions (supported values depend on the model).
* `quality` (string). Quality level (supported values depend on the model).
* `style` (string). Style hint (primarily for DALL·E models).
* `response_format` (string). `url` or `b64_json` for DALL·E models. Note. GPT image models always return base64 and do not support `response_format`.
* `user` (string). End-user identifier for abuse monitoring.

{% hint style="warning" %}
`response_format` is **not supported** for GPT image models in OpenAI’s API, because they always return base64-encoded image payloads
{% endhint %}

{% hint style="info" %}
Model availability varies by workspace, teams and provider. Use `GET /v1/models` to discover image-capable models exposed by your AlphaNeural key.
{% endhint %}

### Examples

#### cURL

```bash
curl https://proxy.alfnrl.io/v1/images/generations \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-1",
    "prompt": "A cute baby sea otter in a knitted hat, studio lighting",
    "size": "1024x1024",
    "n": 1
  }'
```

#### Python (OpenAI SDK)

```python
from openai import OpenAI
import os, base64
client = OpenAI(api_key=os.environ["ALPHANEURAL_API_KEY"], base_url="https://proxy.alfnrl.io/v1")
r = client.images.generate(model="gpt-image-1", prompt="A tiny robot making espresso, cinematic", size="1024x1024")
img_b64 = r.data[0].b64_json
open("image.png","wb").write(base64.b64decode(img_b64))
```

### Response

The response matches the OpenAI Images API. You will receive a `data` array with one item per generated image. Depending on the model, each item contains either:

* `b64_json` (base64-encoded image), or
* `url` (a temporary URL)

If you receive URLs, they are time-limited. OpenAI’s reference behaviour is that URLs expire after about 60 minutes. [OpenAI Platform](https://platform.openai.com/docs/api-reference/images)

Example (truncated):

```json
{
  "created": 1730000000,
  "data": [
    { "b64_json": "iVBORw0KGgoAAA..." }
  ]
}
```

#### Decode `b64_json`

```python
import os, base64, requests
r = requests.post(
  "https://proxy.alfnrl.io/v1/images/generations",
  headers={"Authorization": f"Bearer {os.environ['ALPHANEURAL_API_KEY']}",
           "Content-Type": "application/json"},
  json={"model":"gpt-image-1","prompt":"A minimal owl logo","size":"1024x1024"}
)
b64 = r.json()["data"][0]["b64_json"]
open("out.png","wb").write(base64.b64decode(b64))
```


# Image generation (Azure-style deployments)

Some teams prefer the Azure OpenAI-style URL shape where the deployment name is part of the path. AlphaNeural supports that format for image generation too.

**Endpoint**

* `POST https://proxy.alfnrl.io/openai/deployments/{deployment}/images/generations`&#x20;

Where:

* `{deployment}` is your Azure-style deployment identifier (what you would normally put in the Azure URL).

### Quickstart

```bash
curl https://proxy.alfnrl.io/openai/deployments/my-image-deployment/images/generations \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A product photo of a glass bottle on white background",
    "size": "1024x1024"
  }'
```

### Behaviour notes

* You usually **omit `model`** in the JSON body because the deployment is already specified in the path, Azure-style.
* Parameters like `size`, `quality`, `background`, `output_format` behave like OpenAI’s Images API (subject to model support).
* As with OpenAI and Azure OpenAI, GPT image models return base64 and do not support `response_format`.

{% hint style="info" %}
Use this route when you are migrating Azure OpenAI code or you want “deployment-first” routing. Otherwise, prefer the OpenAI-compatible endpoint for the cleanest portability
{% endhint %}


# Image generation (Passthrough. Diffusion and custom APIs)

AlphaNeural also deploys non-LLM image models, like Stable Diffusion-style pipelines and other diffusion systems.

These frequently expose **custom request/response formats**, so they are typically accessed via **passthrough endpoints**, not the OpenAI Images API.

Passthrough means. AlphaNeural forwards your request to the upstream provider or service **without normalising the payload**.

### When to use passthrough

Use passthrough when:

* the model is **diffusion-based** (or otherwise not OpenAI Images compatible),
* the upstream requires a **custom endpoint path** or **custom JSON schema**,
* you want to use the provider’s native features that do not map cleanly to OpenAI parameters.

### Endpoint shape

AlphaNeural exposes provider passthrough routes in the form:

* `/{provider}/{endpoint}`

For example, the spec includes a pass-through route for OpenAI itself:

* `POST https://proxy.alfnrl.io/openai/{endpoint}`

{% hint style="warning" %}
Passthrough routes are **not OpenAI-compatible by definition**. Your payload and response format are whatever the upstream expects.
{% endhint %}

### Example. Passing through to an upstream Images endpoint

If you need to call a openai deployment directly (or reproduce an upstream call exactly), you can passthrough the endpoint path:

```bash
curl https://proxy.alfnrl.io/openai/v1/images/generations \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-1",
    "prompt": "An isometric diagram of a neural network as a subway map"
  }'
```

### Example. Diffusion deployment via passthrough (template)

For Stable Diffusion-style deployments, you will call the **deployment’s native path** and send its **native payload**:

```bash
curl https://proxy.alfnrl.io/<provider>/<native-endpoint-path> \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '<native-json-payload>'
```

AlphaNeural will document each diffusion deployment with:

* the `{provider}` prefix,
* the exact `<native-endpoint-path>`,
* the required auth headers (if any) beyond the AlphaNeural key.

{% hint style="info" %}
If you want a diffusion model to be callable via `POST /v1/images/generations`, it must be deployed behind an OpenAI-compatible adapter. Otherwise, passthrough is the correct interface.
{% endhint %}


# Embeddings

Embeddings turn text into vectors you can use for semantic search, clustering, recommendations, and RAG. The AlphaNeural proxy follows the same API shape as OpenAI’s Embeddings endpoint.

### Create embeddings

`POST /v1/embeddings`

#### Request body

**Required**

* `model` (string). The embedding model to use.

**Common**

* `input` (string or array of strings). The text to embed.
  * If you pass an array, you will get one embedding per item.

{% hint style="info" %}
The proxy supports OpenAI-style payloads. It also exposes a few proxy-only fields (below) for routing and reliability. openapi
{% endhint %}

#### Basic example (single input)

```bash
curl https://proxy.alfnrl.io/v1/embeddings \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "text-embedding-3-small",
    "input": "The quick brown fox jumps over the lazy dog"
  }'
```

The proxy documentation includes the same request pattern for embeddings. openapi

#### Batch example (multiple inputs)

```bash
curl https://proxy.alfnrl.io/v1/embeddings \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "text-embedding-3-small",
    "input": [
      "Paris is the capital of France.",
      "Berlin is the capital of Germany."
    ]
  }'
```

#### Python (OpenAI SDK)

```python
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["ALPHANEURAL_API_KEY"], base_url="https://proxy.alfnrl.io/v1")
resp = client.embeddings.create(model="text-embedding-3-small", input=["hello", "world"])
print(len(resp.data), len(resp.data[0].embedding))
```

#### JavaScript/TypeScript (OpenAI SDK)

```js
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.ALPHANEURAL_API_KEY, baseURL: "https://proxy.alfnrl.io/v1" });
const resp = await client.embeddings.create({ model: "text-embedding-3-small", input: ["hello", "world"] });
console.log(resp.data.length, resp.data[0].embedding.length);
```

### Response

The response matches the OpenAI embeddings format. You receive a `data` array with one embedding per input, plus `usage` metadata.

Example (truncated):

```json
{
  "object": "list",
  "data": [
    { "object": "embedding", "index": 0, "embedding": [0.0123, -0.0456, 0.0789] }
  ],
  "model": "text-embedding-3-small",
  "usage": { "prompt_tokens": 8, "total_tokens": 8 }
}
```

### Proxy-only options

Most teams do not need these. They exist to control proxy behaviour across multiple upstream providers.

* `timeout` (integer, default `600`). Request timeout in seconds.
* `caching` (boolean, default `false`). Enable proxy caching when configured.
* `user` (string). End-user identifier for tracing and abuse monitoring.


# Models

List the models available to your AlphaNeural API key. This endpoint is OpenAI-compatible, so tools and SDKs that expect GET /v1/models will work out of the box.

### List models

`GET /v1/models` openapi

AlphaNeural also exposes `GET /models` as an alias for compatibility. openapi

#### Authentication

Send your key in the `Authorization` header.

```bash
-H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

### Query parameters

These are optional. If you do not pass anything, you get the default model list for your key. openapi

* `return_wildcard_routes` (boolean). Include wildcard routes in the returned list.
* `team_id` (string). Filter models by team.
* `include_model_access_groups` (boolean). Include model access group information.&#x20;
* `only_model_access_groups` (boolean). Return only model access groups.
* `include_metadata` (boolean). Include additional metadata in the response with fallback information.
* `fallback_type` (string). Which fallback class to include when `include_metadata=true`. Supported values include `general`, `context_window`, `content_policy`.

{% hint style="info" %}
For richer model details like pricing, mode, and config-derived metadata, the spec recommends using `/v1/model/info`. This page focuses on OpenAI-compatible listing for developer tooling compatibility.&#x20;
{% endhint %}

### Examples

#### cURL

```bash
curl https://proxy.alfnrl.io/v1/models \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

With metadata and fallback info:

```bash
curl "https://proxy.alfnrl.io/v1/models?include_metadata=true&fallback_type=general" \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

#### Python (OpenAI SDK style)

```python
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["ALPHANEURAL_API_KEY"], base_url="https://proxy.alfnrl.io/v1")
models = client.models.list()
print([m.id for m in models.data][:10])
```

#### JavaScript/TypeScript (OpenAI SDK style)

```js
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.ALPHANEURAL_API_KEY, baseURL: "https://proxy.alfnrl.io/v1" });
const models = await client.models.list();
console.log(models.data.map(m => m.id).slice(0, 10));
```

### Response

Returns an OpenAI-style “list” of model objects. The exact fields can vary by upstream and by whether you enable metadata. openapi

Example shape (illustrative):

```json
{
  "object": "list",
  "data": [
    { "id": "gpt-4o-mini", "object": "model", "owned_by": "alphaneural" },
    { "id": "qwen3", "object": "model", "owned_by": "alphaneural" }
  ]
}
```

### Related

* Retrieve a specific model: `GET /v1/models/{model_id}`


# Usage & Billing

Retrieve token usage and cost.

AlphaNeural includes a small set of **usage and billing** endpoints for tracking spend across API keys, users, and teams. These endpoints are designed for dashboards, internal chargeback, and debugging unusual spend patterns.

All endpoints use the same authentication as the rest of the proxy. The spend log object returned by these endpoints includes request metadata, token counts, and calculated cost.

### View spend logs

Returns spend records. You can filter by `request_id`, `api_key`, `user_id`, and optionally a date range.

When `start_date` and `end_date` are provided:

* `summarize=true` (default) returns **aggregated spend grouped by date** (legacy behaviour)
* `summarize=false` returns **individual log entries** within the date range

**GET** `/spend/logs`&#x20;

#### Query parameters

* `request_id` (string, optional). Return logs for a specific request id
* `api_key` (string, optional). Filter by API key
* `user_id` (string, optional). Filter by user id
* `start_date` (string, optional). Start of the window (commonly `YYYY-MM-DD`)
* `end_date` (string, optional). End of the window (commonly `YYYY-MM-DD`)
* `summarize` (boolean, optional, default `true`). Aggregate by date vs return raw logs

#### Example (curl)

```bash
curl https://proxy.alfnrl.io/spend/logs \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

Date range with **individual** logs:

```bash
curl "https://proxy.alfnrl.io/spend/logs?start_date=2024-01-01&end_date=2024-01-02&summarize=false" \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

#### Response

Returns an array of spend log objects.

***

### View spend tags

Returns spend grouped by request tags. This is useful when you attach tags like `project:search`, `env:staging`, `customer:acme` to requests and want lightweight spend breakdowns.

**GET** `/spend/tags`

#### Query parameters

* `start_date` (string, optional). Start of the window
* `end_date` (string, optional). End of the window

#### Example (curl)

```bash
curl "https://proxy.alfnrl.io/spend/tags?start_date=2022-01-01&end_date=2022-02-01" \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY"
```

#### Response

Returns an array of spend log objects (tagged).

***

### Calculate spend

Compute cost without running a request (estimate), or compute cost from an existing completion response (post hoc). This endpoint accepts the same inputs used for cost calculation.

**POST** `/spend/calculate`&#x20;

#### Request body (one of)

* `model` + `messages` (estimate before calling a model)
* `completion_response` (calculate after you already have a response)

#### Example (curl). Pre-call estimate

```bash
curl https://proxy.alfnrl.io/spend/calculate \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic.claude-v2",
    "messages": [{"role":"user","content":"Estimate the cost of this request."}]
  }'
```

#### Example (curl). Post-call calculation

```bash
curl https://proxy.alfnrl.io/spend/calculate \
  -H "Authorization: Bearer $ALPHANEURAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "completion_response": {
      "id": "chatcmpl-123",
      "object": "chat.completion",
      "created": 1677652288,
      "model": "gpt-3.5-turbo-0125",
      "choices": [{
        "index": 0,
        "message": {"role":"assistant","content":"Hello there."},
        "finish_reason": "stop"
      }],
      "usage": {"prompt_tokens": 9, "completion_tokens": 12, "total_tokens": 21}
    }
  }'
```

#### Response

Returns the calculated `cost` as a float


# Error Codes

Standard HTTP error codes are used.

### Common Errors

\| Code | Meaning | Description |

\|------|------------|-------------|

\| **400** | Bad Request | Invalid parameters |

\| **401** | Unauthorized | Missing/invalid API key |

\| **404** | Not Found | Wrong endpoint/model |

\| **429** | Rate Limit | Too many requests |

\| **500** | Server Error | Internal issue |

### Example Error

**json**

```json
{
  "error": {
    "message": "Rate limit exceeded",
    "type": "rate_limit_error",
    "code": 429
  }
}
```


# Best Practices

#### 1. Use Environment Variables

Never hardcode your API key.

#### 2. Implement Retries

Retry on:

<sub>- 429 (rate limit)</sub> &#x20;

<sub>- 500 (server error)</sub> &#x20;

#### 3. Log Token Usage

Include:

<sub>- model</sub> &#x20;

<sub>- prompt tokens</sub> &#x20;

<sub>- completion tokens</sub> &#x20;

<sub>- total tokens</sub> &#x20;

#### 4. Separate API Keys

Use different keys for:

<sub>- development</sub> &#x20;

<sub>- staging</sub> &#x20;

<sub>- production</sub> &#x20;


# Use AlphaNeural with OpenCode

OpenCode can talk to any OpenAI-compatible API by setting a provider baseURL and giving it an API key. AlphaNeural fits that shape, so the integration is mostly config and credentials.

OpenCode can talk to any **OpenAI-compatible** API by setting a provider `baseURL` and giving it an API key. AlphaNeural fits that shape, so the integration is mostly config and credentials.

### Add your AlphaNeural API key to OpenCode

In OpenCode, run:

```
/connect
```

Choose **Other**, then enter a provider id like `alphaneural`, then paste your AlphaNeural API key. OpenCode stores credentials in `~/.local/share/opencode/auth.json`.

### Create a project config

Create `opencode.json` in your project root. Project config has high precedence and is safe to commit. It overrides global config at `~/.config/opencode/opencode.json`.

#### Recommended setup. Custom provider `alphaneural`

```json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "alphaneural/qwen3",
  "provider": {
    "alphaneural": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "AlphaNeural",
      "options": {
        "baseURL": "https://proxy.alfnrl.io/v1"
      },
      "models": {
        "qwen3": { "name": "Qwen 3" }
      }
    }
  }
}
```

Notes:

* OpenCode supports overriding a provider’s `baseURL` via `options.baseURL`.
* The `model` format is `providerId/modelId`, like `anthropic/claude-sonnet-4-5` in their examples.
* Replace `qwen3` with any model id exposed by your AlphaNeural `/v1/models` endpoint.

### Pick a model in the UI and run

OpenCode will detect your provider and models. Use:

```
/models
```

Select `AlphaNeural`, then pick the model you configured.

Quick smoke test from the CLI is also fine:

```bash
opencode run "Explain what this repo does and suggest 3 improvements"
```

***

### Troubleshooting

#### “It ignores my baseURL” or “NotFoundError” for custom OpenAI-compatible providers

There is an open issue where OpenCode’s bundled `@ai-sdk/openai-compatible` provider may fail to forward `options` like `baseURL`, causing requests to be sent without your custom endpoint settings.

**What to do**

* Upgrade OpenCode to the latest version available for your platform, then retry.
* If it still fails, use the workaround below.

#### Workaround. Use the built-in `openai` provider with a custom baseURL

OpenCode docs state you can customise the base URL for any provider by setting `options.baseURL`.\
So you can route the built-in `openai` provider to AlphaNeural:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "openai/qwen3",
  "provider": {
    "openai": {
      "options": {
        "baseURL": "https://proxy.alfnrl.io/v1"
      },
      "models": {
        "qwen3": { "name": "Qwen 3" }
      }
    }
  }
}
```

This keeps you on the built-in OpenAI provider path while still pointing traffic at AlphaNeural.

***

### Optional. Put AlphaNeural in global config

If you want AlphaNeural available in every repo, add the provider block to `~/.config/opencode/opencode.json`. OpenCode merges global and project configs, with project taking precedence.


# Use AlphaNeural with Continue (VS Code and JetBrains)

Continue supports OpenAI API compatible providers by letting you set a custom apiBase. AlphaNeural is OpenAI-compatible, so the integration is mostly configuration.

### Create a local secret for your AlphaNeural key

Continue can load secrets from `.env` files (workspace or global), then reference them from `config.yaml`.

Pick one of these locations (searched in this order):

* `<workspace-root>/.env`
* `<workspace-root>/.continue/.env`
* `~/.continue/.env` (global)

Example `~/.continue/.env`:

```bash
ALPHANEURAL_API_KEY=your_key_here
```

### Configure Continue to use AlphaNeural

Edit (or create) your local config file:

* macOS/Linux: `~/.continue/config.yaml`
* Windows: `%USERPROFILE%\.continue\config.yaml`

Minimal config using AlphaNeural as an OpenAI-compatible provider:

```yaml
name: AlphaNeural
version: 0.0.1
schema: v1

models:
  - name: AlphaNeural Chat
    provider: openai
    model: qwen3
    apiBase: https://proxy.alfnrl.io/v1
    apiKey: ${{ secrets.ALPHANEURAL_API_KEY }}
    roles: [chat, edit, apply]

  - name: AlphaNeural Autocomplete
    provider: openai
    model: qwen3
    apiBase: https://proxy.alfnrl.io/v1
    apiKey: ${{ secrets.ALPHANEURAL_API_KEY }}
    roles: [autocomplete]
```

* Continue’s OpenAI provider supports overriding `apiBase` for OpenAI-compatible servers.
* Continue lets you reference secrets from `.env` using the `secrets` namespace.
* `roles` controls where the model is available (chat vs autocomplete, etc).

### Reload Continue

If your model does not show up, reload VS Code so extensions re-read the config.

* Command palette: type **Reload Window**

For JetBrains, restarting the IDE is the simplest equivalent.

### Select the model and run a smoke test

Open the Continue sidebar, choose **AlphaNeural Chat**, then try:

* “Summarise this file and suggest improvements”
* “Explain this stack trace and propose a fix”

### Optional. Enable tools and vision explicitly

If Agent mode is disabled or tools are flaky, you can force capabilities in the model block.

```yaml
capabilities: [tool_use, image_input]
```

This is especially useful when you are routing through proxies where capability auto-detection is imperfect.


