OpenAI 文件转录

2026-11-06 12:39 更新

已有完整录音或有明确边界的音频请求时,使用文件转录。上传音频后可以接收最终转录,也可在模型处理文件时流式接收文字。

首先使用 gpt-transcribe,这是按录音原语言转录已录制语音的推荐模型。下方说话人标签、逐词时间戳和字幕格式等专用示例使用已弃用模型。

whisper-1、gpt-4o-transcribe、gpt-4o-mini-transcribe、gpt-4o-transcribe-diarize 和 /v1/audio/translations 已弃用,将于 2027年2月26日关闭。见弃用公告并选择当前转录工作流。下列专用示例用于记录关闭前既有集成的兼容用法。

文件最大 25 MB,支持 mp3、mp4、mpeg、mpga、m4a、wav 和 webm。

麦克风、通话或媒体流仍在持续送入音频时,应使用实时转录。

快速开始

转录

将音频文件发送到 /v1/audio/transcriptions,模型使用 gpt-transcribe:

来源示例 1(javascript):

// [中文] 示例 1:转录;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const transcription = await openai.audio.transcriptions.create({
  file: fs.createReadStream("fixtures/audio.wav"),
  model: "gpt-transcribe",
});

console.log(transcription.text);

来源示例 2(python):

## [中文] 示例 2:转录;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
from openai import OpenAI

client = OpenAI()
audio_file = open("audio.wav", "rb")

transcription = client.audio.transcriptions.create(
    model="gpt-transcribe", file=audio_file
)

print(transcription.text)

来源示例 3(go):

// [中文] 示例 3:转录;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.Audio.Transcriptions.New;异步调用及事件接收顺序保留。
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
)

func main() {
    file, err := os.Open("fixtures/audio.wav")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    client := openai.NewClient()
    transcription, err := client.Audio.Transcriptions.New(context.Background(), openai.AudioTranscriptionNewParams{
        File:  file,
        Model: "gpt-transcribe",
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(transcription.Text)
}

来源示例 4(java):

// [中文] 示例 4:转录;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import java.nio.file.Path;

var result =
    client
        .audio()
        .transcriptions()
        .create(
            TranscriptionCreateParams.builder()
                .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))
                .model("gpt-transcribe")
                .build());

System.out.println(result.asTranscription().text());

来源示例 5(csharp):

// [中文] 示例 5:转录;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.TranscribeAudioAsync;异步调用及事件接收顺序保留。
using OpenAI.Audio;

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-transcribe";
AudioClient client = new(model, key);

await using FileStream audio = File.OpenRead("audio.wav");
AudioTranscription transcription = await client.TranscribeAudioAsync(
    audio,
    "audio.wav"
);

Console.WriteLine(transcription.Text);

来源示例 6(ruby):

程序文字译释117:预期JSON格式转录响应。

## [中文] 示例 6:转录;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
require "openai"
require "pathname"

client = OpenAI::Client.new
audio = Pathname("audio.wav")
transcript = client.audio.transcriptions.create(
  file: audio,
  model: "gpt-transcribe"
)
raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

puts(transcript.text)

来源示例 7(bash):

## [中文] 示例 7:转录;以下保留本语言原始示例。
## [中文] 上传本地音频文件到转录接口,使用 gpt-transcribe;运行前将文件路径替换为实际录音并完成 CLI 认证。
## [中文] --raw-output 与 --transform text 从响应中取出 text,便于在终端查看;这里不是实时音频流。
openai audio:transcriptions create \
  --model gpt-transcribe \
  --file /path/to/file/audio.mp3 \
  --raw-output \
  --transform text

来源示例 8(bash):

## [中文] 示例 8:转录;以下保留本语言原始示例。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/transcriptions;认证和请求体保持原示例形式。
curl --request POST \
  --url https://api.openai.com/v1/audio/transcriptions \
  --header "Authorization: Bearer $OPENAI_API_KEY" \
  --header 'Content-Type: multipart/form-data' \
  --form file=@/path/to/file/audio.mp3 \
  --form model=gpt-transcribe

模型以 JSON 返回转录和检测语言:

来源示例 9(json):字段名、事件类型和示意值保留原样,含义见相邻正文;片段中的省略号不表示完整可运行程序。

{
  "text": "Bonjour, pouvez-vous m'entendre ?",
  "languages": [{ "code": "fr" }]
}

不能可靠预测语言时,返回 "languages": []。完整请求和响应字段见 Audio API 参考。

添加转录上下文

结合 gpt-transcribe 的 prompt、keywords 和 languages,改善领域术语与多语言音频的转录:

来源示例 10(javascript):

程序文字译释109:一段涉及高级套餐及账户AC-42的客服通话。

程序文字译释110:高级套餐。

// [中文] 示例 10:添加转录上下文;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const request = {
  model: "gpt-transcribe",
  file: fs.createReadStream("fixtures/audio.wav"),
  prompt: "A customer support call about a premium plan and account AC-42.",
};

const transcription = await openai.audio.transcriptions.create(request, {
  body: {
    ...request,
    keywords: ["premium plan", "AC-42", "billing"],
    languages: ["en", "fr"],
  },
});

console.log(transcription.text);

来源示例 11(python):

