AI chat interfaces
Code from slides
R shinychat
library(dotenv)
library(shiny)
library(shinychat)
<- bslib::page_fluid(
ui chat_ui("chat")
)
<- function(input, output, session) {
server <- ellmer::chat_openai(system_prompt = "You're a trickster who answers in riddles")
chat
observeEvent(input$chat_user_input, {
<- chat$stream_async(input$chat_user_input)
stream chat_append("chat", stream)
})
}
shinyApp(ui, server)
Python shinychat
from shiny.express import render, ui
from shinychat.express import Chat
# Set some Shiny page options
="Hello Chat")
ui.page_opts(title
# Create a chat instance, with an initial message
= Chat(
chat id="chat",
=[
messages"content": "Hello! How can I help you today?", "role": "assistant"},
{
],
)
# Display the chat
chat.ui()
# Define a callback to run when the user submits a message
@chat.on_user_submit
async def handle_user_input(user_input: str):
await chat.append_message(f"You said: {user_input}")
"Message state:"
@render.code
def message_state():
return str(chat.messages())
querrychat R
library(dotenv)
library(shiny)
library(bslib)
library(querychat)
# 1. Configure querychat. This is where you specify the dataset and can also
# override options like the greeting message, system prompt, model, etc.
<- querychat_init(mtcars)
querychat_config
<- page_sidebar(
ui # 2. Use querychat_sidebar(id) in a bslib::page_sidebar.
# Alternatively, use querychat_ui(id) elsewhere if you don't want your
# chat interface to live in a sidebar.
sidebar = querychat_sidebar("chat"),
::DTOutput("dt")
DT
)
<- function(input, output, session) {
server
# 3. Create a querychat object using the config from step 1.
<- querychat_server("chat", querychat_config)
querychat
$dt <- DT::renderDT({
output# 4. Use the filtered/sorted data frame anywhere you wish, via the
# querychat$df() reactive.
::datatable(querychat$df())
DT
})
}
shinyApp(ui, server)
querychat Python
import querychat
from chatlas import ChatAnthropic
from seaborn import load_dataset
from shiny.express import render
# data -----
= load_dataset("titanic")
titanic
# chatbot setup -----
def create_chat_callback(system_prompt):
return ChatAnthropic(system_prompt=system_prompt)
= querychat.init(
querychat_config
titanic,"titanic",
="""Hello! I'm here to help you explore the Titanic dataset.""",
greeting=create_chat_callback,
create_chat_callback
)
= querychat.server("chat", querychat_config)
chat
# shiny application -----
# querychat UI
"chat")
querychat.sidebar(
# querychat filtered dataframe
@render.data_frame
def data_table():
return chat["df"]()