Docs / AI connections and gateway

AI connections and gateway

Connect OpenRouter and build AI features with conversation history, tools, streaming, caching and error diagnostics.

Connect an OpenRouter key to your project

  1. Prepare your OpenRouter key

    Create an API key on the OpenRouter website. Browse models and copy the ID of a model that supports the task you want to use.

  2. Open the AI connection tab

    Select a project and save the key on its AI connection tab. Project owners and editors can add or replace the key, or disconnect to remove it.

  3. Call from server code

    Once you save the key, your server code can use env.OPENROUTER_API_KEY and env.AI_GATEWAY. No gateway URL is needed.

AI requests use the OpenRouter key you registered. The key is stored as a Secret on your project Worker, and you cannot view its value after saving. Save a new key to replace it, or disconnect to delete it. Keep the key out of browser code, Git, logs and conversations with your coding agent.

run(model, input, options)

Call env.AI_GATEWAY.run() from your project’s server code. The examples below belong inside a Hono request handler, after you have checked the user’s login and permissions. Each example uses c.env to access the project’s bindings.

JavaScript
const response = await env.AI_GATEWAY.run(model, input, { apiKey, task });
model · required
An OpenRouter model ID that supports the selected task. Replace the model ID placeholders below with real IDs.
input · required
An object containing the model’s input. Put chat messages in messages, text to embed in input, or an image description in prompt.
options.apiKey · required
Pass your saved key as env.OPENROUTER_API_KEY.
options.task · required
Set this to chat, responses, messages, embeddings or image. If it is missing or has another value, the gateway returns 400 without sending a request to OpenRouter.
Return value
Returns a Response object. Forward streaming responses directly. For JSON responses, check response.ok before calling response.json().

Chat and streaming

Choose a chat model and put the conversation in messages. Set stream: true to receive the answer as an SSE stream. Return the response directly rather than reading it with response.json().

JavaScript
const env = c.env;
const response = await env.AI_GATEWAY.run(
  "<CHAT_MODEL_ID>",
  {
    messages: [{ role: "user", content: "Hello" }],
    stream: true,
  },
  { apiKey: env.OPENROUTER_API_KEY, task: "chat" },
);
return response;

Send the conversation history

The gateway does not store conversations or append earlier messages. Load the authenticated user’s conversation in your app and send it with the new question. Here, history is the authorized message array and userMessage is the validated new question.

JavaScript
const env = c.env;
// history belongs to the authenticated conversation; userMessage is validated.
const messages = [...history, { role: "user", content: userMessage }];
const response = await env.AI_GATEWAY.run(
  "<CHAT_MODEL_ID>",
  { messages },
  { apiKey: env.OPENROUTER_API_KEY, task: "chat" },
);
if (!response.ok) return response;
const result = await response.json();
const assistant = result.choices[0].message;
// Save this complete history in your app before the next turn.
messages.push(assistant);
return Response.json(result);

Keep the complete assistant message for the next request, including tool_calls and reasoning_details. For streaming, assemble the completed response before saving it to history. Apply your app’s summarization and retention rules as the model’s context limit approaches, and keep each user’s conversations separate.

Read the response for the selected task: chat uses choices[].message, responses uses output[], messages uses content[], embeddings uses data[].embedding and image uses data[].b64_json. Changing models within one task keeps that API shape; changing tasks requires matching input and response handling.

Responses API

task: "responses" calls OpenRouter /v1/responses. Send input, tools, reasoning and multimodal options in their OpenRouter format. This API is stateless: include prior output and tool results in input for later turns. OpenRouter does not support loading an earlier response with previous_response_id or setting store: true.

JavaScript
const env = c.env;
return env.AI_GATEWAY.run(
  "<RESPONSES_MODEL_ID>",
  { input: "Hello", stream: true },
  { apiKey: env.OPENROUTER_API_KEY, task: "responses" },
);

Anthropic Messages API

task: "messages" calls OpenRouter /v1/messages. It preserves system, thinking, tool_use/tool_result and image/document blocks. Read content, stop_reason and usage in this API’s format rather than Chat Completions choices.

JavaScript
const env = c.env;
return env.AI_GATEWAY.run(
  "<MESSAGES_MODEL_ID>",
  { messages: [{ role: "user", content: "Hello" }], max_tokens: 1024 },
  { apiKey: env.OPENROUTER_API_KEY, task: "messages" },
);

Advanced chatbots and tools

The gateway forwards JSON fields such as tools, tool_choice, parallel_tool_calls, response_format, reasoning, plugins, models and provider unchanged. Use the formats supported by your selected model and OpenRouter API for structured output, image/audio/file input and model/provider fallbacks.

Your project server executes allowed function tools and validates their arguments. OpenRouter server tools and plugins follow their own API execution rules. Return one result per tool_call_id, including parallel calls, and preserve the full assistant message with reasoning_details. This example limits rounds and exposes only the server clock.

