You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prompt内容泄露至OpenAI响应及Excel输出的问题排查

解决OpenAI text-davinci-003响应重复Prompt末尾内容的问题

问题现象

  • 调用text-davinci-003模型时,约10%的响应开头会重复Prompt末尾的内容(如句号、问号、短语)
  • 重复内容同时出现在VS Code终端输出和写入Excel的结果中
  • 原Excel中对应Prompt的部分被移除

排查与解决方案

1. 修正代码变量错误

代码中存在未定义变量myCurrentBusinessIdea,需替换为实际读取的单元格变量myCurrentText,否则会引发运行错误或异常拼接内容:

myCurrentPrompt = "What is the color of most of the following objects: " + myCurrentText

2. 优化OpenAI请求参数,降低重复概率

text-davinci-003作为补全模型,偶尔会重复上下文内容,可通过调整参数改善:

  • presence_penalty:设置0.5-1.0,降低模型重复生成已有内容的概率
  • temperature:调低至0.3-0.5,减少输出随机性,提升确定性
  • stop参数:若Prompt以特定符号(如问号)结尾,设置stop=["?"]让模型在该符号处停止生成,避免续写重复

示例修改后的请求代码:

response = openai.Completion.create(
    model="text-davinci-003",
    prompt=myCurrentPrompt,
    max_tokens=1000,
    presence_penalty=0.7,
    temperature=0.3,
    stop=["?"]
)

3. 主动处理响应内容,移除重复部分

在获取响应后,检查开头是否包含Prompt末尾内容,若存在则移除:

TheOutputtedSummary = response['choices'][0]['text'].strip()
# 取Prompt最后10个字符作为检测后缀
prompt_suffix = myCurrentPrompt[-10:]
if TheOutputtedSummary.startswith(prompt_suffix):
    TheOutputtedSummary = TheOutputtedSummary[len(prompt_suffix):].strip()

4. 优化Excel操作逻辑

  • 将OpenAI API密钥初始化移到循环外,避免重复赋值
  • 增加空单元格判断,跳过无效数据行
  • 当前代码仅写入第6列,不会修改第1列原数据,若原数据丢失,需排查是否有其他操作或代码改动了Excel文件

修改后的完整代码:

import openpyxl
import openai

# 初始化API密钥(移至循环外)
openai.api_key = "你的API密钥"

filename = 'testing-openai-gpt3-requests-v1.xlsx'
wb = openpyxl.load_workbook(filename, read_only=False)
sheet = wb.active

for x in range(sheet.max_row):
    c = sheet.cell(row=x+1, column=1)
    myCurrentText = c.value 
    if not myCurrentText:  # 跳过空单元格
        continue
    myCurrentPrompt = "What is the color of most of the following objects: " + myCurrentText

    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=myCurrentPrompt,
        max_tokens=1000,
        presence_penalty=0.7,
        temperature=0.3,
        stop=["?"]
    )

    TheOutputtedSummary = response['choices'][0]['text'].strip()
    # 移除开头可能重复的Prompt后缀
    prompt_suffix = myCurrentPrompt[-10:]
    if TheOutputtedSummary.startswith(prompt_suffix):
        TheOutputtedSummary = TheOutputtedSummary[len(prompt_suffix):].strip()

    print(TheOutputtedSummary)
    sheet.cell(row=x+1, column=6).value = TheOutputtedSummary

wb.save(filename)
print('All finished!')

内容的提问来源于stack exchange,提问作者king_anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:30:22