沿用程序文字译释109。

沿用程序文字译释110。

## [中文] 示例 11:添加转录上下文;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
from openai import OpenAI

client = OpenAI()

with open("meeting.wav", "rb") as audio_file:
    transcription = client.audio.transcriptions.create(
        model="gpt-transcribe",
        file=audio_file,
        prompt="A customer support call about a premium plan and account AC-42.",
        extra_body={
            "keywords": ["premium plan", "AC-42", "billing"],
            "languages": ["en", "fr"],
        },
    )

print(transcription.text)

来源示例 12(go):

沿用程序文字译释109。

沿用程序文字译释110。

// [中文] 示例 12:添加转录上下文;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.Audio.Transcriptions.New;异步调用及事件接收顺序保留。
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
)

func main() {
    file, err := os.Open("fixtures/audio.wav")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    parameters := openai.AudioTranscriptionNewParams{
        File:   file,
        Model:  "gpt-transcribe",
        Prompt: openai.String("A customer support call about a premium plan and account AC-42."),
    }
    parameters.SetExtraFields(map[string]any{
        "keywords":  []string{"premium plan", "AC-42", "billing"},
        "languages": []string{"en", "fr"},
    })
    client := openai.NewClient()
    transcription, err := client.Audio.Transcriptions.New(context.Background(), parameters)
    if err != nil {
        panic(err)
    }
    fmt.Println(transcription.Text)
}

来源示例 13(java):

沿用程序文字译释109。

沿用程序文字译释110。

// [中文] 示例 13:添加转录上下文;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import java.nio.file.Path;
import java.util.List;

var result =
    client
        .audio()
        .transcriptions()
        .create(
            TranscriptionCreateParams.builder()
                .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))
                .model("gpt-transcribe")
                .prompt("A customer support call about a premium plan and account AC-42.")
                .putAdditionalBodyProperty(
                    "keywords", JsonValue.from(List.of("premium plan", "AC-42", "billing")))
                .putAdditionalBodyProperty("languages", JsonValue.from(List.of("en", "fr")))
                .build());

System.out.println(result.asTranscription().text());

来源示例 14(ruby):

沿用程序文字译释117。

程序文字译释118:Responses API为产品名称,保留原文。

## [中文] 示例 14:添加转录上下文;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
require "openai"
require "pathname"

client = OpenAI::Client.new
audio = Pathname("audio.wav")
transcript = client.audio.transcriptions.create(
  file: audio,
  model: "gpt-transcribe",
  keywords: ["OpenAI", "Responses API", "Codex"]
)
raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

puts(transcript.text)

来源示例 15(bash):

程序文字译释119:prompt背景:涉及高级套餐及账户AC-42的客服通话。

程序文字译释120:keywords关键词:高级套餐。

## [中文] 示例 15:添加转录上下文;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/transcriptions;认证和请求体保持原示例形式。
curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F model="gpt-transcribe" \
  -F file="@/path/to/file/meeting.wav" \
  -F 'prompt=A customer support call about a premium plan and account AC-42.' \
  -F 'keywords[]=premium plan' \
  -F 'keywords[]=AC-42' \
  -F 'keywords[]=billing' \
  -F 'languages[]=en' \
  -F 'languages[]=fr'

  • prompt 提供录音的非结构化背景。
  • keywords 提供预计听到的字面术语。
  • languages 指定预计输入语言。

关键词是提示,并非必须输出。只包含相关词语,并评估它们是否提升准确性,同时避免出现音频没说过的术语。

gpt-transcribe 用 languages 替代单数 language,不要同时发送。每个关键词保持一行,不包含 <、>、回车或换行。遇到任一这类字符,或 prompt 超过模型长度限制,API 会拒绝整个请求。

说话人分离

既有集成可在 2027年2月26日前使用已弃用的 gpt-4o-transcribe-diarize,识别录音不同部分由谁讲话。该专用说话人标注模型不是普通文件转录的推荐模型。

请求 diarized_json 格式,得到含 speaker、start、end 元数据的片段。音频超过 30 秒时,将 chunking_strategy 设为 "auto" 或语音活动检测配置。

可选提供最多四份短参考音频,通过 known_speaker_names[] 和 known_speaker_references[] 将片段映射到已知讲话者。参考片段为 2–10 秒,格式可为主音频上传支持的任意类型;使用 multipart 表单时,将参考编码成 data URL。

为会议录音标注说话人:

来源示例 16(javascript):

// [中文] 示例 16:说话人分离;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-transcribe-diarize;各值的作用按其所在配置对象区分。
// [中文] 需要发送的原始字节先编码为 Base64;编码不会替代重采样或改变编解码格式。
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const agentRef = fs.readFileSync("fixtures/agent.wav").toString("base64");

const transcript = await openai.audio.transcriptions.create({
  file: fs.createReadStream("fixtures/meeting.wav"),
  model: "gpt-4o-transcribe-diarize",
  response_format: "diarized_json",
  chunking_strategy: "auto",
  known_speaker_names: ["agent"],
  known_speaker_references: ["data:audio/wav;base64," + agentRef],
});

for (const segment of transcript.segments) {
  if (!("speaker" in segment)) continue;

  console.log(
    `${segment.speaker}: ${segment.text}`,
    segment.start,
    segment.end
  );
}

