From 48e19e7dea5ebf61958b99aecb9b41b9b60441ed Mon Sep 17 00:00:00 2001 From: Carson Date: Mon, 9 Dec 2024 12:27:55 -0600 Subject: [PATCH] Add streamlit example --- docs/web-apps.qmd | 46 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/docs/web-apps.qmd b/docs/web-apps.qmd index 20107f7..5dda68f 100644 --- a/docs/web-apps.qmd +++ b/docs/web-apps.qmd @@ -17,14 +17,13 @@ Using Shiny's [`ui.Chat` component](https://shiny.posit.co/py/components/display from chatlas import ChatAnthropic from shiny.express import ui -chat = ChatAnthropic() - chat_ui = ui.Chat( id="ui_chat", messages=["Hi! How can I help you today?"], ) chat_ui.ui() +chat = ChatAnthropic() @chat_ui.on_user_submit async def _(): @@ -34,4 +33,45 @@ async def _(): ## Streamlit -Coming soon +Streamlit is a popular Python library for building web apps. You can use the `st.chat_input()` and `st.chat_message()` methods to create a chat interface. Here's an example of how you can use Chatlas with Streamlit: + + +```python +import streamlit as st +from chatlas import ChatOpenAI, Turn + +with st.sidebar: + openai_api_key = st.text_input( + "OpenAI API Key", key="chatbot_api_key", type="password" + ) + "[Get an OpenAI API key](https://platform.openai.com/account/api-keys)" + "[View the source code](https://github.com/streamlit/llm-examples/blob/main/Chatbot.py)" + +st.title("💬 Chatbot") + +if "turns" not in st.session_state: + st.session_state["turns"] = [ + Turn(role="assistant", contents="How can I help you?"), + ] + +turns: list[Turn] = st.session_state.turns + +for turn in turns: + st.chat_message(turn.role).write(turn.text) + + +if prompt := st.chat_input(): + if not openai_api_key: + st.info("Please add your OpenAI API key to continue.") + st.stop() + + st.chat_message("user").write(prompt) + + chat = ChatOpenAI(api_key=openai_api_key, turns=turns) + response = chat.stream(prompt) + + with st.chat_message("assistant"): + st.write_stream(response) + + st.session_state["turns"] = chat.turns() +``` \ No newline at end of file