### Full ExplorerUI Configuration Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/ui.md A comprehensive example demonstrating the setup of ExplorerUI with a Snowflake data source, custom LLM, analysis agent, tools, title, suggestions, logging, and log level. ```python import lumen.ai as lmai from lumen.sources.snowflake import SnowflakeSource source = SnowflakeSource( account='acme', database='sales', authenticator='externalbrowser' ) llm = lmai.llm.OpenAI( model_kwargs={ 'default': {'model': 'gpt-4o-mini'}, 'sql': {'model': 'gpt-4o'}, } ) analysis_agent = lmai.agents.AnalysisAgent(analyses=[MyAnalysis]) ui = lmai.ExplorerUI( data=source, llm=llm, agents=[analysis_agent], tools=[my_tool], title='Sales Analytics', suggestions=[ ("trending_up", "Revenue trends"), ("people", "Top customers"), ], log_level='INFO', logs_db_path='logs.db' ) ui.servable() ``` -------------------------------- ### Build a Basic Report with Custom Actions Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/reports.md This example demonstrates building a report by defining a custom Action for visualization and using SQLQuery for aggregation. It passes data through shared context and renders an interactive Vega-Lite chart. Ensure Panel and Lumen libraries are installed. ```python import pandas as pd import panel as pn from lumen.ai.llm import OpenAI from lumen.ai.report import Action, Report, Section from lumen.ai.actions import SQLQuery from lumen.pipeline import Pipeline from lumen.sources.duckdb import DuckDBSource from lumen.views import VegaLiteView pn.extension("vega") class MonthlyRevenue(Action): async def _execute(self, context, **kwargs): df = pd.DataFrame({"month": ["Jan", "Feb", "Mar"], "revenue": [100000, 125000, 150000]}) source = DuckDBSource.from_df(tables={"q1": df}) pipeline = Pipeline(source=source, table="q1") chart = VegaLiteView( pipeline=pipeline, spec={ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "mark": "bar", "encoding": {"x": {"field": "month", "type": "ordinal"}, "y": {"field": "revenue", "type": "quantitative"}}, "width": "container", }, sizing_mode="stretch_width", height=400, ) return [chart], {"source": source} report = Report( Section( MonthlyRevenue(title="Monthly Revenue"), SQLQuery( sql_expr=""" SELECT SUM(CASE WHEN month = 'Jan' THEN revenue ELSE 0 END) AS jan, SUM(CASE WHEN month = 'Feb' THEN revenue ELSE 0 END) AS feb, SUM(CASE WHEN month = 'Mar' THEN revenue ELSE 0 END) AS mar, SUM(revenue) AS total FROM q1 """, table="q1_total", llm=OpenAI(), ), title="Q1 Revenue Report", ), title="Sales Report", ) await report.execute() report.show() ``` -------------------------------- ### Full Configuration Example Source: https://github.com/holoviz/lumen/blob/main/docs/getting_started/building_lumen_apps.md This example shows a comprehensive Lumen AI application configuration. It includes custom agents, tools, analyses, LLM overrides, semantic search, and UI customizations. This setup allows for advanced data analysis and interaction. ```python import lumen.ai as lmai from lumen.ai.agents import SourceAgent from lumen.ai.analyses import Analysis from lumen.ai.controls import CodeSourceControls, UploadSourceControls from lumen.ai.coordinator import Planner from lumen.ai.embeddings import OpenAIEmbeddings from lumen.ai.vector_store import DuckDBVectorStore import pandas as pd # Custom tool def calculate_growth(current: float, previous: float) -> float: """Calculate percentage growth between two values.""" return ((current - previous) / previous) * 100 if previous else 0.0 # Custom analysis class CorrelationAnalysis(Analysis): async def analyze(self, pipeline, **kwargs): return pipeline.data.select_dtypes(include='number').corr() # Custom data fetcher def fetch_sales(region: str = "US", year: int = 2024): """Fetch sales data.""" return pd.read_csv(f"sales_{region}_{year}.csv") # LLM with per-agent model overrides llm = lmai.llm.OpenAI( model_kwargs={ "default": {"model": "gpt-4.1-mini", "temperature": 0.2}, "sql": {"model": "gpt-4.1", "temperature": 0.1}, } ) # Semantic search (optional) vector_store = DuckDBVectorStore(uri='embeddings.db', embeddings=OpenAIEmbeddings()) ui = lmai.ExplorerUI( # Data sources (file paths, Source, or Pipeline objects) data=['customers.csv', 'orders.csv'], # LLM configuration llm=llm, # Agents (extend default agents: TableListAgent, ChatAgent, SQLAgent, etc.) agents=[SourceAgent()], # Source controls for fetching external data source_controls=[ CodeSourceControls(functions={"Fetch Sales": fetch_sales}), UploadSourceControls(), ], # Custom tools the LLM can invoke tools=[calculate_growth], # Custom analyses for the AnalysisAgent analyses=[CorrelationAnalysis], # Coordinator for planning responses coordinator=Planner, # Mostly unnecessary unless you want to customize the planning algorithm coordinator_params={}, # Vector stores for semantic search vector_store=vector_store, document_vector_store=None, # Separate store for document search, else uses same vector store # UI customization title='Sales Analytics', suggestions=[ ('search', 'What data is available?'), ('bar_chart', 'Show sales by region'), ], # Predefined suggestions for users to click on # Code execution: 'hidden', 'disabled', 'prompt', 'llm', 'allow' code_execution='prompt', # Export configuration notebook_preamble='# Generated by Sales Analytics App', export_functions={}, # Logging log_level='INFO', # 'DEBUG', 'INFO', 'WARNING', 'ERROR' logfire_tags=['sales', 'analytics'], # Tags for logfire tracing logs_db_path=None, # Path to store LLM message logs # File upload settings filedropper_kwargs={'max_file_size': '100MB'}, upload_handlers={}, # Custom handlers by file extension # Page configuration (panel-material-ui Page component) page_config={}, ) u.servable() ``` -------------------------------- ### Install Lumen with AI Navigator Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install Lumen with support for AI Navigator. Ensure AI Navigator is running and its API server is started. ```bash pip install 'lumen[ai-openai]' ``` ```bash export AINAVIGATOR_BASE_URL=http://localhost:8080/v1 ``` -------------------------------- ### Install Required Packages Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/weather_data_ai_explorer.md Install Lumen AI, MetPy, and Panel for building the weather data explorer. ```bash pip install lumen-ai metpy panel matplotlib ``` -------------------------------- ### Run Precipitation Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/gallery/precip.md Execute the Lumen example by serving the saved precipitation.yaml file. This command will launch the visualization. ```bash lumen serve precipitation.yaml --show ``` -------------------------------- ### Enable and Start systemd Service Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Commands to enable the systemd service to start on boot and to start it immediately. ```bash sudo systemctl enable lumen-dashboard sudo systemctl start lumen-dashboard ``` -------------------------------- ### Complete Lumen Configuration Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/cli.md Example of a complete Lumen CLI configuration for serving a CSV file with specific LLM and agent settings. ```bash lumen-ai serve penguins.csv \ --provider openai \ --model 'gpt-4o-mini' \ --model-kwargs '{"sql": {"model": "gpt-4o"}}' \ --temperature 0.5 \ --agents SQLAgent ChatAgent VegaLiteAgent \ --port 8080 \ --show ``` -------------------------------- ### Test Serving Dashboard in CI/CD Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Example CI/CD workflow step to test serving the Lumen dashboard. It starts the dashboard in the background and then attempts to access it via `curl`. ```bash # .github/workflows/test.yml - name: Test serving run: | lumen serve dashboard.yaml --port 5006 & sleep 5 curl http://localhost:5006/ ``` -------------------------------- ### Run Earthquakes Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/gallery/earthquakes.md Use this command to serve the earthquakes example locally. Ensure the YAML file is saved as 'earthquakes.yaml' in the current directory. ```bash lumen serve earthquakes.yaml --show ``` -------------------------------- ### Set Up Lumen Development Environment Source: https://github.com/holoviz/lumen/blob/main/docs/contributing.md Commands to install Lumen and its test dependencies using either pixi (recommended) or pip. ```bash # Using pixi (recommended) pixi install # Or using pip pip install -e ".[tests]" ``` -------------------------------- ### Start Lumen AI Server Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/cli.md Launches the Lumen AI server. By default, it starts at `localhost:5006`. ```bash lumen-ai serve ``` -------------------------------- ### Install Packages and Set API Key Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/massive_stock_explorer.md Install the necessary Lumen and Massive packages and set your Massive API key as an environment variable. ```bash pip install lumen-ai massive export MASSIVE_API_KEY="your_api_key_here" ``` -------------------------------- ### Development Environment Variables Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Example `.env` file for development environment settings. ```bash APP_TITLE="Development Dashboard" DATABASE_URL="sqlite:///dev.db" DEBUG=true ``` -------------------------------- ### Start Lumen Explorer Server Source: https://github.com/holoviz/lumen/blob/main/README.md Run this command to start a Lumen Explorer server. Replace `data.csv` with the path to your data file. ```bash lumen-ai serve data.csv ``` -------------------------------- ### Production Environment Variables Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Example `.env` file for production environment settings. ```bash APP_TITLE="Production Dashboard" DATABASE_URL="postgresql://prod-server/db" DEBUG=false ``` -------------------------------- ### Install Lumen Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/penguins_dashboard_spec.md Install the Lumen library using pip. This is a prerequisite for running Lumen dashboards. ```bash pip install lumen ``` -------------------------------- ### Full Mesonet Weather Explorer Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/mesonet_weather_explorer.md This complete example integrates preprocessing for station codes and provides improved labels for the Mesonet Daily data source control. It sets up an ExplorerUI for interacting with weather data. ```python """ Mesonet Weather Explorer - Full Example Fetches daily weather data from Iowa Environmental Mesonet """ import datetime import param from lumen.ai.agents import SourceAgent from lumen.ai.controls import URLSourceControls, UploadSourceControls from lumen.ai.ui import ExplorerUI class MesonetDailyControls(URLSourceControls): """ Fetch daily weather observations from the Iowa Environmental Mesonet for one or more ASOS/AWOS stations. Data includes high/low temperature, precipitation, average wind speed, and other daily summary fields. """ url_template = ( "https://mesonet.agron.iastate.edu/cgi-bin/request/daily.py" "?stations={stations}&network={network}&sts={sts}&ets={ets}&format=csv" ) stations = param.String( default="SEA", doc="FAA station identifier(s), comma-separated (e.g. 'ORD', 'SEA,PDX'). " "A leading 'K' ICAO prefix is stripped automatically.", ) network = param.Selector( default="WA_ASOS", objects=[ "CA_ASOS", "CO_ASOS", "FL_ASOS", "GA_ASOS", "IL_ASOS", "MA_ASOS", "MI_ASOS", "MN_ASOS", "NY_ASOS", "OH_ASOS", "OR_ASOS", "PA_ASOS", "TX_ASOS", "WA_ASOS", ], doc="IEM network code for the state ASOS network.", ) sts = param.CalendarDate( default=datetime.date.today() - datetime.timedelta(days=7), doc="Start date for the data request.", ) ets = param.CalendarDate( default=datetime.date.today() - datetime.timedelta(days=1), doc="End date for the data request (exclusive). " "Note: today's daily summary may not be available until tomorrow.", ) label = ( '' "thermostat" " IEM Mesonet Daily" ) async def _fetch_data(self, action_name: str, **params) -> "SourceResult": # IEM uses 3-letter FAA codes; strip the ICAO 'K' prefix users often add raw = params.get("stations", "") params["stations"] = ",".join( s[1:] if len(s) == 4 and s.startswith("K") else s for s in (t.strip() for t in raw.split(',')) ) return await super()._fetch_data(action_name, **params) ui = ExplorerUI( agents=[SourceAgent()], source_controls=[MesonetDailyControls(), UploadSourceControls()], title="Weather Data Explorer", log_level="DEBUG", ) ui.servable() ``` -------------------------------- ### Complete Pipeline Example (Python) Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/pipelines.md Constructs a data pipeline programmatically using Python, mirroring the declarative YAML example. ```python from lumen.pipeline import Pipeline pipeline = Pipeline.from_spec({ 'source': { 'type': 'file', 'tables': { 'data': 'https://datasets.holoviz.org/penguins/v1/penguins.csv' } }, 'filters': [ {'type': 'widget', 'field': 'species'}, {'type': 'widget', 'field': 'island'}, {'type': 'widget', 'field': 'sex'}, ], 'transforms': [ {'type': 'aggregate', 'method': 'mean', 'by': ['species', 'sex', 'year']} ] }) pipeline.data # Preview the result ``` -------------------------------- ### Install Lumen with LiteLLM Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install the LiteLLM provider for Lumen. This enables support for over 100 models across various LLM providers. ```bash pip install 'lumen[ai-litellm]' ``` -------------------------------- ### Install Lumen with Ollama Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install Lumen with the necessary dependencies for Ollama integration. Ensure Ollama is installed and a model is pulled. ```bash pip install 'lumen[ai-ollama]' ``` ```bash ollama pull qwen3:32b ``` ```bash export OLLAMA_BASE_URL=http://localhost:11434 ``` -------------------------------- ### List Dependencies in requirements.txt Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Example of a `requirements.txt` file listing all necessary Python packages for the project, including Lumen, Panel, and Hvplot. ```txt lumen panel hvplot # Add other dependencies ``` -------------------------------- ### Serve Data from Databases Source: https://github.com/holoviz/lumen/blob/main/docs/quick_start.md Command-line examples for connecting to and serving data from various database types using Lumen. ```bash lumen serve postgresql://user:pass@localhost/mydb lumen serve mysql://user:pass@localhost/mydb lumen serve sqlite:///data.db ``` -------------------------------- ### Install Lumen AI and Panel Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/saas_company_report_dashboard.md Install the necessary packages for Lumen AI and Panel to build interactive dashboards and reports. ```bash pip install lumen-ai panel ``` -------------------------------- ### Install Lumen with Pip Source: https://github.com/holoviz/lumen/blob/main/README.md Use this command to install Lumen using pip. The `[ai]` extra installs additional dependencies for AI-related features. ```bash pip install 'lumen[ai]' ``` -------------------------------- ### Install Lumen AI Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/mesonet_weather_explorer.md Install the necessary lumen-ai package using pip. ```bash pip install lumen-ai ``` -------------------------------- ### Install Lumen with OpenRouter Support Source: https://github.com/holoviz/lumen/blob/main/docs/quick_start.md Install the Lumen package with OpenRouter integration. Set the OPENROUTER_API_KEY environment variable before running. ```bash pip install 'lumen[ai-openrouter]' export OPENROUTER_API_KEY=sk-or-... ``` -------------------------------- ### Install kagglehub package Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/controls.md Command to install the 'kagglehub' package, which is required for Kaggle URL support in DownloadControls. ```bash pip install kagglehub ``` -------------------------------- ### Full Massive Stock Explorer Example with param_overrides Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/massive_stock_explorer.md This example demonstrates a full stock market explorer using the Massive SDK and Lumen. It utilizes `param_overrides` to provide richer widgets for parameters like 'ticker', 'timespan', 'multiplier', 'from_', 'to', and 'limit'. ```python """ Stock Market Explorer - Full Example Massive SDK with param_overrides for richer widgets """ import os import param from massive import RESTClient from lumen.ai.agents import SourceAgent from lumen.ai.controls import CodeSourceControls, UploadSourceControls from lumen.ai.ui import ExplorerUI client = RESTClient(api_key=os.environ["MASSIVE_API_KEY"]) controls = CodeSourceControls( instance=client, methods=["list_aggs", "get_last_trade", "get_ticker_details"], param_overrides={ "list_aggs": { # (1)! "ticker": param.Selector( # (2)! default="AAPL", objects=["AAPL", "MSFT", "NVDA", "GOOGL", "TSLA", "AMZN"], ), "timespan": param.Selector( default="day", objects=["minute", "hour", "day", "week", "month"], ), "multiplier": {"default": 1, "bounds": (1, 100)}, # (3)! "from_": {"default": "2024-01-01"}, "to": {"default": "2024-12-31"}, "limit": {"default": 5000, "bounds": (1, 50000)}, }, }, skip_params=frozenset({"self", "cls", "return", "raw", "params", "options"}), table_name="prices", label=( '' "show_chart" " Massive Stocks" ), ) ui = ExplorerUI( agents=[SourceAgent()], source_controls=[controls, UploadSourceControls()], title="Stock Market Explorer", log_level="DEBUG", ) ui.servable() ``` -------------------------------- ### Install Lumen with OpenAI Support Source: https://github.com/holoviz/lumen/blob/main/docs/quick_start.md Install the Lumen package with OpenAI integration. Set the OPENAI_API_KEY environment variable before running. ```bash pip install 'lumen[ai-openai]' export OPENAI_API_KEY=sk-... ``` -------------------------------- ### Install Lumen with AI Catalyst Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install Lumen with support for AI Catalyst. Set the AI_CATALYST_BASE_URL and AI_CATALYST_API_KEY environment variables with your credentials. ```bash pip install 'lumen[ai-openai]' ``` ```bash export AI_CATALYST_BASE_URL=https://... ``` ```bash export AI_CATALYST_API_KEY=... ``` ```bash # macOS/Linux export AI_CATALYST_BASE_URL='https://your-company.anacondaconnect.com/.../v1' export AI_CATALYST_API_KEY='your-key-here' ``` ```powershell # Windows PowerShell $env:AI_CATALYST_BASE_URL='https://your-company.anacondaconnect.com/.../v1' $env:AI_CATALYST_API_KEY='your-key-here' ``` -------------------------------- ### Install Lumen with Llama.cpp Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install Lumen with Llama.cpp support. Lumen will automatically download the specified model on first use. Optionally, set a custom model URL. ```bash pip install 'lumen[ai-llama]' ``` ```bash lumen-ai serve data.csv --provider llama-cpp \ --llm-model-url 'https://huggingface.co/unsloth/Qwen2.5-7B-Instruct-GGUF/blob/main/Qwen2.5-7B-Instruct-Q4_K_M.gguf' ``` -------------------------------- ### Minimal Custom Weather Control Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/controls.md A minimal example of a custom source control for fetching weather data. It defines parameters for station and year, renders UI widgets, and implements the _load hook to fetch data from an API. ```python import asyncio import param import pandas as pd import lumen.ai as lmai from lumen.ai.controls import BaseSourceControls, SourceResult from panel_material_ui import IntSlider, TextInput class WeatherControl(BaseSourceControls): """Fetch weather data from an API.""" station = param.String(default="NYC", doc="Weather station code in New York") year = param.Integer(default=2024, bounds=(2020, 2024)) label = 'wb_sunny Weather Data' load_button_label = "Fetch Weather" def _render_controls(self): """Provide widgets - rendered above the load button.""" return [ TextInput.from_param(self.param.station, label="Station", sizing_mode="stretch_width"), IntSlider.from_param(self.param.year, label="Year", sizing_mode="stretch_width"), ] async def _load(self) -> SourceResult: """Main hook - fetch data and return result.""" self.progress("Fetching weather data...") url = ( f"https://mesonet.agron.iastate.edu/cgi-bin/request/daily.py?" f"stations={self.station}&sts={self.year}-01-01&ets={self.year}-12-31&network=NY_ASOS&format=csv" ) df = await asyncio.to_thread(pd.read_csv, url) if df.empty: return SourceResult.empty("No data returned") return SourceResult.from_dataframe( df, table_name=f"weather_{self.year}", year=self.year, source="mesonet_api", station=self.station, ) ui = lmai.ExplorerUI(source_controls=[WeatherControl]) ui.servable() ``` -------------------------------- ### Start with 4 Lines Source: https://github.com/holoviz/lumen/blob/main/docs/getting_started/building_lumen_apps.md This is the most basic configuration for a Lumen AI application. It initializes the ExplorerUI with data and makes it servable. Run this with `panel serve app.py --show`. ```python import lumen.ai as lmai ui = lmai.ExplorerUI(data='data.csv') ui.servable() ``` -------------------------------- ### Full Weather API Explorer Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/weather_openapi_explorer.md A complete implementation of the Weather API Explorer using `OpenAPISourceControls` with filtered endpoints and a custom label. This example sets up the UI with a specific title and log level. ```python """ Weather API Explorer - Full Example Auto-discovered from the National Weather Service OpenAPI spec """ from lumen.ai.agents import SourceAgent from lumen.ai.controls import OpenAPISourceControls, UploadSourceControls from lumen.ai.ui import ExplorerUI controls = OpenAPISourceControls( spec_url="https://api.weather.gov/openapi.json", headers={"User-Agent": "LumenWeatherExplorer/1.0"}, include_paths=[ "/alerts", # Active weather alerts "/stations", # Observation stations "/points", # Forecast by lat/lon "/gridpoints", # Raw forecast grids "/radar", # Radar stations ], label=( '' "cloud" " Weather.gov API" ), ) ui = ExplorerUI( agents=[SourceAgent()], source_controls=[controls, UploadSourceControls()], title="Weather API Explorer", log_level="DEBUG", ) ui.servable() ``` -------------------------------- ### Start MLX Server Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/llm_providers.md Start the mlx_lm server for running models natively on Apple Silicon Macs. Configure model, port, max tokens, and chat template arguments. ```bash mlx_lm.server \ --model mlx-community/Qwen3.5-9B-MLX-4bit \ --port 8080 \ --max-tokens 8192 \ --chat-template-args '{"enable_thinking":false}' ``` -------------------------------- ### Build a Complete Dashboard with Lumen and Panel Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/python-api.md Combines pipeline, views, and layout into a Lumen Dashboard object. This example shows how to set up a dashboard with filters and visualizations. ```python import lumen as lm import panel as pn pn.extension('tabulator', design='material') # Create pipeline pipeline = lm.Pipeline.from_spec({ 'source': { 'type': 'file', 'tables': { 'penguins': 'https://datasets.holoviz.org/penguins/v1/penguins.csv' } }, 'filters': [ {'type': 'widget', 'field': 'island'}, {'type': 'widget', 'field': 'sex'}, {'type': 'widget', 'field': 'year'} ], }) # Create views scatter = lm.views.hvPlotView( pipeline=pipeline, kind='scatter', x='bill_length_mm', y='bill_depth_mm', by='species', responsive=True, height=400 ) table = lm.views.Table( pipeline=pipeline, page_size=10, sizing_mode='stretch_width' ) # Create layout layout = lm.Layout( views={'scatter': scatter, 'table': table}, title='Palmer Penguins' ) # Create dashboard dashboard = lm.Dashboard( config={'title': 'Palmer Penguins', 'theme': 'dark'}, layouts=[layout] ) dashboard ``` -------------------------------- ### Run Wind Turbines Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/gallery/windturbines.md Save the provided YAML configuration and run this command in your terminal to serve and display the Wind Turbines Lumen dashboard. ```bash lumen serve windturbines.yaml --show ``` -------------------------------- ### Install Lumen for AWS Bedrock Providers Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install Lumen with either the AnthropicBedrock provider or boto3 for general AWS Bedrock access. ```bash pip install 'lumen[ai-anthropic]' # For AnthropicBedrock # OR pip install boto3 # For Bedrock ``` -------------------------------- ### Specific AI Instruction Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/reports.md Provides an example of how to write specific and detailed instructions for AI agents within `ActorTask` to ensure desired output format and scope. ```python # ❌ Vague ActorTask(ChatAgent(), instruction="Analyze the data") # ✅ Specific ActorTask(ChatAgent(), instruction=""" Based on the metrics above: 1. Top 3 trends (bullet points) 2. Top 3 risks (High/Medium/Low) Keep under 200 words. """) ``` -------------------------------- ### Serve Local CSV Files Source: https://github.com/holoviz/lumen/blob/main/docs/quick_start.md Command-line examples for serving local CSV files or CSV files from a URL using Lumen. ```bash lumen serve data/sales.csv lumen serve https://example.com/data.csv ``` -------------------------------- ### Install Lumen with Mistral AI Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install the Lumen package with Mistral AI integration. Set the MISTRAL_API_KEY environment variable with your Mistral API key. ```bash pip install 'lumen[ai-mistralai]' export MISTRAL_API_KEY=your-key ``` -------------------------------- ### Install Lumen with Google Gemini Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install the Lumen package with Google Gemini integration. Set the GEMINI_API_KEY environment variable with your Google API key. ```bash pip install 'lumen[ai-google]' export GEMINI_API_KEY=your-key ``` -------------------------------- ### Complete Pipeline Example (YAML) Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/pipelines.md A comprehensive YAML configuration for a data pipeline, including sources, filters, and transformations. ```yaml sources: penguins: type: file tables: data: https://datasets.holoviz.org/penguins/v1/penguins.csv pipelines: analysis: source: penguins table: data filters: - type: widget field: species - type: widget field: island - type: widget field: sex transforms: - type: aggregate method: mean by: [species, sex, year] layouts: - title: Penguin Analysis pipeline: analysis views: - type: table ``` -------------------------------- ### Full Census Data Explorer Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/census_data_ai_explorer.md A complete implementation of the Census Data Explorer, integrating multiple functions and reactive options. This serves as a comprehensive example of the concepts discussed throughout the tutorial. ```python """ Census Data Explorer - Full Example Multiple functions with reactive options """ import pandas as pd import param import lumen.ai as lmai from lumen.ai.agents import SourceAgent from lumen.ai.controls import CodeSourceControls, UploadSourceControls # ───────────────────────────────────────────────────────────────────────────── # Census functions to expose ``` -------------------------------- ### Lumen Configuration with Ollama Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/cli.md Example of configuring Lumen CLI to use Ollama locally for serving multiple CSV files. ```bash lumen-ai serve data/*.csv \ --provider ollama \ --model 'qwen3:32b' \ --temperature 0.4 \ --log-level debug \ --show ``` -------------------------------- ### Passing Variables via Command Line Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/variables.md Example of how to pass template variables to the lumen serve command. ```bash lumen serve dashboard.yaml --template-vars="{'DATA_FILE': 'sales.csv', 'USER': 'Bob'}" ``` -------------------------------- ### Define Agent Instructions in agents.py Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/prompts.md Content for the agents.py file, defining rules and examples for the SQL agent's behavior. ```python Your SQL agent handles customer data queries. Rules: - Always use INNER JOIN for relationships - Sanitize date inputs to YYYY-MM-DD format - Group by customer segments first Examples: - "Top customers" → Order by revenue DESC - "Monthly trends" → Use DATE_TRUNC ``` -------------------------------- ### Kaggle Dataset URL Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/controls.md Example URL for fetching a Kaggle dataset. This functionality requires the 'kagglehub' package to be installed. ```text https://www.kaggle.com/datasets/sharmajicoder/gen-z-social-media-usage-dataset ``` -------------------------------- ### Minimal Runnable Example for Stock Explorer Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/massive_stock_explorer.md This Python script initializes the Massive SDK client and configures CodeSourceControls to expose specific methods as UI actions. It then sets up an ExplorerUI to serve the application. ```python import os from massive import RESTClient from lumen.ai.agents import SourceAgent from lumen.ai.controls import CodeSourceControls, UploadSourceControls from lumen.ai.ui import ExplorerUI client = RESTClient(api_key=os.environ["MASSIVE_API_KEY"]) # (1)! controls = CodeSourceControls( instance=client, # (2)! methods=["list_aggs", "get_last_trade", "get_ticker_details"], # (3)! skip_params=frozenset({"self", "cls", "return", "raw", "params", "options"}), # (4)! table_name="prices", label=( '' "show_chart" " Massive Stocks" ), ) ui = ExplorerUI( agents=[SourceAgent()], source_controls=[controls, UploadSourceControls()], title="Stock Market Explorer", log_level="DEBUG", ) ui.servable() ``` -------------------------------- ### YAML List Syntax Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/concepts.md Illustrates how to define lists in YAML using leading dashes for each item. This is commonly used for filters and other multi-item configurations. ```yaml filters: - type: widget field: category - type: widget field: region ``` -------------------------------- ### Install Lumen with Conda Source: https://github.com/holoviz/lumen/blob/main/README.md Use this command to install Lumen using the conda package manager. Ensure you have Anaconda or Miniconda installed. ```bash conda install -c pyviz lumen ``` -------------------------------- ### Verify Lumen Installation Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Command to check the installed version of the Lumen CLI. ```bash lumen-ai --version ``` -------------------------------- ### Build and Serve Documentation Locally Source: https://github.com/holoviz/lumen/blob/main/docs/contributing.md Commands to serve the Lumen documentation locally with live reload and to build the documentation. ```bash # Serve docs locally with live reload pixi run -e docs docs-serve # Build docs pixi run -e docs docs-build ``` -------------------------------- ### Install xarray dependencies Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/sources.md Install the necessary dependencies for using xarray with Lumen. ```bash pip install lumen[xarray] ``` -------------------------------- ### Run Lumen Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/gallery/bikes.md This command serves the specified Lumen YAML configuration file and displays the dashboard. Ensure the YAML file is saved correctly before running this command. ```bash lumen serve bikes.yaml --show ``` -------------------------------- ### AWS Bedrock IAM Policy Example Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md An example IAM policy for allowing Bedrock model invocation. ```json { "Effect": "Allow", "Action": ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"], "Resource": "*" } ``` -------------------------------- ### Create Lumen Pipelines and Views Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/python-api.md Demonstrates creating aggregated and sorted pipelines, then visualizing them using Panel Tabs with different Lumen views. ```python agg_pipeline = base_pipeline.chain( transforms=[{'type': 'aggregate', 'method': 'sum', 'by': ['region']}] ) top_pipeline = base_pipeline.chain( transforms=[ {'type': 'sort', 'by': ['revenue'], 'ascending': False}, {'type': 'query', 'query': 'index < 10'} ] ) # Different views of same data pn.Tabs( ('Raw', lm.views.Table(pipeline=base_pipeline)), ('Aggregated', lm.views.hvPlotView(pipeline=agg_pipeline, kind='bar')), ('Top 10', lm.views.Table(pipeline=top_pipeline)) ) ``` -------------------------------- ### Load Prompt Instructions from File Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/prompts.md Load agent instructions from an external Python file using an absolute path. Ensure the file exists and contains the necessary instructions. ```python from pathlib import Path template_overrides = { "main": { "instructions": str(Path(__file__).parent / 'agents.py') } } agent = lmai.agents.SQLAgent(template_overrides=template_overrides) ``` -------------------------------- ### Lumen CLI Serve Commands Source: https://github.com/holoviz/lumen/blob/main/docs/getting_started/building_lumen_apps.md Examples of using the Lumen CLI to serve applications with different configurations, including specifying providers, models, agents, code execution, and temperature. ```bash lumen-ai serve data.csv # Basic ``` ```bash lumen-ai serve data.csv --provider anthropic # Change provider ``` ```bash lumen-ai serve data.csv --model gpt-4.1 # Change model ``` ```bash lumen-ai serve data.csv --provider openrouter --model openai/gpt-4o-mini ``` ```bash lumen-ai serve data.csv --agents sql vega_lite # Limit agents ``` ```bash lumen-ai serve data.csv --code-execution prompt # Enable code execution ``` ```bash lumen-ai serve data.csv --temperature 0.1 # Set temperature ``` ```bash lumen-ai serve --help # All options ``` -------------------------------- ### Install Missing Package Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Provides commands to install a missing Python package required by a component, using either Conda or Pip. ```bash conda install intake # or pip install intake ``` -------------------------------- ### Configure Basic Table View (Python) Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/views.md Instantiate a basic table view in Python, setting parameters like 'show_index', 'page_size', and 'height' for controlling table display and interaction. ```python from lumen.views import Table table = Table( pipeline=pipeline, show_index=False, page_size=20, height=400 ) ``` -------------------------------- ### Build Custom Panel App with Pipeline Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/pipelines.md This example demonstrates building a custom Panel application by creating a Lumen pipeline, defining views (scatter plot and table), and arranging them within a MaterialTemplate layout. ```python from lumen.pipeline import Pipeline from lumen.views import hvPlotView, Table import panel as pn pn.extension('tabulator') # Create pipeline pipeline = Pipeline.from_spec({ 'source': { 'type': 'file', 'tables': {'penguins': 'penguins.csv'} }, 'filters': [ {'type': 'widget', 'field': 'species'}, {'type': 'widget', 'field': 'island'} ] }) # Create views scatter = hvPlotView( pipeline=pipeline, kind='scatter', x='bill_length_mm', y='bill_depth_mm', by='species' ) table = Table(pipeline=pipeline, page_size=10) # Custom layout app = pn.template.MaterialTemplate( title='Penguin Analysis', sidebar=[pipeline.control_panel], main=[ pn.Row(scatter, table) ] ) app.servable() ``` -------------------------------- ### Install Lumen with Anthropic Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install the Lumen package with Anthropic integration. Set the ANTHROPIC_API_KEY environment variable with your Anthropic API key. ```bash pip install 'lumen[ai-anthropic]' export ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Coordinator tools setup Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/tools.md Configure tools to be used as coordinator tools by passing them to the `tools` argument of `ExplorerUI`. These tools are orchestrated by Lumen's planner as part of a multi-step plan. ```python import lumen.ai as lmai from lumen.ai.tools import MCPTool tools = asyncio.run(MCPTool.from_server(mcp_server)) ui = lmai.ExplorerUI( data='penguins.csv', tools=tools # (1)! ) ``` -------------------------------- ### Validation Error Output Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Example of detailed error messages provided during validation, highlighting the specific issue and location within the YAML. ```text ERROR: View component specification declared unknown type 'hvplotqedq'. Did you mean 'hvplot' or 'hvplot_ui'? table: penguins type: hvplotqedq kind: scatter x: bill_length_mm ``` -------------------------------- ### Run NYC Taxi Example Source: https://github.com/holoviz/lumen/blob/main/docs/examples/gallery/nyc_taxi.md Command to serve and display the NYC Taxi analysis dashboard using the Lumen CLI. Ensure the YAML file is saved before running. ```bash lumen serve nyc_taxi.yaml --show ``` -------------------------------- ### Install Lumen with Azure OpenAI Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install the Lumen package with Azure OpenAI integration. Set AZUREAI_ENDPOINT_KEY and AZUREAI_ENDPOINT_URL environment variables with your Azure credentials. ```bash pip install 'lumen[ai-openai]' export AZUREAI_ENDPOINT_KEY=your-key export AZUREAI_ENDPOINT_URL=https://your-resource.openai.azure.com/ ``` -------------------------------- ### Minimal Runnable Example for Weather API Explorer Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/weather_openapi_explorer.md This snippet sets up an OpenAPI source control to connect to the National Weather Service API. It filters endpoints to include only alerts, stations, and points, and configures a user-agent header. Run this with `panel serve weather_openapi.py --show`. ```python from lumen.ai.agents import SourceAgent from lumen.ai.controls import OpenAPISourceControls, UploadSourceControls from lumen.ai.ui import ExplorerUI controls = OpenAPISourceControls( spec_url="https://api.weather.gov/openapi.json", # (1)! headers={"User-Agent": "LumenWeatherExplorer/1.0"}, # (2)! include_paths=["/alerts", "/stations", "/points"], # (3)! label=( '' "cloud" " Weather.gov" ), ) ui = ExplorerUI( agents=[SourceAgent()], source_controls=[controls, UploadSourceControls()], title="Weather API Explorer", log_level="DEBUG", ) ui.servable() ``` -------------------------------- ### Configure Local HuggingFace Embeddings Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/embeddings.md Uses HuggingFace Sentence Transformers for local embeddings. Specify the model and device (CPU or CUDA). Install with 'pip install sentence-transformers'. ```python from lumen.ai.embeddings import HuggingFaceEmbeddings embeddings = HuggingFaceEmbeddings( model="ibm-granite/granite-embedding-107m-multilingual", device="cpu" # or "cuda" for GPU ) ``` -------------------------------- ### Serve Dashboard from Python Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Launches a dashboard defined in a Python script. The Python file must call `.servable()` on the dashboard object. ```bash lumen serve app.py --show ``` ```python import lumen as lm dashboard = lm.Dashboard(...) dashboard.servable() ``` -------------------------------- ### Install Lumen with Azure Mistral AI Support Source: https://github.com/holoviz/lumen/blob/main/docs/installation.md Install the Lumen package with Azure Mistral AI integration. Set AZUREAI_ENDPOINT_KEY and AZUREAI_ENDPOINT_URL environment variables with your Azure credentials. ```bash pip install 'lumen[ai-mistralai]' export AZUREAI_ENDPOINT_KEY=your-key export AZUREAI_ENDPOINT_URL=https://your-resource-endpoint.com/ ``` -------------------------------- ### Install Lumen with Local LLM Support Source: https://github.com/holoviz/lumen/blob/main/docs/faq.md Install Lumen AI with support for local LLM providers like Ollama or Llama.cpp. Ensure you have the necessary dependencies for AI models. ```bash pip install 'lumen[ai-llama]' ``` -------------------------------- ### Discover tools from an MCP server Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/tools.md Use `MCPTool.from_server` to discover all tools on a server and create an `MCPTool` instance for each. This is useful for integrating with existing MCP services. ```python import asyncio import lumen.ai as lmai from lumen.ai.tools import MCPTool tools = asyncio.run(MCPTool.from_server("https://my-mcp-server.example.com/mcp")) ui = lmai.ExplorerUI( data='penguins.csv', tools=tools ) u.servable() ``` -------------------------------- ### Set API Key and Serve Data Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/llm_providers.md Set your API key as an environment variable and then serve a CSV file. Lumen auto-detects the provider. ```bash export OPENAI_API_KEY="sk-..." lumen-ai serve penguins.csv ``` -------------------------------- ### Per-call tools combined with instance tools Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/tools.md Demonstrates how to combine instance tools (always available) with per-call tools for a specific LLM invocation. Per-call tools are added on top for that particular call. ```python # Instance tools are always available llm = lmai.llm.OpenAI(tools=[always_available_tool]) # Per-call tools are added on top for this specific call result = await llm.invoke(messages, tools=[extra_tool]) ``` -------------------------------- ### Example Report with Load and Analyze Actions Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/reports.md Demonstrates a complete report structure using custom `Action` subclasses to load data from a CSV via DuckDB and then analyze it using VegaLiteView. Requires `panel` extension for 'tabulator' and 'vega'. ```python import panel as pn from lumen.ai.report import Action, Report, Section from lumen.ai.editors import LumenEditor from lumen.pipeline import Pipeline from lumen.sources.duckdb import DuckDBSource from lumen.views.base import VegaLiteView pn.extension("tabulator", "vega") class LoadDataAction(Action): async def _execute(self, context, **kwargs): source = DuckDBSource(tables={"penguins": "https://datasets.holoviz.org/penguins/v1/penguins.csv"}) pipeline = Pipeline(source=source, table="penguins") return [pipeline.__panel__()], {"source": source} class AnalyzeAction(Action): async def _execute(self, context, **kwargs): source = context["source"] avg_source = source.create_sql_expr_source( tables={"avg_data": "SELECT species, AVG(CAST(NULLIF(body_mass_g, 'NA') AS DOUBLE)) AS avg_mass FROM penguins GROUP BY species"} ) pipeline = Pipeline(source=avg_source, table="avg_data") chart = VegaLiteView( pipeline=pipeline, spec={ "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "mark": "bar", "encoding": { "x": {"field": "species", "type": "nominal"}, "y": {"field": "avg_mass", "type": "quantitative"}, }, }, sizing_mode="stretch_width", ) return [LumenEditor(component=chart, title="Avg Body Mass by Species")], {} report = Report( Section(LoadDataAction(title="Load"), AnalyzeAction(title="Analyze"), title="Penguins") ) report.show() ``` -------------------------------- ### Setting Environment Variables and Serving Dashboard Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/deployment.md Demonstrates how to export environment variables and then serve the Lumen dashboard using these variables for configuration. ```bash export APP_TITLE="Production Dashboard" export DATABASE_URL="postgresql://localhost/mydb" export CACHE_DIR="/var/cache/lumen" lumen serve dashboard.yaml ``` -------------------------------- ### Run Panel Serve Application Source: https://github.com/holoviz/lumen/blob/main/docs/examples/tutorials/weather_data_ai_explorer.md Starts the Lumen application using the `panel serve` command, making it accessible via a web browser. This command serves the specified Python file and automatically opens it in the browser. ```bash panel serve weather_sounding.py --show ``` -------------------------------- ### Component Design: Document Parameters Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/customization.md Illustrates documenting component parameters using docstrings for clarity and maintainability. ```python class MyTransform(Transform): field = param.String(doc="Column name to transform") method = param.Selector( default='mean', objects=['mean', 'median', 'mode'], doc="Aggregation method to apply" ) ``` -------------------------------- ### Variable Naming: Descriptive Example Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/variables.md Illustrates the use of clear and descriptive names for variables in Lumen configuration. ```yaml # ✅ Good - descriptive variables: sales_threshold: type: widget value: 100 ``` -------------------------------- ### Security: Setting Environment Variable Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/variables.md Example of how to export an environment variable in bash for use in Lumen configuration. ```bash export API_KEY="secret-api-key-12345" lumen serve dashboard.yaml ``` -------------------------------- ### Create Scatter and Table Views with Layout Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/python-api.md Demonstrates creating a scatter plot view and a table view, then arranging them in a layout. This is a basic example of building interactive components. ```python import lumen as lm # Create views scatter = lm.views.hvPlotView( pipeline=pipeline, kind='scatter', x='bill_length_mm', y='bill_depth_mm', by='species' ) table = lm.views.Table(pipeline=pipeline, page_size=10) # Create layout layout = lm.Layout( views={'scatter': scatter, 'table': table}, title='Palmer Penguins', layout=[[0], [1]] # Scatter on top, table below ) layout ``` -------------------------------- ### Change LLM Provider Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/ui.md Customize the Large Language Model provider for ExplorerUI, using Anthropic as an example. ```python ui = lmai.ExplorerUI( data='penguins.csv', llm=lmai.llm.Anthropic() ) ``` -------------------------------- ### Create Pipeline from FileSource (Python) Source: https://github.com/holoviz/lumen/blob/main/docs/configuration/spec/pipelines.md Initializes a Lumen pipeline programmatically, starting with a FileSource pointing to a CSV dataset. ```python from lumen.sources import FileSource from lumen.pipeline import Pipeline source = FileSource(tables={ 'penguins': 'https://datasets.holoviz.org/penguins/v1/penguins.csv' }) pipeline = Pipeline(source=source, table='penguins') ```