来源示例 17(python):

## [中文] 示例 17:说话人分离;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-transcribe-diarize;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
## [中文] 需要发送的原始字节先编码为 Base64;编码不会替代重采样或改变编解码格式。
import base64
from openai import OpenAI

client = OpenAI()


def to_data_url(path: str) -> str:
    with open(path, "rb") as fh:
        return "data:audio/wav;base64," + base64.b64encode(fh.read()).decode("utf-8")


with open("meeting.wav", "rb") as audio_file:
    transcript = client.audio.transcriptions.create(
        model="gpt-4o-transcribe-diarize",
        file=audio_file,
        response_format="diarized_json",
        chunking_strategy="auto",
        extra_body={
            "known_speaker_names": ["agent"],
            "known_speaker_references": [to_data_url("agent.wav")],
        },
    )

for segment in transcript.segments:
    print(segment.speaker, segment.text, segment.start, segment.end)

来源示例 18(go):

// [中文] 示例 18:说话人分离;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-transcribe-diarize;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.Audio.Transcriptions.New;异步调用及事件接收顺序保留。
// [中文] 需要发送的原始字节先编码为 Base64;编码不会替代重采样或改变编解码格式。
package main

import (
    "context"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/shared/constant"
)

type diarizedTranscript struct {
    Segments []struct {
        Speaker string  `json:"speaker"`
        Text    string  `json:"text"`
        Start   float64 `json:"start"`
        End     float64 `json:"end"`
    } `json:"segments"`
}

func main() {
    agentAudio, err := os.ReadFile("fixtures/agent.wav")
    if err != nil {
        panic(err)
    }
    meeting, err := os.Open("fixtures/meeting.wav")
    if err != nil {
        panic(err)
    }
    defer meeting.Close()

    client := openai.NewClient()
    transcription, err := client.Audio.Transcriptions.New(context.Background(), openai.AudioTranscriptionNewParams{
        File:           meeting,
        Model:          "gpt-4o-transcribe-diarize",
        ResponseFormat: openai.AudioResponseFormatDiarizedJSON,
        ChunkingStrategy: openai.AudioTranscriptionNewParamsChunkingStrategyUnion{
            OfAuto: constant.ValueOf[constant.Auto](),
        },
        KnownSpeakerNames:      []string{"agent"},
        KnownSpeakerReferences: []string{"data:audio/wav;base64," + base64.StdEncoding.EncodeToString(agentAudio)},
    })
    if err != nil {
        panic(err)
    }
    var result diarizedTranscript
    if err := json.Unmarshal([]byte(transcription.RawJSON()), &result); err != nil {
        panic(err)
    }
    for _, segment := range result.Segments {
        fmt.Println(segment.Speaker+":", segment.Text, segment.Start, segment.End)
    }
}

来源示例 19(java):

// [中文] 示例 19:说话人分离;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-transcribe-diarize;各值的作用按其所在配置对象区分。
// [中文] 需要发送的原始字节先编码为 Base64;编码不会替代重采样或改变编解码格式。
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioResponseFormat;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.audio.transcriptions.TranscriptionDiarized;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

Path audio = Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH"));
Path speakerAudio = Path.of(System.getenv("OPENAI_EXAMPLE_SPEAKER_AUDIO_PATH"));
String speakerReference =
    "data:audio/wav;base64,"
        + Base64.getEncoder().encodeToString(Files.readAllBytes(speakerAudio));

var result =
    client
        .audio()
        .transcriptions()
        .create(
            TranscriptionCreateParams.builder()
                .file(audio)
                .model("gpt-4o-transcribe-diarize")
                .responseFormat(AudioResponseFormat.DIARIZED_JSON)
                .chunkingStrategyAuto()
                .addKnownSpeakerName("agent")
                .addKnownSpeakerReference(speakerReference)
                .build());

TranscriptionDiarized diarized =
    result.isDiarized()
        ? result.asDiarized()
        : new JsonMapper()
            .readValue(result.asTranscription().text(), TranscriptionDiarized.class);
for (var segment : diarized.segments()) {
  System.out.println(
      segment.speaker()
          + ": "
          + segment.text()
          + " ("
          + segment.start()
          + "-"
          + segment.end()
          + ")");
}

来源示例 20(ruby):

程序文字译释121:转录中没有包含说话人片段。

程序文字译释122:说话人片段无效。

## [中文] 示例 20:说话人分离;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-transcribe-diarize;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
## [中文] 需要发送的原始字节先编码为 Base64;编码不会替代重采样或改变编解码格式。
require "base64"
require "openai"
require "pathname"

client = OpenAI::Client.new
audio = Pathname("meeting.wav")
speaker_reference = Base64.strict_encode64(File.binread("agent.wav"))
transcript = client.audio.transcriptions.create(
  file: audio,
  model: "gpt-4o-transcribe-diarize",
  response_format: :diarized_json,
  chunking_strategy: :auto,
  known_speaker_names: ["agent"],
  known_speaker_references: ["data:audio/wav;base64,#{speaker_reference}"]
)
segments = Array(
  transcript.to_h.fetch(:segments) do
    raise "The transcription did not include speaker segments"
  end
)
segments.each do |segment|
  segment = Hash.try_convert(segment) or raise "Invalid speaker segment"
  puts(
    "#{segment.fetch(:speaker)}: #{segment.fetch(:text)} " \
      "(#{segment.fetch(:start)}-#{segment.fetch(:end_)})"
  )
