pywebio 流式输出,显示为markdown(一)

前言

pywebio作为一个简单易用的前端框架,可以有效与Python生态结合,用于快速开发信息系统,随着大型语言模型兴起,考虑使用pywebio流式输出显示,并最终渲染为markdown,做一个简单的交互界面。

首先总结了作者的实现思路与精简代码,然后结合交互界面经验进行改进,此外编写了与LLM服务器交互部分以及测试代码。

最后参考中有一篇研究人类阅读速度的文章,可以作为LLM推理速度、交互界面显示速度(人机工程)的参考。

感谢作者另一项目提供的实现借鉴https://github.com/pywebio/qa-bot

创作时间:2025年2月

1 作者实现方法

流式过程中用原始文本输出,都完毕后清除原始文本,用makdown统一渲染

核心部分如下:

for chunk in reply_chunks:
    put_text(chunk, inline=True)
clear()  # clear above text
put_markdown(reply_chunks.result())

参考自作者项目qa-bot main.py 104-135行

qa-bot/main.py at master · pywebio/qa-bot · GitHub

从中抽取改编,可运行的演示代码如下:

'''
基于pywebio的流式响应界面1_0(原版)

参考pywebio作者的qa-bot项目
https://github.com/pywebio/qa-bot
直接从项目中摘取代码实现基本功能

原理:
流式过程中用原始文本输出,都完毕后清除原始文本,用makdown统一渲染

使用迭代器模拟接收到的流式响应
'''
from pywebio import start_server
from pywebio.input import *
from pywebio.output import *
from pywebio.session import set_env
import time

# 模拟的流式传输
from Flow_response_test import get_completion_stream_test

def main():
    set_env(title="流式响应展示", output_max_width="100%")
    put_markdown("## ChatGPT Answers")
    question = textarea(rows=3,
                        placeholder="Input your question when using PyWebIO. (e.g., how to output matplotlib chart)")
    put_info(put_text(question, inline=True))
    while True:
        with use_scope(f'reply-{int(time.time())}'):
            put_loading('grow', 'info')
            try:
                # 迭代器
                reply_chunks = get_completion_stream_test(question)
            except Exception as e:
                popup('ChatGPT Error', put_error(e))
                break
            finally:
                clear()

            # 拼接流式返回的生成文本
            all_chunk_response = []
            for chunk in reply_chunks:
                put_text(chunk, inline=True)
                all_chunk_response.append(chunk)
            clear()  # clear above text
            all_chunk_response_result = ''.join(all_chunk_response)
            put_markdown(all_chunk_response_result)
        question = textarea(placeholder="Follow up question", rows=3)
        put_info(put_text(question, inline=True))
if __name__ == '__main__':
    start_server(main, port=8080, debug=True)

2 模拟数据接收

这里为了测试对makdown的渲染测试效果,给出模拟接受服务器的函数的测试代码&

你可能感兴趣的:(大模型,chatgpt,前端,python,人工智能,语言模型)