Python JSON聊天机器人对话跳转失效问题排查求助
Python聊天机器人对话跳转问题解决
问题说明
开发的基于JSON配置的Python聊天机器人无法实现跨类别对话跳转:输入hello触发greetings回复后,输入what is your name无法触发continuation的对应回复,反而提示"听不懂",并重复greetings的回复。
原代码与配置
Python脚本
import json import random # Load the JSON data from the specified file path file_path = "chatbot_responces.json" with open(file_path) as file: chat_data = json.load(file) def chat(category, step_data): while True: print(random.choice(step_data['responses'])) user_input = input("> ").lower() found_match = False for words in step_data['words']: if words in user_input: found_match = True break if found_match: if 'answer_from_user' in step_data: next_category = step_data['answer_from_user'] next_step_data = chat_data.get(next_category) chat(next_category, next_step_data) else: break else: print("I'm sorry, I didn't understand that. Please try again.") def restart_chat(): print("Listening for conversation starters...") while True: user_input = input("> ").lower() for category, step_data in chat_data.items(): found_match = False for words in step_data['words']: if words in user_input: found_match = True break if found_match: print(f"Starting conversation in category: {category}") chat(category, step_data) break else: print("I'm sorry, I didn't understand that. Please try again.") if __name__ == "__main__": restart_chat()
JSON配置
{ "greetings": { "words": ["hello", "hi"], "responses": ["Hi", "Hello"] }, "continuation": { "words": ["who are you", "what is your name"], "responses": ["idk", "you tell me"] } }
实际运行结果
Listening for conversation starters... > hello Starting conversation in category: greetings Hi > what is your name I'm sorry, I didn't understand that. Please try again. Hi
问题原因
- chat函数逻辑局限:进入指定category的对话后,仅检查当前category的触发词,无法识别其他category的触发词,导致
what is your name无法匹配到continuation类别。 - 对话退出逻辑错误:当匹配到当前category的触发词但无
answer_from_user字段时,会直接退出chat函数,回到初始监听状态;若未匹配则重复当前category的回复,不符合持续对话需求。
解决方法
修改代码逻辑,实现全局触发词匹配与持续对话:
- 移除仅检查当前category触发词的限制,改为每次用户输入都遍历所有category寻找匹配项。
- 简化对话循环逻辑,实现持续交互,无需在单次匹配后退出。
修改后的代码
import json import random file_path = "chatbot_responces.json" with open(file_path) as file: chat_data = json.load(file) def handle_user_input(user_input): """处理用户输入,返回匹配的回复或错误提示""" user_input = user_input.lower() for category, step_data in chat_data.items(): for word in step_data['words']: if word in user_input: return random.choice(step_data['responses']) return "I'm sorry, I didn't understand that. Please try again." def start_chat(): print("Listening for conversation starters...") while True: user_input = input("> ") response = handle_user_input(user_input) print(response) if __name__ == "__main__": start_chat()
测试结果
运行修改后的代码,输入如下:
Listening for conversation starters... > hello Hi > what is your name idk > who are you you tell me > hi Hello
符合预期效果,输入对应触发词均可触发正确回复,支持持续对话。
内容的提问来源于stack exchange,提问作者3hy
相关产品推荐
相关产品推荐

