调用OpenAI davinci-codex API返回异常内容,是否API故障或操作有误?
调用Davinci-Codex API返回非预期内容的原因及解决办法
我的调用代码(JavaScript)
async generateArticles() { console.log('article') const response = await fetch('https://api.openai.com/v1/engines/davinci-codex/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }, body: JSON.stringify({ prompt: `Hey, how are you?`, max_tokens: 2048, n: 1, temperature: 0.7 }) }); console.log(response) const data = await response.json(); console.log(data) const generatedText = data.choices[0].text.trim(); console.log(generatedText) }
非预期的返回示例
示例1:对话模板代码片段
'positive': [ 'That\'s great!', 'Nice!', 'Good!', 'Alright!', 'Cool!', 'Yeah!', ], 'negative': [ 'That\'s too bad', 'Too bad', 'I\'m sorry', ], 'current_user': [ 'My name is {}', 'My name is {}. Nice to meet you', 'The name\'s {}', 'The name\'s {}. Pleased to meet you', ],
示例2:Python代码片段
# def greet(): # print("Hey, how are you?") # print("I hope you are fine!") # print("Bye!") # # def say_bye(): # print("Bye!") # # def greet_bye(): # greet() # say_bye() # # print("I am not in the function") # greet_bye()
原因分析
这不是API故障,是模型选择错误导致的:
- Davinci-Codex是代码专用模型,训练数据以各类代码库为主,核心能力是补全、生成代码,而非自然语言对话。
- 输入自然语言问候时,模型会从训练数据中匹配和该问候相关的代码片段(比如对话系统的代码模板、包含问候的示例代码)进行补全,出现其他语言内容也是因为训练数据中包含多语言代码/文本。
解决办法
- 更换通用对话模型:如果需要生成自然语言对话,改用GPT-3.5-turbo或GPT-4这类通用对话模型,调用端点为
https://api.openai.com/v1/chat/completions,请求格式需调整为对话消息数组(比如包含role: "user"的消息)。 - 明确代码类prompt:如果一定要使用Codex系列模型,需给prompt添加明确的代码任务指令,比如:
# 编写一个处理用户问候"Hey, how are you?"的Python函数,返回友好的回复。 - 使用最新代码模型:Davinci-Codex已逐步被弃用,推荐使用
code-davinci-002等仍在维护的代码专用模型,但依然仅适用于代码生成场景。
内容的提问来源于stack exchange,提问作者Louskac
相关产品推荐
相关产品推荐

