diff --git a/.gitignore b/.gitignore
index c9094dbf6a..2426de22c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,4 @@ openapi.json
llmgateway_data
.claude/settings.local.json
http
+*.txt
diff --git a/apps/docs/content/(api)/v1_messages.mdx b/apps/docs/content/(api)/v1_messages.mdx
new file mode 100644
index 0000000000..eff57f6ef0
--- /dev/null
+++ b/apps/docs/content/(api)/v1_messages.mdx
@@ -0,0 +1,17 @@
+---
+title: Anthropic Messages
+description: Create a message using Anthropic's API format
+full: true
+_openapi:
+ method: POST
+ route: /v1/messages
+ toc: []
+ structuredData:
+ headings: []
+ contents:
+ - content: Create a message using Anthropic's API format
+---
+
+{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
+
+
\ No newline at end of file
diff --git a/apps/docs/content/features/anthropic-endpoint.mdx b/apps/docs/content/features/anthropic-endpoint.mdx
new file mode 100644
index 0000000000..3855e93d49
--- /dev/null
+++ b/apps/docs/content/features/anthropic-endpoint.mdx
@@ -0,0 +1,98 @@
+---
+title: Anthropic API Compatibility
+description: Use the Anthropic-compatible endpoint to access any LLM model through the familiar Anthropic API format.
+icon: MessageCircle
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+# Anthropic API Compatibility
+
+LLMGateway provides a native Anthropic-compatible endpoint at `/v1/messages` that allows you to use any model in our catalog while maintaining the familiar Anthropic API format
+This is especially useful for applications designed for Claude that you want to extend to use other models.
+
+## Overview
+
+The Anthropic endpoint transforms requests from Anthropic's message format to the OpenAI-compatible format used by LLMGateway, then transforms the responses back to Anthropic's format. This means you can:
+
+- Use **any model** available in LLMGateway with Anthropic's API format
+- Maintain existing code that uses Anthropic's SDK or API format
+- Access models from OpenAI, Google, Cohere, and other providers through the Anthropic interface
+- Leverage LLMGateway's routing, caching, and cost optimization features
+
+## Basic Usage
+
+## Configuration for Claude Code
+
+This endpoint is perfect for configuring Claude Code to use any model available in LLMGateway:
+
+```bash
+export ANTHROPIC_BASE_URL=https://api.llmgateway.io/v1/messages
+export ANTHROPIC_AUTH_TOKEN=llmgtwy_your_api_key_here
+export ANTHROPIC_MODEL=openai/gpt-4o # or any model from our catalog
+```
+
+
+ Note the different base URL: we use `/v1/anthropic` instead of just `/v1` to
+ point to the Anthropic-compatible endpoint.
+
+
+### Choosing Models
+
+You can use any model from the [models page](https://llmgateway.io/models). Popular options for Claude Code include:
+
+```bash
+# Use OpenAI's latest model
+export ANTHROPIC_MODEL=openai/gpt-4o
+
+# Use a cost-effective alternative
+export ANTHROPIC_MODEL=openai/gpt-4o-mini
+
+# Use Google's Gemini
+export ANTHROPIC_MODEL=google/gemini-1.5-pro
+
+# Use Anthropic's actual Claude models
+export ANTHROPIC_MODEL=anthropic/claude-3-5-sonnet-20241022
+```
+
+## Advanced Features
+
+### Making a manual request
+
+```bash
+curl -X POST "https://api.llmgateway.io/v1/messages" \
+ -H "Authorization: Bearer $LLM_GATEWAY_API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [
+ {"role": "user", "content": "Hello, how are you?"}
+ ],
+ "max_tokens": 100
+ }'
+```
+
+### Response Format
+
+The endpoint returns responses in Anthropic's message format:
+
+```json
+{
+ "id": "msg_abc123",
+ "type": "message",
+ "role": "assistant",
+ "model": "openai/gpt-4o-mini",
+ "content": [
+ {
+ "type": "text",
+ "text": "Hello! I'm doing well, thank you for asking. How can I help you today?"
+ }
+ ],
+ "stop_reason": "end_turn",
+ "stop_sequence": null,
+ "usage": {
+ "input_tokens": 13,
+ "output_tokens": 20
+ }
+}
+```
diff --git a/apps/docs/content/meta.json b/apps/docs/content/meta.json
index 17cc0648dd..bb11d7e958 100644
--- a/apps/docs/content/meta.json
+++ b/apps/docs/content/meta.json
@@ -12,6 +12,7 @@
"features/api-keys",
"---Features---",
"features/routing",
+ "features/anthropic-endpoint",
"features/source",
"features/image-generation",
"features/vision",
diff --git a/apps/gateway/src/anthropic/anthropic.ts b/apps/gateway/src/anthropic/anthropic.ts
new file mode 100644
index 0000000000..3e82aa0aeb
--- /dev/null
+++ b/apps/gateway/src/anthropic/anthropic.ts
@@ -0,0 +1,767 @@
+import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
+import { HTTPException } from "hono/http-exception";
+
+import type { ServerTypes } from "@/vars";
+
+export const anthropic = new OpenAPIHono();
+
+const anthropicMessageSchema = z.object({
+ role: z.enum(["user", "assistant", "tool", "function"]),
+ content: z.union([
+ z.string(),
+ z.array(
+ z.union([
+ z.object({
+ type: z.literal("text"),
+ text: z.string(),
+ }),
+ z.object({
+ type: z.literal("image"),
+ source: z.object({
+ type: z.literal("base64"),
+ media_type: z.string(),
+ data: z.string(),
+ }),
+ }),
+ z.object({
+ type: z.literal("tool_use"),
+ id: z.string(),
+ name: z.string(),
+ input: z.record(z.unknown()),
+ }),
+ z.object({
+ type: z.literal("tool_result"),
+ tool_use_id: z.string(),
+ content: z.union([z.string(), z.array(z.unknown())]).optional(),
+ is_error: z.boolean().optional(),
+ }),
+ ]),
+ ),
+ ]),
+ // OpenAI message properties
+ tool_call_id: z.string().optional(),
+ name: z.string().optional(),
+ tool_calls: z
+ .array(
+ z.object({
+ id: z.string(),
+ type: z.literal("function"),
+ function: z.object({
+ name: z.string(),
+ arguments: z.string(),
+ }),
+ }),
+ )
+ .optional(),
+ function_call: z
+ .object({
+ id: z.string().optional(),
+ name: z.string(),
+ arguments: z.union([z.string(), z.record(z.unknown())]),
+ })
+ .optional(),
+});
+
+const anthropicToolSchema = z.object({
+ name: z.string(),
+ description: z.string(),
+ input_schema: z.record(z.unknown()),
+});
+
+const anthropicRequestSchema = z.object({
+ model: z.string().openapi({
+ description: "The model to use for completion",
+ example: "claude-3-5-sonnet-20241022",
+ }),
+ messages: z.array(anthropicMessageSchema).openapi({
+ description: "Array of message objects",
+ }),
+ max_tokens: z.number().min(1).openapi({
+ description: "Maximum number of tokens to generate",
+ example: 1024,
+ }),
+ system: z
+ .union([
+ z.string(),
+ z.array(
+ z.object({
+ type: z.literal("text"),
+ text: z.string(),
+ }),
+ ),
+ ])
+ .optional()
+ .openapi({
+ description: "System prompt to provide context",
+ }),
+ temperature: z.number().min(0).max(1).optional().openapi({
+ description: "Sampling temperature between 0 and 1",
+ example: 0.7,
+ }),
+ tools: z.array(anthropicToolSchema).optional().openapi({
+ description: "Available tools for the model to use",
+ }),
+ stream: z.boolean().optional().default(false).openapi({
+ description: "Whether to stream the response",
+ example: false,
+ }),
+});
+
+const anthropicContentBlockSchema = z.object({
+ type: z.enum(["text", "tool_use"]),
+ text: z.string().optional(),
+ id: z.string().optional(),
+ name: z.string().optional(),
+ input: z.record(z.unknown()).optional(),
+});
+
+const anthropicResponseSchema = z.object({
+ id: z.string(),
+ type: z.literal("message"),
+ role: z.literal("assistant"),
+ model: z.string(),
+ content: z.array(anthropicContentBlockSchema),
+ stop_reason: z
+ .enum(["end_turn", "max_tokens", "stop_sequence", "tool_use"])
+ .nullable(),
+ stop_sequence: z.string().nullable(),
+ usage: z.object({
+ input_tokens: z.number(),
+ output_tokens: z.number(),
+ }),
+});
+
+type AnthropicRequest = z.infer;
+
+const messages = createRoute({
+ operationId: "v1_messages",
+ summary: "Anthropic Messages",
+ description: "Create a message using Anthropic's API format",
+ method: "post",
+ path: "/",
+ security: [
+ {
+ bearerAuth: [],
+ },
+ ],
+ request: {
+ body: {
+ content: {
+ "application/json": {
+ schema: anthropicRequestSchema,
+ },
+ },
+ },
+ },
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: anthropicResponseSchema,
+ },
+ "text/event-stream": {
+ schema: z.string(),
+ },
+ },
+ description: "Successful response",
+ },
+ },
+});
+
+anthropic.openapi(messages, async (c) => {
+ // Manual request parsing with better error handling
+ let rawRequest: unknown;
+ try {
+ rawRequest = await c.req.json();
+ } catch (error) {
+ // console.log("Failed to parse JSON from request:", error);
+ throw new HTTPException(400, {
+ message: `Invalid JSON in request body: ${error}`,
+ });
+ }
+
+ // console.log("Raw Anthropic request:", JSON.stringify(rawRequest, null, 2));
+
+ // Validate with our schema
+ const validation = anthropicRequestSchema.safeParse(rawRequest);
+ if (!validation.success) {
+ // console.log(
+ // "Anthropic request validation failed:",
+ // JSON.stringify(validation.error.issues, null, 2),
+ // );
+ throw new HTTPException(400, {
+ message: `Invalid request format: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`,
+ });
+ }
+
+ const anthropicRequest: AnthropicRequest = validation.data;
+ // console.log(
+ // "Validated Anthropic request:",
+ // JSON.stringify(anthropicRequest, null, 2),
+ // );
+
+ // Transform Anthropic request to OpenAI format
+ const openaiMessages: Array> = [];
+
+ // Add system message if provided
+ if (anthropicRequest.system) {
+ let systemContent: string;
+ if (typeof anthropicRequest.system === "string") {
+ systemContent = anthropicRequest.system;
+ } else {
+ // Handle array format - concatenate all text blocks
+ systemContent = anthropicRequest.system
+ .map((block) => block.text)
+ .join(" ");
+ }
+ openaiMessages.push({
+ role: "system",
+ content: systemContent,
+ });
+ }
+
+ // Transform messages using the approach from claude-code-proxy
+ for (const message of anthropicRequest.messages) {
+ // Handle tool role → convert to OpenAI tool format
+ if (message.role === "tool") {
+ openaiMessages.push({
+ role: "tool",
+ content:
+ typeof message.content === "string"
+ ? message.content
+ : JSON.stringify(message.content),
+ tool_call_id: message.tool_call_id,
+ });
+ continue;
+ }
+
+ // Handle function role → convert to OpenAI tool format (legacy)
+ if (message.role === "function") {
+ openaiMessages.push({
+ role: "tool",
+ content: message.content,
+ tool_call_id: message.tool_call_id || message.name,
+ });
+ continue;
+ }
+
+ // Handle assistant messages with tool_calls (OpenAI format)
+ if (message.role === "assistant" && message.tool_calls) {
+ openaiMessages.push({
+ role: message.role,
+ content: message.content || "",
+ tool_calls: message.tool_calls,
+ });
+ continue;
+ }
+
+ // Handle assistant messages with function_call (legacy OpenAI format)
+ if (message.role === "assistant" && message.function_call) {
+ const toolCalls = [
+ {
+ id:
+ message.function_call.id ||
+ `call_${Math.random().toString(36).substring(2, 10)}`,
+ type: "function" as const,
+ function: {
+ name: message.function_call.name,
+ arguments:
+ typeof message.function_call.arguments === "string"
+ ? message.function_call.arguments
+ : JSON.stringify(message.function_call.arguments),
+ },
+ },
+ ];
+
+ openaiMessages.push({
+ role: message.role,
+ content: message.content || "",
+ tool_calls: toolCalls,
+ });
+ continue;
+ }
+
+ // Handle assistant messages with tool_use blocks (native Anthropic format)
+ if (
+ message.role === "assistant" &&
+ Array.isArray(message.content) &&
+ message.content.some((block) => block.type === "tool_use")
+ ) {
+ const toolCalls = message.content
+ .filter((block) => block.type === "tool_use")
+ .map((block) => ({
+ id: block.id,
+ type: "function" as const,
+ function: {
+ name: block.name,
+ arguments: JSON.stringify(block.input),
+ },
+ }));
+
+ const textContent = message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+
+ openaiMessages.push({
+ role: message.role,
+ content: textContent || "",
+ tool_calls: toolCalls,
+ });
+ continue;
+ }
+
+ // Handle user messages with tool_result blocks (native Anthropic format)
+ if (
+ message.role === "user" &&
+ Array.isArray(message.content) &&
+ message.content.some((block) => block.type === "tool_result")
+ ) {
+ // Group tool_result blocks by tool_use_id to avoid duplicates
+ const toolResults = new Map();
+ for (const block of message.content) {
+ if (block.type === "tool_result") {
+ const toolUseId = block.tool_use_id;
+ if (!toolResults.has(toolUseId)) {
+ toolResults.set(toolUseId, []);
+ }
+ toolResults.get(toolUseId)!.push(block);
+ }
+ }
+
+ // Convert each unique tool_use_id to a single tool message
+ for (const [toolUseId, blocks] of toolResults) {
+ // Combine content from all blocks with the same tool_use_id
+ const combinedContent = blocks
+ .map((block) =>
+ typeof block.content === "string"
+ ? block.content
+ : JSON.stringify(block.content),
+ )
+ .join("\n");
+
+ openaiMessages.push({
+ role: "tool",
+ content: combinedContent,
+ tool_call_id: toolUseId,
+ });
+ }
+
+ // Handle any remaining text content as a user message
+ const textContent = message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+
+ if (textContent) {
+ openaiMessages.push({
+ role: "user",
+ content: textContent,
+ });
+ }
+ continue;
+ }
+
+ // Handle regular messages and multi-modal content
+ if (Array.isArray(message.content)) {
+ // Check if this is complex multi-modal content that should be flattened
+ const hasOnlyText = message.content.every(
+ (block) => block.type === "text",
+ );
+
+ if (hasOnlyText) {
+ // For text-only content, flatten to a simple string to avoid content type issues
+ const textContent = message.content
+ .filter((block) => block.type === "text")
+ .map((block) => block.text)
+ .join("");
+
+ openaiMessages.push({
+ role: message.role,
+ content: textContent,
+ });
+ } else {
+ // For true multi-modal content, transform blocks
+ const content = message.content.map((block) => {
+ if (block.type === "text" && block.text) {
+ return { type: "text", text: block.text };
+ }
+ if (block.type === "image" && block.source) {
+ return {
+ type: "image_url",
+ image_url: {
+ url: `data:${block.source.media_type};base64,${block.source.data}`,
+ },
+ };
+ }
+ return block;
+ });
+
+ openaiMessages.push({
+ role: message.role,
+ content,
+ });
+ }
+ } else {
+ // Simple string content
+ openaiMessages.push({
+ role: message.role,
+ content: message.content,
+ });
+ }
+ }
+
+ // Transform tools if provided
+ let openaiTools;
+ if (anthropicRequest.tools) {
+ openaiTools = anthropicRequest.tools.map((tool) => ({
+ type: "function",
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.input_schema,
+ },
+ }));
+ }
+
+ // Build OpenAI request
+ const openaiRequest: Record = {
+ model: anthropicRequest.model,
+ messages: openaiMessages,
+ max_tokens: anthropicRequest.max_tokens,
+ temperature: anthropicRequest.temperature,
+ stream: anthropicRequest.stream,
+ };
+
+ if (openaiTools) {
+ openaiRequest.tools = openaiTools;
+ }
+
+ // Make request to the existing chat completions endpoint
+ const chatCompletionsUrl = new URL(c.req.url);
+ chatCompletionsUrl.pathname = "/v1/chat/completions";
+
+ const response = await fetch(chatCompletionsUrl.toString(), {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: c.req.header("Authorization") || "",
+ "x-request-id": c.req.header("x-request-id") || "",
+ "x-source": c.req.header("x-source") || "",
+ "x-debug": c.req.header("x-debug") || "",
+ },
+ body: JSON.stringify(openaiRequest),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new HTTPException(response.status as 400 | 401 | 403 | 404 | 500, {
+ message: errorData.error?.message || "Request failed",
+ });
+ }
+
+ // Handle streaming response
+ if (anthropicRequest.stream) {
+ return new Response("Not implemented yet, sorry!", { status: 501 });
+ // return streamSSE(c, async (stream) => {
+ // if (!response.body) {
+ // throw new HTTPException(500, { message: "No response body" });
+ // }
+ //
+ // const reader = response.body.getReader();
+ // const decoder = new TextDecoder();
+ //
+ // let buffer = "";
+ // let messageId = "";
+ // let model = "";
+ // let contentBlocks: Array<{
+ // type: string;
+ // text?: string;
+ // id?: string;
+ // name?: string;
+ // input?: string;
+ // }> = [];
+ // let usage = { input_tokens: 0, output_tokens: 0 };
+ // let currentTextBlockIndex: number | null = null;
+ // const toolCallBlockIndex = new Map();
+ //
+ // try {
+ // while (true) {
+ // const { done, value } = await reader.read();
+ // if (done) {
+ // break;
+ // }
+ //
+ // buffer += decoder.decode(value, { stream: true });
+ // const lines = buffer.split("\n");
+ // buffer = lines.pop() || "";
+ //
+ // for (const line of lines) {
+ // if (line.startsWith("data: ")) {
+ // const data = line.slice(6).trim();
+ // if (data === "[DONE]") {
+ // // Send final Anthropic streaming event
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "message_stop",
+ // }),
+ // event: "message_stop",
+ // });
+ // return;
+ // }
+ //
+ // // Skip empty data lines
+ // if (!data) {
+ // continue;
+ // }
+ //
+ // try {
+ // const chunk = JSON.parse(data);
+ //
+ // if (!messageId && chunk.id) {
+ // messageId = chunk.id;
+ // model = chunk.model || anthropicRequest.model;
+ //
+ // // Send message_start event
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "message_start",
+ // message: {
+ // id: messageId,
+ // type: "message",
+ // role: "assistant",
+ // model: model,
+ // content: [],
+ // stop_reason: null,
+ // stop_sequence: null,
+ // usage: { input_tokens: 0, output_tokens: 0 },
+ // },
+ // }),
+ // event: "message_start",
+ // });
+ // }
+ //
+ // const choice = chunk.choices?.[0];
+ // if (!choice) {
+ // continue;
+ // }
+ //
+ // const delta = choice.delta;
+ // if (!delta) {
+ // continue;
+ // }
+ //
+ // // Handle content delta
+ // if (delta.content) {
+ // // Find or create a text block
+ // if (currentTextBlockIndex === null) {
+ // // Look for existing text block (search from end)
+ // let lastTextBlockIndex = -1;
+ // for (let i = contentBlocks.length - 1; i >= 0; i--) {
+ // if (contentBlocks[i].type === "text") {
+ // lastTextBlockIndex = i;
+ // break;
+ // }
+ // }
+ //
+ // if (lastTextBlockIndex !== -1) {
+ // currentTextBlockIndex = lastTextBlockIndex;
+ // } else {
+ // // Create new text block
+ // currentTextBlockIndex = contentBlocks.length;
+ // contentBlocks.push({ type: "text", text: "" });
+ // // Send content_block_start event
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "content_block_start",
+ // index: currentTextBlockIndex,
+ // content_block: { type: "text", text: "" },
+ // }),
+ // event: "content_block_start",
+ // });
+ // }
+ // }
+ //
+ // const textBlock = contentBlocks[currentTextBlockIndex];
+ // if (textBlock && textBlock.text !== undefined) {
+ // textBlock.text += delta.content;
+ // }
+ //
+ // // Send content_block_delta event
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "content_block_delta",
+ // index: currentTextBlockIndex,
+ // delta: { type: "text_delta", text: delta.content },
+ // }),
+ // event: "content_block_delta",
+ // });
+ // }
+ //
+ // // Handle tool calls
+ // if (delta.tool_calls) {
+ // for (const toolCall of delta.tool_calls) {
+ // if (toolCall.index === undefined) {
+ // continue;
+ // }
+ //
+ // let blockIndex = toolCallBlockIndex.get(toolCall.index);
+ // if (blockIndex === undefined) {
+ // blockIndex = contentBlocks.length;
+ // toolCallBlockIndex.set(toolCall.index, blockIndex);
+ // const id = toolCall.id || `tool_${toolCall.index}`;
+ // const name = toolCall.function?.name || "";
+ // contentBlocks.push({
+ // type: "tool_use",
+ // id,
+ // name,
+ // input: "",
+ // });
+ //
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "content_block_start",
+ // index: blockIndex,
+ // content_block: {
+ // type: "tool_use",
+ // id,
+ // name,
+ // input: {},
+ // },
+ // }),
+ // event: "content_block_start",
+ // });
+ // }
+ //
+ // if (toolCall.function?.arguments) {
+ // const toolBlock = contentBlocks[blockIndex] as {
+ // type: "tool_use";
+ // id: string;
+ // name: string;
+ // input: string;
+ // };
+ // toolBlock.input += toolCall.function.arguments;
+ //
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "content_block_delta",
+ // index: blockIndex,
+ // delta: {
+ // type: "input_json_delta",
+ // partial_json: toolCall.function.arguments,
+ // },
+ // }),
+ // event: "content_block_delta",
+ // });
+ // }
+ // }
+ // }
+ //
+ // // Handle finish_reason
+ // if (choice.finish_reason) {
+ // // Send content_block_stop events
+ // for (let i = 0; i < contentBlocks.length; i++) {
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "content_block_stop",
+ // index: i,
+ // }),
+ // event: "content_block_stop",
+ // });
+ // }
+ //
+ // // Update usage if available
+ // if (chunk.usage) {
+ // usage = {
+ // input_tokens: chunk.usage.prompt_tokens || 0,
+ // output_tokens: chunk.usage.completion_tokens || 0,
+ // };
+ // }
+ //
+ // // Send message_delta with usage
+ // await stream.writeSSE({
+ // data: JSON.stringify({
+ // type: "message_delta",
+ // delta: {
+ // stop_reason: determineStopReason(choice.finish_reason),
+ // stop_sequence: null,
+ // },
+ // usage: usage,
+ // }),
+ // event: "message_delta",
+ // });
+ // }
+ // } catch {
+ // // Ignore parsing errors for individual chunks
+ // }
+ // }
+ // }
+ // }
+ // } catch (error) {
+ // throw new HTTPException(500, {
+ // message: `Streaming error: ${error instanceof Error ? error.message : String(error)}`,
+ // });
+ // } finally {
+ // reader.releaseLock();
+ // }
+ // });
+ }
+
+ // Handle non-streaming response
+ const openaiResponse = await response.json();
+
+ // Transform OpenAI response to Anthropic format
+ const content: any[] = [];
+
+ if (openaiResponse.choices?.[0]?.message?.content) {
+ content.push({
+ type: "text",
+ text: openaiResponse.choices[0].message.content,
+ });
+ }
+
+ // Handle tool calls
+ if (openaiResponse.choices?.[0]?.message?.tool_calls) {
+ for (const toolCall of openaiResponse.choices[0].message.tool_calls) {
+ content.push({
+ type: "tool_use",
+ id: toolCall.id,
+ name: toolCall.function.name,
+ input: JSON.parse(toolCall.function.arguments || "{}"),
+ });
+ }
+ }
+
+ const anthropicResponse = {
+ id: openaiResponse.id,
+ type: "message" as const,
+ role: "assistant" as const,
+ model: openaiResponse.model,
+ content,
+ stop_reason: determineStopReason(
+ openaiResponse.choices?.[0]?.finish_reason,
+ ),
+ stop_sequence: null,
+ usage: {
+ input_tokens: openaiResponse.usage?.prompt_tokens || 0,
+ output_tokens: openaiResponse.usage?.completion_tokens || 0,
+ },
+ };
+
+ return c.json(anthropicResponse);
+});
+
+function determineStopReason(
+ finishReason: string | undefined,
+): "end_turn" | "max_tokens" | "stop_sequence" | "tool_use" | null {
+ switch (finishReason) {
+ case "stop":
+ return "end_turn";
+ case "length":
+ return "max_tokens";
+ case "tool_calls":
+ return "tool_use";
+ default:
+ return "end_turn";
+ }
+}
diff --git a/apps/gateway/src/anthropic/index.ts b/apps/gateway/src/anthropic/index.ts
new file mode 100644
index 0000000000..c0557b6920
--- /dev/null
+++ b/apps/gateway/src/anthropic/index.ts
@@ -0,0 +1,9 @@
+import { OpenAPIHono } from "@hono/zod-openapi";
+
+import { anthropic } from "./anthropic";
+
+import type { ServerTypes } from "@/vars";
+
+export const exposed = new OpenAPIHono();
+
+exposed.route("/messages", anthropic);
diff --git a/apps/gateway/src/index.ts b/apps/gateway/src/index.ts
index 7f7a1452d5..b3c2911e62 100644
--- a/apps/gateway/src/index.ts
+++ b/apps/gateway/src/index.ts
@@ -10,6 +10,7 @@ import { redisClient } from "@llmgateway/cache";
import { db } from "@llmgateway/db";
import { logger } from "@llmgateway/logger";
+import { anthropic } from "./anthropic/anthropic";
import { chat } from "./chat/chat";
import { tracingMiddleware } from "./middleware/tracing";
import { models } from "./models";
@@ -198,6 +199,7 @@ const v1 = new OpenAPIHono();
v1.route("/chat", chat);
v1.route("/models", models);
+v1.route("/messages", anthropic);
app.route("/v1", v1);
diff --git a/apps/ui/public/blog/how-to-configure-claude-code-with-llmgateway.png b/apps/ui/public/blog/how-to-configure-claude-code-with-llmgateway.png
new file mode 100644
index 0000000000..937fcf74b1
Binary files /dev/null and b/apps/ui/public/blog/how-to-configure-claude-code-with-llmgateway.png differ
diff --git a/apps/ui/public/changelog/claude-code-configuration-support.png b/apps/ui/public/changelog/claude-code-configuration-support.png
new file mode 100644
index 0000000000..f32074b84d
Binary files /dev/null and b/apps/ui/public/changelog/claude-code-configuration-support.png differ
diff --git a/apps/ui/src/content/blog/2025-09-08-how-configure-claude-code-with-llmgateway.md b/apps/ui/src/content/blog/2025-09-08-how-configure-claude-code-with-llmgateway.md
new file mode 100644
index 0000000000..816323a173
--- /dev/null
+++ b/apps/ui/src/content/blog/2025-09-08-how-configure-claude-code-with-llmgateway.md
@@ -0,0 +1,107 @@
+---
+id: blog-claude-code-llmgateway
+slug: how-to-configure-claude-code-with-llmgateway
+date: 2025-09-08
+title: How to configure Claude Code to Use Any Model via LLMGateway
+summary: Learn how to configure Claude Code to access any LLM model through LLMGateway's unified API, including models with tool calling support.
+categories: ["Guides"]
+image:
+ src: "/blog/how-to-configure-claude-code-with-llmgateway.png"
+ alt: "Configure Claude Code with LLMGateway"
+ width: 2282
+ height: 1198
+---
+
+Claude Code is a powerful CLI tool that can be configured to use any LLM model through LLMGateway's unified API. This guide shows you how to set up Claude Code to access models beyond Anthropic's offerings.
+
+## Why Use LLMGateway with Claude Code?
+
+- **Model Diversity**: Access models from OpenAI, Google, Cohere, and more
+- **Cost Optimization**: Choose the most cost-effective model for your tasks
+- **Tool Calling**: Use models that support function calling and tool use
+- **Unified Interface**: Single configuration for all providers
+
+## Configuration
+
+Set these environment variables to configure Claude Code with LLMGateway:
+
+```bash
+export ANTHROPIC_BASE_URL=https://api.llmgateway.io
+export ANTHROPIC_AUTH_TOKEN=llmgtwy_.... # your llmgateway.io api key here
+export ANTHROPIC_MODEL=glm-4.5v # choose your model on llmgateway which supports tool calls
+```
+
+### Getting Your API Key
+
+1. Sign up at [llmgateway.io](https://llmgateway.io)
+2. Create a project and generate an API key
+3. Configure your preferred LLM provider keys in the dashboard
+
+### Choosing a Model
+
+Visit [llmgateway.io/models](https://llmgateway.io/models?filters=1&tools=true) to browse available models with tool calling support. Popular options include:
+
+- `openai/gpt-5` - OpenAI's Flagship GPT-5 model
+- `anthropic/claude-sonnet-4-20250514` - Anthropic's default model
+- `glm-4.5v` - Similar performance with 50-70% cost savings over Anthropic
+
+## Advanced Configuration
+
+### Model Switching
+
+You can easily switch models by updating the environment variable:
+
+```bash
+# Switch to GPT-4o Mini for cost savings
+export ANTHROPIC_MODEL=openai/gpt-4o-mini
+
+# Switch to Claude Sonnet for complex reasoning
+export ANTHROPIC_MODEL=anthropic/claude-3-5-sonnet-20241022
+```
+
+To see the full list of models available to you, check out [models with tool calls](https://llmgateway.io/models?filters=1&tools=true)
+
+### Provider-Specific Models
+
+Use models from any configured provider:
+
+```bash
+# Google Gemini
+export ANTHROPIC_MODEL=google/gemini-1.5-pro
+
+# Cohere Command R+
+export ANTHROPIC_MODEL=cohere/command-r-plus
+```
+
+### Persistent Configuration
+
+Add the environment variables to your shell profile (`.bashrc`, `.zshrc`, or `.profile`) for persistent configuration:
+
+```bash
+echo 'export ANTHROPIC_BASE_URL=https://api.llmgateway.io' >> ~/.zshrc
+echo 'export ANTHROPIC_AUTH_TOKEN=llmgtwy_your_key_here' >> ~/.zshrc
+echo 'export ANTHROPIC_MODEL=openai/gpt-4o' >> ~/.zshrc
+source ~/.zshrc
+```
+
+## Benefits
+
+### Cost Management
+
+Track usage and costs across all models in the LLMGateway dashboard. Compare costs between providers to optimize your spending.
+
+### Performance Analytics
+
+Monitor response times, token usage, and success rates to choose the best model for your workflows.
+
+### Reliability
+
+LLMGateway provides automatic failover and retry logic, ensuring Claude Code continues working even if a provider has issues.
+
+## Next Steps
+
+- Explore the [Models page](https://llmgateway.io/models) to discover new models
+- Check out [Usage Analytics](https://llmgateway.io/analytics) to optimize costs
+- Read more about [LLMGateway features](https://docs.llmgateway.io) in our documentation
+
+With this configuration, Claude Code becomes a gateway to the entire ecosystem of LLM models, giving you the flexibility to choose the right tool for each task.
diff --git a/apps/ui/src/content/changelog/2025-09-08-claude-code-configuration-support.md b/apps/ui/src/content/changelog/2025-09-08-claude-code-configuration-support.md
new file mode 100644
index 0000000000..c4cc0e0d34
--- /dev/null
+++ b/apps/ui/src/content/changelog/2025-09-08-claude-code-configuration-support.md
@@ -0,0 +1,64 @@
+---
+id: "19"
+slug: "claude-code-configuration-support"
+date: "2025-09-08"
+title: "Claude Code Configuration Now Supported"
+summary: "Configure Claude Code to use any LLM model through LLMGateway's unified API with simple environment variable setup."
+draft: true
+image:
+ src: "/changelog/claude-code-configuration-support.png"
+ alt: "Claude Code configuration support on LLM Gateway"
+ width: 2282
+ height: 1198
+---
+
+You can now configure **Claude Code** to work with any LLM model available through LLMGateway! Access models from OpenAI, Google, Anthropic, and more using Claude's powerful CLI interface.
+
+## 🔧 Simple Configuration
+
+Set up Claude Code with LLMGateway using three environment variables:
+
+```bash
+export ANTHROPIC_BASE_URL=https://api.llmgateway.io
+export ANTHROPIC_AUTH_TOKEN=llmgtwy_.... # your llmgateway.io api key here
+export ANTHROPIC_MODEL=glm-4.5v # choose your model with tool support
+```
+
+## 🚀 Key Benefits
+
+**Model Flexibility**: Switch between any supported model - from GPT-4o to Claude Sonnet, Gemini, or cost-effective alternatives like GLM-4.5v.
+
+**Cost Optimization**: Choose the most cost-effective model for your specific tasks while maintaining Claude Code's full functionality.
+
+**Tool Support**: Use models that support function calling and tool use for advanced coding workflows.
+
+**Unified Interface**: Single configuration gives you access to the entire ecosystem of LLM models.
+
+## 🎯 Popular Model Options
+
+**OpenAI Models**
+
+- `openai/gpt-5` - OpenAI's Flagship GPT-5 model
+
+**Anthropic Models**
+
+- `anthropic/claude-sonnet-4-20250514` - Anthropic's default model
+
+**Cost-Effective Alternatives**
+
+- `glm-4.5v` - Similar performance with 50-70% cost savings over Anthropic
+
+## 📚 Complete Guide
+
+Read our comprehensive guide: **[Configure Claude Code to Use Any Model via LLMGateway](/blog/how-to-configure-claude-code-with-llmgateway)**
+
+The guide covers:
+
+- ⚙️ Step-by-step setup instructions
+- 🔄 Model switching strategies
+- 💰 Cost optimization tips
+- 📊 Performance comparisons
+
+---
+
+**[Browse all models with tool support](https://llmgateway.io/models?filters=1&tools=true)** to find the perfect fit for your workflow! 🚀
diff --git a/packages/models/src/models/anthropic.ts b/packages/models/src/models/anthropic.ts
index 71c63dfc3c..9bf7476d01 100644
--- a/packages/models/src/models/anthropic.ts
+++ b/packages/models/src/models/anthropic.ts
@@ -23,6 +23,28 @@ export const anthropicModels = [
},
],
},
+ {
+ id: "claude-3-5-haiku-20241022",
+ name: "Claude 3.5 Haiku (2024-10-22)",
+ family: "anthropic",
+ deprecatedAt: undefined,
+ deactivatedAt: undefined,
+ providers: [
+ {
+ providerId: "anthropic",
+ modelName: "claude-3-5-haiku-20241022",
+ inputPrice: 0.8 / 1e6,
+ outputPrice: 4.0 / 1e6,
+ cachedInputPrice: 0.08 / 1e6,
+ requestPrice: 0,
+ contextSize: 200000,
+ maxOutput: 8192,
+ streaming: true,
+ vision: false,
+ tools: true,
+ },
+ ],
+ },
{
id: "claude-3-7-sonnet-20250219",
name: "Claude 3.7 Sonnet (2025-02-19)",
diff --git a/packages/models/src/provider-api.ts b/packages/models/src/provider-api.ts
index 4c47b976c4..65287fa82a 100644
--- a/packages/models/src/provider-api.ts
+++ b/packages/models/src/provider-api.ts
@@ -223,14 +223,64 @@ function transformMessagesForNoSystemRole(messages: any[]): any[] {
}
/**
- * Transforms Anthropic messages to handle image URLs by converting them to base64
+ * Transforms Anthropic messages
*/
async function transformAnthropicMessages(
messages: BaseMessage[],
isProd = false,
): Promise {
const results: AnthropicMessage[] = [];
- for (const m of messages) {
+
+ // Keep track of all tool_use IDs seen so far to ensure uniqueness
+ const seenToolUseIds = new Set();
+ // Map original IDs to unique IDs - using arrays to handle multiple mappings for duplicate IDs
+ const idMapping = new Map();
+ // Keep track of how many tool results we've seen for each original ID
+ const toolResultCount = new Map();
+
+ // Group consecutive tool messages with the same tool_call_id to combine their content
+ const groupedMessages: BaseMessage[] = [];
+ const toolMessageGroups = new Map();
+
+ for (const message of messages) {
+ // Check if this is a tool message
+ const originalRole =
+ message.role === "user" && message.tool_call_id ? "tool" : message.role;
+ if (originalRole === "tool" && message.tool_call_id) {
+ if (!toolMessageGroups.has(message.tool_call_id)) {
+ toolMessageGroups.set(message.tool_call_id, []);
+ }
+ toolMessageGroups.get(message.tool_call_id)!.push(message);
+ } else {
+ // Process any accumulated tool message groups first
+ for (const [_toolCallId, toolMessages] of Array.from(toolMessageGroups)) {
+ if (toolMessages.length > 0) {
+ // Process each tool message individually (don't combine them)
+ // This allows the individual tool_result handling to assign the correct unique IDs
+ toolMessages.forEach((toolMessage) => {
+ groupedMessages.push(toolMessage);
+ });
+ }
+ }
+ toolMessageGroups.clear();
+
+ // Add the non-tool message
+ groupedMessages.push(message);
+ }
+ }
+
+ // Process any remaining tool message groups at the end
+ for (const [_toolCallId, toolMessages] of Array.from(toolMessageGroups)) {
+ if (toolMessages.length > 0) {
+ // Process each tool message individually (don't combine them)
+ // This allows the individual tool_result handling to assign the correct unique IDs
+ toolMessages.forEach((toolMessage) => {
+ groupedMessages.push(toolMessage);
+ });
+ }
+ }
+
+ for (const m of groupedMessages) {
let content: MessageContent[] = [];
// Handle existing content
@@ -273,12 +323,44 @@ async function transformAnthropicMessages(
// Handle OpenAI-style tool_calls by converting them to Anthropic tool_use content blocks
if (m.tool_calls && Array.isArray(m.tool_calls)) {
- const toolUseBlocks: ToolUseContent[] = m.tool_calls.map((toolCall) => ({
- type: "tool_use",
- id: toolCall.id,
- name: toolCall.function.name,
- input: JSON.parse(toolCall.function.arguments),
- }));
+ const toolUseBlocks: ToolUseContent[] = m.tool_calls.map(
+ (toolCall, index) => {
+ let uniqueId = toolCall.id;
+
+ // Handle duplicates within the same message first
+ const duplicatesInSameMessage = m
+ .tool_calls!.slice(0, index)
+ .filter((tc) => tc.id === toolCall.id);
+ if (duplicatesInSameMessage.length > 0) {
+ uniqueId = `${toolCall.id}_${duplicatesInSameMessage.length + 1}`;
+ }
+
+ // Ensure global uniqueness
+ if (seenToolUseIds.has(uniqueId)) {
+ let counter = 1;
+ let newId = `${uniqueId}_${counter}`;
+ while (seenToolUseIds.has(newId)) {
+ counter++;
+ newId = `${uniqueId}_${counter}`;
+ }
+ uniqueId = newId;
+ }
+
+ // Track the mapping and mark as seen
+ if (!idMapping.has(toolCall.id)) {
+ idMapping.set(toolCall.id, []);
+ }
+ idMapping.get(toolCall.id)!.push(uniqueId);
+ seenToolUseIds.add(uniqueId);
+
+ return {
+ type: "tool_use",
+ id: uniqueId,
+ name: toolCall.function.name,
+ input: JSON.parse(toolCall.function.arguments),
+ };
+ },
+ );
content = content.concat(toolUseBlocks);
}
@@ -304,13 +386,38 @@ async function transformAnthropicMessages(
toolResultContent = contentStr;
}
- content = [
- {
- type: "tool_result",
- tool_use_id: m.tool_call_id,
- content: toolResultContent,
- } as ToolResultContent,
+ // Use the mapped IDs if they exist, otherwise use the original ID
+ const mappedToolUseIds = idMapping.get(m.tool_call_id) || [
+ m.tool_call_id,
];
+
+ // Get the current count for this original ID and increment it
+ const currentCount = toolResultCount.get(m.tool_call_id) || 0;
+ toolResultCount.set(m.tool_call_id, currentCount + 1);
+
+ // If there are multiple mapped IDs, create tool_result blocks for each one
+ // This handles the case where we have duplicate tool_use but only one tool_result
+ if (mappedToolUseIds.length > 1 && currentCount === 0) {
+ // Create tool_result blocks for all mapped IDs
+ content = mappedToolUseIds.map(
+ (mappedId) =>
+ ({
+ type: "tool_result",
+ tool_use_id: mappedId,
+ content: toolResultContent,
+ }) as ToolResultContent,
+ );
+ } else {
+ // Use the appropriate mapped ID based on the count
+ const toolUseId = mappedToolUseIds[currentCount] || mappedToolUseIds[0];
+ content = [
+ {
+ type: "tool_result",
+ tool_use_id: toolUseId,
+ content: toolResultContent,
+ } as ToolResultContent,
+ ];
+ }
}
// Filter out empty text content blocks as Anthropic requires non-empty text