Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

2.1 KB
Raw Blame
import { observeResponseHeaders, type ResponseHeadersListener } from "@/lib/http/observeResponseHeaders";
import openai from "openai";
import { getGatewayBaseUrl } from "@/components/networking";
import { buildPlaygroundHeaders, type CustomHeaders } from "@/components/llm_calls/request_headers";
import { toast } from "@/lib/toast";
import type { OpenAIVoice } from "../components/chat_ui/chatConstants";

export async function makeOpenAIAudioSpeechRequest(
  input: string,
  voice: OpenAIVoice,
  updateUI: (audioUrl: string, model: string) => void,
  selectedModel: string,
  accessToken: string,
  tags?: string[],
  signal?: AbortSignal,
  responseFormat?: string,
  speed?: number,
  customBaseUrl?: string,
  customHeaders?: CustomHeaders,
  onResponseHeaders?: ResponseHeadersListener,
) {
  // base url should be the current base_url
  const isLocal = process.env.NODE_ENV === "development";
  if (isLocal !== true) {
    console.log = function () {};
  }
  const proxyBaseUrl = customBaseUrl || getGatewayBaseUrl();
  const client = new openai.OpenAI({
    apiKey: accessToken,
    baseURL: proxyBaseUrl,
    dangerouslyAllowBrowser: true,
    defaultHeaders: buildPlaygroundHeaders(tags, customHeaders),
    ...(onResponseHeaders ? { fetch: observeResponseHeaders(onResponseHeaders) } : {}),
  });

  try {
    const response = await client.audio.speech.create(
      {
        model: selectedModel,
        input: input,
        voice,
        ...(responseFormat ? { response_format: responseFormat as any } : {}),
        ...(speed ? { speed: speed } : {}),
      },
      { signal },
    );

    // Convert the response to a blob and create an object URL
    // The response from OpenAI SDK in the browser is a Response object with a blob() method
    const blob = await response.blob();
    const audioUrl = URL.createObjectURL(blob);

    updateUI(audioUrl, selectedModel);
  } catch (error) {
    if (signal?.aborted) {
    } else {
      toast.fromError(`Error occurred while generating speech. Please try again. Error: ${error}`);
    }
    throw error; // Re-throw to allow the caller to handle the error
  }
}