### Install QueryChat from GitHub Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/README.md Install the library directly from the GitHub repository with framework extras. ```bash pip install "querychat[gradio] @ git+https://github.com/posit-dev/querychat" ``` -------------------------------- ### Install QueryChat with framework extras Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/README.md Install the library with support for specific web frameworks. ```bash pip install "querychat[gradio]" pip install "querychat[dash]" pip install "querychat[streamlit]" ``` -------------------------------- ### Run QueryChat Module Example from Directory Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/03-module-app/README.md Navigate to the example directory and run this bash command to execute the Shiny application. ```bash Rscript app.R ``` -------------------------------- ### Suggestion Syntax Examples Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/prompts/prompt.md Examples of how to format suggestion tags in lists, inline text, and nested structures. ```markdown * Show me examples of … * What are the key differences between … * Explain how … ``` ```markdown You might want to explore the advanced features or show me a practical example. ``` ```markdown * Analyze the data * What's the average …? * How many …? * Filter and sort * Show records from the year … * Sort the ____ by ____ … ``` -------------------------------- ### R Package Setup and Checks Source: https://github.com/posit-dev/querychat/blob/main/CLAUDE.md Commands for installing R dependencies, running checks for formatting, tests, and package integrity, and formatting code. ```bash # Install R dependencies make r-setup ``` ```bash # Run R checks (format, tests, package) make r-check make r-check-format make r-check-tests make r-check-package ``` ```bash # Format R code make r-format ``` ```bash # Document R package make r-document ``` ```bash # Build R documentation make r-docs ``` -------------------------------- ### Install QueryChat via pip Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/README.md Install the latest stable release of the library from PyPI. ```bash pip install querychat ``` -------------------------------- ### Python Package Setup and Checks Source: https://github.com/posit-dev/querychat/blob/main/CLAUDE.md Commands for setting up the Python environment, running checks for formatting, types, and tests, and formatting code. ```bash # Setup Python environment make py-setup ``` ```bash # Run Python checks (format, types, tests) make py-check make py-check-format make py-check-types make py-check-tests ``` ```bash # Format Python code make py-format ``` ```bash # Build Python package make py-build ``` ```bash # Build Python documentation make py-docs ``` ```bash uv run ruff check --fix pkg-py --config pyproject.toml ``` -------------------------------- ### $console() Source: https://context7.com/posit-dev/querychat/llms.txt Starts an interactive console chat session for data exploration. ```APIDOC ## $console(new, tools) ### Description Start an interactive console chat session for data exploration. ### Parameters #### Request Body - **new** (boolean) - Optional - Whether to start a fresh conversation. - **tools** (string) - Optional - Tools to enable (e.g., "query"). ``` -------------------------------- ### Run QueryChat Module Example App Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/03-module-app/README.md Execute this R code to run the Shiny application demonstrating the QueryChat module pattern. ```r shiny::runApp(system.file("examples-shiny/03-module-app", package = "querychat")) ``` -------------------------------- ### Launch Quick Start Shiny App with QueryChat Source: https://context7.com/posit-dev/querychat/llms.txt Launches a complete Shiny application for chatting with data. Accepts a data frame and optional parameters for customization. ```r library(querychat) library(palmerpenguins) # Quickest way to start querychat_app(penguins) # With options querychat_app( penguins, greeting = "Explore penguin data!", client = "anthropic/claude-sonnet-4-5", bookmark_store = "url" ) ``` ```r # Using QueryChat object qc <- QueryChat$new(mtcars) pc$app() ``` -------------------------------- ### Install querychat Development Version Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/README.md Installs the development version of the querychat package from GitHub. This is useful for testing the latest features or contributing to the project. ```r # install.packages("pak") pak::pak("posit-dev/querychat/pkg-r") ``` -------------------------------- ### Install querychat from CRAN Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/README.md Installs the stable release of the querychat package from CRAN. Use this for general use. ```r install.packages("querychat") ``` -------------------------------- ### Quick Start with querychat App Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/README.md Launches the querychat Shiny app with a specified dataset and an optional LLM client. Requires an API key for the LLM. ```r library(querychat) library(palmerpenguins) querychat_app(penguins, client = "openai/gpt-4.1") ``` -------------------------------- ### Implement Custom DataSource for QueryChat Source: https://context7.com/posit-dev/querychat/llms.txt Provides an example of creating a custom data source by inheriting from the DataSource class and implementing required methods. ```r library(querychat) library(R6) # Built-in data sources: # - DataFrameSource: for data.frames (uses DuckDB internally) # - DBISource: for DBI database connections # - TblSqlSource: for dbplyr tbl_sql objects # Custom data source example CustomSource <- R6Class( "CustomSource", inherit = DataSource, public = list( initialize = function(data, table_name) { self$table_name <- table_name private$data <- data }, get_db_type = function() "Custom", get_schema = function(categorical_threshold = 20) { # Return schema string for LLM paste("Table:", self$table_name, "\nColumns: ...") }, execute_query = function(query) { # Execute and return results private$data }, test_query = function(query, require_all_columns = FALSE) { head(private$data, 1) }, get_data = function() private$data, cleanup = function() invisible(NULL) ), private = list(data = NULL) ) ``` -------------------------------- ### Connect to MySQL Database with querychat Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/sqlite/README.md Connects to a MySQL database and initializes a QueryChat instance. Ensure DBI, RMySQL, and querychat libraries are installed. ```r library(DBI) library(RMySQL) library(querychat) # Connect to MySQL conn <- dbConnect( RMySQL::MySQL(), dbname = "your_database", host = "localhost", user = "your_username", password = "your_password" ) # Create QueryChat instance pc <- QueryChat$new(conn, "your_table_name") # Launch the app pc$app() ``` -------------------------------- ### DBISource$new() missing table error Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DBISource.md This example demonstrates the error triggered when the specified table does not exist in the database. ```R DBISource$new(db$conn, "non_existent_table") ``` -------------------------------- ### Connect to SQLite Database with querychat Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/sqlite/README.md Connects to a SQLite database and initializes a QueryChat instance. Ensure you have the DBI, RSQLite, and querychat libraries installed. ```r library(DBI) library(RSQLite) library(querychat) # Connect to SQLite database conn <- dbConnect(RSQLite::SQLite(), "path/to/your/database.db") # Create QueryChat instance qc <- QueryChat$new( conn, "your_table_name", greeting = "Welcome! Ask me about your data.", data_description = "Description of your data..." ) # Launch the app pc$app() ``` -------------------------------- ### QueryChat.app() - Quick Start Application Source: https://context7.com/posit-dev/querychat/llms.txt Generates and returns a complete Shiny web application with a chat sidebar, SQL display, and data table view for rapid data exploration. ```APIDOC ## QueryChat.app() ### Description Creates a complete Shiny web application with chat sidebar, SQL display, and data table view - the fastest way to start chatting with your data. ### Method `app(bookmark_store='disable')` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `app()` - **bookmark_store**: (str, optional) - Controls bookmarking behavior. Options: "url", "server", "disable". Defaults to "disable". ### Request Example ```python from querychat import QueryChat from querychat.data import titanic pc = QueryChat(titanic(), "titanic") # Create and run the app app = qc.app() # app.run() # Uncomment to launch # With bookmarking enabled app = qc.app(bookmark_store="url") ``` ### Response - **app**: (shiny.App) - A Shiny App object that can be run. ``` -------------------------------- ### Start Interactive Terminal Chat with QueryChat Source: https://context7.com/posit-dev/querychat/llms.txt Initiates an interactive console chat session for data exploration. Supports continuing previous conversations or starting fresh with specific tools. ```r library(querychat) pc <- QueryChat$new(mtcars) # Start interactive chat pc$console() # Continue previous conversation pc$console(new = FALSE) # Fresh conversation with only query tool pc$console(new = TRUE, tools = "query") ``` -------------------------------- ### DBISource$new() connection validation errors Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DBISource.md These examples demonstrate errors triggered when the provided connection object is not a valid DBIConnection. ```R DBISource$new(list(fake = "connection"), "test_table") ``` ```R DBISource$new(NULL, "test_table") ``` ```R DBISource$new("not a connection", "test_table") ``` -------------------------------- ### Launch Interactive QueryChat Console Source: https://context7.com/posit-dev/querychat/llms.txt Start an interactive, terminal-based chat session for data exploration using the `console()` method. This provides a command-line interface for QueryChat. ```python from querychat import QueryChat from querychat.data import titanic pc = QueryChat(titanic(), "titanic") # Start interactive console chat pc.console() ``` -------------------------------- ### DBISource$new() table_name validation errors Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DBISource.md These examples show errors when the table_name argument is not a single character string or a DBI::Id object. ```R DBISource$new(db$conn, 123) ``` ```R DBISource$new(db$conn, c("table1", "table2")) ``` ```R DBISource$new(db$conn, list(name = "table")) ``` -------------------------------- ### Start Fresh QueryChat Console Conversation Source: https://context7.com/posit-dev/querychat/llms.txt Initiate a new, independent chat conversation in the QueryChat console by calling `console()` with `new=True`. This clears any previous conversation history. ```python # Start fresh conversation pc.console(new=True) ``` -------------------------------- ### Get Standalone QueryChat Client Source: https://context7.com/posit-dev/querychat/llms.txt Obtain a QueryChat client for programmatic data exploration outside of Shiny applications. This client provides access to QueryChat's tools. ```python from querychat import QueryChat import pandas as pd df = pd.DataFrame({ "product": ["A", "B", "C", "A", "B"], "sales": [100, 200, 150, 120, 180], "region": ["East", "West", "East", "West", "East"] }) pc = QueryChat(df, "sales_data") # Get client with all tools client = pc.client() ``` -------------------------------- ### Build Custom Shiny App Layout with QueryChat Source: https://context7.com/posit-dev/querychat/llms.txt Integrate QueryChat components into a custom Shiny application layout. Use `qc.sidebar()` for the chat sidebar and `qc.ui()` for the chat interface. This example demonstrates a custom UI with a title, data table, and SQL display. ```python from shiny import App, render, ui from querychat import QueryChat import pandas as pd df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) pc = QueryChat(df, "my_data") def app_ui(request): return ui.page_sidebar( pc.sidebar(width=400), # Chat in sidebar ui.card( ui.card_header(ui.output_text("title")), ui.output_data_frame("data_table") ), ui.card( ui.card_header("SQL Query"), ui.output_code("sql_display") ), title="Custom QueryChat App", fillable=True, ) def server(input, output, session): pc_vals = pc.server(enable_bookmarking=True) @render.data_frame def data_table(): return pc_vals.df() @render.text def title(): return pc_vals.title() or "Full Dataset" @render.code def sql_display(): return pc_vals.sql() or "SELECT * FROM my_data" app = App(app_ui, server, bookmark_store="url") ``` -------------------------------- ### test_query Column Validation: Missing Single Column Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md This example demonstrates the test_query column validation when require_all_columns is TRUE, and a single required column ('value') is missing from the query result. ```R source$test_query("SELECT id, name FROM test_table", require_all_columns = TRUE) ``` -------------------------------- ### Get Standalone Chat Client for Programmatic Use Source: https://context7.com/posit-dev/querychat/llms.txt Obtains a chat client object for programmatic interaction outside of a Shiny application. Allows asking questions and defining custom update callbacks. ```r library(querychat) pc <- QueryChat$new(mtcars) # Get chat client with tools chat <- qc$client() # Ask questions programmatically response <- chat$chat("What's the average mpg by cylinder count?") print(response) ``` ```r # Custom update callbacks chat <- qc$client( update_dashboard = function(query, title) { message("Filter: ", title) message("SQL: ", query) }, reset_dashboard = function() { message("Dashboard reset") } ) ``` -------------------------------- ### DataFrameSource$new() errors with invalid table names Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataFrameSource.md The `table_name` argument must be a valid SQL table name. It must start with a letter and contain only letters, numbers, and underscores. Empty strings or NULL are also invalid. ```R DataFrameSource$new(test_df, "123_invalid") ``` ```R DataFrameSource$new(test_df, "table-name") ``` ```R DataFrameSource$new(test_df, "table name") ``` ```R DataFrameSource$new(test_df, "") ``` ```R DataFrameSource$new(test_df, NULL) ``` -------------------------------- ### Documentation Build Commands Source: https://github.com/posit-dev/querychat/blob/main/CLAUDE.md Commands for building and previewing documentation for the project. ```bash # Build all documentation make docs ``` ```bash # Preview R docs make r-docs-preview ``` ```bash # Preview Python docs make py-docs-preview ``` -------------------------------- ### Initialize QueryChat with Sample Data Source: https://context7.com/posit-dev/querychat/llms.txt Instantiate the QueryChat class with sample data and a table name for basic usage. ```python from querychat import QueryChat from querychat.data import titanic import pandas as pd # Basic usage with sample data pc = QueryChat(titanic(), "titanic") ``` -------------------------------- ### Initialize QueryChat with Custom Configuration Source: https://context7.com/posit-dev/querychat/llms.txt Configure QueryChat with advanced options like custom greetings, LLM client, data descriptions, enabled tools, and categorical thresholds. ```python pc = QueryChat( df, "employees", greeting="Welcome! Ask me about employee data.", client="openai/gpt-4o", # or "anthropic/claude-sonnet-4-5" data_description="Employee records with demographic info", tools=("update", "query"), # Both tools enabled by default categorical_threshold=20 # Max unique values for categorical detection ) ``` -------------------------------- ### Initialize QueryChat application Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/README.md Create a QueryChat instance using a data source and launch the application interface. ```python from querychat import QueryChat from querychat.data import titanic qc = QueryChat(titanic(), "titanic") app = qc.app() # app.run() ``` -------------------------------- ### SEMANTIC_VIEW() Single Metric Query Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/prompts/semantic-views/syntax.md Retrieve a single total metric from a semantic view. This is useful for getting an overall value. ```sql SELECT * FROM SEMANTIC_VIEW(MODEL_NAME METRICS T_DATA.NET_REVENUE) ``` -------------------------------- ### Run Playwright E2E Tests via Makefile Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/tests/playwright/README.md Commands to initialize the environment and execute the full test suite. ```bash # Install playwright browsers (one-time setup) make py-e2e-setup # Run all tests (requires OPENAI_API_KEY) make py-e2e-tests ``` -------------------------------- ### Connect QueryChat to SQLite Database Source: https://context7.com/posit-dev/querychat/llms.txt Demonstrates connecting QueryChat to an in-memory SQLite database, writing data to it, and then initializing QueryChat with the connection. ```r library(querychat) library(DBI) library(RSQLite) # SQLite database con <- dbConnect(RSQLite::SQLite(), ":memory:") dbWriteTable(con, "mtcars", mtcars) pc <- QueryChat$new(con, "mtcars") pc$app() # Cleanup when done pc$cleanup() ``` -------------------------------- ### SEMANTIC_VIEW() Post-aggregation Filter Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/prompts/semantic-views/syntax.md Apply a WHERE clause outside SEMANTIC_VIEW() to filter results after metrics have been computed. This example filters for net revenue greater than 1,000,000. ```sql SELECT * FROM SEMANTIC_VIEW( MODEL_NAME METRICS T_DATA.NET_REVENUE DIMENSIONS REF_ENTITIES.ACC_TYPE_CD ) WHERE NET_REVENUE > 1000000 ``` -------------------------------- ### Manage querychat Connection in Shiny App Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/sqlite/README.md Demonstrates how to initialize the querychat server, render data, and clean up the database connection when a Shiny session ends. ```r server <- function(input, output, session) { # Initialize QueryChat server pc$server() # Your custom outputs here output$table <- renderTable(pc$df()) # Clean up connection when session ends session$onSessionEnded(function() { if (dbIsValid(conn)) { dbDisconnect(conn) } }) } ``` -------------------------------- ### SEMANTIC_VIEW() Pre-aggregation Filter Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/prompts/semantic-views/syntax.md Use the WHERE clause inside SEMANTIC_VIEW() to filter base data before metrics are computed. This example filters for accounts of type 'EXT'. ```sql SELECT * FROM SEMANTIC_VIEW( MODEL_NAME METRICS T_DATA.NET_REVENUE DIMENSIONS REF_ENTITIES.ACC_TYPE_CD WHERE REF_ENTITIES.ACC_TYPE_CD = 'EXT' ) ``` -------------------------------- ### Initialize QueryChat Client in Python Source: https://context7.com/posit-dev/querychat/llms.txt Initializes the QueryChat client with a DataFrame and specifies available tools. The 'update' tool allows the LLM to generate filter queries. ```python qc = QueryChat(df, "orders") client = qc.client(tools=("update",)) ``` -------------------------------- ### Query Tool for LLM Data Exploration (Python) Source: https://context7.com/posit-dev/querychat/llms.txt Demonstrates how to enable the 'query' tool for an LLM client in Python, allowing it to execute SQL queries against a data source. ```python # Python - tool is automatically registered pc = QueryChat(df, "sales") client = qc.client(tools=("query",)) # Only query tool # The LLM will generate SQL like: # SELECT region, AVG(amount) as avg_sales # FROM sales # GROUP BY region # ORDER BY avg_sales DESC ``` -------------------------------- ### Create and Run a QueryChat Shiny App Source: https://context7.com/posit-dev/querychat/llms.txt Generate a complete Shiny web application with a chat interface, SQL display, and data table view using the `app()` method. The `app.run()` command launches the application. ```python from querychat import QueryChat from querychat.data import titanic pc = QueryChat(titanic(), "titanic") # Create and run the app app = pc.app() # app.run() # Uncomment to launch ``` -------------------------------- ### Create a QueryChat Shiny App with Bookmarking Source: https://context7.com/posit-dev/querychat/llms.txt Enable bookmarking for the Shiny application to preserve state across sessions. Specify the bookmark store type (e.g., 'url'). ```python app = pc.app(bookmark_store="url") # Options: "url", "server", "disable" ``` -------------------------------- ### Connect to PostgreSQL Database with querychat Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/sqlite/README.md Connects to a PostgreSQL database and initializes a QueryChat instance. Requires DBI, RPostgreSQL (or RPostgres), and querychat libraries. ```r library(DBI) library(RPostgreSQL) # or library(RPostgres) library(querychat) # Connect to PostgreSQL conn <- dbConnect( RPostgreSQL::PostgreSQL(), # or RPostgres::Postgres() dbname = "your_database", host = "localhost", port = 5432, user = "your_username", password = "your_password" ) # Create QueryChat instance pc <- QueryChat$new(conn, "your_table_name") # Launch the app pc$app() ``` -------------------------------- ### querychat_app() Source: https://context7.com/posit-dev/querychat/llms.txt Launches a complete Shiny application for chatting with data. ```APIDOC ## querychat_app(data, ...) ### Description Launch a complete Shiny application for chatting with data in one line. ### Parameters #### Request Body - **data** (data.frame/DBI/tbl_sql) - Required - The data source to query. - **greeting** (string) - Optional - Custom greeting message. - **client** (string) - Optional - LLM client identifier. - **bookmark_store** (string) - Optional - Storage method for bookmarks. ### Request Example querychat_app(penguins, greeting = "Explore!", client = "anthropic/claude-sonnet-4-5") ``` -------------------------------- ### test_query Column Validation: Missing Columns Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md When require_all_columns is TRUE, test_query validates that the query result includes all original table columns. This example shows an error when 'name' and 'value' columns are missing. ```R source$test_query("SELECT id FROM test_table", require_all_columns = TRUE) ``` -------------------------------- ### Generate and Save Greeting Messages Source: https://context7.com/posit-dev/querychat/llms.txt Generates and saves welcome messages to a file, which can reduce startup latency for applications. Requires API access for generation. ```r library(querychat) pc <- QueryChat$new(mtcars) # Generate greeting (requires API access) greeting <- qc$generate_greeting(echo = "output") writeLines(greeting, "mtcars_greeting.md") # Use saved greeting in production pc_prod <- QueryChat$new( mtcars, greeting = "mtcars_greeting.md" ) ``` -------------------------------- ### Build Custom Shiny Apps with QueryChat UI Components Source: https://context7.com/posit-dev/querychat/llms.txt Enables building custom Shiny applications by integrating QueryChat's chat interface components into a Shiny UI. Requires Shiny and bslib libraries. ```r library(querychat) library(shiny) library(bslib) pc <- QueryChat$new(mtcars) ui <- page_sidebar( qc$sidebar(width = 400), card( card_header(textOutput("title")), DT::dataTableOutput("data") ), card( card_header("SQL Query"), verbatimTextOutput("sql") ) ) server <- function(input, output, session) { qc_vals <- qc$server(enable_bookmarking = TRUE) output$title <- renderText({ qc_vals$title() %||% "Full Dataset" }) output$data <- DT::renderDataTable({ qc_vals$df() }) output$sql <- renderText({ qc_vals$sql() %||% "SELECT * FROM mtcars" }) } shinyApp(ui, server, enableBookmarking = "url") ``` -------------------------------- ### Initialize QueryChat Client in R Source: https://context7.com/posit-dev/querychat/llms.txt Initializes the QueryChat client in R with a data object and specifies the 'update' tool. This enables the LLM to update the dashboard with filtered views. ```r qc <- QueryChat$new(orders, tools = "update") ``` -------------------------------- ### Generate and Save Greeting Messages Source: https://context7.com/posit-dev/querychat/llms.txt Create a reusable greeting message to minimize LLM latency during startup. Save the output to a file for production use. ```python from querychat import QueryChat from pathlib import Path qc = QueryChat(titanic(), "titanic") # Generate and save greeting greeting = qc.generate_greeting() Path("greeting.md").write_text(greeting) # Use saved greeting in production qc_prod = QueryChat( titanic(), "titanic", greeting=Path("greeting.md") ) ``` -------------------------------- ### Initialize R QueryChat Instance Source: https://context7.com/posit-dev/querychat/llms.txt Create QueryChat instances in R using R6 classes, supporting various configurations and privacy modes. ```r library(querychat) # Basic usage with data frame qc <- QueryChat$new(mtcars) # With table name for database-style reference qc <- QueryChat$new(mtcars, table_name = "cars") # With configuration options qc <- QueryChat$new( mtcars, greeting = "Welcome to the mtcars explorer!", client = "openai/gpt-4o", data_description = "Motor Trend Car Road Tests dataset", tools = c("update", "query"), categorical_threshold = 20 ) # Privacy mode - LLM cannot see raw data qc <- QueryChat$new(mtcars, tools = "update") # Using convenience function qc <- querychat(mtcars, greeting = "Hello!") ``` -------------------------------- ### Pre-aggregation vs Post-aggregation Filtering Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/src/querychat/prompts/semantic-views/syntax.md Demonstrates the difference between filtering data before or after metric computation. ```sql -- Pre-aggregation: only include 'EXT' accounts in the calculation SELECT * FROM SEMANTIC_VIEW( MODEL_NAME METRICS T_DATA.NET_REVENUE DIMENSIONS REF_ENTITIES.ACC_TYPE_CD WHERE REF_ENTITIES.ACC_TYPE_CD = 'EXT' ) -- Post-aggregation: compute all, then filter results SELECT * FROM SEMANTIC_VIEW( MODEL_NAME METRICS T_DATA.NET_REVENUE DIMENSIONS REF_ENTITIES.ACC_TYPE_CD ) WHERE NET_REVENUE > 1000000 ``` -------------------------------- ### Integrate with Streamlit Source: https://context7.com/posit-dev/querychat/llms.txt Utilize native Streamlit support with built-in session state management. ```python from querychat.streamlit import QueryChat import pandas as pd df = pd.DataFrame({ "category": ["A", "B", "A", "C", "B"], "value": [10, 20, 15, 30, 25] }) qc = QueryChat(df, "data") # Complete app qc.app() # Custom layout # qc.sidebar() # Chat in sidebar # st.header(qc.title() or "Data View") # st.dataframe(qc.df()) # st.code(qc.sql() or "SELECT * FROM data", language="sql") # if st.button("Reset"): # qc.reset() ``` -------------------------------- ### $client() Source: https://context7.com/posit-dev/querychat/llms.txt Provides a chat client for programmatic use outside of Shiny. ```APIDOC ## $client(update_dashboard, reset_dashboard) ### Description Get a chat client for programmatic use outside of Shiny, supporting custom update callbacks. ### Parameters #### Request Body - **update_dashboard** (function) - Optional - Callback for dashboard updates. - **reset_dashboard** (function) - Optional - Callback for dashboard resets. ### Response - **chat** (object) - A chat client object with a chat() method. ``` -------------------------------- ### Initialize QueryChat with Pandas DataFrame Source: https://context7.com/posit-dev/querychat/llms.txt Create a QueryChat instance using a pandas DataFrame. Ensure the DataFrame is properly formatted. ```python df = pd.DataFrame({ "name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35], "salary": [50000, 60000, 70000] }) pc = QueryChat(df, "employees") ``` -------------------------------- ### Query Tool for LLM Data Exploration (R) Source: https://context7.com/posit-dev/querychat/llms.txt Shows how the 'query' tool is automatically registered in R for QueryChat, enabling the LLM to generate and execute SQL queries. ```r # R - tool is automatically registered pc <- QueryChat$new(sales_data, tools = "query") # LLM generates and executes SQL queries ``` -------------------------------- ### QueryChat Class - Creating an Instance Source: https://context7.com/posit-dev/querychat/llms.txt The QueryChat class is the main entry point for initializing the data exploration tool. It supports various data sources like pandas DataFrames, polars DataFrames/LazyFrames, Ibis Tables, SQLAlchemy engines, and PyArrow Tables, along with custom configurations. ```APIDOC ## QueryChat Class - Creating an Instance ### Description The `QueryChat` class is the main entry point for building natural language data applications. It accepts various data sources including pandas DataFrames, polars DataFrames/LazyFrames, Ibis Tables, SQLAlchemy engines, and PyArrow Tables. ### Method `QueryChat(data_source, table_name, **kwargs)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for Initialization - **data_source**: (pandas.DataFrame, polars.DataFrame, polars.LazyFrame, ibis.Table, sqlalchemy.engine.Engine, pyarrow.Table) - The data source to query. - **table_name**: (str) - The name of the table. - **greeting**: (str, optional) - A custom greeting message for the chat interface. - **client**: (str, optional) - The LLM client to use (e.g., "openai/gpt-4o", "anthropic/claude-sonnet-4-5"). - **data_description**: (str, optional) - A description of the data for the LLM. - **tools**: (tuple, optional) - A tuple of enabled tools (e.g., ("update", "query")). Defaults to both enabled. - **categorical_threshold**: (int, optional) - The maximum number of unique values for a column to be considered categorical. ### Request Example ```python from querychat import QueryChat from querychat.data import titanic import pandas as pd # Basic usage with sample data qc = QueryChat(titanic(), "titanic") # With pandas DataFrame df = pd.DataFrame({ "name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35], "salary": [50000, 60000, 70000] }) pc = QueryChat(df, "employees") # With custom configuration pc = QueryChat( df, "employees", greeting="Welcome! Ask me about employee data.", client="openai/gpt-4o", data_description="Employee records with demographic info", tools=("update", "query"), categorical_threshold=20 ) # Privacy-focused mode pc = QueryChat(df, "employees", tools="update") ``` ### Response None (This is a constructor) ``` -------------------------------- ### Initialize Shiny Express QueryChat Source: https://context7.com/posit-dev/querychat/llms.txt Use the express module for automatic server logic initialization in Shiny Express applications. ```python from querychat.express import QueryChat from shiny.express import render, ui import pandas as pd df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) qc = QueryChat(df, "my_data") # Automatically creates sidebar with chat qc.sidebar() with ui.card(): @render.data_frame def data_view(): return qc.df() # Reactive accessor @render.text def current_filter(): return qc.title() or "Showing all data" ui.page_opts(title="Express QueryChat", fillable=True) ``` -------------------------------- ### Integrate with Dash Source: https://context7.com/posit-dev/querychat/llms.txt Create Dash applications with QueryChat's natural language interface and callback registration. ```python from querychat.dash import QueryChat from dash import Dash, html, Input, Output import pandas as pd df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) qc = QueryChat(df, "my_table") # Quick app app = qc.app() # app.run() # Custom layout custom_app = Dash(__name__) custom_app.layout = html.Div([ qc.ui(height="500px", width="400px"), html.Pre(id="sql-display"), html.Div(id="data-info"), ]) qc.init_app(custom_app) # Register callbacks @custom_app.callback( Output("sql-display", "children"), Output("data-info", "children"), Input(qc.store_id, "data") ) def update_displays(state): sql = qc.sql(state) or "SELECT * FROM my_table" df = qc.df(state) return sql, f"Rows: {len(df)}" ``` -------------------------------- ### QueryChat$new() Source: https://context7.com/posit-dev/querychat/llms.txt Initializes a new QueryChat object for data interaction. ```APIDOC ## QueryChat$new(data, table_name, ...) ### Description Creates a new QueryChat instance to manage data source connections and LLM interactions. ### Parameters #### Request Body - **data** (object) - Required - Data source (data.frame, DBI connection, or dbplyr tbl). - **table_name** (string) - Optional - Name of the table for the data source. ### Request Example qc <- QueryChat$new(mtcars) ``` -------------------------------- ### QueryChat Module Server Function Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/examples-shiny/03-module-app/README.md In the corresponding server function, pass the unwrapped ID to `qc$server()` to connect to the UI component. ```r module_server <- function(id) { moduleServer(id, function(input, output, session) { qc_vals <- qc$server(id = "qc-ui") # Use unwrapped ID # ... rest of server logic }) } ``` -------------------------------- ### Enable Reset Tool in Python Source: https://context7.com/posit-dev/querychat/llms.txt Initializes QueryChat with 'update' and 'query' tools enabled. This makes the reset functionality automatically available, allowing users to reset filters or view all data. ```python qc = QueryChat(df, "data", tools=("update", "query")) ``` -------------------------------- ### Basic SEMANTIC_VIEW() Syntax Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/prompts/semantic-views/syntax.md This is the fundamental structure for using the SEMANTIC_VIEW() function. It allows specifying metrics, dimensions, and optional filters. ```sql SELECT * FROM SEMANTIC_VIEW( {view_name} METRICS {logical_table}.{metric_name} DIMENSIONS {logical_table}.{dimension_name} [WHERE {dimension} = 'value'] -- Optional: pre-aggregation filter ) [WHERE {column} = 'value'] -- Optional: post-aggregation filter ``` -------------------------------- ### DataSource Abstract Method: test_query Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md The test_query method is an abstract method in the DataSource base class and must be implemented by any subclass. Calling it directly on the base class will result in a not_implemented_error. ```R base_source$test_query("SELECT * FROM test LIMIT 1") ``` -------------------------------- ### Connect Data Sources Source: https://context7.com/posit-dev/querychat/llms.txt QueryChat supports various data backends including SQLAlchemy engines, Ibis tables, Polars LazyFrames, and PyArrow tables. ```python from querychat import QueryChat from sqlalchemy import create_engine import ibis import polars as pl # SQLAlchemy database connection engine = create_engine("postgresql://user:pass@localhost/mydb") qc = QueryChat(engine, "customers") # Ibis Table (DuckDB, PostgreSQL, BigQuery, etc.) conn = ibis.duckdb.connect("mydata.db") table = conn.table("sales") qc = QueryChat(table, "sales") # Polars LazyFrame (lazy evaluation) lf = pl.scan_parquet("large_dataset.parquet") qc = QueryChat(lf, "dataset") # PyArrow Table import pyarrow as pa arrow_table = pa.table({"a": [1, 2, 3], "b": [4, 5, 6]}) qc = QueryChat(arrow_table, "arrow_data") ``` -------------------------------- ### Initialize QueryChat in Privacy-Focused Mode Source: https://context7.com/posit-dev/querychat/llms.txt Set up QueryChat to prevent the LLM from accessing raw data, suitable for sensitive information. Only the 'update' tool is enabled by default in this mode. ```python pc = QueryChat(df, "employees", tools="update") ``` -------------------------------- ### DataSource Abstract Method: execute_query Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md The execute_query method is an abstract method in the DataSource base class and must be implemented by any subclass. Calling it directly on the base class will result in a not_implemented_error. ```R base_source$execute_query("SELECT * FROM test") ``` -------------------------------- ### tool_query() Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/querychat_tools.md Executes a query against a data source. ```APIDOC ## tool_query() ### Description Performs a query operation. ### Parameters - **data_source** (DataSource) - Required - Must be a object. ``` -------------------------------- ### DataSource Abstract Method: cleanup Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md The cleanup method is an abstract method in the DataSource base class and must be implemented by any subclass. Calling it directly on the base class will result in a not_implemented_error. ```R base_source$cleanup() ``` -------------------------------- ### QueryChat.sidebar() and QueryChat.ui() - Custom Layouts Source: https://context7.com/posit-dev/querychat/llms.txt Provides components for building custom Shiny applications. `sidebar()` returns a bslib sidebar component, and `ui()` returns only the chat interface. ```APIDOC ## QueryChat.sidebar() and QueryChat.ui() ### Description For building custom Shiny applications, `sidebar()` returns a bslib sidebar component and `ui()` returns just the chat interface. ### Method `sidebar(**kwargs)` `ui(**kwargs)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `sidebar()` and `ui()` - **width**: (int, optional) - The width of the sidebar. - ****kwargs**: Additional arguments passed to the underlying Shiny UI components. ### Request Example ```python from shiny import App, render, ui from querychat import QueryChat import pandas as pd df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) pc = QueryChat(df, "my_data") def app_ui(request): return ui.page_sidebar( qc.sidebar(width=400), # Chat in sidebar ui.card( ui.card_header(ui.output_text("title")), ui.output_data_frame("data_table") ), ui.card( ui.card_header("SQL Query"), ui.output_code("sql_display") ), title="Custom 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 "Full Dataset" @render.code def sql_display(): return qc_vals.sql() or "SELECT * FROM my_data" app = App(app_ui, server, bookmark_store="url") ``` ### Response - **sidebar()**: (bslib.sidebar) - A bslib sidebar component. - **ui()**: (shiny.ui.TagList) - A list of UI elements for the chat interface. ``` -------------------------------- ### Connect QueryChat to Database using dbplyr Source: https://context7.com/posit-dev/querychat/llms.txt Shows how to connect QueryChat to a database table represented as a dbplyr tbl_sql object. ```r library(querychat) library(dplyr) library(dbplyr) tbl_cars <- tbl(con, "mtcars") pc <- QueryChat$new(tbl_cars, "mtcars") ``` -------------------------------- ### DataSource Abstract Method: get_data Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md The get_data method is an abstract method in the DataSource base class and must be implemented by any subclass. Calling it directly on the base class will result in a not_implemented_error. ```R base_source$get_data() ``` -------------------------------- ### Integrate with Gradio Source: https://context7.com/posit-dev/querychat/llms.txt Build natural language data exploration interfaces using Gradio blocks. ```python from querychat.gradio import QueryChat import pandas as pd import gradio as gr df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) qc = QueryChat(df, "my_table") # Quick app app = qc.app() # app.launch() # Custom layout with gr.Blocks() as custom_app: with gr.Row(): with gr.Column(): state = qc.ui() # Returns gr.State with gr.Column(): data_table = gr.Dataframe() sql_display = gr.Code(language="sql") def update_outputs(state_dict): return qc.df(state_dict).to_native(), qc.sql(state_dict) or "" state.change( fn=update_outputs, inputs=[state], outputs=[data_table, sql_display], ) # custom_app.launch(css=qc.css, head=qc.head) ``` -------------------------------- ### DataSource Abstract Method: get_schema Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/tests/testthat/_snaps/DataSource.md The get_schema method is an abstract method in the DataSource base class and must be implemented by any subclass. Calling it directly on the base class will result in a not_implemented_error. ```R base_source$get_schema() ``` -------------------------------- ### Execute SQL Query Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/src/querychat/prompts/tool-query.md This endpoint executes a SQL SELECT query against the database and returns the raw result data for analysis. It is designed for data analysis, aggregation, and calculations. ```APIDOC ## POST /posit-dev/querychat ### Description Executes a {{db_type}} SQL SELECT query against the database and returns the raw result data for analysis. ### Method POST ### Endpoint /posit-dev/querychat ### Parameters #### Request Body - **query** (string) - Required - A valid {{db_type}} SQL SELECT statement. Must follow the database schema provided in the system prompt. Use clear column aliases (e.g., 'AVG(price) AS avg_price') and include SQL comments for complex logic. Subqueries and CTEs are encouraged for readability. - **_intent** (string) - Required - A brief, user-friendly description of what this query calculates or retrieves. ### Request Example { "query": "SELECT COUNT(*) AS total_records FROM users WHERE status = 'active';", "_intent": "Count the number of active users." } ### Response #### Success Response (200) - **results** (object) - The tabular data results from executing the SQL query. #### Response Example { "results": [ { "total_records": 150 } ] } ``` -------------------------------- ### QueryChat.console() - Interactive Terminal Chat Source: https://context7.com/posit-dev/querychat/llms.txt Launches an interactive console-based chat session for data exploration directly within the terminal. ```APIDOC ## QueryChat.console() ### Description Launch an interactive console-based chat session for exploring data directly in the terminal. ### Method `console(new=True)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `console()` - **new**: (bool, optional) - If True, starts a new conversation. If False, continues the previous conversation. Defaults to True. ### Request Example ```python from querychat import QueryChat from querychat.data import titanic pc = QueryChat(titanic(), "titanic") # Start interactive console chat pc.console() # Continue previous conversation pc.console(new=False) # Start fresh conversation pc.console(new=True) ``` ### Response None (This method starts an interactive session). ``` -------------------------------- ### Programmatic Chat with QueryChat Client Source: https://context7.com/posit-dev/querychat/llms.txt Interact with the QueryChat client programmatically by sending chat messages and printing the responses. This allows for automated data analysis. ```python # Chat programmatically response = client.chat("What's the average sales by product?") print(response) ``` -------------------------------- ### DuckDB Quantile Function Syntax Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/src/querychat/prompts/prompt.md Use the concise quantile functions in DuckDB instead of the standard ordered set aggregate syntax. ```sql -- Standard SQL syntax (works but verbose) percentile_cont(0.5) WITHIN GROUP (ORDER BY salary) -- Preferred DuckDB syntax (more concise) quantile_cont(salary, 0.5) ``` -------------------------------- ### POST /posit-dev/querychat Source: https://github.com/posit-dev/querychat/blob/main/pkg-py/src/querychat/prompts/tool-update-dashboard.md Executes a SQL SELECT query to filter or sort dashboard data. This tool is suitable for requests involving showing a subset of data or reordering it. ```APIDOC ## POST /posit-dev/querychat ### Description Executes a {{db_type}} SQL SELECT query to filter or sort the data used in the dashboard. This tool is appropriate for any request that involves showing a subset of the data or reordering it. ### Method POST ### Endpoint /posit-dev/querychat ### Parameters #### Request Body - **query** (string) - Required - A {{db_type}} SQL SELECT query that MUST return all existing schema columns (use SELECT * or explicitly list all columns). May include additional computed columns, subqueries, CTEs, WHERE clauses, ORDER BY, and any {{db_type}}-supported SQL functions. - **title** (string) - Required - A brief title for display purposes, summarizing the intent of the SQL query. ### Request Example { "query": "SELECT * FROM \"sales_data\" WHERE \"region\" = 'North' ORDER BY \"order_date\" DESC", "title": "Recent North Region Sales" } ### Response #### Success Response (200) - **message** (string) - A confirmation that the dashboard was updated successfully. #### Error Response (400/500) - **error** (string) - The error that occurred when running the SQL query. #### Response Example { "message": "Dashboard data updated successfully." } ``` -------------------------------- ### SEMANTIC_VIEW() Multiple Metrics and Dimensions Source: https://github.com/posit-dev/querychat/blob/main/pkg-r/inst/prompts/semantic-views/syntax.md Retrieve multiple metrics and group them by multiple dimensions. This provides a comprehensive view of the data. ```sql SELECT * FROM SEMANTIC_VIEW( MODEL_NAME METRICS T_DATA.NET_REVENUE, T_DATA.GROSS_REVENUE DIMENSIONS REF_ENTITIES.ACC_TYPE_CD, T_DATA.LOG_DT ) ORDER BY LOG_DT ASC ``` -------------------------------- ### QueryChat Client with Custom Callbacks Source: https://context7.com/posit-dev/querychat/llms.txt Configure the QueryChat client with custom callback functions for dashboard updates and resets. These callbacks are triggered by specific events during the chat interaction. ```python # Custom callbacks for dashboard updates def on_update(data): print(f"Filter applied: {data['title']}") print(f"SQL: {data['query']}") def on_reset(): print("Dashboard reset to show all data") client = pc.client( update_dashboard=on_update, reset_dashboard=on_reset ) ```