end

来源示例 21(bash):

## [中文] 示例 21:说话人分离;以下保留本语言原始示例。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/transcriptions;认证和请求体保持原示例形式。
curl --request POST \
  --url https://api.openai.com/v1/audio/transcriptions \
  --header "Authorization: Bearer $OPENAI_API_KEY" \
  --header 'Content-Type: multipart/form-data' \
  --form file=@/path/to/file/meeting.wav \
  --form model=gpt-4o-transcribe-diarize \
  --form response_format=diarized_json \
  --form chunking_strategy=auto \
  --form 'known_speaker_names[]=agent' \
  --form 'known_speaker_references[]=data:audio/wav;base64,AAA...'

当 stream=true 时,每个带说话人标签的片段完成后发出 transcript.text.segment。transcript.text.delta 包含 segment_id,但增量不包含部分说话人分配;只有片段最终确定时才分配说话人。

说话人标注通过 /v1/audio/transcriptions 提供,不支持 Realtime 转录会话。

翻译

已弃用的 /v1/audio/translations 使用 whisper-1 将完整录音翻译成英语,保留至 2027年2月26日。转录保留原语言,而该端点只返回英语文字。

应迁移到 /v1/realtime/translations 上使用 gpt-realtime-translate 的实时翻译。迁移需要翻译会话、流式音频输入和翻译事件,仅修改 /v1/audio/translations 请求中的模型 ID 并不能完成迁移。

支持的语言

知道预计输入语言时,为 gpt-transcribe 设置 languages。支持的代码格式包括:

  • ISO 639-1,如 en、es、fr。
  • 部分 ISO 639-3,如 eng、spa、yue、cmn。
  • zh 地区语言代码,如 zh-cn、zh-tw、zh-hk。

不支持或格式错误的代码会被拒绝。响应也会标识模型能可靠检测的语言。

whisper-1 参阅 Whisper 语言列表。Whisper 支持 98 种语言,但准确性因语言而异。接受单一语言提示的既有模型使用 language,而不是 languages。

时间戳

既有集成可在 2027年2月26日前使用已弃用的 whisper-1 获取词级或片段级时间戳。timestamp_granularities[] 参数返回结构化时间数据,供字幕制作和视频编辑使用。

时间戳选项:

来源示例 22(javascript):

// [中文] 示例 22:时间戳;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const transcription = await openai.audio.transcriptions.create({
  file: fs.createReadStream("fixtures/audio.wav"),
  model: "whisper-1",
  response_format: "verbose_json",
  timestamp_granularities: ["word"],
});

console.log(transcription.words);

来源示例 23(python):

## [中文] 示例 23:时间戳;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
from openai import OpenAI

client = OpenAI()
audio_file = open("speech.wav", "rb")

transcription = client.audio.transcriptions.create(
    file=audio_file,
    model="whisper-1",
    response_format="verbose_json",
    timestamp_granularities=["word"],
)

print(transcription.words)

来源示例 24(go):

// [中文] 示例 24:时间戳;以下保留本语言原始示例。
// [中文] 沿原示例执行这些方法:client.Audio.Transcriptions.New;异步调用及事件接收顺序保留。
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
)

func main() {
    file, err := os.Open("fixtures/audio.wav")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    client := openai.NewClient()
    transcription, err := client.Audio.Transcriptions.New(context.Background(), openai.AudioTranscriptionNewParams{
        File:                   file,
        Model:                  openai.AudioModelWhisper1,
        ResponseFormat:         openai.AudioResponseFormatVerboseJSON,
        TimestampGranularities: []string{"word"},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(transcription.Words)
}

来源示例 25(java):

// [中文] 示例 25:时间戳;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.AudioResponseFormat;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import java.nio.file.Path;

var result =
    client
        .audio()
        .transcriptions()
        .create(
            TranscriptionCreateParams.builder()
                .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))
                .model("whisper-1")
                .responseFormat(AudioResponseFormat.VERBOSE_JSON)
                .addTimestampGranularity(TranscriptionCreateParams.TimestampGranularity.WORD)
                .build());

result
    .asVerbose()
    .words()
    .orElseThrow()
    .forEach(
        word -> System.out.println(word.word() + ": " + word.start() + " - " + word.end()));

来源示例 26(csharp):

// [中文] 示例 26:时间戳;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.TranscribeAudioAsync;异步调用及事件接收顺序保留。
using OpenAI.Audio;

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "whisper-1";
AudioClient client = new(model, key);

await using FileStream audio = File.OpenRead("speech.wav");
AudioTranscriptionOptions options = new()
{
    ResponseFormat = AudioTranscriptionFormat.Verbose,
    TimestampGranularities = AudioTimestampGranularities.Word,
};
AudioTranscription transcription = await client.TranscribeAudioAsync(
    audio,
    "speech.wav",
    options
);

