prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.1k stars 717 forks source link

Is it possible to force rendering TextArea? #1845

Open marcadella opened 4 months ago

marcadella commented 4 months ago

I am using ChatGPT streaming API, which I would like to print to a TextArea. Using the standard print method, it looks like this:

chat_translation_stream = self.client.chat.completions.create(
            ...,
            stream=True
        )
        reply = ""
        for chunk in chat_translation_stream:
            delta = chunk.choices[0].delta.content or ""
            reply += delta
            print(delta, end="", flush=True)

I replaced the print method with something like this in the accept_handler: output_field.buffer.document = Document( text=reply, cursor_position=len(reply) ) But it looks like the the TextArea is only at the end of the handler and not each time the document is modified. Is there a way to force the re-rendering?

joouha commented 4 months ago

You can set the contents of the text-area using output_field.text = reply instead of your print command. To force re-rendering, use get_app().invalidate()