JavaScript
const env = c.env;
const messages = [{ role: "user", content: "What time is it?" }];
const tools = [{ type: "function", function: {
  name: "get_server_time",
  description: "Get the current UTC time",
  parameters: { type: "object", properties: {}, additionalProperties: false },
} }];
for (let round = 0; round < 4; round++) {
  const response = await env.AI_GATEWAY.run(
    "<TOOL_CAPABLE_MODEL_ID>",
    { messages, tools, provider: { require_parameters: true } },
    { apiKey: env.OPENROUTER_API_KEY, task: "chat" },
  );
  if (!response.ok) return response;
  const result = await response.json();
  const assistant = result.choices[0].message;
  if (!assistant.tool_calls?.length) return Response.json(result);
  // Preserve the full assistant message, including reasoning metadata.
  messages.push(assistant);
  for (const call of assistant.tool_calls) {
    if (call.function.name !== "get_server_time") {
      return Response.json({ error: { code: "unsupported_tool" } }, { status: 400 });
    }
    let args;
    try { args = JSON.parse(call.function.arguments); }
    catch { return Response.json({ error: { code: "invalid_tool_arguments" } }, { status: 400 }); }
    if (!args || Array.isArray(args) || Object.keys(args).length) {
      return Response.json({ error: { code: "invalid_tool_arguments" } }, { status: 400 });
    }
    messages.push({ role: "tool", tool_call_id: call.id,
      content: JSON.stringify({ utc: new Date().toISOString() }),
    });
  }
}
return Response.json({ error: { code: "tool_limit" } }, { status: 422 });

Streaming arguments can arrive in fragments. Accumulate them by call ID or index and validate the completed JSON before execution. The gateway does not rewrite SSE events or usage data.

Prompt caching and response caching

Provider prompt caching accepts cache_control, prompt_cache_options and session_id in input. Check usage.prompt_tokens_details.cached_tokens, or usage.input_tokens_details.cached_tokens for Responses, to measure actual hits. Token minimums, TTL and model/provider support apply.

OpenRouter response caching is separate and stays opt-in. Use a fixed model and input with identical content and field order for reproducible hit checks.

JavaScript
const env = c.env;
const response = await env.AI_GATEWAY.run(
  "<CHAT_MODEL_ID>",
  { messages, session_id: conversationId },
  {
    apiKey: env.OPENROUTER_API_KEY,
    task: "chat",
    headers: {
      "X-OpenRouter-Cache": "true",
      "X-OpenRouter-Cache-TTL": "300",
    },
  },
);
// HIT or MISS; prompt cache usage is reported separately in the body.
const cacheStatus = response.headers.get("X-OpenRouter-Cache-Status");
return response;

options.headers allows only X-OpenRouter-Cache, X-OpenRouter-Cache-TTL, X-OpenRouter-Cache-Clear, X-Session-Id and X-OpenRouter-Metadata, plus protocol headers anthropic-version and anthropic-beta. TTL is 1–86400 seconds. To refresh one request, send X-OpenRouter-Cache: true with X-OpenRouter-Cache-Clear: true, then check that the next normal cached request hits the new result. Authorization and Cookie overrides are rejected. Cache status, age, TTL and current/source generation IDs are preserved. Browser Cache-Control remains no-store, independently of OpenRouter caching. Check the official cache documentation for eligibility and account-policy conditions.

Text embeddings

Choose an embedding model and pass a string or an array of strings in input. If the request succeeds, the JSON response contains vectors in data[].embedding. Your app is responsible for storing the vectors and source text and using them for search.

JavaScript
const env = c.env;
const response = await env.AI_GATEWAY.run(
  "<EMBEDDING_MODEL_ID>",
  { input: ["Hello", "World"] },
  { apiKey: env.OPENROUTER_API_KEY, task: "embeddings" },
);
return response;

Image generation

Choose a model supported by the OpenRouter Image API and describe the image in prompt. This example requests one image. Once generation finishes, the JSON response contains a Base64-encoded image in data[].b64_json. If media_type is present, it identifies the image format. Check the OpenRouter image generation docs for model-specific options.

JavaScript
const env = c.env;
const response = await env.AI_GATEWAY.run(
  "<IMAGE_MODEL_ID>",
  { prompt: "A cat sitting by a sunny window", n: 1 },
  { apiKey: env.OPENROUTER_API_KEY, task: "image" },
);
return response;

Handle errors and control access

  • The gateway returns 400 if task is missing or unsupported, the model ID is empty or is not a string, or the input is not an object.
  • A missing or malformed API key returns 401. If OpenRouter returns an error, the gateway keeps its HTTP status and includes error.code, source, upstream_status, request_id and a safe error message in the response.
  • If the gateway cannot connect to OpenRouter, it returns 502. Binding calls can also throw exceptions, so handle these in your app’s error handling code.
  • Use the API key only on the server. Check the login and permissions of users who call AI features in your app, and set request limits where needed. The project’s AI connection settings do not check those users’ permissions for you.
  • Keep keys, prompts and raw AI responses out of logs. A streaming request can fail after the HTTP response has started, so check for error messages while your app reads the stream.

See the app authentication and authorization guide and your project’s AI connection tab.

Verify and troubleshoot your deployment

Verify through your deployed project’s server route. Check model/provider feature support separately from gateway transport.

  1. Basic calls and conversation

    Ask a short question, then ask about a value from the previous turn. Check that the second request includes both earlier user and assistant messages.

  2. Tools and streaming

    Execute an allowed tool, send the result with its tool_call_id and verify the final answer. Match all IDs and results for parallel calls. Observe the first stream chunk and completion or error events; HTTP 200 alone does not prove completion.

  3. Caching

    Repeat an identical request and check that X-OpenRouter-Cache-Status changes from MISS to HIT. Match X-OpenRouter-Cache-Source-Id to the original X-Generation-Id, and verify a new source after clearing. Response cache HIT and prompt cached_tokens in usage are separate metrics. A zero cached_tokens value alone does not indicate a gateway failure.

  4. Error diagnosis

    Preserve HTTP status, error.code, error.source, error.upstream_status, error.provider_code, error.request_id and X-AI-Gateway-Request-Id. When diagnostics identify a provider error, inspect the provider/model route rather than assuming every 401 means an invalid user key. Do not map every failure to 502; honor Retry-After on 429. Record only status, codes and request IDs, never keys or raw conversations.