foreach (TranscribedWord word in transcription.Words)
{
    Console.WriteLine(
        $"{word.Word}: {word.StartTime.TotalSeconds:0.00}s - {word.EndTime.TotalSeconds:0.00}s"
    );
}

来源示例 27(ruby):

沿用程序文字译释117。

## [中文] 保留原例中客户端、输入和返回值的处理顺序;本段需结合所在小节的连接前提使用,未通过真实API调用验证。
require "openai"
require "pathname"
require "pp"

client = OpenAI::Client.new
audio = Pathname("audio.wav")
transcript = client.audio.transcriptions.create(
  file: audio,
  model: "whisper-1",
  response_format: :verbose_json,
  timestamp_granularities: [:word]
)
raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

pp(transcript.deep_to_h.fetch(:words))

来源示例 28(bash):

## [中文] 示例 28:时间戳;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/transcriptions;认证和请求体保持原示例形式。
curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F "timestamp_granularities[]=word" \
  -F model="whisper-1" \
  -F response_format="verbose_json"

timestamp_granularities[] 仅支持 whisper-1。

较长输入

Transcriptions API 接受最大 25 MB 文件。更大录音应压缩或切成不超过 25 MB 的块。避免在句子中间切开,否则可能丢失上下文并降低准确性。

可用开源 Python 包 PyDub 分割音频:

来源示例 29(python):

## [中文] 示例 29:较长输入;以下保留本语言原始示例。
## [中文] 从 WAV 文件载入音频;PyDub 切片的时间单位是毫秒,10 * 60 * 1000 表示十分钟。
## [中文] 截取开头十分钟并导出为新的 WAV;此示例不会自动判断文件是否小于 25 MB,上传前仍需检查大小。
from pydub import AudioSegment

song = AudioSegment.from_wav("good_morning.wav")

## PyDub handles time in milliseconds
## [中文] 下面的十分钟需换算成毫秒,再用于切片。
ten_minutes = 10 * 60 * 1000

first_10_minutes = song[:ten_minutes]

first_10_minutes.export("good_morning_10.wav", format="wav")

OpenAI 不保证 PyDub 等第三方软件的可用性或安全性。

提示词

使用 prompt 改善姓名、缩写、格式及录音专用词汇识别。gpt-transcribe 可配合添加转录上下文中的 keywords 和 languages。

既有 gpt-4o-transcribe、gpt-4o-mini-transcribe 也支持提示词,gpt-4o-transcribe-diarize 不支持。

有用的场景包括:

  • 正确转录产品名、技术术语与缩写。
  • 传递长录音前一块的上下文。
  • 保留标点、大小写与填充词。
  • 为某种语言选择偏好的书写系统。

whisper-1 的提示最多 224 个词元,控制力弱于推荐转录模型。必须用 Whisper 时,见提高可靠性。

流式转录:文件转录可以在模型处理完整录音时流式输出部分文字,不需要 Realtime 会话。

流式转录完整录音

对 gpt-transcribe 设置 stream=true。Transcriptions API 在转录文件各部分时返回转录事件。

来源示例 30(javascript):

本例采用同页 HTML 保存的代码,去除 Markdown 导出中的 highlight-start / highlight-end 展示标记;接口、参数和其他程序内容不变。

// [中文] 按会话ID下载录音并写入文件;下载结果依赖服务端录音是否可用,不等同于本段已经录制音频。
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const stream = await openai.audio.transcriptions.create({
  file: fs.createReadStream("fixtures/speech.wav"),
  model: "gpt-transcribe",
  // highlight-start
  stream: true,
  // highlight-end
});

// highlight-start
for await (const event of stream) {
  console.log(event);
}
// highlight-end

来源示例 31(python):

本例采用同页 HTML 保存的代码,去除 Markdown 导出中的 highlight-start / highlight-end 展示标记;接口、参数和其他程序内容不变。

## [中文] 按会话ID下载录音并写入文件;下载结果依赖服务端录音是否可用,不等同于本段已经录制音频。
from openai import OpenAI

client = OpenAI()
audio_file = open("speech.wav", "rb")

stream = client.audio.transcriptions.create(
    model="gpt-transcribe",
    file=audio_file,
    # highlight-start
    stream=True,
    # highlight-end
)

## highlight-start
for event in stream:
    print(event)
## highlight-end

来源示例 32(go):

// [中文] 示例 32:流式转录完整录音;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.Audio.Transcriptions.NewStreaming;异步调用及事件接收顺序保留。
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
)

func main() {
    file, err := os.Open("fixtures/speech.wav")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    client := openai.NewClient()
    stream := client.Audio.Transcriptions.NewStreaming(context.Background(), openai.AudioTranscriptionNewParams{
        File:  file,
        Model: "gpt-transcribe",
    })
    for stream.Next() {
        fmt.Println(stream.Current().Type)
    }
    if err := stream.Err(); err != nil {
        panic(err)
    }
}

来源示例 33(java):

// [中文] 示例 33:流式转录完整录音;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.audio;异步调用及事件接收顺序保留。
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import java.nio.file.Path;

var params =
    TranscriptionCreateParams.builder()
        .model("gpt-transcribe")
        .file(Path.of("speech.wav"))
        .build();
