### SKILL.md Frontmatter Example Source: https://context7.com/streamlit/agent-skills/llms.txt Example of YAML frontmatter for a SKILL.md file, including name, description, license, and metadata. ```yaml --- name: building-streamlit-dashboards # Lowercase, hyphens only, max 64 chars description: > Building dashboards in Streamlit. Use when creating KPI displays, metric cards, or data-heavy layouts. Covers borders, cards, responsive layouts, and dashboard composition. license: Apache-2.0 metadata: author: streamlit tags: [dashboard, metrics, layout] --- ``` -------------------------------- ### Run Streamlit Example App Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md Run the example application using Streamlit. This is the final step to test the custom component's functionality and rendering. ```bash streamlit run example.py ``` -------------------------------- ### Generate New CCv2 Component Project Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md This command is the required starting point for every packaged CCv2 component. Ensure you have uv and cookiecutter installed. ```bash uvx --from cookiecutter cookiecutter gh:streamlit/component-template --directory cookiecutter/v2 ``` -------------------------------- ### Launch Streamlit Demo App Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Start the built-in Streamlit demo application by running the 'streamlit hello' command. ```bash streamlit hello ``` -------------------------------- ### Install Custom Component (Bash) Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-custom-components/SKILL.md Use this command to install a custom component from PyPI. The package name might differ from the repository name. ```bash uv add ``` -------------------------------- ### SKILL.md Frontmatter and Instructions Source: https://github.com/streamlit/agent-skills/blob/main/CONTRIBUTING.md Example of the `SKILL.md` file structure, including YAML frontmatter with name and description, followed by markdown instructions. ```yaml --- name: skill-name description: A clear description of what this skill does and when to use it. --- # Skill Instructions Your instructions here... ``` -------------------------------- ### Run a Streamlit Template Locally Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/templates/apps/README.md Navigate to a template directory, install dependencies using uv, and run the Streamlit app. ```bash cd templates/apps/dashboard-metrics uv pip install -e . uv run streamlit run streamlit_app.py ``` -------------------------------- ### Run a theme locally Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/templates/themes/README.md Navigate to a theme's directory and use `uv` to install dependencies and run the Streamlit app locally. ```bash cd templates/themes/spotify uv sync uv run streamlit run streamlit_app.py ``` -------------------------------- ### Install Streamlit Agent Skills for Snowflake Cortex Code Source: https://github.com/streamlit/agent-skills/blob/main/README.md Install the agent skill directly from GitHub using the Cortex CLI. ```bash cortex skill add streamlit/agent-skills ``` -------------------------------- ### pyproject.toml Example for Streamlit Project Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/setting-up-streamlit-environment/SKILL.md An example `pyproject.toml` file for a Streamlit project managed with uv. It specifies project metadata, Python version, and core dependencies including Streamlit. ```toml [project] name = "my-streamlit-app" version = "0.1.0" requires-python = ">=3.11" dependencies = [ "streamlit>=1.53.0", "plotly>=5.0.0", "snowflake-connector-python>=3.0.0", ] [tool.uv] dev-dependencies = [ "pytest>=8.0.0", ] ``` -------------------------------- ### Install Skills for AI Assistants Source: https://context7.com/streamlit/agent-skills/llms.txt Commands to copy a skill folder to the appropriate directory for Claude Code or Cursor. ```bash # Claude Code cp -r developing-with-streamlit ~/.claude/skills/ ``` ```bash # Cursor cp -r developing-with-streamlit ~/.cursor/skills/ ``` ```bash # Snowflake Cortex Code (install directly from GitHub) cortex skill add streamlit/agent-skills ``` -------------------------------- ### Snowflake Brand Theme Example Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md A comprehensive example of a Streamlit theme configured to match the Snowflake brand. ```toml [theme] primaryColor = "#29B5E8" backgroundColor = "#ffffff" secondaryBackgroundColor = "#f4f9fc" codeBackgroundColor = "#e8f4f8" textColor = "#11567F" linkColor = "#29B5E8" borderColor = "#d0e8f2" showWidgetBorder = true showSidebarBorder = true baseRadius = "8px" buttonRadius = "8px" font = "'Inter':https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" codeFontSize = "13px" codeTextColor = "#11567F" baseFontSize = 14 baseFontWeight = 400 headingFontSizes = ["32px", "24px", "20px", "16px", "14px", "12px"] headingFontWeights = [600, 600, 600, 500, 500, 500] linkUnderline = false chartCategoricalColors = ["#29B5E8", "#11567F", "#71C8E5", "#174D6A", "#A5DDF2", "#0E4D6B", "#52B8D9"] blueColor = "#29B5E8" greenColor = "#36B37E" yellowColor = "#FFAB00" redColor = "#DE350B" violetColor = "#6554C0" dataframeBorderColor = "#d0e8f2" dataframeHeaderBackgroundColor = "#e8f4f8" [theme.sidebar] backgroundColor = "#11567F" secondaryBackgroundColor = "#174D6A" codeBackgroundColor = "#0E4D6B" textColor = "#ffffff" borderColor = "#1E6D94" ``` -------------------------------- ### Create Virtual Environment with uv Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/setting-up-streamlit-environment/SKILL.md Quickly create a virtual environment for simple Streamlit apps using uv. Activate the environment and install Streamlit. ```bash uv venv source .venv/bin/activate # or .venv\Scripts\activate on Windows uv pip install streamlit ``` -------------------------------- ### Build Frontend Assets Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md Build the frontend assets for the custom component. This step is crucial for ensuring that the `asset_dir` contains the necessary files before installation and use. ```bash npm i npm run build ``` -------------------------------- ### Copy Skill Template Source: https://github.com/streamlit/agent-skills/blob/main/CONTRIBUTING.md Use this command to copy the skill template to start developing a new skill. ```bash cp -r template developing-with-streamlit/skills/my-new-skill ``` -------------------------------- ### Streamlit CLI - Version, Help, Docs Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Utility commands for Streamlit CLI: 'streamlit version' to check the installed version, 'streamlit help' to list commands, and 'streamlit docs' to open the documentation. ```bash streamlit version ``` ```bash streamlit help ``` ```bash streamlit docs ``` -------------------------------- ### Complementary Color Palette Example Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Example of a theme using a brand primary color with supporting accent colors for different states. ```toml primaryColor = "#29B5E8" # Brand blue (Snowflake) textColor = "#11567F" # Darker blue for text greenColor = "#36B37E" # Success states redColor = "#DE350B" # Error states ``` -------------------------------- ### Inline Quickstart: State and Trigger Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/SKILL.md Implement a minimal bidirectional communication loop between JavaScript and Python using `setStateValue` for persistent state and `setTriggerValue` for events. Python re-hydrates the UI via `data=...` on each run. Use multi-line strings for inline JS/CSS and query under `parentElement` to prevent cross-instance leakage. ```python import streamlit as st HTML = """""" JS = """ export default function (component) { const { data, parentElement, setStateValue, setTriggerValue } = component const input = parentElement.querySelector("#txt") const btn = parentElement.querySelector("#btn") if (!input || !btn) return const nextValue = (data && data.value) ?? "" if (input.value !== nextValue) input.value = nextValue input.oninput = (e) => { setStateValue("value", e.target.value) } btn.onclick = () => { setTriggerValue("submitted", input.value) } } """ my_text_input = st.components.v2.component( "my_inline_text_input", html=HTML, js=JS, ) KEY = "txt-1" component_state = st.session_state.get(KEY, {}) value = component_state.get("value", "") result = my_text_input( key=KEY, data={"value": value}, on_value_change=lambda: None, # optional; include to always get `result.value` on_submitted_change=lambda: None, # optional; include to always get `result.submitted` ) st.write("value (state):", result.value) st.write("submitted (trigger):", result.submitted) ``` -------------------------------- ### Packaged Component Development Checklist Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md A checklist to guide the development and debugging of packaged custom components, helping to prevent common loading failures. ```text Packaged CCv2 checklist - [ ] Generate project from `component-template` v2 - [ ] Confirm this is template-generated (not hand-scaffolded, not copied from internet snippets) - [ ] Activate the target project environment before Python/uv commands - [ ] Rename template defaults (`streamlit-component-x`, `streamlit_component_x`, etc.) if needed - [ ] Build frontend assets into the manifest’s `asset_dir` (template: `frontend/build/`) - [ ] Editable install the Python package (`uv pip install -e . --force-reinstall`) - [ ] Verify `js=`/`css=` globs match exactly one file each under `asset_dir` - [ ] Run via `streamlit run ...` and confirm the component renders/events work - [ ] If something breaks: read `references/troubleshooting.md`, fix, rebuild, re-verify glob uniqueness ``` -------------------------------- ### Brand Accent Color Palette Example Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Example of a theme using a neutral base with a single brand accent color. ```toml primaryColor = "#635bff" # Brand purple backgroundColor = "#ffffff" textColor = "#425466" # Neutral gray ``` -------------------------------- ### GitHub-Flavored Markdown Example Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-markdown/SKILL.md Demonstrates standard GitHub-flavored Markdown syntax including headings, bold, italic, strikethrough, inline code, links, lists, task lists, tables, blockquotes, and code blocks. ```python st.markdown(""" # Heading **Bold**, *italic*, ~~strikethrough~~, `inline code`, [links](url) - Unordered list - [x] Task list | Column | Column | |--------|--------| | Cell | Cell | > Blockquote ```python code_block = "with syntax highlighting" ``` ") ``` -------------------------------- ### Streamlit App Directory Structure Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/organizing-streamlit-code/SKILL.md Example directory structure for organizing a Streamlit application into main script, page modules, and utility modules. ```tree my-app/ ├── streamlit_app.py # Main entry point ├── app_pages/ # Page UI modules │ ├── dashboard.py │ └── settings.py └── utils/ # Business logic & helpers ├── data.py └── api.py ``` -------------------------------- ### Separating UI from Logic in Streamlit Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/organizing-streamlit-code/SKILL.md Example of a Streamlit app file that focuses on UI elements and imports business logic from utility modules. ```python # streamlit_app.py - UI-focused import streamlit as st from utils.data import load_sales_data, compute_metrics st.title("Sales Dashboard") start = st.date_input("Start") end = st.date_input("End") data = load_sales_data(start, end) metrics = compute_metrics(data) st.metric("Revenue", f"${metrics['revenue']:,.0f}") st.dataframe(data) ``` -------------------------------- ### Component Registration Key Example Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md The Python registration key for a component must precisely match the component's name defined in the manifest. This ensures Streamlit can correctly identify and load the component. ```python st.components.v2.component(".", ...) ``` -------------------------------- ### Editable Install Python Package Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md Perform an editable install of the Python package. This command ensures that changes made to the Python code are immediately reflected without needing to reinstall. ```bash uv pip install -e . --force-reinstall ``` -------------------------------- ### Run Streamlit App with Specific Port Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/SKILL.md Execute this command to start a Streamlit application, specifying the server port. This is useful for ensuring your app runs on a predictable port. ```bash streamlit run [path/to/app.py] --server.port 8501 ``` -------------------------------- ### Build Streamlit Custom Components v2 Source: https://context7.com/streamlit/agent-skills/llms.txt Author bidirectional HTML/JS/CSS components using the v2 API. This example shows basic state and trigger handling between Python and JavaScript. ```python import streamlit as st from collections.abc import Callable # Inline quickstart — bidirectional state + trigger HTML = "" JS = """ export default function (component) { const { data, parentElement, setStateValue, setTriggerValue } = component const input = parentElement.querySelector("#txt") const btn = parentElement.querySelector("#btn") if (!input || !btn) return // Hydrate from Python → JS if (input.value !== (data?.value ?? "")) input.value = data?.value ?? "" // JS → Python (state: persists across reruns) input.oninput = (e) => setStateValue("value", e.target.value) // JS → Python (trigger: one-shot event) btn.onclick = () => setTriggerValue("submitted", input.value) } """ ``` -------------------------------- ### Run Streamlit Apps Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Use 'streamlit run' to start your Streamlit application. It can run a default app, a specific file, or a remote script via URL. It can also be run as a Python module. ```bash streamlit run ``` ```bash streamlit run app.py ``` ```bash streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py ``` ```bash python -m streamlit run app.py ``` -------------------------------- ### Load Data with Streamlit Caching Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/templates/apps/README.md Employ `st.cache_data` to cache data loading functions, improving performance by avoiding redundant computations. Set a Time-To-Live (TTL) for the cache. This example shows a placeholder for data loading, which should be replaced with actual data retrieval logic. ```python @st.cache_data(ttl=3600) def load_metric_data() -> pd.DataFrame: """Load metric data. Replace with your actual data source.""" # Replace this with: # - Snowflake query via st.connection("snowflake") # - API call # - Database query return generate_synthetic_data() ``` -------------------------------- ### Initialize Full Project with uv Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/setting-up-streamlit-environment/SKILL.md Set up a new Streamlit project with reproducible builds using `uv init`. This creates a `pyproject.toml`, `uv.lock`, and a virtual environment. ```bash uv init my-streamlit-app cd my-streamlit-app uv add streamlit ``` -------------------------------- ### Monochromatic Color Palette Example Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Example of a monochromatic color scheme using variations of a single hue. ```toml primaryColor = "#18181B" textColor = "#09090B" borderColor = "#E4E4E7" grayColor = "#71717A" ``` -------------------------------- ### Streamlit Project Scaffolding Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Initialize a new Streamlit project with starter files using the 'streamlit init' command. ```bash streamlit init ``` -------------------------------- ### Using `default` for Initializing Component State Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/state-sync.md This Python snippet demonstrates how to use the `default` argument when mounting a component to initialize its state. Remember that every key in `default` must have a corresponding `on__change` callback parameter. ```python result = _COMPONENT( key=key, data={"value": value}, default={"value": value}, on_value_change=lambda: None, # required if using default["value"] ) ``` -------------------------------- ### Add Dependencies with uv Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/setting-up-streamlit-environment/SKILL.md Install additional Python packages into your Streamlit project using uv. Use `uv pip install` for venv approaches or `uv add` for projects initialized with `uv init`. ```bash # With venv approach uv pip install plotly snowflake-connector-python # With full project (uv init) uv add plotly snowflake-connector-python ``` -------------------------------- ### Suggestion Chips for Onboarding Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-chat-ui/SKILL.md Provides clickable suggestion chips that disappear after the first user message, offering a clean onboarding experience. ```python SUGGESTIONS = { ":blue[:material/help:] What is Streamlit?": "Explain what Streamlit is", ":green[:material/code:] Show me an example": "Show a simple Streamlit example", } # Only show before first message - they disappear after if not st.session_state.messages: selected = st.pills("Try asking:", list(SUGGESTIONS.keys()), label_visibility="collapsed") if selected: # Use the selection as the first prompt prompt = SUGGESTIONS[selected] st.session_state.messages.append({"role": "user", "content": prompt}) st.rerun() ``` -------------------------------- ### Script Output Conventions Source: https://context7.com/streamlit/agent-skills/llms.txt Example of a shell script that writes status messages to stderr and machine-readable JSON output to stdout. ```bash # scripts/process.sh echo "Processing files..." >&2 python process.py | jq '.' # JSON to stdout ``` -------------------------------- ### Basic Theme Configuration Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Configure basic theme elements like link underlines. ```toml [theme] linkUnderline = false # Remove underlines for cleaner look ``` -------------------------------- ### Create New Skill Directory Source: https://github.com/streamlit/agent-skills/blob/main/CLAUDE.md Command to copy the skill template to create a new skill directory. Use lowercase, hyphen-separated names, preferably in gerund form. ```bash cp -r template skills/my-new-skill ``` -------------------------------- ### Run Streamlit App with uv init Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/setting-up-streamlit-environment/SKILL.md Execute a Streamlit application within a project initialized with `uv init`, using `uv run` to manage the environment. ```bash uv run streamlit run streamlit_app.py ``` -------------------------------- ### Initialize Multiple Session State Variables Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-session-state/SKILL.md It's good practice to initialize all necessary session state variables at the top of your application for clarity and to ensure they exist when needed. ```python st.session_state.setdefault("user", None) st.session_state.setdefault("page", "home") st.session_state.setdefault("filters", {}) ``` -------------------------------- ### View Streamlit Configuration Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Display all current Streamlit configuration settings by running the 'streamlit config show' command. ```bash streamlit config show ``` -------------------------------- ### Create New Streamlit Skill Source: https://context7.com/streamlit/agent-skills/llms.txt Steps to scaffold a new skill from a template, edit its SKILL.md, and register it. ```bash # 1. Copy template cp -r template developing-with-streamlit/skills/my-new-skill # 2. Edit SKILL.md — replace frontmatter and add instructions # 3. Register in developing-with-streamlit/SKILL.md routing table # 4. Add to README.md "Available skills" table ``` -------------------------------- ### Build Chat Interface with Snowflake Cortex LLMs Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/connecting-streamlit-to-snowflake/SKILL.md Integrate Snowflake Cortex LLMs into a Streamlit chat interface using `snowflake.cortex.complete`. This example demonstrates streaming responses and managing chat history. ```python import streamlit as st from snowflake.cortex import complete st.set_page_config(page_title="AI Assistant", page_icon=":sparkles:") if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: with st.chat_message(msg["role"]): st.write(msg["content"]) if prompt := st.chat_input("Ask anything"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.write(prompt) with st.chat_message("assistant"): response = st.write_stream( complete( "claude-3-5-sonnet", prompt, session=st.connection("snowflake").session(), stream=True, ) ) st.session_state.messages.append({"role": "assistant", "content": response}) ``` -------------------------------- ### Build Streamlit dashboards with KPI cards and charts Source: https://context7.com/streamlit/agent-skills/llms.txt This snippet demonstrates how to build a Streamlit dashboard using containers, metrics, charts, and dataframes. It includes horizontal containers for KPIs, a two-column layout for charts, and a data table. ```python import streamlit as st import pandas as pd # Sample data rev_trend = [980, 1020, 1050, 1100, 1150, 1180, 1200] user_trend = [640, 680, 700, 720, 740, 755, 762] # KPI row — horizontal container wraps on small screens with st.container(horizontal=True): st.metric("Revenue", "$1.2M", "+12%", border=True, chart_data=rev_trend, chart_type="line") st.metric("Users", "762k", "+7.4%", border=True, chart_data=user_trend, chart_type="line") st.metric("Churn", "3.1%", "-0.4%", border=True, delta_color="inverse") # Two-column chart grid col1, col2 = st.columns(2) with col1: with st.container(border=True): st.subheader("Revenue by Region") st.bar_chart(pd.DataFrame({"region": ["US","EU","APAC"], "revenue": [600, 400, 200]}).set_index("region")) with col2: with st.container(border=True): st.subheader("Monthly Trend") st.line_chart(pd.DataFrame({"month": range(1, 8), "value": rev_trend}).set_index("month")) # Data table with st.container(border=True): st.subheader("Recent Orders") st.dataframe( pd.DataFrame({"Order": ["#001","#002","#003"], "Amount": [120, 340, 89], "Status": ["Shipped","Pending","Delivered"]}), hide_index=True, ) # Sidebar filters with st.sidebar: import datetime date_range = st.date_input("Date range", value=(datetime.date(2024, 1, 1), datetime.date.today())) region = st.multiselect("Region", ["US", "EU", "APAC"], default=["US", "EU", "APAC"]) ``` -------------------------------- ### Organize content using tabs Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-layouts/SKILL.md Use `st.tabs` to create switchable views for organizing content. Each tab can contain different Streamlit elements. ```python tab1, tab2 = st.tabs(["Chart", "Data"]) with tab1: st.line_chart(data) with tab2: st.dataframe(df) ``` -------------------------------- ### Create Responsive KPI Rows with Horizontal Containers Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-dashboards/SKILL.md Use `st.container(horizontal=True)` to create rows of metrics that adapt to different screen sizes. This is preferred over `st.columns` for metric rows as they wrap on smaller screens. ```python with st.container(horizontal=True): st.metric("Revenue", "$1.2M", "-7%", border=True) st.metric("Users", "762k", "+12%", border=True) st.metric("Orders", "1.4k", "+5%", border=True) ``` -------------------------------- ### Check for Running Streamlit Apps Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/SKILL.md Use this command to list running Streamlit applications on ports starting with 850. It filters processes by name and port, and provides a fallback message if none are found. ```bash lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null | grep -i python | awk '{print $2, $9}' | grep ':85' || echo "No Streamlit apps detected on ports 850*" ``` -------------------------------- ### Combine Multiple Streamlit Configuration Options Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Apply multiple configuration settings simultaneously using command-line flags. This allows for fine-grained control over the Streamlit server and client behavior. ```bash streamlit run app.py \ --server.port=8080 \ --server.headless=true \ --theme.primaryColor=blue \ --client.showErrorDetails=false ``` -------------------------------- ### Activate Project Environment Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md Activate the target project environment before running Python/uv commands. This ensures that all dependencies and configurations are correctly loaded. ```bash source /path/to/project/.venv/bin/activate ``` -------------------------------- ### Streamlit Multi-Page App Main Module Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-multipage-apps/SKILL.md This is the main entry point for a multi-page Streamlit app. It initializes global state, defines the navigation structure, and runs the selected page. Ensure individual pages do not redefine titles if handled here. ```python # streamlit_app.py import streamlit as st # Initialize global state (shared across pages) if "api_client" not in st.session_state: st.session_state.api_client = init_api_client() # Define navigation page = st.navigation([ st.Page("app_pages/home.py", title="Home", icon=":material/home:"), st.Page("app_pages/analytics.py", title="Analytics", icon=":material/bar_chart:"), st.Page("app_pages/settings.py", title="Settings", icon=":material/settings:"), ]) # App-level UI runs before page content # Useful for shared elements like titles st.title(f"{page.icon} {page.title}") page.run() ``` -------------------------------- ### Run Streamlit App with uv Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/setting-up-streamlit-environment/SKILL.md Execute your Streamlit application using the `streamlit run` command within an activated uv virtual environment. ```bash streamlit run streamlit_app.py ``` -------------------------------- ### Manage Streamlit session state with callbacks and keys Source: https://context7.com/streamlit/agent-skills/llms.txt This snippet demonstrates how to manage Streamlit session state by initializing state variables, implementing callbacks for button clicks, and automatically syncing widget values to session state using keys. ```python import streamlit as st # Initialize state at the top — setdefault is idempotent st.session_state.setdefault("count", 0) st.session_state.setdefault("user", None) # Callback executes BEFORE the next script run def increment(amount: int): st.session_state.count += amount st.button("Add 5", on_click=increment, args=(5,)) st.button("Add 10", on_click=increment, args=(10,)) st.write("Count:", st.session_state.count) # Widget key → synced automatically to session state name = st.text_input("Name", key="user_name") # st.session_state.user_name == name (always in sync) ``` -------------------------------- ### Basic Chat Structure in Streamlit Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-chat-ui/SKILL.md Sets up a basic chat interface by managing message history in session state, displaying messages, and handling user input with `st.chat_input`. ```python import streamlit as st if "messages" not in st.session_state: st.session_state.messages = [] # Display chat history for msg in st.session_state.messages: with st.chat_message(msg["role"]): st.write(msg["content"]) # Handle new input if prompt := st.chat_input("Ask a question"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.write(prompt) with st.chat_message("assistant"): response = get_response(prompt) # Your LLM call st.write(response) st.session_state.messages.append({"role": "assistant", "content": response}) ``` -------------------------------- ### Verify Manifest Asset Glob Matching Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/packaged-components.md Ensure that the `js=` and `css=` globs registered in Python match exactly one file within the `asset_dir`. If multiple files match, clean the build output and rebuild. ```text Typical: `js="index-*.js"` and `css="index-*.css"` If multiple matches: clean the build output (template: `npm run clean`) and rebuild. ``` -------------------------------- ### Resource Cleanup with @st.cache_resource(on_release) Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/optimizing-streamlit-performance/SKILL.md Use the `on_release` argument in `@st.cache_resource` to specify a cleanup function that will be called when the cached resource is evicted. ```python def cleanup_connection(conn): conn.close() @st.cache_resource(on_release=cleanup_connection) def get_database(): return create_connection() ``` -------------------------------- ### Fetch Streamlit Documentation Source: https://github.com/streamlit/agent-skills/blob/main/AGENTS.md Command to fetch the latest Streamlit documentation in markdown format, optimized for LLMs. This is crucial for ensuring skills use current API practices. ```bash curl -o llms-full.txt https://docs.streamlit.io/llms-full.txt ``` -------------------------------- ### Streamlit Navigation with Ungrouped Pages Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-multipage-apps/SKILL.md Use an empty string key `""` to place pages at the beginning of the navigation, before any named sections. All ungrouped pages should be within this single key. ```python page = st.navigation({ "": [ st.Page("app_pages/home.py", title="Home"), st.Page("app_pages/about.py", title="About"), ], "Analytics": [ st.Page("app_pages/dashboard.py", title="Dashboard"), st.Page("app_pages/reports.py", title="Reports"), ], }, position="top") ``` -------------------------------- ### Create columns with specified ratios Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-layouts/SKILL.md Use `st.columns` to divide the main area into multiple columns. You can specify the number of columns or their relative widths. ```python col1, col2 = st.columns(2) ``` ```python col1, col2 = st.columns([2, 1]) # 2:1 ratio ``` ```python cols = st.columns(4, vertical_alignment="center") ``` -------------------------------- ### Skill Directory Structure Source: https://github.com/streamlit/agent-skills/blob/main/CONTRIBUTING.md Illustrates the standard directory structure for a skill, including required and optional directories. ```tree skill-name/ ├── SKILL.md # Required - skill instructions ├── scripts/ # Optional - executable code (Python, Bash, JavaScript) ├── references/ # Optional - additional documentation └── assets/ # Optional - static resources (templates, images, data files) ``` -------------------------------- ### Initialize and Access Session State Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-session-state/SKILL.md Initialize session state variables using `setdefault` for preferred handling or by checking for key existence. Access and update values using attribute or bracket notation. Be aware that accessing uninitialized keys raises a `KeyError`; use `.get()` for safe access. ```python st.session_state.setdefault("count", 0) if "count" not in st.session_state: st.session_state.count = 0 current = st.session_state.count st.session_state.count += 1 st.session_state["count"] = 5 del st.session_state.count ``` -------------------------------- ### Self-Host Custom Fonts Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Load custom fonts from a `static/` directory using `[[theme.fontFaces]]`. Ensure font files are correctly placed and accessible. Changes require a server restart. ```toml [[theme.fontFaces]] family = "CustomFont" url = "app/static/CustomFont-Regular.woff2" weight = 400 [[theme.fontFaces]] family = "CustomFont" url = "app/static/CustomFont-Bold.woff2" weight = 700 [theme] font = "CustomFont" ``` -------------------------------- ### Control container width and height Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-layouts/SKILL.md Use the `height` and `width` arguments in `st.container` to control sizing. 'stretch' makes columns equal height, 'content' shrinks to content size, and pixel values set fixed dimensions. ```python # Stretch to fill available space (equal height columns) cols = st.columns(2) with cols[0].container(border=True, height="stretch"): st.line_chart(data) with cols[1].container(border=True, height="stretch"): st.dataframe(df) # Shrink to content size st.container(width="content") # Fixed pixel sizes st.container(height=300) ``` -------------------------------- ### Define Multiple Snowflake Connections Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/connecting-streamlit-to-snowflake/SKILL.md Configure multiple Snowflake connections by defining separate sections in `.streamlit/secrets.toml`, such as `[connections.snowflake]` and `[connections.snowflake_staging]`. Instantiate them using their respective names. ```toml # .streamlit/secrets.toml [connections.snowflake] account = "prod_account" # ... prod credentials [connections.snowflake_staging] account = "staging_account" # ... staging credentials ``` -------------------------------- ### Configure Snowflake Credentials with st.secrets Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/connecting-streamlit-to-snowflake/SKILL.md Store Snowflake credentials in `.streamlit/secrets.toml` for secure access. Ensure `account` and `host` values are derived from `snow connection list` to prevent redirection issues. ```toml # .streamlit/secrets.toml [connections.snowflake] account = "ORGNAME-ACCTNAME" # from `snow connection list` host = "myaccount.snowflakecomputing.com" # from `snow connection list` (include if present) user = "your_user" authenticator = "externalbrowser" warehouse = "your_warehouse" database = "your_database" schema = "your_schema" ``` -------------------------------- ### Selectbox for Many Options (Single Select) Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/choosing-streamlit-selection-widgets/SKILL.md Use `st.selectbox` when dealing with a large number of options for single selection, as dropdowns scale better than visible controls for long lists. ```python country = st.selectbox( "Select a country", ["USA", "UK", "Canada", "Germany", "France", ...] ) ``` -------------------------------- ### Programmatic Page Navigation with Button Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-multipage-apps/SKILL.md Use `st.switch_page` within a button click or other event handler to navigate the user to a different page programmatically. Provide the file path to the target page. ```python if st.button("Go to Settings"): st.switch_page("app_pages/settings.py") ``` -------------------------------- ### Configure Streamlit Themes Source: https://context7.com/streamlit/agent-skills/llms.txt Customize application themes using .streamlit/config.toml for brand alignment without custom CSS. Supports light/dark modes and semantic colors. ```toml # .streamlit/config.toml [theme] # Base — override only what you need base = "light" primaryColor = "#0969da" # Buttons, links, active elements backgroundColor = "#ffffff" secondaryBackgroundColor = "#f6f8fa" textColor = "#1F2328" linkColor = "#0969da" borderColor = "#d0d7de" # Typography — Google Fonts via URL font = "Inter:https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" codeFont = "'JetBrains Mono':https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&display=swap" baseFontSize = 14 headingFontSizes = ["32px", "24px", "20px", "16px", "14px", "12px"] headingFontWeights = [600, 600, 600, 500, 500, 500] linkUnderline = false # Shape baseRadius = "8px" showWidgetBorder = true # Semantic palette (used in st.markdown colored text, badges, sparklines) greenColor = "#1a7f37" redColor = "#cf222e" blueColor = "#0969da" # Chart colors chartCategoricalColors = ["#0969da","#1a7f37","#bf3989","#8250df","#cf222e"] # Sidebar — independent styling [theme.sidebar] backgroundColor = "#f6f8fa" secondaryBackgroundColor = "#eaeef2" textColor = "#1F2328" borderColor = "#d0d7de" ``` ```toml [theme.light] primaryColor = "#0969da" backgroundColor = "#ffffff" textColor = "#1F2328" [theme.dark] primaryColor = "#58a6ff" backgroundColor = "#0d1117" secondaryBackgroundColor = "#161b22" textColor = "#e6edf3" ``` -------------------------------- ### Shared Widgets Pattern in Multipage Apps Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-session-state/SKILL.md Place common widgets, like theme selectors, in the entrypoint file of a multipage app to ensure they are available and their state is managed consistently across all pages. ```python # app.py (entrypoint) with st.sidebar: st.session_state.theme = st.selectbox("Theme", ["Light", "Dark"]) nav = st.navigation(pages) nav.run() ``` -------------------------------- ### JavaScript Recommended: True Sync Hydration Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/building-streamlit-custom-components-v2/references/state-sync.md This JavaScript code demonstrates the recommended approach for true state synchronization. It reconciles the UI from `data.value` on every render and only writes to the input when the value has actually changed, ensuring Python updates are reflected. ```javascript const nextValue = data.value ?? "" if (input.value !== nextValue) input.value = nextValue ``` -------------------------------- ### Configure Theme Colors Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Define primary, background, secondary, and text colors for the Streamlit app. Ensure `primaryColor` has sufficient contrast for white text. ```toml [theme] primaryColor = "#0969da" # Buttons, links, active elements backgroundColor = "#ffffff" # Main content background secondaryBackgroundColor = "#f6f8fa" # Widget backgrounds, code blocks textColor = "#1F2328" # Body text # Optional refinements linkColor = "#0969da" # Markdown links (defaults to primaryColor) codeTextColor = "#1F2328" # Inline code text codeBackgroundColor = "#f6f8fa" # Code block background borderColor = "#d0d7de" # Widget borders ``` -------------------------------- ### Build Streamlit Chat UI with OpenAI Source: https://context7.com/streamlit/agent-skills/llms.txt Python code using Streamlit and OpenAI to create a basic chat interface with message history and suggestion chips. ```python import streamlit as st from openai import OpenAI client = OpenAI() # Initialize history st.session_state.setdefault("messages", []) # Pre-conversation suggestion chips SUGGESTIONS = { ":blue[:material/help:] What is Streamlit?": "Explain what Streamlit is", ":green[:material/code:] Show me an example": "Show a simple Streamlit example", } if not st.session_state.messages: selected = st.pills("Try asking:", list(SUGGESTIONS.keys()), label_visibility="collapsed") if selected: st.session_state.messages.append({"role": "user", "content": SUGGESTIONS[selected]}) st.rerun() # Render history for msg in st.session_state.messages: with st.chat_message(msg["role"]): st.markdown(msg["content"]) ``` -------------------------------- ### Snowflake deployment configuration Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/templates/themes/README.md Before deploying to Snowflake, update the `snowflake.yml` file with your account-specific resources like compute pools and external access integrations. ```yaml # Find available compute pools SHOW COMPUTE POOLS; # Find available external access integrations SHOW EXTERNAL ACCESS INTEGRATIONS; ``` -------------------------------- ### Run Streamlit Apps with uv Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-cli/SKILL.md Use 'uv run' to execute Streamlit within a managed virtual environment, automatically handling dependencies. This is the recommended approach for reproducible environments. ```bash uv run streamlit run app.py ``` ```bash uv run streamlit run app.py --server.headless=true ``` ```bash uv run streamlit run app.py -- arg1 arg2 ``` -------------------------------- ### Use empty placeholders for dynamic content Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/using-streamlit-layouts/SKILL.md Use `st.empty()` to create a placeholder that can be updated or cleared later. This is useful for showing loading states or updating content dynamically. ```python placeholder = st.empty() # Update the placeholder placeholder.text("Loading...") result = load_data() placeholder.dataframe(result) # Clear it placeholder.empty() ``` -------------------------------- ### Connect to Snowflake with Streamlit Source: https://context7.com/streamlit/agent-skills/llms.txt Use st.connection for secrets-based credentials, parameterized queries, and caller's-rights access. Cached queries refresh automatically. ```python import streamlit as st from datetime import timedelta # Connection (pooled, reconnects automatically, reads .streamlit/secrets.toml) conn = st.connection("snowflake") # Cached query — refresh every 10 minutes @st.cache_data(ttl=timedelta(minutes=10)) def load_sales(region: str) -> "pd.DataFrame": return conn.query( "SELECT date, revenue FROM sales WHERE region = :region ORDER BY date", params={"region": region}, # Parameterized — prevents SQL injection ) # Caller's-rights connection — viewer sees only data their Snowflake role allows conn_cr = st.connection("snowflake", type="snowflake-callers-rights") # Write data session = conn.session() session.write_pandas(load_sales("US"), "SALES_BACKUP", auto_create_table=True) # Chat with Snowflake Cortex from snowflake.cortex import complete if prompt := st.chat_input("Ask about sales"): with st.chat_message("assistant"): response = st.write_stream( complete("claude-3-5-sonnet", prompt, session=conn.session(), stream=True) ) ``` ```toml [connections.snowflake] account = "ORGNAME-ACCTNAME" # from `snow connection list` host = "myaccount.snowflakecomputing.com" user = "your_user" authenticator = "externalbrowser" warehouse = "COMPUTE_WH" database = "ANALYTICS" schema = "PUBLIC" ``` -------------------------------- ### Display Streamlit Data with Charts and DataFrames Source: https://context7.com/streamlit/agent-skills/llms.txt Visualize data using Streamlit's native charts, Altair for complex visualizations, and `st.dataframe` with `column_config` for rich, interactive data tables. ```python import streamlit as st import pandas as pd import altair as alt df = pd.DataFrame({ "name": ["Alice", "Bob", "Carol"], "revenue": [12000, 8500, 21000], "completion": [87, 62, 95], "url": ["https://alice.example", "https://bob.example", "https://carol.example"], "trend": [[100,110,105,120], [80,85,90,88], [200,210,215,220]], }) # Native chart — prefer for simple cases st.bar_chart(df, x="name", y="revenue", x_label="Sales Rep", y_label="Revenue ($)") # Altair — for multi-series with custom axes chart = ( alt.Chart(df) .mark_bar() .encode( x=alt.X("name:N", title="Sales Rep"), y=alt.Y("revenue:Q", title="Revenue ($)"), color=alt.Color("name:N", legend=None), tooltip=["name", "revenue"], ) ) st.altair_chart(chart, use_container_width=True) # Rich dataframe with column config st.dataframe( df, column_config={ "revenue": st.column_config.NumberColumn("Revenue", format="$%d"), "completion": st.column_config.ProgressColumn("Progress", min_value=0, max_value=100), "url": st.column_config.LinkColumn("Profile"), "trend": st.column_config.LineChartColumn("Trend", y_min=0, y_max=250), "name": st.column_config.TextColumn("Name", pinned=True), }, hide_index=True, use_container_width=True, ) ``` -------------------------------- ### Script Output Conventions Source: https://github.com/streamlit/agent-skills/blob/main/CLAUDE.md Guideline for writing executable scripts: status messages to stderr and machine-readable output (JSON) to stdout. ```bash echo 'Processing...' >&2 ``` -------------------------------- ### Build Streamlit Multi-Page Apps Source: https://context7.com/streamlit/agent-skills/llms.txt Structure multi-page Streamlit applications using `st.navigation`, manage shared state with `st.session_state`, and implement conditional page rendering and programmatic routing. ```python # streamlit_app.py — entry point import streamlit as st # Global state (runs before every page) st.session_state.setdefault("api_client", init_api_client()) st.session_state.setdefault("user", get_current_user()) # Build pages list — conditionally include admin page pages = [ st.Page("app_pages/home.py", title="Home", icon=":material/home:"), st.Page("app_pages/analytics.py", title="Analytics", icon=":material/bar_chart:"), ] if st.session_state.user.is_admin: pages.append(st.Page("app_pages/admin.py", title="Admin", icon=":material/settings:")) page = st.navigation(pages, position="top") # "sidebar" for many pages / sections # Shared header rendered on all pages st.title(f"{page.icon} {page.title}") page.run() # ── app_pages/analytics.py ────────────────────────────────────────────────── import streamlit as st # Prefix page-specific state keys to avoid collisions st.session_state.setdefault("analytics_range", 30) api = st.session_state.api_client data = api.fetch_analytics(days=st.session_state.analytics_range) st.line_chart(data) # Programmatic navigation if st.button("Go to Home"): st.switch_page("app_pages/home.py") ``` -------------------------------- ### Streamlit theme configuration Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/templates/themes/README.md Configure your Streamlit theme by defining base, primary color, background colors, text color, and fonts in the `.streamlit/config.toml` file. ```toml [theme] base = "dark" # "dark" or "light" primaryColor = "#1DB954" # Buttons, links, highlights backgroundColor = "#121212" # Main background secondaryBackgroundColor = "#181818" # Sidebar, cards textColor = "#FFFFFF" # Main text color font = "Inter" # Body font codeFont = "FiraCode" # Code blocks ``` -------------------------------- ### Ensure Sufficient Text Contrast Source: https://github.com/streamlit/agent-skills/blob/main/developing-with-streamlit/skills/creating-streamlit-themes/SKILL.md Verify that text colors have adequate contrast against their backgrounds for readability. This is crucial for accessibility. ```toml # BAD: Light gray text on white textColor = "#CCCCCC" backgroundColor = "#FFFFFF" # GOOD: Dark text on light background textColor = "#1F2328" backgroundColor = "#FFFFFF" ```