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

如何通过Google Gemini API为单个Prompt生成多个响应?

解决单个Prompt生成多个响应的问题

要让Gemini API返回多个响应候选,你需要在调用generate_content时传入generation_config参数,明确设置candidate_count(候选数量)。默认情况下,API只会返回1个候选响应,这就是你当前只得到1个结果的原因。

修改后的代码示例

# ... 上方为更多代码
model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest", system_instruction=system_instruction)

# 配置生成参数,指定候选数量和多样性(可选)
generation_config = genai.GenerationConfig(
    candidate_count=3,  # 设置你想要的候选响应数量,Gemini 1.5 Pro最大支持4个
    temperature=0.8,    # 可选:调高温度增加响应多样性,范围0-1
)

response = model.generate_content("What is the meaning of life?", generation_config=generation_config)
resps = response.candidates

# 遍历输出所有候选
for idx, candidate in enumerate(resps):
    print(f"候选响应 {idx+1}: {candidate.content.parts[0].text}")

注意事项

  • candidate_count的取值范围取决于你使用的模型,Gemini 1.5 Pro的最大候选数为4,需符合对应模型的参数限制。
  • 如果需要更具多样性的响应,可以配合调整temperature参数,数值越高,输出的随机性越强。
  • 确保你的API密钥权限正常,且调用次数在配额范围内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:53:17