try (var stream = client.audio().transcriptions().createStreaming(params)) {
  stream.stream().forEach(event -> System.out.println(event));
}

来源示例 34(csharp):

// [中文] 示例 34:流式转录完整录音;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.TranscribeAudioStreamingAsync;异步调用及事件接收顺序保留。
using OpenAI.Audio;
#pragma warning disable OPENAI001

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-transcribe";
AudioClient client = new(model, key);

await foreach (StreamingAudioTranscriptionUpdate update in client.TranscribeAudioStreamingAsync("speech.wav"))
{
    if (update is StreamingAudioTranscriptionTextDeltaUpdate delta)
    {
        Console.Write(delta.Delta);
    }
}
Console.WriteLine();

来源示例 35(ruby):

## [中文] 示例 35:流式转录完整录音;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-transcribe;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create_streaming;异步调用及事件接收顺序保留。
require "openai"
require "pathname"

client = OpenAI::Client.new
audio = Pathname("speech.wav")
stream = client.audio.transcriptions.create_streaming(
  file: audio,
  model: "gpt-transcribe"
)

stream.each { |event| puts(event.type) }

来源示例 36(bash):

本例采用同页 HTML 保存的代码,去除 Markdown 导出中的 highlight-start / highlight-end 展示标记;接口、参数和其他程序内容不变。

## [中文] 按会话ID下载录音并写入文件;下载结果依赖服务端录音是否可用,不等同于本段已经录制音频。
curl --request POST \
  --url https://api.openai.com/v1/audio/transcriptions \
  --header "Authorization: Bearer $OPENAI_API_KEY" \
  --header 'Content-Type: multipart/form-data' \
  --form file=@example.wav \
  --form model=gpt-transcribe \
  # highlight-start
  --form stream=true

模型边转录边发出 transcript.text.delta,最后通过 transcript.text.done 返回全文。response_format="diarized_json" 的说话人标注转录,还会在片段定稿时发出 transcript.text.segment。

gpt-transcribe 最终事件还包含检测语言:

来源示例 37(json):字段名、事件类型和示意值保留原样,含义见相邻正文;片段中的省略号不表示完整可运行程序。

{
  "type": "transcript.text.done",
  "text": "Bonjour, pouvez-vous m'entendre ?",
  "languages": [{ "code": "fr" }]
}

既有 gpt-4o-transcribe、gpt-4o-mini-transcribe、gpt-4o-transcribe-diarize 集成也支持文件流式输出,whisper-1 不支持。

流式转录正在录制的音频

麦克风、通话或媒体实时输入,应使用实时转录指南,而不是上述面向文件的路径。该指南说明当前转录会话流程,以及推荐的 gpt-live-transcribe 实时路径。

提高可靠性

为时间戳、字幕或翻译使用 whisper-1 时,以下方式可改善罕见词与缩写识别。新的通用转录应用应首先使用 gpt-transcribe 和转录上下文。

使用 prompt 参数

第一种方法用可选 prompt 传入正确拼写词典。

Whisper 不像通用文本模型那样遵循指令,提示最多接受 224 个词元。

来源示例 38(javascript):

程序文字译释123:这是正确拼写词典,包含产品名和SKU:这些专名及缩写保持原样,不翻译或重写。

// [中文] 示例 38:使用 prompt 参数;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI();

const transcription = await openai.audio.transcriptions.create({
  file: fs.createReadStream("fixtures/speech.wav"),
  model: "whisper-1",
  response_format: "text",
  prompt:
    "ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T.",
});

console.log(transcription);

来源示例 39(python):

沿用程序文字译释123。

## [中文] 保留原例中客户端、输入和返回值的处理顺序;本段需结合所在小节的连接前提使用,未通过真实API调用验证。
from openai import OpenAI

client = OpenAI()
audio_file = open("speech.wav", "rb")

transcription = client.audio.transcriptions.create(
    model="whisper-1",
    file=audio_file,
    response_format="text",
    prompt="ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T.",
)

print(transcription)

来源示例 40(go):

沿用程序文字译释123。

// [中文] 示例 40:使用 prompt 参数;以下保留本语言原始示例。
// [中文] 沿原示例执行这些方法:client.Post;异步调用及事件接收顺序保留。
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
)

func main() {
    file, err := os.Open("fixtures/speech.wav")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    client := openai.NewClient()
    var transcription []byte
    err = client.Post(context.Background(), "audio/transcriptions", openai.AudioTranscriptionNewParams{
        File:           file,
        Model:          openai.AudioModelWhisper1,
        ResponseFormat: openai.AudioResponseFormatText,
        Prompt:         openai.String("ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T."),
    }, &transcription)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(transcription))
}

来源示例 41(java):

程序文字译释124:产品拼写词典的第一段,专名保持原样。

程序文字译释125:产品拼写词典的第二段,专名保持原样。

// [中文] 示例 41:使用 prompt 参数;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import com.openai.models.audio.AudioResponseFormat;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

try (HttpResponse result =
    client
        .audio()
        .transcriptions()
        .withRawResponse()
        .create(
            TranscriptionCreateParams.builder()
                .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))
                .model("whisper-1")
                .responseFormat(AudioResponseFormat.TEXT)
                .prompt(
                    "ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, "
                        + "OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., "
                        + "Q.U.A.R.T.Z., F.L.I.N.T.")
                .build())) {
  System.out.println(new String(result.body().readAllBytes(), StandardCharsets.UTF_8));
}

