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

Python JSON聊天机器人重复请求输入问题排查

问题描述

我开发了一个基于JSON的轻量Python聊天机器人,预期逻辑如下:

  • 程序请求用户输入后,在JSON配置中匹配包含该输入的words列表所属分类,返回对应responses列表中的随机响应
  • 若分类字典中无answer_from_user字段,则重启会话并再次请求输入
  • 若存在answer_from_user字段,则等待用户后续输入并匹配返回对应响应

但实际运行时出现重复请求输入的问题:例如输入“what is your name”需要重复两次才能触发响应。需要修复实现无需重复输入,且支持基于answer_from_user的会话延续。

原代码与配置

Python代码

import json
import random

# Load the JSON data from the specified file path
file_path = "E:/Projects/X1OSCB/chatbot_responces.json"
with open(file_path) as file:
    chat_data = json.load(file)

def find_matching_category(user_input, step_data):
    for category, step_data in chat_data.items():
        for words in step_data['words']:
            if words in user_input:
                return category, step_data
    return None, None

def chat(category, step_data):
    print(random.choice(step_data['responses']))
    user_input = input("> ").lower().strip()

    while True:
        if 'answer_from_user' in step_data and any(word in user_input for word in step_data['answer_from_user']['words']):
            print(random.choice(step_data['answer_from_user']['responses']))
            next_category = step_data['answer_from_user'].get('next_category')
            if next_category:
                next_step_data = chat_data.get(next_category)
                if next_step_data:
                    chat(next_category, next_step_data)
                    break
                else:
                    break
            else:
                break

        if 'next_category' in step_data:
            next_category = step_data['next_category']
            next_step_data = chat_data.get(next_category)
            if next_step_data:
                chat(next_category, next_step_data)
                break
            else:
                break
        else:
            break

def restart_chat():
    while True:
        print("Listening for conversation starters...")
        user_input = input("> ").lower().strip()
        category, step_data = find_matching_category(user_input, chat_data)
        if category:
            print(f"Starting conversation in category: {category}")
            chat(category, step_data)
        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"],
        "answer_from_user": {
            "words": ["test"],
            "responses":["confirmed"]

        }
    }
}
问题根源
  1. 重复输入触发:在restart_chat中已经获取用户输入并匹配到分类,但调用chat函数后,chat开头立刻打印响应并再次请求输入,导致用户第一次输入仅用于分类匹配,第二次输入才会进入后续逻辑
  2. 会话流程混乱:chat函数内的循环逻辑没有正确区分“初始响应”和“后续输入处理”,导致流程跳转不符合预期
修复后的代码
import json
import random

file_path = "E:/Projects/X1OSCB/chatbot_responces.json"
with open(file_path) as file:
    chat_data = json.load(file)

def find_matching_category(user_input):
    for category, step_data in chat_data.items():
        for word in step_data['words']:
            if word in user_input:
                return category, step_data
    return None, None

def chat(step_data):
    # 先返回当前分类的响应
    print(random.choice(step_data['responses']))
    
    # 如果有answer_from_user,等待用户后续输入
    if 'answer_from_user' in step_data:
        user_input = input("> ").lower().strip()
        # 匹配answer_from_user的关键词
        if any(word in user_input for word in step_data['answer_from_user']['words']):
            print(random.choice(step_data['answer_from_user']['responses']))
            # 处理下一个分类(如果有)
            next_category = step_data['answer_from_user'].get('next_category')
            if next_category and next_category in chat_data:
                chat(chat_data[next_category])
    
    # 如果有next_category,直接进入下一个分类
    elif 'next_category' in step_data:
        next_category = step_data['next_category']
        if next_category in chat_data:
            chat(chat_data[next_category])

def restart_chat():
    while True:
        print("Listening for conversation starters...")
        user_input = input("> ").lower().strip()
        category, step_data = find_matching_category(user_input)
        if category:
            print(f"Starting conversation in category: {category}")
            chat(step_data)
        else:
            print("I'm sorry, I didn't understand that. Please try again.")

if __name__ == "__main__":
    restart_chat()
修复说明
  • 调整find_matching_category函数,移除冗余的step_data参数,逻辑更简洁
  • 修改chat函数:不再一进入就请求输入,而是先返回当前分类的响应,仅当存在answer_from_user时才请求后续输入
  • 优化会话流程:处理完answer_from_user或next_category后,正确延续会话或结束当前分支,回到监听状态
测试交互示例
Listening for conversation starters...
> what is your name
Starting conversation in category: continuation
idk
> test
confirmed
Listening for conversation starters...
> hello
Starting conversation in category: greetings
Hi
Listening for conversation starters...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:55:29