file 字段的 multipart 表单把音频上传到 POST /v1/audio/transcriptions。带 base64 字符串的 JSON 正文无法通过验证。只有 TypeScript SDK 能发送这种表单;在其他语言中,请像下面那样用标准 HTTP 客户端提交,或者改为发送 URL(参见从 URL 转写音频)。
上传音频文件
import { readFile } from "node:fs/promises";
const form = new FormData();
form.append("model", "openai/gpt-4o-transcribe");
form.append("language", "en");
form.append("file", new Blob([await readFile("call.mp3")], { type: "audio/mpeg" }), "call.mp3");
const transcript = await client.generateTranscription(form as unknown as Record<string, unknown>);
console.log(transcript.text);
# generate_transcription() 目前还不能发送 multipart,所以用 HTTPX 提交表单。
import os
import httpx
with open("call.mp3", "rb") as audio:
response = httpx.post(
"https://api.phaseo.app/v1/audio/transcriptions",
headers={"Authorization": f"Bearer {os.environ['PHASEO_API_KEY']}"},
data={"model": "openai/gpt-4o-transcribe", "language": "en"},
files={"file": ("call.mp3", audio, "audio/mpeg")},
timeout=120,
)
response.raise_for_status()
print(response.json()["text"])
// CreateTranscription() 发送的是 JSON,所以用 net/http 和 mime/multipart 提交表单。
var body bytes.Buffer
form := multipart.NewWriter(&body)
_ = form.WriteField("model", "openai/gpt-4o-transcribe")
_ = form.WriteField("language", "en")
part, _ := form.CreateFormFile("file", "call.mp3")
audio, _ := os.ReadFile("call.mp3")
_, _ = part.Write(audio)
_ = form.Close()
req, _ := http.NewRequest("POST", "https://api.phaseo.app/v1/audio/transcriptions", &body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("PHASEO_API_KEY"))
req.Header.Set("Content-Type", form.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
// CreateTranscription() 发送的是 JSON,所以用 HttpClient 提交表单。
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
new("Bearer", Environment.GetEnvironmentVariable("PHASEO_API_KEY"));
using var form = new MultipartFormDataContent
{
{ new StringContent("openai/gpt-4o-transcribe"), "model" },
{ new StringContent("en"), "language" },
{ new ByteArrayContent(await File.ReadAllBytesAsync("call.mp3")), "file", "call.mp3" },
};
var response = await http.PostAsync("https://api.phaseo.app/v1/audio/transcriptions", form);
Console.WriteLine(await response.Content.ReadAsStringAsync());
<?php
// generateTranscription() 发送的是 JSON,所以用 Guzzle 提交表单;Composer 安装 SDK 时已一并安装 Guzzle。
require 'vendor/autoload.php';
$http = new GuzzleHttp\Client();
$response = $http->post('https://api.phaseo.app/v1/audio/transcriptions', [
'headers' => ['Authorization' => 'Bearer ' . getenv('PHASEO_API_KEY')],
'multipart' => [
['name' => 'model', 'contents' => 'openai/gpt-4o-transcribe'],
['name' => 'language', 'contents' => 'en'],
['name' => 'file', 'contents' => fopen('call.mp3', 'r'), 'filename' => 'call.mp3'],
],
]);
echo $response->getBody();
# generate_transcription 发送的是 JSON,所以用 Net::HTTP 提交表单。
require 'net/http'
uri = URI('https://api.phaseo.app/v1/audio/transcriptions')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV.fetch('PHASEO_API_KEY')}"
request.set_form(
[['model', 'openai/gpt-4o-transcribe'], ['language', 'en'], ['file', File.open('call.mp3')]],
'multipart/form-data'
)
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
puts response.body
// SDK 的 JSON 辅助方法不编码 multipart,所以用 java.net.http 提交表单。
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Path;
import java.time.Duration;
import java.util.UUID;
String baseUrl = System.getenv().getOrDefault("PHASEO_BASE_URL", "https://api.phaseo.app/v1")
.replaceAll("/+$", "");
String apiKey = System.getenv("PHASEO_API_KEY");
String boundary = "phaseo-" + UUID.randomUUID();
var body = BodyPublishers.concat(
BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nopenai/gpt-4o-transcribe\r\n"),
BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\nen\r\n"),
BodyPublishers.ofString("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"call.mp3\"\r\nContent-Type: audio/mpeg\r\n\r\n"),
BodyPublishers.ofFile(Path.of("call.mp3")),
BodyPublishers.ofString("\r\n--" + boundary + "--\r\n")
);
var request = HttpRequest.newBuilder(URI.create(baseUrl + "/audio/transcriptions"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.timeout(Duration.ofSeconds(60))
.POST(body)
.build();
var response = HttpClient.newHttpClient().send(request, BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IOException("HTTP " + response.statusCode() + ": " + response.body());
}
System.out.println(response.body());
| 语言 | SDK 方法 | 能上传文件吗? |
|---|---|---|
| TypeScript | client.generateTranscription(form) | 能。传入 FormData 正文,SDK 会原样以 multipart 发送。需要类型转换,是因为该方法的类型描述的是 JSON 正文。 |
| Python | client.generate_transcription(request) | 不能。它总是发送 JSON,所以请像上面那样用 HTTPX 提交表单。 |
| Go | client.CreateTranscription(ctx, req) | 不能。它发送 JSON;请使用 net/http 和 mime/multipart。 |
| C# | client.CreateTranscription(request) | 不能。它发送 JSON;请使用 HttpClient 和 MultipartFormDataContent。 |
| PHP | $client->generateTranscription($request),别名 createTranscription() | 不能。它发送 JSON;请使用 Guzzle 的 multipart 选项。 |
| Ruby | client.generate_transcription(...),别名 create_transcription | 不能。它发送 JSON;请使用 Net::HTTP 和 set_form。 |
| Java | 无 | 不能。请使用 java.net.http.HttpClient 发送 multipart 正文。 |
| Rust | 无 | 不能。client.post() 只发送 JSON,因此只适用于 URL 来源。 |
从 URL 转写音频
Mistral、ElevenLabs 和 Morpheus 模型可以从 URL 读取音频,而不需要上传。由于这种请求是 JSON,无法上传文件的 SDK 方法也能处理它:result = client.generate_transcription({
"model": "mistral/voxtral-mini-transcribe-2",
"file_url": "https://example.com/call.mp3",
"language": "en",
})
print(result["text"])
resp, err := client.CreateTranscription(context.Background(), map[string]interface{}{
"model": "mistral/voxtral-mini-transcribe-2",
"file_url": "https://example.com/call.mp3",
"language": "en",
})
if err != nil {
panic(err)
}
fmt.Println(resp["text"])
var response = await client.CreateTranscription(new Dictionary<string, object>
{
["model"] = "mistral/voxtral-mini-transcribe-2",
["file_url"] = "https://example.com/call.mp3",
["language"] = "en",
});
$response = $client->generateTranscription([
'model' => 'mistral/voxtral-mini-transcribe-2',
'file_url' => 'https://example.com/call.mp3',
'language' => 'en',
]);
echo $response['text'];
response = client.generate_transcription(
model: 'mistral/voxtral-mini-transcribe-2',
file_url: 'https://example.com/call.mp3',
language: 'en'
)
let response = client.post("/audio/transcriptions", &json!({
"model": "mistral/voxtral-mini-transcribe-2",
"file_url": "https://example.com/call.mp3",
"language": "en"
}))?;
println!("{}", response.body["text"]);
参数
在每种语言中,字段名都是表单字段(使用 URL 来源时为 JSON 字段)。| 字段 | 说明 |
|---|---|
model | 必填。转写模型 ID。 |
file | 上传的音频:aac、flac、mp3、mp4、mpeg、mpga、m4a、ogg、opus、wav 或 webm。除使用下面的 URL 选项外均为必填。大多数模型最大 25 MB。 |
file_url、file_id、s3_presigned_url | Mistral、ElevenLabs 和 Morpheus 模型只接受一个音频来源,因此可以用 URL 代替 file。 |
language | 语言提示,例如 en。 |
prompt | 用于提高准确度的上下文。 |
temperature | 0 到 1(ElevenLabs 为 0 到 2)。 |
response_format | json、text、srt、verbose_json、vtt 或 diarized_json。 |
timestamp_granularities | word 和/或 segment。 |
stream | 在模型支持时,边生成边流式输出转写文本。 |
响应
AudioTranscriptionResponse,以各 SDK 的映射类型返回(Go 中为 map[string]interface{},C# 中为 Dictionary<string, object>?,PHP 中为数组,Ruby 中为 Hash):
{
"text": "Hello world"
}