Skip to content

Commit

Permalink
Add streamlit example
Browse files Browse the repository at this point in the history
  • Loading branch information
cpsievert committed Dec 9, 2024
1 parent bde8556 commit 48e19e7
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions docs/web-apps.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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 _():
Expand All @@ -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()
```

0 comments on commit 48e19e7

Please sign in to comment.