C#调用OpenAI音频转录接口失败:已传model仍提示需提供该参数
问题排查与修正方案
你的代码存在两个核心问题,导致API返回"必须提供model参数"的错误:
1. 参数传递逻辑完全错误
你错误地将音频内容绑定到了model字段,而正确的参数格式要求:
model是独立的文本参数,值为whisper-1- 音频文件需要绑定到
file字段
2. API端点地址错误
你使用的https://api.openai.com/v1/engines/whisper-1/transcriptions是旧的错误端点,正确的音频转录端点为https://api.openai.com/v1/audio/transcriptions
修正后的HttpClient代码
static async Task<string> ConvertAudioToText(string filePath, string apiKey) { using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); var content = new MultipartFormDataContent(); // 添加model参数(文本类型) content.Add(new StringContent("whisper-1"), "model"); // 添加音频文件 var audioStream = File.OpenRead(filePath); var audioContent = new StreamContent(audioStream); audioContent.Headers.ContentType = new MediaTypeHeaderValue("audio/wav"); content.Add(audioContent, "file", Path.GetFileName(filePath)); var response = await httpClient.PostAsync("https://api.openai.com/v1/audio/transcriptions", content); response.EnsureSuccessStatusCode(); // 主动抛出HTTP错误,方便调试 var responseContent = await response.Content.ReadAsStringAsync(); return responseContent; }
用官方OpenAI NuGet包的简化写法
如果使用OpenAI NuGet包(版本≥1.0),代码会更简洁且不易出错:
using OpenAI; using OpenAI.Audio; static async Task<string> ConvertAudioToText(string filePath, string apiKey) { var client = new OpenAIClient(apiKey); var transcriptionRequest = new AudioTranscriptionRequest { FilePath = filePath, Model = "whisper-1" }; var result = await client.Audio.CreateTranscriptionAsync(transcriptionRequest); return result.Text; }
内容的提问来源于stack exchange,提问作者Andrew Harbert
相关产品推荐
相关产品推荐

