V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
EeffDev
V2EX  ›  问与答

Python 大佬帮忙看一下 GPT 流式返回后如何处理的代码?

  •  
  •   EeffDev · 311 天前 · 324 次点击
    这是一个创建于 311 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下,目前可以流式返回内容到页面上,但是我希望流式返回结束后,我可以进行一些操作,例如保存完整返回到日志、计费等。但是目前 process_response 只会在页面打开后立即执行,并且打印的是“完成 [ ]” 空的 list

    应该怎么写呢?(问了 GPT ,翻来覆去也是不对

    @app.route("/chat/test", methods=["GET", "POST"])
    def chat():
        #  app.logger.info
        os.environ["API_URL"] = "https://api.openai.com/v1/chat/completions"
        chatbot = Chatbot(api_key="key",
                          system_prompt='请帮我生成一句诗,描写春天的'
                          )
    
        output = []
    
        def generate_response():
            for data in chatbot.ask_stream("生成"):
                output.append(data)
                yield data
    
        @after_this_request
        def process_response(response):  # 响应结束后调用该函数
            print("完成", output)
            return response
    
        return Response(generate_response(), mimetype="text/event-stream")
    
    EeffDev
        1
    EeffDev  
    OP
       311 天前
    解决了其实很简单,想多了😂
    提问方法:
    你好,我有一个文本文件,我想使用 python flask 制作一个服务,打开页面后,该文本文件的内容将通过 text/event-stream 的形式,一个字一个字的打印在页面上,流式返回。
    同时我希望在所有文字返回结束后,可以执行删除服务器上该文件的动作。应该怎么写呢?

    综合回答后的解决方法:

    def generate_response():
    for data in chatbot.ask_stream("生成"):
    output.append(data)
    yield data
    print(output)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2940 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 14:24 · PVG 22:24 · LAX 07:24 · JFK 10:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.