惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
雷峰网
雷峰网
罗磊的独立博客
T
The Blog of Author Tim Ferriss
阮一峰的网络日志
阮一峰的网络日志
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
Cisco Talos Blog
Cisco Talos Blog
Engineering at Meta
Engineering at Meta
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
About on SuperTechFans
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Cloudflare Blog
Know Your Adversary
Know Your Adversary
T
Threat Research - Cisco Blogs
Spread Privacy
Spread Privacy
D
DataBreaches.Net
T
The Exploit Database - CXSecurity.com
K
Kaspersky official blog
Cyberwarzone
Cyberwarzone
爱范儿
爱范儿
U
Unit 42
Security Latest
Security Latest
M
MIT News - Artificial intelligence
月光博客
月光博客
Scott Helme
Scott Helme
G
Google Developers Blog
有赞技术团队
有赞技术团队
T
Tor Project blog
宝玉的分享
宝玉的分享
Y
Y Combinator Blog
博客园 - Franky
H
Hackread – Cybersecurity News, Data Breaches, AI and More
aimingoo的专栏
aimingoo的专栏
The GitHub Blog
The GitHub Blog
V
V2EX
B
Blog
Apple Machine Learning Research
Apple Machine Learning Research
S
Securelist
博客园 - 三生石上(FineUI控件)
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
腾讯CDC
D
Docker
Google Online Security Blog
Google Online Security Blog

OpenAI Developers

API deployment checklist | OpenAI API Sora 2 Prompting Guide Codex Prompting Guide Docs MCP | OpenAI Developers Gpt-image-1.5 Prompting Guide GPT-5.2 Prompting Guide Transcribing User Audio with a Separate Realtime Request Modernizing your Codebase with Codex GitHub - openai/openai-sora-sample-app: Sample app to get started using the Video API with Sora GitHub - openai/openai-apps-sdk-examples: Example apps for the Apps SDK GitHub - openai/openai-chatkit-advanced-samples: Starter app to build with OpenAI ChatKit SDK GitHub - openai/openai-chatkit-starter-app: Starter app to build with OpenAI ChatKit + Agent Builder Rate limits | OpenAI API Web search | OpenAI API Getting started with datasets | OpenAI API Prompt optimizer | OpenAI API Verifying gpt-oss implementations How to run gpt-oss locally with LM Studio Fine-tuning with gpt-oss and Hugging Face Transformers How to run gpt-oss locally with Ollama Function calling | OpenAI API Models | OpenAI API Reasoning best practices | OpenAI API Reasoning models | OpenAI API Background mode | OpenAI API Batch API | OpenAI API Conversation state | OpenAI API File search | OpenAI API Flex processing | OpenAI API MCP and Connectors | OpenAI API Code Interpreter | OpenAI API Quickstart - OpenAI Agents SDK Build Hour: Agentic Tool Calling Build Hour: Built-In Tools Reasoning best practices | OpenAI API Graders | OpenAI API Evaluation best practices | OpenAI API Working with evals | OpenAI API Guardrails - OpenAI Agents SDK Latency optimization | OpenAI API Optimizing LLM Accuracy | OpenAI API Agent orchestration - OpenAI Agents SDK Production best practices | OpenAI API Realtime transcription | OpenAI API Optimizing LLM Accuracy | OpenAI API Realtime and audio | OpenAI API Realtime conversations | OpenAI API Responses guide Migrate to the Responses API | OpenAI API Speech to text | OpenAI API Supervised fine-tuning | OpenAI API Tracing - OpenAI Agents SDK Vision fine-tuning | OpenAI API Audio and speech | OpenAI API GitHub - openai/openai-cs-agents-demo: Demo of a customer service use case implemented with the OpenAI Agents SDK Voice agents | OpenAI API Fine-tuning best practices | OpenAI API GitHub - openai/openai-agents-python: A lightweight, powerful framework for multi-agent workflows GitHub - openai/openai-agents-js: A lightweight, powerful framework for multi-agent workflows and voice agents Agents SDK | OpenAI API Using tools | OpenAI API Computer use | OpenAI API GitHub - openai/openai-cua-sample-app: Learn how to use CUA (our Computer Using Agent) via the API on multiple computer environments. GitHub - openai/openai-testing-agent-demo: Demo of a UI testing agent using the OpenAI CUA model and the Responses API. Model optimization | OpenAI API GitHub - openai/openai-fm: Code for openai.fm, a demo for the OpenAI Speech API Predicted Outputs | OpenAI API GitHub - openai/openai-realtime-console: React app for inspecting, building and debugging with the Realtime API Building Voice Agents GitHub - openai/openai-realtime-solar-system: Demo showing how to use the OpenAI Realtime API to navigate a 3D scene via tool calling GitHub - openai/openai-realtime-twilio-demo Reinforcement fine-tuning | OpenAI API GitHub - openai/openai-responses-starter-app: Starter app to build with the OpenAI Responses API Structured model outputs | OpenAI API GitHub - openai/openai-structured-outputs-samples: Sample apps to help developers get started with Structured Outputs Voice agents | OpenAI API Model optimization | OpenAI API GitHub - openai/openai-realtime-agents: This is a simple demonstration of more advanced, agentic patterns built on top of the Realtime API. GitHub - openai/openai-support-agent-demo: Demo of a customer support agent interface using NextJS and the OpenAI Responses API with File Search Building Voice Agents Generate images with high input fidelity AI app development: Concept to production Model optimization Building agents Eval Driven System Design - From Prototype to Production Multi-Agent Portfolio Collaboration with OpenAI Agents SDK o3/o4-mini Function Calling Guide Exploring Model Graders for Reinforcement Fine-Tuning Guide to Using the Responses API Reinforcement Fine-Tuning for Conversational Reasoning with the OpenAI API Evals API Use-case - Responses Evaluation Comparing Speech-to-Text Methods with the OpenAI API Generate images with GPT Image Multi-Tool Orchestration with RAG approach using OpenAI Doing RAG on PDFs using File Search in the Responses API How to use the Usage API and Cost API to monitor your OpenAI usage Leveraging model distillation to fine-tune a model Orchestrating Agents: Routines and Handoffs Prompt Caching 101 Developing Hallucination Guardrails
Multi-Language One-Way Translation with the Realtime API
2025-03-24 · via OpenAI Developers

