如何在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
相关产品推荐
相关产品推荐

