bottle stream 模式数据返回简单示例

bottle对于支持迭代以及生成器的方法会使用类似stream 的模式返回数据,以下是一个简单的对于基于ollama 的stream 数据渲染处理示例

bottle 应用

  • app.py
from bottle import route, run, template,static_file

from ollama import chat

# ollama 集成
def chat_demo(message):
    stream = chat(model='qwen2.5:0.5b',stream=True, messages=[
        {
          'role': 'system',
          'content': '你是指导助手,使用中文进行交流',
        },
        {
            'role': 'user',
            'content': message,
        },
    ])
    for chunk in stream:
        print(chunk['message']['content'])
        yield template("{{content}}",**{"content":chunk['message']['content']})


# 提供了web资源处理
@route('/static/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='static')

# 通过生成器包装的ollama 服务
@route('/<name>')
def index(name):
    for item in  chat_demo(name):
        yield item

run(host='localhost', port=8080,reloader=True)
  • static/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div id="chat"></div>
    <script >
        const chatDiv = document.getElementById('chat');
        // stream 模式的数据调用
        async function stream_fetch() {
            const response = await fetch('/软件测试', {
                method: 'GET',
            });
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let done = false;
            let output = '';
            while (!done) {
                const { value, done: streamDone } = await reader.read();
                done = streamDone;
                output += decoder.decode(value, { stream: true });
                //  数据显示
                chatDiv.innerHTML = marked.parse(output);
                chatDiv.scrollTop = chatDiv.scrollHeight;
            }
        }
        stream_fetch();

    </script>
</body>
</html>

说明

以上是一个简单示例,包含了ollama stream 模式的集成,以及一个web stream api 数据的渲染,代码我提交github了,可以参考

参考资料

https://github.com/bottlepy/bottle

https://bottlepy.org/docs/dev/tutorial.html#generating-content

https://github.com/ollama/ollama-python

https://marked.js.org/#usage

posted on 2025-02-25 08:00  荣锋亮  阅读(64)  评论(0)    收藏  举报

导航