来源示例 42(csharp):

沿用程序文字译释123。

// [中文] 示例 42:使用 prompt 参数;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.TranscribeAudioAsync;异步调用及事件接收顺序保留。
using OpenAI.Audio;

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "whisper-1";
AudioClient client = new(model, key);

await using FileStream audio = File.OpenRead("speech.wav");
AudioTranscriptionOptions options = new()
{
    ResponseFormat = AudioTranscriptionFormat.Text,
    Prompt = "ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T.",
};
AudioTranscription transcription = await client.TranscribeAudioAsync(
    audio,
    "speech.wav",
    options
);

Console.WriteLine(transcription.Text);

来源示例 43(ruby):

沿用程序文字译释117。

程序文字译释126:讲话者说的是OpenAI和Responses API。

## [中文] 示例 43:使用 prompt 参数;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:whisper-1;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create;异步调用及事件接收顺序保留。
require "openai"
require "pathname"

client = OpenAI::Client.new
audio = Pathname("speech.wav")
transcript = client.audio.transcriptions.create(
  file: audio,
  model: "whisper-1",
  prompt: "The speaker says OpenAI and Responses API"
)
raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

puts(transcript.text)

来源示例 44(bash):

沿用程序文字译释123。

## [中文] 示例 44:使用 prompt 参数;以下保留本语言原始示例。
## [中文] 本段涉及的 HTTP 端点:/v1/audio/transcriptions;认证和请求体保持原示例形式。
curl --request POST \
  --url https://api.openai.com/v1/audio/transcriptions \
  --header "Authorization: Bearer $OPENAI_API_KEY" \
  --header 'Content-Type: multipart/form-data' \
  --form file=@/path/to/file/speech.mp3 \
  --form model=whisper-1 \
  --form prompt="ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T."

这种方法虽然能提高可靠性,但受 224 个词元限制,要作为可扩展方案,SKU 清单必须相对较小。

使用文本模型后处理

第二种方法让文本模型对转录进行后处理。

通过 system_prompt 变量提供指令,可以像转录提示一样包含公司和产品名。

来源示例 45(javascript):

程序文字译释127:你是ZyntriQix公司的助手,纠正转录中的拼写差异,保证所列ZyntriQix、Digique Plus、CynapseFive、VortiQore V8、EchoNix Array、OrbitalLink Seven、DigiFractal Matrix、PULSE、RAPT、B.R.I.C.K.、Q.U.A.R.T.Z.、F.L.I.N.T.等名称拼写准确。只补必要句号、逗号和大小写,仅使用提供的上下文。

// [中文] 示例 45:使用文本模型后处理;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4.1;各值的作用按其所在配置对象区分。
const systemPrompt = `
You are a helpful assistant for the company ZyntriQix. Your task is
to correct any spelling discrepancies in the transcribed text. Make
sure that the names of the following products are spelled correctly:
ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array,
OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K.,
Q.U.A.R.T.Z., F.L.I.N.T. Only add necessary punctuation such as
periods, commas, and capitalization, and use only the context provided.
`;

const transcript = await transcribe(audioFile);
const completion = await openai.chat.completions.create({
  model: "gpt-4.1",
  temperature: temperature,
  messages: [
    {
      role: "system",
      content: systemPrompt,
    },
    {
      role: "user",
      content: transcript,
    },
  ],
  store: true,
});

console.log(completion.choices[0].message.content);

来源示例 46(python):

程序文字译释128:作为ZyntriQix助手,纠正转录拼写,确保列出的全部公司、产品与缩写名称准确;仅做必要标点和大小写调整,只依据已给上下文。专名清单与原代码保持一致。

## [中文] 示例 46:使用文本模型后处理;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4.1;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.chat.completions.create;异步调用及事件接收顺序保留。
system_prompt = """
You are a helpful assistant for the company ZyntriQix. Your task is to correct
any spelling discrepancies in the transcribed text. Make sure that the names of
the following products are spelled correctly: ZyntriQix, Digique Plus,
CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven, DigiFractal
Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T. Only add necessary
punctuation such as periods, commas, and capitalization, and use only the
context provided.
"""


def generate_corrected_transcript(temperature, system_prompt, audio_file):
    response = client.chat.completions.create(
        model="gpt-4.1",
        temperature=temperature,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": transcribe(audio_file, "")},
        ],
    )
    return response.choices[0].message.content


corrected_text = generate_corrected_transcript(0, system_prompt, fake_company_filepath)

来源示例 47(go):

// [中文] 示例 47:使用文本模型后处理;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4.1;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.Audio.Transcriptions.New、client.Chat.Completions.New;异步调用及事件接收顺序保留。
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/openai/openai-go/v3"
)

const systemPrompt = `
You are a helpful assistant for the company ZyntriQix. Your task is
to correct any spelling discrepancies in the transcribed text. Make
sure that the names of the following products are spelled correctly:
ZyntriQix, Digique Plus, CynapseFive, VortiQore V8, EchoNix Array,
OrbitalLink Seven, DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K.,
Q.U.A.R.T.Z., F.L.I.N.T. Only add necessary punctuation such as
periods, commas, and capitalization, and use only the context provided.
`

