调用OpenAI Completions API遇上下文长度超限问题求助
解决OpenAI Completions API上下文长度超限问题
问题详情
调用OpenAI Completions端点时,prompt经Playground和Tokenizer验证为1360 tokens,使用Node.js的openai npm包发起的请求如下:
const response = await openai.createCompletion({ model: 'text-davinci-003', prompt, max_tokens: 4000, temperature: 0.2 })
在Playground测试时响应后总tokens为1374,但通过API提交请求时收到错误:
error: { message: "This model's maximum context length is 4097 tokens, however you requested 5360 tokens (1360 in your prompt; 4000 for the completion). Please reduce your prompt; or completion length.", type: 'invalid_request_error', param: null, code: null }
解决方案
- 调整max_tokens参数:text-davinci-003的上下文总长度上限为4097 tokens,必须保证
prompt token数 + max_tokens ≤ 4097。按1360的prompt token数计算,最大允许的max_tokens为4097 - 1360 = 2737,修改代码如下:const response = await openai.createCompletion({ model: 'text-davinci-003', prompt, max_tokens: 2737, temperature: 0.2 }) - 核对prompt实际token数:虽然Playground和Tokenizer验证为1360,但API端可能存在细微计算差异,建议用OpenAI官方token计算工具重新确认prompt的准确token数。
- 拆分prompt分段请求:如果需要更长的输出内容,可将原prompt拆分为多个逻辑片段,分批次调用API获取结果后再拼接。
内容的提问来源于stack exchange,提问作者Kane Hooper
相关产品推荐
相关产品推荐

