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

如何在try块中实现response满足指定内容时执行重试逻辑

调整重试触发的条件判断逻辑

将原代码中精确匹配固定字符串的条件,替换为以下复合判断逻辑,即可满足需求:

try:
    instructions = instruction
    prompt_query = query + instructions

    response = await conv_chain.acall({"question": prompt_query, "chat_history": chat_history_new})
    
    end_time = time.time()
    logger.info("response generated in :" + str(end_time - start_time) + "secs")

    # 调整后的条件判断:满足任一条件则执行重试
    answer = response["answer"].lower()  # 统一转为小写,避免大小写差异影响判断
    if answer.startswith("unable") or "unable to find the answer" in answer:
        second_instruction = instruction1
        retry_prompt_query = query + second_instruction
        response = await conv_chain.acall({"question": retry_prompt_query, "chat_history": chat_history_new})
except:
    # 保留原有异常处理逻辑
    pass

关键修改说明

  • 先将response["answer"]转为小写,避免因大小写不一致(如Unable、UNABLE)导致的判断遗漏
  • 使用startswith("unable")判断回答是否以指定前缀开头
  • 使用in操作符判断回答中是否包含目标子串
  • 两个条件通过or连接,满足任一条件即触发重试流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:12:43