func main() {
    file, err := os.Open("fixtures/speech.wav")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    client := openai.NewClient()
    transcription, err := client.Audio.Transcriptions.New(context.Background(), openai.AudioTranscriptionNewParams{
        File:  file,
        Model: openai.AudioModelGPT4oTranscribe,
    })
    if err != nil {
        panic(err)
    }
    completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
        Model:       "gpt-4.1",
        Temperature: openai.Float(0),
        Messages: []openai.ChatCompletionMessageParamUnion{
            openai.SystemMessage(systemPrompt),
            openai.UserMessage(transcription.Text),
        },
        Store: openai.Bool(true),
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(completion.Choices[0].Message.Content)
}

来源示例 48(java):

程序文字译释129:纠正转录拼写,保留所列全部产品名的正确拼写;只补必要标点和大小写,只使用提供的上下文。产品清单为源代码中的完整清单。

// [中文] 示例 48:使用文本模型后处理;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4o-transcribe、gpt-4.1;各值的作用按其所在配置对象区分。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.audio.transcriptions.TranscriptionCreateParams;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.nio.file.Path;

String systemPrompt =
    """
    You are a helpful assistant for the company ZyntriQix. Your task is to
    correct any spelling discrepancies in the transcribed text. Make sure that
    the names of the following products are spelled correctly: ZyntriQix,
    Digique Plus, CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven,
    DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T.
    Only add necessary punctuation such as periods, commas, and capitalization,
    and use only the context provided.
    """;

var result =
    client
        .audio()
        .transcriptions()
        .create(
            TranscriptionCreateParams.builder()
                .file(Path.of(System.getenv("OPENAI_EXAMPLE_AUDIO_PATH")))
                .model("gpt-4o-transcribe")
                .build());

var completion =
    client
        .chat()
        .completions()
        .create(
            ChatCompletionCreateParams.builder()
                .model("gpt-4.1")
                .temperature(0.0)
                .store(true)
                .addSystemMessage(systemPrompt)
                .addUserMessage(result.asTranscription().text())
                .build());
completion.choices().stream()
    .flatMap(choice -> choice.message().content().stream())
    .forEach(System.out::println);

来源示例 49(csharp):

程序文字译释130:作为ZyntriQix助手,修正转录拼写,所列产品名必须正确,仅添加必要句号、逗号和大小写,且只根据给定上下文。

// [中文] 示例 49:使用文本模型后处理;以下保留本语言原始示例。
// [中文] 原代码明确设置的模型值:gpt-4.1;各值的作用按其所在配置对象区分。
// [中文] 沿原示例执行这些方法:client.CompleteChatAsync;异步调用及事件接收顺序保留。
using OpenAI.Audio;
using OpenAI.Chat;

string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-4.1";
ChatClient client = new(model, key);

string transcriptionModel = "gpt-4o-transcribe";
AudioClient audio = new(transcriptionModel, key);

await using FileStream source = File.OpenRead("speech.wav");
AudioTranscription transcription = await audio.TranscribeAudioAsync(source, "speech.wav");

string systemPrompt =
    """
    You are a helpful assistant for the company ZyntriQix. Correct any
    spelling discrepancies in the transcribed text. Make sure the names
    of these products are spelled correctly: ZyntriQix, Digique Plus,
    CynapseFive, VortiQore V8, EchoNix Array, OrbitalLink Seven,
    DigiFractal Matrix, PULSE, RAPT, B.R.I.C.K., Q.U.A.R.T.Z., F.L.I.N.T.
    Only add necessary punctuation such as periods, commas, and
    capitalization, and use only the context provided.
    """;
ChatCompletionOptions correctionOptions = new() { Temperature = 0 };
ChatCompletion completion = await client.CompleteChatAsync(
    [
        new SystemChatMessage(systemPrompt),
        new UserChatMessage(transcription.Text),
    ],
    correctionOptions
);
Console.WriteLine(completion.Content[0].Text);

来源示例 50(ruby):

沿用程序文字译释117。

程序文字译释131:不改变词语,只添加标点和段落分隔;随后传入实际transcript.text。

## [中文] 示例 50:使用文本模型后处理;以下保留本语言原始示例。
## [中文] 原代码明确设置的模型值:gpt-4o-mini-transcribe、gpt-4.1;各值的作用按其所在配置对象区分。
## [中文] 沿原示例执行这些方法:client.audio.transcriptions.create、client.responses.create;异步调用及事件接收顺序保留。
require "openai"
require "pathname"

client = OpenAI::Client.new
audio = Pathname("speech.wav")
transcript = client.audio.transcriptions.create(
  file: audio,
  model: "gpt-4o-mini-transcribe"
)

raise "Expected a JSON transcript response" if transcript.is_a?(StringIO)

response = client.responses.create(
  model: "gpt-4.1",
  input: "Add punctuation and paragraph breaks without changing the words:\n#{transcript.text}"
)
puts(response.output_text)

文本模型可纠正拼写错误,处理比 Whisper 的 224 词元窗口更长的术语列表。应对照原音频评估纠正,避免改变讲话者本意。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号