### Install querychat Source: https://posit-dev.github.io/querychat/py/index.html Install the core package via pip. ```bash pip install querychat ``` -------------------------------- ### Install QueryChat Source: https://posit-dev.github.io/querychat/py Install the latest stable release of querychat from PyPI. ```bash pip install querychat__ ``` -------------------------------- ### Install querychat Source: https://posit-dev.github.io/querychat/r/index.html Installation instructions for the stable release from CRAN or the development version from GitHub. ```R install.packages("querychat") ``` ```R # install.packages("pak") pak::pak("posit-dev/querychat/pkg-r") ``` -------------------------------- ### Install Framework Dependencies Source: https://posit-dev.github.io/querychat/py/index.html Install optional dependencies for specific web frameworks. ```bash pip install "querychat[streamlit]" # or [gradio] or [dash] ``` -------------------------------- ### Install PostgreSQL Driver Source: https://posit-dev.github.io/querychat/py/data-sources.html Installs the psycopg2 binary for PostgreSQL connectivity. ```bash pip install psycopg2-binary ``` -------------------------------- ### Manage API credentials Source: https://posit-dev.github.io/querychat/r/articles/models.html Examples for setting environment variables and editing the .Renviron file. ```R OPENAI_API_KEY="your_api_key_here" ``` ```R usethis::edit_r_environ() ``` -------------------------------- ### Install QueryChat with Dash support Source: https://posit-dev.github.io/querychat/py/build-dash.html Use this command to install the necessary dependencies for Dash integration. ```bash pip install "querychat[dash]" ``` -------------------------------- ### Create a pre-baked Dash app Source: https://posit-dev.github.io/querychat/py/build-dash.html Use the .app() method for a quick-start Dash application setup. ```python from querychat.dash import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") app = qc.app() if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Initialize QueryChat with Alternative Frameworks Source: https://posit-dev.github.io/querychat/py/index.html Examples for integrating QueryChat with Streamlit, Gradio, and Dash. ```python from querychat.streamlit import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") qc.app() ``` ```python from querychat.gradio import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") qc.app().launch() ``` ```python from querychat.dash import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") qc.app().run() ``` -------------------------------- ### Install Optional Dependencies Source: https://posit-dev.github.io/querychat/py Install querychat with optional dependencies for specific web frameworks like Streamlit, Gradio, or Dash. ```bash pip install "querychat[streamlit]" # or [gradio] or [dash]__ ``` -------------------------------- ### Load required libraries Source: https://posit-dev.github.io/querychat/r/articles/models.html Initial setup for using querychat with ellmer and data packages. ```R library(querychat) library(palmerpenguins) library(ellmer) ``` -------------------------------- ### Run the Dash application Source: https://posit-dev.github.io/querychat/py/build-dash.html Execute the Python script to start the Dash server. ```bash python dash-app.py ``` -------------------------------- ### Quick Start with Shiny App Source: https://posit-dev.github.io/querychat/py Initialize QueryChat with a data source and name, then launch the default Shiny application. ```python from querychat import QueryChat from querychat.data import titanic nc = QueryChat(titanic(), "titanic") app = qc.app()__ ``` -------------------------------- ### Install Ibis BigQuery Source: https://posit-dev.github.io/querychat/py/data-sources.html Installs the necessary dependencies for BigQuery support in Ibis. ```bash pip install ibis-framework[bigquery] ``` -------------------------------- ### QueryChat Shiny App Example Source: https://posit-dev.github.io/querychat/py/reference/QueryChat.html A complete example demonstrating how to set up a Shiny app with QueryChat, including UI definition and server logic. This example uses the 'titanic' dataset. ```python from shiny import App, render, ui from seaborn import load_dataset from querychat import QueryChat titanic = load_dataset("titanic") pc = QueryChat(titanic, "titanic") def app_ui(request): return ui.page_sidebar( qc.sidebar(), ui.card( ui.card_header(ui.output_text("title")), ui.output_data_frame("data_table"), ), title="Titanic QueryChat App", fillable=True, ) def server(input, output, session): qc_vals = qc.server(enable_bookmarking=True) @render.data_frame def data_table(): return qc_vals.df() @render.text def title(): return qc_vals.title() or "My Data" app = App(app_ui, server, bookmark_store="url")__ ``` -------------------------------- ### Install MySQL Driver Source: https://posit-dev.github.io/querychat/py/data-sources.html Installs the PyMySQL driver for MySQL connectivity. ```bash pip install pymysql ``` -------------------------------- ### Install QueryChat with Gradio Support Source: https://posit-dev.github.io/querychat/py/build-gradio.html Install the necessary package to enable Gradio integration with QueryChat. This command ensures all Gradio-specific dependencies are included. ```bash pip install "querychat[gradio]" ``` -------------------------------- ### Install DuckDB Engine Source: https://posit-dev.github.io/querychat/py/data-sources.html Installs DuckDB and the SQLAlchemy engine adapter. ```bash pip install duckdb duckdb-engine ``` -------------------------------- ### Install Ibis for PostgreSQL Source: https://posit-dev.github.io/querychat/py/data-sources.html Command to install the necessary Ibis framework components for PostgreSQL integration. ```bash pip install ibis-framework[postgres] ``` -------------------------------- ### Initialize TblSqlSource with Database Connection Source: https://posit-dev.github.io/querychat/r/reference/TblSqlSource.html Example showing how to set up a database connection using DBI and duckdb, write a table, and then create a TblSqlSource object from it. ```R con <- DBI::dbConnect(duckdb::duckdb()) DBI::dbWriteTable(con, "mtcars", mtcars) ``` -------------------------------- ### DBISource Usage Example Source: https://posit-dev.github.io/querychat/r/reference/DBISource.html A complete workflow demonstrating database connection, source creation, querying, and cleanup. ```R # Connect to a database con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") DBI::dbWriteTable(con, "mtcars", mtcars) # Create a DBI source db_source <- DBISource$new(con, "mtcars") # Get database type db_source$get_db_type() # Returns "SQLite" #> [1] "SQLite" # Execute a query result <- db_source$execute_query("SELECT * FROM mtcars WHERE mpg > 25") # Note: cleanup() will disconnect the connection # If you want to keep the connection open, don't call cleanup() db_source$cleanup() ``` -------------------------------- ### Quick Start with QueryChat .app() Source: https://posit-dev.github.io/querychat/py/build-streamlit.html Use the `.app()` method for a pre-built Streamlit interface. This provides a functional chat application with minimal code. ```python from querychat.streamlit import QueryChat from querychat.data import titanic nc = QueryChat(titanic(), "titanic") nc.app() ``` -------------------------------- ### Quick Start: Pre-baked Gradio App Source: https://posit-dev.github.io/querychat/py/build-gradio.html Use the `.app()` method for a quick, pre-configured Gradio application. This method provides a ready-to-launch interface for data exploration. ```python from querychat.gradio import QueryChat from querychat.data import titanic pc = QueryChat(titanic(), "titanic") app = qc.app() app.launch() ``` -------------------------------- ### QueryChat Initialization and Usage Examples Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Demonstrates various ways to initialize QueryChat with data frames or database connections, and how to handle greetings. ```R # Basic usage with a data frame qc <- QueryChat$new(mtcars) #> Using model = "gpt-4.1". if (FALSE) { # \dontrun{ app <- qc$app() } # } # With a custom greeting greeting <- "Welcome! Ask me about the mtcars dataset." qc <- QueryChat$new(mtcars, greeting = greeting) #> Using model = "gpt-4.1". # With a specific LLM provider qc <- QueryChat$new(mtcars, client = "anthropic/claude-sonnet-4-5") # Generate a greeting for reuse (requires internet/API access) if (FALSE) { # \dontrun{ qc <- QueryChat$new(mtcars) greeting <- qc$generate_greeting(echo = "text") # Save greeting for next time writeLines(greeting, "mtcars_greeting.md") } # } # Or specify greeting and additional options at initialization qc <- QueryChat$new( mtcars, greeting = "Welcome to the mtcars explorer!", client = "openai/gpt-4o", data_description = "Motor Trend car road tests dataset" ) # Create a QueryChat object from a database connection # 1. Set up the database connection con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") # 2. (For this demo) Create a table in the database DBI::dbWriteTable(con, "mtcars", mtcars) # 3. Pass the connection and table name to `QueryChat` qc <- QueryChat$new(con, "mtcars") #> Using model = "gpt-4.1". ``` -------------------------------- ### Install and load dotenv Source: https://posit-dev.github.io/querychat/py/models.html Use the dotenv package to load environment variables from a .env file into the application. ```bash pip install dotenv ``` ```python from dotenv import load_dotenv load_dotenv() ``` -------------------------------- ### Initialize QueryChat Application Source: https://posit-dev.github.io/querychat/py/tools.html Basic setup for a QueryChat application using the titanic dataset. ```python from querychat import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") app = qc.app()__ ``` -------------------------------- ### Install Dash Dependencies Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Install Dash framework dependencies for QueryChat using pip extras. ```bash pip install querychat[dash] ``` -------------------------------- ### Install querychat Development Version Source: https://posit-dev.github.io/querychat/r Install the development version of the querychat package from GitHub using pak. ```r # install.packages("pak") pak::pak("posit-dev/querychat/pkg-r") ``` -------------------------------- ### Install querychat from CRAN Source: https://posit-dev.github.io/querychat/r Install the stable release of the querychat package from CRAN. ```r install.packages("querychat") ``` -------------------------------- ### Install Gradio Dependencies Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Install Gradio framework dependencies for QueryChat using pip extras. ```bash pip install querychat[gradio] ``` -------------------------------- ### Add Custom Instructions via String Source: https://posit-dev.github.io/querychat/py/context.html Provide custom instructions directly as a string to guide the LLM's behavior. This allows for immediate customization without needing a separate file. ```python instructions = """ - Use British spelling conventions - Stay on topic and only discuss the data dashboard - Refuse to answer unrelated questions """ pc = QueryChat(titanic, "titanic", extra_instructions=instructions) ``` -------------------------------- ### Initialize a QueryChat Shiny Application Source: https://posit-dev.github.io/querychat/r/articles/build.html A complete starter template demonstrating the three-step integration process: initialization, UI setup, and server-side reactive handling. ```R library(shiny) library(bslib) library(querychat) library(DT) library(palmerpenguins) # Step 1: Initialize QueryChat qc <- QueryChat$new(penguins) # Step 2: Add UI component ui <- page_sidebar( sidebar = qc$sidebar(), card( card_header("Data Table"), dataTableOutput("table") ), card( fill = FALSE, card_header("SQL Query"), verbatimTextOutput("sql") ) ) # Step 3: Use reactive values in server server <- function(input, output, session) { qc_vals <- qc$server() output$table <- renderDataTable({ datatable(qc_vals$df(), fillContainer = TRUE) }) output$sql <- renderText({ qc_vals$sql() %||% "SELECT * FROM penguins" }) } shinyApp(ui, server) ``` -------------------------------- ### Install Streamlit Dependencies Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Install Streamlit framework dependencies for QueryChat using pip extras. ```bash pip install querychat[streamlit] ``` -------------------------------- ### Launch a querychat Shiny app Source: https://posit-dev.github.io/querychat/r/index.html Starts a pre-built Shiny application for data exploration. Requires a data source and an LLM client configuration. ```R library(querychat) library(palmerpenguins) querychat_app(penguins, client = "openai/gpt-4.1") ``` -------------------------------- ### Install QueryChat with Streamlit Support Source: https://posit-dev.github.io/querychat/py/build-streamlit.html Install the necessary package for Streamlit integration. This command ensures all dependencies for using QueryChat within a Streamlit application are included. ```bash pip install "querychat[streamlit]" ``` -------------------------------- ### Implement custom data source Source: https://posit-dev.github.io/querychat/r/reference/DataSource.html Example of creating a concrete subclass inheriting from the DataSource base class. ```R MyDataSource <- R6::R6Class( "MyDataSource", inherit = DataSource, public = list( initialize = function(table_name) { self$table_name <- table_name } # Implement abstract methods here... ) ) ``` -------------------------------- ### Add Custom Instructions via File Source: https://posit-dev.github.io/querychat/py/context.html Guide the LLM's behavior by providing custom instructions from a Markdown file using the `extra_instructions` parameter. ```python from pathlib import Path from querychat import QueryChat pc = QueryChat( titanic, "titanic", extra_instructions=Path("instructions.md") ) ``` -------------------------------- ### Run the Gradio Application Source: https://posit-dev.github.io/querychat/py/build-gradio.html Execute the Python script to launch the Gradio application. This command starts the web server for your data exploration interface. ```bash python gradio-app.py ``` -------------------------------- ### Quick Start: QueryChat App with mtcars Source: https://posit-dev.github.io/querychat/r/reference/querychat-convenience.html Launches a QueryChat application directly with the `mtcars` dataset for immediate interaction. ```R if (FALSE) { # rlang::is_interactive() && rlang::is_installed("RSQLite") # Quick start - chat with mtcars dataset in one line querychat_app(mtcars) # Add options querychat_app( mtcars, greeting = "Welcome to the mtcars explorer!", client = "openai/gpt-4o" ) # Chat with a database table (table_name required) con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:") DBI::dbWriteTable(con, "mtcars", mtcars) querychat_app(con, "mtcars") # Create QueryChat class object pc <- querychat(mtcars, greeting = "Welcome to the mtcars explorer!") # Run the app later pc$app() } ``` -------------------------------- ### TblSqlSource Example Usage Source: https://posit-dev.github.io/querychat/r/reference/TblSqlSource.html Demonstrates how to create a TblSqlSource object, connect to a database, execute queries, and chain results with dplyr. ```APIDOC ## Examples ```R con <- DBI::dbConnect(duckdb::duckdb()) DBI::dbWriteTable(con, "mtcars", mtcars) mtcars_source <- TblSqlSource$new(dplyr::tbl(con, "mtcars")) mtcars_source$get_db_type() # "DuckDB" result <- mtcars_source$execute_query("SELECT * FROM mtcars WHERE cyl > 4") # Note, the result is not the *full* data frame, but a lazy SQL tibble print(result) # You can chain this result into a dplyr pipeline dplyr::count(result, cyl, gear) ``` ``` -------------------------------- ### QueryChat with Gradio Source: https://posit-dev.github.io/querychat/py Launch a Gradio application powered by QueryChat. Ensure Gradio is installed. ```python from querychat.gradio import QueryChat from querychat.data import titanic nc = QueryChat(titanic(), "titanic") nc.app().launch()__ ``` -------------------------------- ### Additional Instructions as String Source: https://posit-dev.github.io/querychat/r/articles/context.html Provide custom instructions as a string to guide the LLM's behavior, such as enforcing spelling conventions or restricting the topic of discussion. ```r instructions <- " - Use British spelling conventions - Stay on topic and only discuss the data dashboard - Refuse to answer unrelated questions " qc <- querychat( penguins, extra_instructions = instructions ) cat(qc$system_prompt) ``` -------------------------------- ### Launch Console Chat Interface Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Starts an interactive chat session in the console for querying the data source. ```R QueryChat$console(new = FALSE, ..., tools = "query") ``` -------------------------------- ### Load PyArrow Table with QueryChat Source: https://posit-dev.github.io/querychat/py/data-sources.html Utilize PyArrow Tables as a data source. This example demonstrates reading a CSV and converting it to a PyArrow Table. ```python import pyarrow as pa import pyarrow.csv as pv from querychat import QueryChat mtcars = pv.read_csv( "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv" ).to_table() qc = QueryChat(mtcars, "mtcars") app = qc.app()__ ``` -------------------------------- ### Complete Streamlit App with Metrics and Charts Source: https://posit-dev.github.io/querychat/py/build-streamlit.html A comprehensive example demonstrating a Streamlit app with QueryChat, including metrics, multiple Plotly charts, and a sidebar with chat and reset functionality. The layout is configured for wide mode. ```python import plotly.express as px from querychat.data import titanic from querychat.streamlit import QueryChat import streamlit as st st.set_page_config(page_title="Titanic Explorer", layout="wide") nc = QueryChat(titanic(), "titanic") # Sidebar with chat and reset with st.sidebar: qc.ui() st.divider() if st.button("Reset Filters", use_container_width=True): qc.reset() # Main content st.header(qc.title() or "Titanic Dataset") # Metrics row df = qc.df().to_pandas() col1, col2, col3 = st.columns(3) col1.metric("Passengers", len(df)) col2.metric("Survivors", df["survived"].sum()) col3.metric("Survival Rate", f"{df['survived'].mean():.1%}") # Visualizations col1, col2 = st.columns(2) with col1: fig1 = px.histogram( df, x="age", color="survived", title="Age Distribution by Survival" ) st.plotly_chart(fig1, use_container_width=True) with col2: fig2 = px.bar( df.groupby("pclass")["survived"].mean().reset_index(), x="pclass", y="survived", title="Survival by Class", ) st.plotly_chart(fig2, use_container_width=True) ``` -------------------------------- ### Basic Gradio Layout with QueryChat UI Source: https://posit-dev.github.io/querychat/py/build-gradio.html Integrate the QueryChat interface into a custom Gradio Blocks layout. This example shows how to place the chat UI alongside a data table that updates based on user interactions. ```python import gradio as gr from querychat.gradio import QueryChat from querychat.data import titanic from querychat.types import AppStateDict pc = QueryChat(titanic(), "titanic") with gr.Blocks() as app: with gr.Row(): with gr.Column(): state = qc.ui() with gr.Column(): data_table = gr.Dataframe(label="Data") def update_table(state_dict: AppStateDict): return qc.df(state_dict).to_pandas() state.change(fn=update_table, inputs=[state], outputs=[data_table]) app.launch(css=qc.css, head=qc.head) ``` -------------------------------- ### Launch Interactive Console Session Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Use QueryChat.console() to start an interactive, console-based chat session with your data source. Conversation state is persistent across invocations. ```python qc.console() ``` -------------------------------- ### Configure GitHub model marketplace Source: https://posit-dev.github.io/querychat/r/articles/models.html Initialize a GitHub-hosted model client using environment variables. ```R library(ellmer) # Just works if GITHUB_TOKEN is set in your environment client <- chat_github(model = "gpt-4.1") ``` -------------------------------- ### Data Description Example Source: https://posit-dev.github.io/querychat/r/articles/context.html An example of a markdown file providing a data description for the penguins dataset. This includes explanations for each column. ```markdown This dataset contains information about Palmer Archipelago penguins, collected for studying penguin populations. - species: Penguin species (Adelie, Chinstrap, Gentoo) - island: Island where observed (Torgersen, Biscoe, Dream) - bill_length_mm: Bill length in millimeters - bill_depth_mm: Bill depth in millimeters - flipper_length_mm: Flipper length in millimeters - body_mass_g: Body mass in grams - sex: Penguin sex (male, female) - year: Year of observation ``` -------------------------------- ### Install Polars Extra for SQLAlchemy Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Install the polars extra for QueryChat if you are using a SQLAlchemy connection and need to realize the query result as a polars DataFrame. ```bash pip install querychat[polars] ``` -------------------------------- ### Install Pandas Extra for SQLAlchemy Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Install the pandas extra for QueryChat if you are using a SQLAlchemy connection and need to realize the query result as a pandas DataFrame. ```bash pip install querychat[pandas] ``` -------------------------------- ### Use Sample Datasets Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Import and use sample datasets like 'titanic()' and 'tips()' from the querychat.data module for easy testing. ```python from querychat.data import titanic, tips titanic_data = titanic() tips_data = tips() ``` -------------------------------- ### Initialize QueryChat object Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Demonstrates the constructor for the QueryChat class, showing how to initialize it with a data source and optional parameters. ```R QueryChat$new( data_source, table_name = missing_arg(), ..., id = NULL, greeting = NULL, client = NULL, tools = c("update", "query"), data_description = NULL, categorical_threshold = 20, extra_instructions = NULL, prompt_template = NULL, cleanup = NA ) ``` -------------------------------- ### GET /get_schema Source: https://posit-dev.github.io/querychat/py/reference/types.DataFrameSource.html Generates schema information for the underlying DataFrame. ```APIDOC ## GET /get_schema ### Description Generate schema information from the DataFrame. ### Method GET ### Parameters #### Query Parameters - **categorical_threshold** (int) - Required - Maximum number of unique values for a text column to be considered categorical ### Response #### Success Response (200) - **schema** (str) - String describing the schema ``` -------------------------------- ### Get Database Type Source: https://posit-dev.github.io/querychat/r/reference/DBISource.html Retrieve the database type identifier as a string. ```R DBISource$get_db_type() ``` -------------------------------- ### Get Unfiltered Data Source: https://posit-dev.github.io/querychat/py/reference/types.SQLAlchemySource.html Returns the complete dataset as a narwhals DataFrame. ```python types.SQLAlchemySource.get_data()__ ``` -------------------------------- ### Get Database Type Source: https://posit-dev.github.io/querychat/py/reference/types.DataSource.html Returns the identifier for the underlying database system. ```python types.DataSource.get_db_type()__ ``` -------------------------------- ### Running a QueryChat App Later Source: https://posit-dev.github.io/querychat/r/reference/querychat-convenience.html Launches a previously created `QueryChat` application. ```R pc$app() ``` -------------------------------- ### Get unfiltered data Source: https://posit-dev.github.io/querychat/r/reference/DataSource.html Retrieves the entire dataset from the table as a data frame. ```R DataSource$get_data() ``` -------------------------------- ### Get Schema Information Source: https://posit-dev.github.io/querychat/py/reference/types.SQLAlchemySource.html Generates a string description of the database table schema. ```python types.SQLAlchemySource.get_schema(categorical_threshold)__ ``` -------------------------------- ### Get Database Type Source: https://posit-dev.github.io/querychat/py/reference/types.SQLAlchemySource.html Retrieves the database type by inspecting the SQLAlchemy engine. ```python types.SQLAlchemySource.get_db_type()__ ``` -------------------------------- ### Initialize QueryChat Source: https://posit-dev.github.io/querychat/py/build-dash.html Import the Dash-specific class and initialize it with a data source. ```python from querychat.dash import QueryChat ``` ```python from querychat.data import titanic qc = QueryChat(titanic(), "titanic") ``` -------------------------------- ### Create QueryChat Client with Tools Source: https://posit-dev.github.io/querychat/py/reference/QueryChat.html Creates a chat client with registered tools. Specify which tools to include like 'update', 'query', or both. Optional callbacks can be provided for tool success or invocation. ```python QueryChat.client(tools=MISSING, update_dashboard=None, reset_dashboard=None)__ ``` -------------------------------- ### Create a Comprehensive Dash App with Metrics and Charts Source: https://posit-dev.github.io/querychat/py/build-dash.html Extends the basic integration to include summary metrics alongside interactive charts. ```python import dash_bootstrap_components as dbc import plotly.express as px from querychat.dash import QueryChat from querychat.data import titanic from querychat.types import AppStateDict from dash import Dash, Input, Output, dcc, html qc = QueryChat(titanic(), "titanic") app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = dbc.Container( [ html.H1("Titanic Dataset Explorer", className="my-3"), dbc.Row( [ dbc.Col(qc.ui(), width=4), dbc.Col( [ html.H3(id="data-title", className="mb-3"), dbc.Row( [ dbc.Col( dbc.Card( [ dbc.CardHeader("Passengers"), dbc.CardBody( html.H4(id="metric-passengers") ), ] ) ), dbc.Col( dbc.Card( [ dbc.CardHeader("Survivors"), dbc.CardBody( html.H4(id="metric-survivors") ), ] ) ), dbc.Col( dbc.Card( [ dbc.CardHeader("Survival Rate"), dbc.CardBody(html.H4(id="metric-rate")), ] ) ), ], className="mb-3", ), dbc.Row( [ dbc.Col(dcc.Graph(id="age-chart")), dbc.Col(dcc.Graph(id="class-chart")), ] ), ], width=8, ), ] ), ], fluid=True, ) qc.init_app(app) @app.callback( [ Output("data-title", "children"), Output("metric-passengers", "children"), Output("metric-survivors", "children"), Output("metric-rate", "children"), Output("age-chart", "figure"), Output("class-chart", "figure"), ], Input(qc.store_id, "data"), ) def update_all(state: AppStateDict): df = qc.df(state).to_pandas() title = qc.title(state) or "All Data" # Metrics n_passengers = len(df) n_survivors = int(df["survived"].sum()) survival_rate = f"{df['survived'].mean():.1%}" # Charts fig1 = px.histogram( df, x="age", color="survived", title="Age Distribution by Survival" ) fig2 = px.bar( df.groupby("pclass")["survived"].mean().reset_index(), x="pclass", y="survived", ``` -------------------------------- ### Initialize QueryChat Client Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Configures a chat client with specific tools and callback functions for dashboard updates and resets. ```R QueryChat$client( tools = NA, update_dashboard = function(query, title) { }, reset_dashboard = function() { } ) ``` -------------------------------- ### Load Libraries Source: https://posit-dev.github.io/querychat/r/articles/context.html Load the querychat and palmerpenguins libraries to begin. ```r library(querychat) library(palmerpenguins) ``` -------------------------------- ### DataFrameSource Usage Examples Source: https://posit-dev.github.io/querychat/r/reference/DataFrameSource.html Common operations including source creation, querying, and engine selection. ```R # Create a data frame source (uses first available: duckdb or sqlite) df_source <- DataFrameSource$new(mtcars, "mtcars") # Get database type df_source$get_db_type() # Returns "DuckDB" or "SQLite" #> [1] "DuckDB" # Execute a query result <- df_source$execute_query("SELECT * FROM mtcars WHERE mpg > 25") # Explicitly choose an engine df_sqlite <- DataFrameSource$new(mtcars, "mtcars", engine = "sqlite") # Clean up when done df_source$cleanup() df_sqlite$cleanup() ``` -------------------------------- ### Initialize QueryChat Source: https://posit-dev.github.io/querychat/py/reference/QueryChat.html Constructor signature for creating a new QueryChat instance. ```python QueryChat( data_source, table_name, *, id=None, greeting=None, client=None, tools=('update', 'query'), data_description=None, categorical_threshold=20, extra_instructions=None, prompt_template=None, ) ``` -------------------------------- ### Get Semantic Views Description Source: https://posit-dev.github.io/querychat/py/reference/types.DataSource.html Retrieves descriptions of semantic views for inclusion in system prompts. ```python types.DataSource.get_semantic_views_description()__ ``` -------------------------------- ### Initialize DBISource Source: https://posit-dev.github.io/querychat/r/reference/DBISource.html Create a new instance of DBISource using a DBI connection and a target table name. ```R DBISource$new(conn, table_name) ``` -------------------------------- ### Launch QueryChat with a custom greeting file Source: https://posit-dev.github.io/querychat/r/articles/greet.html Pass a path to a markdown file to the greeting argument to avoid auto-generating greetings on every session. ```R qc <- querychat( penguins, greeting = "greeting.md" ) qc$app() # Launch the app ``` -------------------------------- ### QueryChat$client() Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Creates a chat client with registered tools for the current data source. ```APIDOC ## QueryChat$client() ### Description Creates a chat client, complete with registered tools, for the current data source. ### Parameters - **tools** (string) - Optional - Tools to include ('update', 'query'). - **update_dashboard** (function) - Optional - Callback for updating the dashboard. - **reset_dashboard** (function) - Optional - Callback for resetting the dashboard. ``` -------------------------------- ### Get Database Type Source: https://posit-dev.github.io/querychat/r/reference/TblSqlSource.html Retrieve the type of the connected database. This is useful for understanding the underlying database system. ```R mtcars_source$get_db_type() ``` -------------------------------- ### Get Database Schema Source: https://posit-dev.github.io/querychat/r/reference/DBISource.html Retrieve schema information for the table, with an optional threshold for identifying categorical columns. ```R DBISource$get_schema(categorical_threshold = 20) ``` -------------------------------- ### Get Database Type Source: https://posit-dev.github.io/querychat/py/reference/types.DataFrameSource.html Returns the type of the database being used. For DataFrameSource, this will always return the string 'DuckDB'. ```python types.DataFrameSource.get_db_type() ``` -------------------------------- ### Initialize QueryChat with Data Source: https://posit-dev.github.io/querychat/py/build.html Initialize the QueryChat instance with a data source and a name. ```python from querychat.data import titanic qc = QueryChat(titanic(), "titanic") ``` -------------------------------- ### Get schema information Source: https://posit-dev.github.io/querychat/r/reference/DataSource.html Retrieves schema information formatted for LLM prompts, with an optional threshold for categorical columns. ```R DataSource$get_schema(categorical_threshold = 20) ``` -------------------------------- ### Get Schema Information Source: https://posit-dev.github.io/querychat/py/reference/types.DataSource.html Returns a string representation of the table schema, using categorical_threshold to define categorical columns. ```python types.DataSource.get_schema(categorical_threshold)__ ``` -------------------------------- ### Initialize QueryChat with OOP API Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Use the QueryChat class as the main entry point, replacing the older functional API like init(). ```python from querychat import QueryChat # Initialize QueryChat using the new OOP-based API qc = QueryChat() # Use methods like .sidebar(), .server(), etc. on the qc object ``` -------------------------------- ### Initialize SQLAlchemySource Source: https://posit-dev.github.io/querychat/py/reference/types.SQLAlchemySource.html Constructor for the SQLAlchemySource class. ```python SQLAlchemySource(engine, table_name)__ ``` -------------------------------- ### Initialize QueryChat server logic Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Sets up reactive logic for the chat interface within a Shiny server function. ```R qc <- QueryChat$new(mtcars) server <- function(input, output, session) { qc_vals <- qc$server(enable_bookmarking = TRUE) output$data <- renderDataTable(qc_vals$df()) output$query <- renderText(qc_vals$sql()) output$title <- renderText(qc_vals$title() %||% "No Query") } ``` ```R QueryChat$server( enable_bookmarking = FALSE, ..., id = NULL, session = shiny::getDefaultReactiveDomain() ) ``` -------------------------------- ### Configure Tool Detail Card Expansion Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html Control the default expansion state of tool detail cards using the QUERYCHAT_TOOL_DETAILS environment variable. ```bash # Set tool details to be expanded by default export QUERYCHAT_TOOL_DETAILS="expanded" # Set tool details to be collapsed by default export QUERYCHAT_TOOL_DETAILS="collapsed" # Use default behavior export QUERYCHAT_TOOL_DETAILS="default" ``` -------------------------------- ### Initialize QueryChat with Shiny Source: https://posit-dev.github.io/querychat/py/index.html Create a basic Shiny application using the QueryChat class. ```python from querychat import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") app = qc.app() ``` -------------------------------- ### Launch Interactive Console Chat Source: https://posit-dev.github.io/querychat/py/reference/express.QueryChat.html Launches an interactive console chat with the data. Use this to start a chat session for querying data. ```python express.QueryChat.console(new=False, tools='query', **kwargs) ``` -------------------------------- ### Connect to PostgreSQL with Ibis Source: https://posit-dev.github.io/querychat/py/data-sources.html Establishes a connection to a PostgreSQL database using the Ibis framework. ```python conn = ibis.postgres.connect( host="localhost", port=5432, database="mydatabase", user="user", password="password", ) table = conn.table("my_table") qc = QueryChat(table, "my_table") app = qc.app() ``` -------------------------------- ### Run Shiny Application Source: https://posit-dev.github.io/querychat/py/index.html Execute the Shiny application from the command line. ```bash shiny run --reload app.py ``` -------------------------------- ### QueryChat$console() Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Launches a console-based chat interface. ```APIDOC ## QueryChat$console() ### Description Launch a console-based chat interface with the data source. ### Parameters - **new** (boolean) - Optional - Whether to create a new instance. - **...** (dots) - Optional - Additional arguments passed to $client(). - **tools** (string) - Optional - Tools to include. ``` -------------------------------- ### Execute SQL Query Source: https://posit-dev.github.io/querychat/py/reference/types.SQLAlchemySource.html Executes a SQL query and returns the results as a narwhals DataFrame. Raises UnsafeQueryError if the query starts with a disallowed operation. ```python types.SQLAlchemySource.execute_query(query)__ ``` -------------------------------- ### QueryChat$new() Source: https://posit-dev.github.io/querychat/r/reference/QueryChat.html Initializes a new QueryChat instance with a specified data source and configuration options. ```APIDOC ## QueryChat$new() ### Description Creates a new QueryChat object to manage natural language data querying. ### Parameters #### Request Body - **data_source** (data.frame/DBIConnection) - Required - The data source to query. - **table_name** (string) - Optional - Name of the table. - **id** (string) - Optional - Unique identifier for the instance. - **greeting** (string) - Optional - Custom greeting message. - **tools** (vector) - Optional - Allowed tools, defaults to c("update", "query"). - **data_description** (string) - Optional - Description of the data for the LLM. - **categorical_threshold** (numeric) - Optional - Threshold for categorical data, defaults to 20. - **extra_instructions** (string) - Optional - Additional instructions for the LLM. - **prompt_template** (string) - Optional - Custom prompt template. - **cleanup** (logical) - Optional - Cleanup configuration. ``` -------------------------------- ### Initialize GitHub model client Source: https://posit-dev.github.io/querychat/py/models.html Use the ChatGithub class, which automatically authenticates if the GITHUB_TOKEN environment variable is set. ```python from chatlas import ChatGithub # Just works if GITHUB_TOKEN is set in your environment client = ChatGithub(model="gpt-4.1") ``` -------------------------------- ### Get Unfiltered Data Source: https://posit-dev.github.io/querychat/py/reference/types.DataFrameSource.html Retrieves the entire dataset as a native DataFrame, without any filtering. The format of the returned DataFrame will match the input DataFrame (polars or pandas). ```python types.DataFrameSource.get_data() ``` -------------------------------- ### Run Dash App Source: https://posit-dev.github.io/querychat/py/build-dash.html This snippet shows how to run the Dash application, configuring the port and debug mode from environment variables. ```python if __name__ == "__main__": import os port = int(os.environ.get("DASH_PORT", "8050")) debug = os.environ.get("DASH_DEBUG", "true").lower() == "true" app.run(debug=debug, port=port) ``` -------------------------------- ### Initialize QueryChat with Client Argument Source: https://posit-dev.github.io/querychat/py/CHANGELOG.html The querychat.init() function now accepts a 'client' argument instead of 'create_chat_callback'. This client can be a chatlas.Chat object, a function returning one, or a provider-model string. ```python from querychat import init import chatlas # Using a chatlas.Chat object my_chat_client = chatlas.ChatOpenAI() init(client=my_chat_client) # Using a function that returns a chatlas.Chat object def create_my_chat(): return chatlas.ChatAnthropic() init(client=create_my_chat) # Using a provider-model string init(client="openai/gpt-4.1") # If client is not provided, it uses the QUERYCHAT_CLIENT environment variable ``` -------------------------------- ### Data Views with Visualizations Source: https://posit-dev.github.io/querychat/py/build-streamlit.html Connect QueryChat to visualizations to automatically update charts based on natural language filters. This example uses Plotly to display a histogram of age distribution. ```python import plotly.express as px from querychat.data import titanic from querychat.streamlit import QueryChat import streamlit as st nc = QueryChat(titanic(), "titanic") nc.sidebar() st.header(qc.title() or "Titanic Explorer") st.dataframe(qc.df()) df = qc.df().to_pandas() fig = px.histogram(df, x="age", color="survived", title="Age Distribution") st.plotly_chart(fig) ``` -------------------------------- ### Connect to BigQuery with Ibis Source: https://posit-dev.github.io/querychat/py/data-sources.html Connects to BigQuery using default environment credentials. ```python import ibis from querychat import QueryChat # Connect to BigQuery (uses default credentials from environment) conn = ibis.bigquery.connect( project_id="my-project", dataset_id="my_dataset", ) table = conn.table("my_table") qc = QueryChat(table, "my_table") app = qc.app() ``` -------------------------------- ### Initialize QueryChat with Deferred Data Source Source: https://posit-dev.github.io/querychat/py/build.html Use this pattern when the data source requires session-specific credentials or reactive calculations available only within the server function. ```python from shiny import App, ui from querychat import QueryChat # Global scope - create QueryChat without data source qc = QueryChat(None, "users") app_ui = ui.page_sidebar( qc.sidebar(), ui.output_data_frame("table"), ) def server(input, output, session): # Server scope - create connection with session credentials conn = get_user_connection(session) qc_vals = qc.server(data_source=conn) @render.data_frame def table(): return qc_vals.df() app = App(app_ui, server) ``` -------------------------------- ### Add Additional Instructions Source: https://posit-dev.github.io/querychat/r/articles/context.html Add custom instructions to guide the LLM's behavior using the `extra_instructions` parameter. This helps tailor the LLM's responses to specific requirements. ```r qc <- querychat( penguins, extra_instructions = "instructions.md" ) cat(qc$system_prompt) ``` -------------------------------- ### QueryChat Initialization and Usage Source: https://posit-dev.github.io/querychat/py/reference/express.QueryChat.html Demonstrates how to initialize QueryChat with a data source and table name, and how to use its methods for UI elements and data display within a Shiny Express app. ```APIDOC ## QueryChat Initialization ### Description Initializes the QueryChat class for use within Shiny Express applications. It automatically calls `.server()` during initialization. ### Parameters #### Required Parameters - **data_source** (IntoFrame | sqlalchemy.Engine | ibis.Table | None) - Either a Narwhals-compatible data frame (e.g., Polars or Pandas) or a SQLAlchemy engine containing the table to query against. Can be `None` for deferred binding. - **table_name** (str) - If `data_source` is a data frame, a name to use to refer to the table in SQL queries. If `data_source` is a SQLAlchemy engine, the name of the table in the database. #### Optional Parameters - **id** (Optional[str]) - An optional ID for the QueryChat module. Defaults to an ID generated based on `table_name`. - **greeting** (Optional[str | Path]) - A string in Markdown format for the initial message. Can also be a `pathlib.Path` object. Defaults to a generated greeting at the start of each new conversation. - **client** (Optional[str | chatlas.Chat]) - A `chatlas.Chat` object or a string specifying the provider and model (e.g., "openai/gpt-4.1"). Defaults to the `QUERYCHAT_CLIENT` environment variable or "openai". - **data_description** (Optional[str | Path]) - Description of the data in plain text or Markdown. Can also be a `pathlib.Path` object. - **categorical_threshold** (int) - Threshold for determining if a column is categorical based on the number of unique values. Defaults to 20. - **extra_instructions** (Optional[str | Path]) - Additional instructions for the chat model. Can also be a `pathlib.Path` object. - **prompt_template** (Optional[str | Path]) - Path to or a string of a custom prompt file. Uses the default querychat template if not provided. ### Example Usage ```python from querychat.express import QueryChat from seaborn import load_dataset from shiny.express import app_opts, render, ui titanic = load_dataset("titanic") qc = QueryChat(titanic, "titanic") qc.sidebar() with ui.card(fill=True): with ui.card_header(): @render.text def title(): return qc.title() or "Titanic Dataset" @render.data_frame def data_table(): return qc.df() ui.page_opts( title="Titanic QueryChat App", fillable=True, ) app_opts(bookmark_store="url") ``` ``` -------------------------------- ### Implement multiple QueryChat instances Source: https://posit-dev.github.io/querychat/r/articles/build.html Shows how to use multiple QueryChat instances in a single app by switching between them using conditional panels and navigation panels. ```R library(shiny) library(bslib) library(palmerpenguins) library(titanic) library(querychat) qc_penguins <- QueryChat$new(penguins) qc_titanic <- QueryChat$new(titanic_train) ui <- page_navbar( title = "Multiple Datasets", sidebar = sidebar( id = "sidebar", conditionalPanel( "input.navbar == 'Penguins'", qc_penguins$ui() ), conditionalPanel( "input.navbar == 'Titanic'", qc_titanic$ui() ) ), nav_panel( "Penguins", card(dataTableOutput("penguins_table")) ), nav_panel( "Titanic", card(dataTableOutput("titanic_table")) ), id = "navbar" ) server <- function(input, output, session) { qc_penguins_vals <- qc_penguins$server() qc_titanic_vals <- qc_titanic$server() output$penguins_table <- renderDataTable({ qc_penguins_vals$df() }) output$titanic_table <- renderDataTable({ qc_titanic_vals$df() }) } shinyApp(ui, server) ``` -------------------------------- ### Custom Chat UI Placement Source: https://posit-dev.github.io/querychat/py/build-streamlit.html Use `.ui()` to embed the chat component anywhere in your Streamlit layout. This example places custom controls, like a reset button, in the sidebar alongside the chat. ```python import streamlit as st from querychat.streamlit import QueryChat from querychat.data import titanic nc = QueryChat(titanic(), "titanic") with st.sidebar: qc.ui() st.divider() if st.button("Reset Filters"): qc.reset() st.dataframe(qc.df()) ``` -------------------------------- ### Create QueryChat Shiny App Source: https://posit-dev.github.io/querychat/py/reference/QueryChat.html Creates a Shiny app with a chat sidebar and data table view. Use this to quickly start chatting with your data. Supports URL, server, or disabled bookmarking. ```python QueryChat.app(bookmark_store='url')__ ```