One of the most exciting things about the Realtime API is that the emotion, tone and pace of speech are all passed to the model for inference. Traditional cascaded voice systems (involving STT and TTS) introduce an intermediate transcription step, relying on SSML or prompting to approximate prosody, which inherently loses fidelity. The speaker’s expressiveness is literally lost in translation. Because it can process raw audio, the Realtime API preserves those audio attributes through inference, minimizing latency and enriching responses with tonal and inflectional cues. Because of this, the Realtime API makes LLM-powered speech translation closer to a live interpreter than ever before.

This cookbook demonstrates how to use OpenAI’s Realtime API to build a multi-lingual, one-way translation workflow with WebSockets. It is implemented using the Realtime + WebSockets integration in a speaker application and a WebSocket server to mirror the translated audio to a listener application.

A real-world use case for this demo is a multilingual, conversational translation where a speaker talks into the speaker app and listeners hear translations in their selected native language via the listener app. Imagine a conference room with a speaker talking in English and a participant with headphones in choosing to listen to a Tagalog translation. Due to the current turn-based nature of audio models, the speaker must pause briefly to allow the model to process and translate speech. However, as models become faster and more efficient, this latency will decrease significantly and the translation will become more seamless.

Let’s explore the main functionalities and code snippets that illustrate how the app works. You can find the code in the accompanying repo if you want to run the app locally.

This project has two applications - a speaker and listener app. The speaker app takes in audio from the browser, forks the audio and creates a unique Realtime session for each language and sends it to the OpenAI Realtime API via WebSocket. Translated audio streams back and is mirrored via a separate WebSocket server to the listener app. The listener app receives all translated audio streams simultaneously, but only the selected language is played. This architecture is designed for a POC and is not intended for a production use case. Let’s dive into the workflow!

Architecture

We need a unique stream for each language - each language requires a unique prompt and session with the Realtime API. We define these prompts in translation_prompts.js.

The Realtime API is powered by GPT-4o Realtime or GPT-4o mini Realtime which are turn-based and trained for conversational speech use cases. In order to ensure the model returns translated audio (i.e. instead of answering a question, we want a direct translation of that question), we want to steer the model with few-shot examples of questions in the prompts. If you’re translating for a specific reason or context, or have specialized vocabulary that will help the model understand context of the translation, include that in the prompt as well. If you want the model to speak with a specific accent or otherwise steer the voice, you can follpow tips from our cookbook on Steering Text-to-Speech for more dynamic audio generation.

We can dynamically input speech in any language.

// Define language codes and import their corresponding instructions from our prompt config file
const languageConfigs = [
  { code: 'fr', instructions: french_instructions },
  { code: 'es', instructions: spanish_instructions },
  { code: 'tl', instructions: tagalog_instructions },
  { code: 'en', instructions: english_instructions },
  { code: 'zh', instructions: mandarin_instructions },
];

SpeakerApp

We need to handle the setup and management of client instances that connect to the Realtime API, allowing the application to process and stream audio in different languages. clientRefs holds a map of RealtimeClient instances, each associated with a language code (e.g., ‘fr’ for French, ‘es’ for Spanish) representing each unique client connection to the Realtime API.

