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

使用while True循环的LLM对话程序仅运行一次,是否需修改循环条件?

问题分析与解决方案

不需要修改while True的循环条件,程序提前结束是由其他代码问题导致的,具体问题及修复方式如下:

1. data_input()函数无返回值

当前data_input()仅注释了功能,没有实际获取数据的逻辑,也没有return语句。调用data = data_input()时,data会是None,传递给chat_with_data后,初始用户消息内容为None,可能触发LLM异常导致程序终止。

修复示例:

def data_input():
    # 补充数据获取逻辑,比如从用户输入读取
    user_data = input("请输入需要分析的数据:")
    return user_data

2. chat_with_data函数内代码缩进错误

messages列表、try块都没有缩进,属于全局代码,未被包含在chat_with_data函数作用域内。函数调用时会因messages未定义触发异常,直接退出程序。

修复后代码结构:

def chat_with_data(data):
    messages = [
        {
            "role": "system",
            "content": "You are given some data and you have to analyze the data correctly if the user asks for any output then give the output as per the data and user's question otherwise don't give answer."
        },
        {
            "role": "user",
            "content": data
        }
    ]

    try:
        while True:
            user_input = input("Enter your message: ")
            if user_input.lower() == 'exit':
                print("Exiting the chat")
                break

            messages.append({"role": "user", "content": user_input})

            assistant_message = ''
            ollama_response = ollama.chat(model='llama3.2', messages=messages, stream=True)

            # 优化流式输出逻辑,避免重复打印完整内容
            for chunk in ollama_response:
                content_chunk = chunk['message']['content']
                assistant_message += content_chunk
                print(content_chunk, end='', flush=True)
            
            print()  # 换行分隔对话
            messages.append({"role": "assistant", "content": assistant_message})

    except Exception as e:
        print(f"错误:{e}")  # 替换ic(e),避免依赖第三方日志库

3. 流式输出打印逻辑优化

原代码每次循环打印完整的assistant_message,会导致重复输出内容,造成程序提前结束的错觉。改为逐块打印单个chunk的内容,更符合流式输出的预期。

总结

while True的循环逻辑本身是正确的,无需修改。修复上述代码错误后,程序就能实现持续对话,直到用户输入exit才终止。

内容的提问来源于stack exchange,提问作者Praveen Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:37:04