Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

2.0 KB
Raw Blame
import { DefaultExecutor } from "./default.ts";
import type { ProviderCredentials } from "./base.ts";
import { stripTrailingSlashes } from "../utils/urlSanitize.ts";
import { applyAzureParamRules } from "./azureParamRules.ts";

const DEFAULT_API_VERSION = "2024-12-01-preview";

function normalizeAzureBaseUrl(rawBaseUrl?: string | null): string {
  const normalized = stripTrailingSlashes((rawBaseUrl || "").trim());
  if (!normalized) return "";

  return normalized
    .replace(/\/openai$/i, "")
    .replace(/\/openai\/deployments\/[^/]+\/chat\/completions[^/]*$/i, "");
}

export class AzureOpenAIExecutor extends DefaultExecutor {
  constructor() {
    super("azure-openai");
  }

  buildUrl(
    model: string,
    stream: boolean,
    urlIndex = 0,
    credentials: ProviderCredentials | null = null
  ) {
    void urlIndex;

    const providerSpecificData = credentials?.providerSpecificData || {};
    const baseUrl = normalizeAzureBaseUrl(
      typeof providerSpecificData.baseUrl === "string"
        ? providerSpecificData.baseUrl
        : this.config.baseUrl
    );
    const apiVersion =
      typeof providerSpecificData.apiVersion === "string" && providerSpecificData.apiVersion.trim()
        ? providerSpecificData.apiVersion.trim()
        : DEFAULT_API_VERSION;
    return `${baseUrl}/openai/deployments/${encodeURIComponent(model)}/chat/completions?api-version=${encodeURIComponent(apiVersion)}`;
  }

  buildHeaders(credentials: ProviderCredentials | null, stream = true) {
    const apiKey = credentials?.apiKey || credentials?.accessToken || "";
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "api-key": apiKey,
    };

    headers.Accept = stream ? "text/event-stream" : "application/json";
    return headers;
  }

  override transformRequest(
    model: string,
    body: unknown,
    stream: boolean,
    credentials: ProviderCredentials
  ): unknown {
    return applyAzureParamRules(
      model,
      body,
      super.transformRequest(model, body, stream, credentials)
    );
  }
}