const clientRefs = useRef(
    languageConfigs.reduce((acc, { code }) => {
      acc[code] = new RealtimeClient({
        apiKey: OPENAI_API_KEY,
        dangerouslyAllowAPIKeyInBrowser: true,
      });
      return acc;
    }, {} as Record<string, RealtimeClient>)
  ).current;

  // Update languageConfigs to include client references
  const updatedLanguageConfigs = languageConfigs.map(config => ({
    ...config,
    clientRef: { current: clientRefs[config.code] }
  }));

Note: The dangerouslyAllowAPIKeyInBrowser option is set to true because we are using our OpenAI API key in the browser for demo purposes but in production you should use an ephemeral API key generated via the OpenAI REST API.

We need to actually initiate the connection to the Realtime API and send audio data to the server. When a user clicks ‘Connect’ on the speaker page, we start that process.

The connectConversation function orchestrates the connection, ensuring that all necessary components are initialized and ready for use.

const connectConversation = useCallback(async () => {
    try {
        setIsLoading(true);
        const wavRecorder = wavRecorderRef.current;
        await wavRecorder.begin();
        await connectAndSetupClients();
        setIsConnected(true);
    } catch (error) {
        console.error('Error connecting to conversation:', error);
    } finally {
        setIsLoading(false);
    }
}, []);

connectAndSetupClients ensures we are using the right model and voice. For this demo, we are using gpt-4o-realtime-preview-2024-12-17 and coral.

   // Function to connect and set up all clients
  const connectAndSetupClients = async () => {
    for (const { clientRef } of updatedLanguageConfigs) {
      const client = clientRef.current;
      await client.realtime.connect({ model: DEFAULT_REALTIME_MODEL });
      await client.updateSession({ voice: DEFAULT_REALTIME_VOICE });
    }
  };

Sending audio with WebSockets requires work to manage the inbound and outbound PCM16 audio streams (more details on that). We abstract that using wavtools, a library for both recording and streaming audio data in the browser. Here we use WavRecorder for capturing audio in the browser.

This demo supports both manual and voice activity detection (VAD) modes for recording that can be toggled by the speaker. For cleaner audio capture we recommend using manual mode here.

const startRecording = async () => {
    setIsRecording(true);
    const wavRecorder = wavRecorderRef.current;

    await wavRecorder.record((data) => {
      // Send mic PCM to all clients
      updatedLanguageConfigs.forEach(({ clientRef }) => {
        clientRef.current.appendInputAudio(data.mono);
      });
    });
  };

We listen for response.audio_transcript.done events to update the transcripts of the audio. These input transcripts are generated by the Whisper model in parallel to the GPT-4o Realtime inference that is doing the translations on raw audio.

We have a Realtime session running simultaneously for every selectable language and so we get transcriptions for every language (regardless of what language is selected in the listener application). Those can be shown by toggling the ‘Show Transcripts’ button.

Listeners can choose from a dropdown menu of translation streams and after connecting, dynamically change languages. The demo application uses French, Spanish, Tagalog, English, and Mandarin but OpenAI supports 57+ languages.

The app connects to a simple Socket.IO server that acts as a relay for audio data. When translated audio is streamed back to from the Realtime API, we mirror those audio streams to the listener page and allow users to select a language and listen to translated streams.

The key function here is connectServer that connects to the server and sets up audio streaming.

  // Function to connect to the server and set up audio streaming
  const connectServer = useCallback(async () => {
    if (socketRef.current) return;
    try {
      const socket = io('http://localhost:3001');
      socketRef.current = socket;
      await wavStreamPlayerRef.current.connect();
      socket.on('connect', () => {
        console.log('Listener connected:', socket.id);
        setIsConnected(true);
      });
      socket.on('disconnect', () => {
        console.log('Listener disconnected');
        setIsConnected(false);
      });
    } catch (error) {
      console.error('Error connecting to server:', error);
    }
  }, []);

POC to Production

This is a demo and meant for inspiration. We are using WebSockets here for easy local development. However, in a production environment we’d suggest using WebRTC (which is much better for streaming audio quality and lower latency) and connecting to the Realtime API with an ephemeral API key generated via the OpenAI REST API.

Current Realtime models are turn based - this is best for conversational use cases as opposed to the uninterrupted, UN-style live translation that we really want for a one-directional streaming use case. For this demo, we can capture additional audio from the speaker app as soon as the model returns translated audio (i.e. capturing more input audio while the translated audio played from the listener app), but there is a limit to the length of audio we can capture at a time. The speaker needs to pause to let the translation catch up.

In summary, this POC is a demonstration of a one-way translation use of the Realtime API but the idea of forking audio for multiple uses can expand beyond translation. Other workflows might be simultaneous sentiment analysis, live guardrails or generating subtitles.