Is there a way to define a custom st.write_stream()?
I would like a way to stream the response until it reaches a certain keyword or similar logic.
Thanks!
Is there a way to define a custom st.write_stream()?
I would like a way to stream the response until it reaches a certain keyword or similar logic.
Thanks!
The original generator could be wrapped in another generator containing the logic that you want to introduce.
import streamlit as st
from time import sleep
from typing import Generator, Callable
def ai_response():
"""Generator to mimic some LLM response"""
response = "This is a long AI generated answer, but I wanted it to stop at the first comma :cry:."
for word in response:
yield word
sleep(0.02)
def conditional_writer(func: Callable[[], Generator]):
"""Wrap a generator with some additional logic"""
generator = func()
for word in generator:
if "," in word:
break
yield word
yield "."
def main():
cols = st.columns(2)
with cols[0]:
if st.button("Stream long answer"):
st.write_stream(ai_response)
with cols[1]:
if st.button("Stream short"):
st.write_stream(conditional_writer(ai_response))
if __name__ == "__main__":
main()
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.