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

如何让OpenAI API仅返回文本结果中的第一条内容?

解决OpenAI API返回多定义仅保留第一条的问题

方法一:优化Prompt,约束AI输出单条定义

直接在prompt中明确要求只返回单个简洁定义,从源头避免生成多条结果:

response = openai.Completion.create(
  model="text-davinci-003",
  prompt=f"Give a single, concise definition for the word: {definition}",
  temperature=0.7,
  max_tokens=50,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)
print(response['choices'][0]['text'].strip())

方法二:处理返回文本,提取第一条结果

如果AI仍偶尔生成多条内容,可通过字符串处理提取第一条有效定义:

response = openai.Completion.create(
  model="text-davinci-003",
  prompt=f"give a definition for {definition}",
  temperature=0.7,
  max_tokens=50,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

raw_text = response['choices'][0]['text'].strip()
# 分割行并过滤空内容
filtered_lines = [line.strip() for line in raw_text.split('\n') if line.strip()]
if filtered_lines:
    # 移除第一条的序号前缀(如"1. ")并输出
    first_def = filtered_lines[0].lstrip('1. ').strip()
    print(first_def)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:45:31