Introduction & Philosophy
Pyvello is a Python-first reactive AI UI framework engineered for building production-grade agentic interfaces, interactive analytics dashboards, and autonomous workflow swarms. Powered by a high-speed React 18, Vite 5, Tailwind CSS, and shadcn/ui frontend communicating over an ultra-low-latency bidirectional WebSocket protocol, Pyvello eliminates the limitations of traditional Python web frameworks.
Instant Reactivity
No entire-script reruns. Fine-grained diffing updates only dirty component DOM nodes over WebSockets.
Multi-Agent Observability
Out-of-the-box Langfuse-style diagnostic sheet and ReactFlow interactive agent graphs.
Live Hot Reload Default
Edit your Python scripts and witness changes instantly without reloading the browser tab or killing processes.
Installation & Quickstart
Install Pyvello via pip or uv:
Hello from Pyvello!
Zero full-page reruns • Fine-grained WebSocket DOM updates
# Install via pip
pip install pyvello
# Or install via uv (recommended for ultra-fast setup)
uv pip install pyvello
Launch in 3 Lines of Python
import pyvello as ui
# Create an autonomous agent and launch its full web UI (Hot Reload is enabled by default)
agent = ui.Agent(name="Assistant", system_prompt="You are a helpful software engineer.")
agent.to_app().launch()
Live Hot Reloading (Enabled by Default)
Pyvello automatically monitors your application script and triggers instant live reloading whenever you save changes. Hot reload is enabled by default in both the CLI (pyvello run) and programmatic execution (app.launch()). It updates the active browser tab without spawning redundant browser windows.
# Run from CLI with automatic hot reload (default):
pyvello run app.py
# Disable hot reload if desired:
pyvello run app.py --no-reload
# In Python code, reload=True is default:
app.launch() # Reload enabled by default
app.launch(reload=False) # Explicitly disable reload
Jupyter Notebooks & Google Colab Support
Pyvello apps can be embedded directly inside Jupyter Notebook (.ipynb) cells. Pyvello automatically detects the IPython kernel, spins up the server in a non-blocking background thread, and renders the interactive UI right in the cell output.
# Inside a Jupyter Notebook (.ipynb) or Google Colab cell:
import pyvello as ui
agent = ui.agent(name="DataAnalyst", system_prompt="Analyze datasets with code.")
# Embeds directly into the cell output without blocking execution:
agent.to_app().launch(inline=True, height=750)
App & Header Configuration
The top-level ui.App() container orchestrates layout mounting, theme palettes, agent DAG computation, and the top navbar toolbar. Every header icon is enabled (True) by default and can be customized or hidden by passing keyword flags.
ui.App() Parameters & Header Controls
| Parameter | Type | Default | Description |
|---|---|---|---|
| title | str | "Pyvello Application" | Application title displayed in browser tab and top header breadcrumb. |
| theme | str | "light" | Default color mode: "light" or "dark". |
| palette | str | "red" | Initial active Shadcn palette: "red", "zinc", "slate", "rose", "orange", "green", "blue", "violet". |
| header | bool | True | Master toggle for the top application header (alias: show_header). Setting header=False completely hides the top navigation bar, giving 100% full-screen viewport space for kiosk, embedded wall displays, or custom headerless layouts. When a sidebar is present, a floating slide-out button docks on the top-left to toggle the drawer. |
| show_search | bool | True | Enables wide Spotlight Command Bar in header (Cmd+K). Set to False to hide. |
| show_graph | bool | True | Displays the interactive Agent Architecture & Execution DAG button when multi-agent nodes exist. |
| show_debug | bool | True | Displays the Debug Inspector button (Bug icon) for telemetry, token economics, and API keys. |
| show_code | bool | True | Displays the View Code button (Code icon) to inspect and download the complete Python application code. |
| show_docs | bool | True | Displays the Documentation icon in the top header. |
| show_palette | bool | True | Displays the 12-palette color picker dropdown in the header. |
| show_export | bool | True | Displays the Export Vite App button (Download icon) to export a standalone React frontend. |
| show_theme | bool | True | Displays the Dark / Light mode toggle switch. |
Hiding the Header for Embedded Displays and Monitoring Walls
Setting header=False completely removes the top application chrome. This is ideal for Network Operations Centers (NOC), dedicated wall dashboards, and embedded kiosks where the browser frame should not distract the operator. When header=False is combined with with ui.sidebar():, Pyvello automatically positions a floating slide-out button on the top-left to expand and collapse the sidebar.
Complete Executable Code
import pyvello as ui
# Launch a clean production application with customized toolbar controls
app = ui.App(
title="Executive Analytics Portal",
palette="slate",
show_search=True, # Keep wide Spotlight Search
show_code=True, # Keep View Code button for transparency
show_debug=False, # Hide developer debug inspector in production
show_export=False, # Hide Vite export tool
show_docs=False, # Hide internal framework documentation link
)
with app:
ui.title("Q3 Performance Dashboard")
ui.metric("Annual Recurring Revenue", ".84M", delta="+18.4%")
if __name__ == "__main__":
app.launch()
Authentication & User Management
Pyvello features a turnkey, zero-dependency authentication engine built directly into the framework. You can protect any application with a single argument: ui.App(auth=True).
Pass auth=True or a credential dictionary {"admin": "secret123"} to immediately gate the entire site behind an authentication card.
Visitors can sign in or register new accounts directly through the UI. Account creation enforces length constraints, alphanumeric rules, and password confirmation.
The application component tree and sensitive server data are never sent over the wire until the client provides a validated session token.
Single-User vs Multi-User Architecture
Pyvello natively handles both single-user private tools and high-concurrency multi-user team workspaces with zero external dependencies:
Single-User Mode (Private Apps & Internal Tools)
allow_registration=FalseIdeal for internal administration dashboards, personal research stations, or tools restricted to verified operators. Pass pre-seeded credentials and disable registration to hide the "Create Account" tab completely.
app = ui.App(
title="Private SRE Console",
auth=ui.Auth(
default_users={"operator": "SecretPass2026"},
allow_registration=False, # Gated: no signups allowed
),
)
Multi-User Mode (SaaS & Team Workspaces)
allow_registration=True
Allows multiple users to sign in simultaneously or create their own accounts. Every user receives a unique session token stored in browser localStorage and has isolated session context in Python.
app = ui.App(
title="Team Intelligence Portal",
auth=ui.Auth(
allow_registration=True, # Team signups enabled
storage="sqlite",
db_path="team_users.db",
default_users={"admin": "admin123"},
),
)
Configuration Options
Pass a boolean, dictionary, or a customized ui.Auth instance to the auth argument:
| Configuration Form | Description | Storage Engine |
|---|---|---|
| ui.App(auth=True) | Enables authentication with automatic user registration and SQLite persistence in pyvello_auth.db. |
SQLite3 |
| ui.App(auth={"admin": "pass123"}) | Pre-seeds default administrative credentials on first startup while allowing new user signups. | SQLite3 |
| ui.App(auth=ui.Auth(...)) | Full granular control over database path, session duration, registration toggles, and memory mode for unit testing. | SQLite3 / Memory |
Accessing User Context in Callbacks
Inside any Python event callback, use ui.current_user() to retrieve the active user object or ui.is_authenticated() to verify session status:
import pyvello as ui
def handle_user_action():
user = ui.current_user()
if user:
# Access attributes directly or as dictionary keys
username = user.username
role = user.role
email = user.email or "none"
ui.toast(f"Action executed by {username} ({role})", title="Success", type="success")
else:
ui.toast("Unauthenticated operation rejected", title="Access Denied", type="destructive")
with ui.App(
title="Secure Workspace",
auth=ui.Auth(
allow_registration=True,
db_path="production_users.db",
default_users={"admin": "admin123"},
),
) as app:
ui.title("Protected Dashboard")
ui.button("Execute Action", on_click=handle_user_action)
if __name__ == "__main__":
app.launch()
Cryptographic Architecture
1. Password Hashing: Utilizes Python standard library hashlib.pbkdf2_hmac with SHA-256 and 100,000 iterations. Each user is assigned a distinct 32-character hexadecimal salt generated via secrets.token_hex(16).
2. Constant-Time Verification: Password verification executes via hmac.compare_digest to protect against timing analysis side-channel attacks.
3. Session Tokens: High-entropy 256-bit URL-safe session tokens generated via secrets.token_urlsafe(32) and indexed in SQLite with expiration timestamps.
4. Session Persistence: Browser tokens are stored in client localStorage. When reloading the page, the client re-authenticates automatically during the WebSocket handshake.
REST API Endpoints
| Method | Endpoint | Payload / Header | Response |
|---|---|---|---|
| POST | /api/auth/login | {"username": "...", "password": "..."} | {"status": "ok", "token": "...", "user": {...}} |
| POST | /api/auth/register | {"username": "...", "password": "...", "email": "..."} | {"status": "ok", "token": "...", "user": {...}} |
| GET | /api/auth/me | Header: Authorization: Bearer <token> | {"authenticated": true, "user": {...}} |
| POST | /api/auth/logout | Header: Authorization: Bearer <token> | {"status": "ok", "message": "Logged out successfully."} |
Reactivity (State & Updates)
Imperative WebSocket prop synchronization without full script reruns. Update single components with ui.update(), push multiple components atomically with ui.batch_update(), and maintain state with ui.session_state.
import pyvello as ui
with ui.App(title="Dynamic Reactivity", theme="dark") as app:
status_metric = ui.metric("Node Status", "Idle", delta="0%", status="neutral")
def activate_nodes():
# Atomically update metric value and status over WebSocket
ui.update(status_metric, value="Running", delta="+100%", status="success")
ui.toast("All 128 nodes activated successfully!", type="success")
ui.button("Activate Cluster", on_click=activate_nodes)
if __name__ == "__main__":
app.launch()
Packaging & PyPI Publishing
Complete production guide to bundling the React frontend, building the Python wheel and source distribution, verifying assets, and releasing to PyPI.
Pyvello is engineered so end users never require Node.js or npm installed. The production React 18, Vite, and Tailwind CSS web application is pre-compiled and packaged directly inside the Python distribution wheel (pyvello/static/ and pyvello/web_template/).
1 PyPI Account & API Token Setup
Before publishing, ensure your PyPI account is secured with Two-Factor Authentication and create an API token:
- Create an account at pypi.org (and optionally test.pypi.org for test releases).
- Enable Two-Factor Authentication (2FA) under Account Settings → Two-factor authentication (2FA). PyPI requires 2FA for all publishers.
- Generate a scoped API token under Account Settings → API tokens with token prefix
pypi-....
2 Compile React Frontend Assets
Compile the web frontend package and sync production static bundles into the Python package directory:
# 1. Build the production React frontend bundle
cd packages/web
pnpm build
cd ../..
# 2. Sync compiled assets into pyvello package distribution directory
cp -r packages/web/dist/* pyvello/static/
3 Package Configuration (pyproject.toml)
Verify that pyproject.toml includes non-Python static bundles and web templates in the wheel build targets:
[project]
name = "pyvello"
version = "0.1.0"
description = "A Python-First AI UI Framework with React, shadcn/ui and Automatic Agent Graph Visualization"
readme = "README.md"
requires-python = ">=3.10"
license = { text = "MIT" }
[project.scripts]
pyvello = "pyvello.cli:main"
[tool.hatch.build.targets.wheel]
packages = ["pyvello"]
include = [
"pyvello/static/**/*",
"pyvello/web_template/**/*",
]
4 Build Wheel & Source Distribution
Build the source archive (.tar.gz) and binary wheel (.whl), then validate metadata with Twine:
# Clean old build artifacts
rm -rf dist/ build/ *.egg-info
# Build using uv (recommended):
uv build
# Or build using python -m build:
# python3 -m pip install --upgrade build && python3 -m build
# Validate package metadata and distribution integrity
uvx twine check dist/*
# Output: Checking dist/pyvello-...-any.whl: PASSED
5 Test Wheel Locally in Clean Environment
Verify that the generated wheel installs cleanly and executes without missing dependencies:
# Create and activate an isolated virtual environment
uv venv /tmp/pyvello-test
source /tmp/pyvello-test/bin/activate
# Install the built wheel
pip install dist/pyvello-0.1.0-py3-none-any.whl
# Test CLI command
pyvello --help
# Test import and assets
python -c "import pyvello as ui; print('Version:', ui.__version__)"
# Clean up
deactivate
rm -rf /tmp/pyvello-test
6 Publish to PyPI
Publish your package to official PyPI using Twine, uv publish, or a saved credentials configuration:
# Option A: Upload using Twine
uvx twine upload dist/*
# Username: __token__
# Password:
# Option B: Upload using uv publish
uv publish --token pypi-AgEI...
# Option C: Test release first on TestPyPI (Recommended Dry Run)
uvx twine upload --repository testpypi dist/*
7 Automate Publishing with GitHub Actions (CI/CD)
Create .github/workflows/publish.yml to automatically build and release whenever a GitHub Release is published:
name: Publish to PyPI
on:
release:
types: [published]
jobs:
build-and-publish:
runs-on: ubuntu-latest
permissions:
id-token: write # Required for OIDC PyPI Trusted Publishing
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js & pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Build Web Frontend Assets
run: |
cd packages/web
pnpm install --frozen-lockfile
pnpm build
cd ../..
cp -r packages/web/dist/* pyvello/static/
- name: Install uv
uses: astral-sh/setup-uv@v3
with:
enable-cache: true
- name: Build Package
run: uv build
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
Model Providers & API Keys (.env)
Pyvello features a universal multi-model runtime powered by LiteLLM. You can run agents with OpenRouter, OpenAI, Anthropic, Google Gemini, Groq, DeepSeek, Mistral, Cohere, or local offline models like Ollama and vLLM by setting the corresponding environment variables in your .env file.
Global Model & Provider Directory
Pyvello supports 50+ worldwide AI providers directly out-of-the-box. Simply prefix the model string with the provider name (e.g. siliconflow/..., kling/..., bfl/..., elevenlabs/...). Pyvello automatically discovers the matching key in your .env and configures the upstream endpoint.
| Provider / Org | Supported Modalities | .env Variable Name | Model String in Code | Default Gateway | Zero-Config Features & Notes |
|---|---|---|---|---|---|
|
Amazon Web Services (Bedrock / Polly)
Amazon Web Services
|
inference llm tts stt
|
AWS_ACCESS_KEY_ID | aws/anthropic.claude-3-5-sonnet-20241022-v2:0 | bedrock-runtime.us-east-1.amazonaws.com | Bedrock Converse API (Claude, Llama, Titan), Polly TTS, and Transcribe STT. |
|
Baseten
Baseten
|
inference llm
|
BASETEN_API_KEY | baseten/llama-3.3-70b-instruct | api.baseten.co | Dedicated autoscaling model infrastructure for private deployments. |
|
Cerebras Systems
Cerebras Systems
|
inference llm
|
CEREBRAS_API_KEY | cerebras/llama3.3-70b | api.cerebras.ai/v1 | Wafer-scale engine delivering 2000+ tokens/second reasoning. |
|
Chutes AI
Chutes
|
inference llm
|
CHUTES_API_KEY | chutes/deepseek-ai/DeepSeek-V3 | llm.chutes.ai/v1 | Decentralized low-cost GPU compute network for open models. |
|
DeepInfra
DeepInfra
|
inference llm image tts stt
|
DEEPINFRA_API_KEY | deepinfra/meta-llama/Meta-Llama-3.1-70B-Instruct | api.deepinfra.com/v1/openai | Pay-per-token serverless inference with 100+ open-source models. |
|
Featherless AI
Featherless AI
|
inference llm
|
FEATHERLESS_API_KEY | featherless/meta-llama/Meta-Llama-3.1-8B-Instruct | api.featherless.ai/v1 | Access to every Hugging Face model without deployment setup. |
|
Fireworks AI
Fireworks AI
|
inference llm image
|
FIREWORKS_API_KEY | fireworks/accounts/fireworks/models/llama-v3p3-70b-instruct | api.fireworks.ai/inference/v1 | Fast production inference for compound AI systems and FLUX. |
|
Groq
Groq
|
inference llm stt
|
GROQ_API_KEY | groq/llama-3.3-70b-versatile | api.groq.com/openai/v1 | Ultra-fast LPU inference engine for Llama, DeepSeek, and Whisper. |
|
Hugging Face Inference Providers
Hugging Face
|
inference llm image stt
|
HF_TOKEN | huggingface/meta-llama/Llama-3.3-70B-Instruct | router.huggingface.co/v1 | Unified serverless router for thousands of Hugging Face Hub open models. |
|
Microsoft Azure AI & Speech
Microsoft
|
inference llm tts stt
|
AZURE_API_KEY | azure/gpt-4o | models.inference.ai.azure.com | Azure AI Foundry models, Cognitive Services Neural Speech, and Fast STT. |
|
NVIDIA NIM
NVIDIA
|
inference llm
|
NVIDIA_API_KEY | nvidia/meta/llama-3.3-70b-instruct | integrate.api.nvidia.com/v1 | Microservices optimized on NVIDIA TensorRT-LLM and Triton server. |
|
Nebius AI Studio
Nebius
|
inference llm image
|
NEBIUS_API_KEY | nebius/deepseek-ai/DeepSeek-V3 | api.studio.nebius.com/v1 | Enterprise European AI cloud with high-performance clusters. |
|
Novita AI
Novita AI
|
inference llm image video
|
NOVITA_API_KEY | novita/meta-llama/llama-3.1-70b-instruct | api.novita.ai/v1 | Serverless GPU cloud for diffusion models, Llama, and CogVideoX. |
|
OpenRouter
OpenRouter
|
inference llm image video tts
|
OPENROUTER_API_KEY | openrouter/z-ai/glm-5.3-flash | openrouter.ai/api/v1 | Universal routing aggregator for 400+ models with unified billing. |
|
Replicate
Replicate
|
inference image video llm tts stt
|
REPLICATE_API_TOKEN | replicate/black-forest-labs/flux-1.1-pro | api.replicate.com/v1 | Serverless deployment for thousands of open-source AI community models. |
|
SambaNova Cloud
SambaNova Systems
|
inference llm
|
SAMBANOVA_API_KEY | sambanova/Meta-Llama-3.3-70B-Instruct | api.sambanova.ai/v1 | Reconfigurable Dataflow Unit (RDU) full-precision inference. |
|
SiliconFlow
SiliconFlow
|
inference llm image tts stt
|
SILICONFLOW_API_KEY | siliconflow/deepseek-ai/DeepSeek-V3 | api.siliconflow.cn/v1 | High-throughput Asian inference network for DeepSeek V3, Qwen, and Kolors. |
|
Together AI
Together AI
|
inference llm image
|
TOGETHER_API_KEY | together/meta-llama/Llama-3.3-70B-Instruct-Turbo | api.together.ai/v1 | High-throughput open-source models, fine-tunes, and FLUX image synthesis. |
|
WaveSpeedAI
WaveSpeedAI
|
inference image video
|
WAVESPEED_API_KEY | wavespeed/flux-schnell | api.wavespeed.ai/api/v3 | High-speed diffusion and cinematic video inference engine. |
|
fal.ai
fal
|
inference image video tts stt
|
FAL_KEY | fal/flux/schnell | queue.fal.run | Ultra-fast media compute cloud with 500+ community diffusion pipelines. |
|
Alibaba Cloud (Qwen / DashScope)
Alibaba Cloud
|
llm image video
|
DASHSCOPE_API_KEY | qwen/qwen-2.5-72b-instruct | dashscope-intl.aliyuncs.com/compatible-mode/v1 | Qwen 2.5 72B, Qwen Max, Wanx image synthesis, and Qwen Omni. |
|
Anthropic
Anthropic
|
llm
|
ANTHROPIC_API_KEY | claude-3-5-sonnet-20241022 | api.anthropic.com/v1 | Claude 3.5 Sonnet, Claude 3.5 Haiku, and Claude 3 Opus. |
|
Baidu (Qianfan / ERNIE)
Baidu
|
llm
|
QIANFAN_API_KEY | baidu/ernie-4.0-turbo-8k | qianfan.baidubce.com/v2 | ERNIE 4.0 Turbo and Baidu enterprise foundation models. |
|
ByteDance / BytePlus (Seedream & Doubao)
ByteDance
|
llm image video
|
BYTEPLUS_API_KEY | byteplus/seedream-5-0 | ark.ap-southeast.bytepluses.com/api/v3 | Seedream image generator, Seedance video generator, and Doubao LLM. |
|
Cohere
Cohere
|
llm
|
COHERE_API_KEY | cohere/command-r-plus-08-2024 | api.cohere.com/v2 | Command R+, Command R, and enterprise RAG embeddings. |
|
DeepSeek
DeepSeek
|
llm
|
DEEPSEEK_API_KEY | deepseek/deepseek-chat | api.deepseek.com | Frontier reasoning models: DeepSeek-V3 and DeepSeek-R1. |
|
Google Gemini
Google
|
llm image tts stt
|
GEMINI_API_KEY | gemini/gemini-2.5-flash | generativelanguage.googleapis.com/v1beta | Gemini 2.5 Flash, Gemini 2.0 Pro, Imagen 3, and multimodal reasoning. |
|
MiniMax (Hailuo)
MiniMax
|
llm video tts
|
MINIMAX_API_KEY | minimax/MiniMax-Text-01 | api.minimax.io/v1 | MiniMax 2.5 reasoning, Hailuo video generation (video-01), and speech. |
|
Mistral AI
Mistral AI
|
llm
|
MISTRAL_API_KEY | mistral/mistral-large-latest | api.mistral.ai/v1 | Mistral Large 2, Pixtral, Codestral, and Mistral Small. |
|
Moonshot AI (Kimi)
Moonshot AI
|
llm
|
MOONSHOT_API_KEY | moonshot/moonshot-v1-128k | api.moonshot.ai/v1 | Moonshot v1 long-context models up to 128k/200k tokens. |
|
NAVER Cloud (HyperCLOVA X)
NAVER Cloud
|
llm
|
CLOVA_API_KEY | naver/HCX-003 | clovastudio.stream.ntruss.com/v1 | Korean flagship foundation model HyperCLOVA X with high regional fluency. |
|
OpenAI
OpenAI
|
llm image video tts stt
|
OPENAI_API_KEY | gpt-4o | api.openai.com/v1 | GPT-4o, o1/o3 reasoning, DALL-E 3, Whisper, and TTS-1. |
|
Sber (GigaChat)
Sber
|
llm
|
GIGACHAT_API_KEY | sber/GigaChat-Pro | gigachat.devices.sberbank.ru/api/v1 | Sber GigaChat Pro, GigaChat Max enterprise neural network. |
|
Tencent (Hunyuan)
Tencent
|
llm
|
HUNYUAN_API_KEY | tencent/hunyuan-turbo | api.hunyuan.cloud.tencent.com/v1 | Hunyuan Turbo and Tencent large language reasoning models. |
|
Yandex Cloud (YandexGPT)
Yandex
|
llm
|
YANDEX_API_KEY | yandex/yandexgpt | llm.api.cloud.yandex.net/foundationModels/v1 | YandexGPT 4 Pro, YandexGPT Lite, and Russian language reasoning. |
|
Zhipu AI (GLM / Z.ai)
Zhipu AI
|
llm image video
|
ZHIPU_API_KEY | zai/glm-4-plus | open.bigmodel.cn/api/paas/v4 | GLM-4 Plus, CogView-3, and CogVideoX video generation. |
|
iFlytek (Spark)
iFlytek
|
llm tts stt
|
SPARK_API_KEY | iflytek/spark-max | spark-api-open.xf-yun.com/v1 | iFlytek Spark Desk cognitive models and leading speech intelligence. |
|
xAI (Grok)
xAI
|
llm image video
|
XAI_API_KEY | xai/grok-2 | api.x.ai/v1 | Grok 2, Grok 2 Vision, and Grok Imagine multi-media. |
|
Black Forest Labs (FLUX)
Black Forest Labs
|
image video
|
BFL_API_KEY | bfl/flux-pro-1.1 | api.bfl.ai/v1 | Creators of FLUX.1 [pro], [dev], [schnell], and FLUX 3 Video. |
|
Ideogram
Ideogram
|
image
|
IDEOGRAM_API_KEY | ideogram/ideogram-v2 | api.ideogram.ai/v2 | Industry leader in typography rendering and graphic design images. |
|
Recraft
Recraft
|
image
|
RECRAFT_API_KEY | recraft/recraft-20b | external.api.recraft.ai/v1 | Vector SVG and raster illustration image generation. |
|
Stability AI
Stability AI
|
image
|
STABILITY_API_KEY | stability/sd3.5-large | api.stability.ai/v2beta/stable-image/generate | Stable Diffusion 3.5 Large, SD3.5 Turbo, and Ultra. |
|
Kuaishou Kling AI
Kuaishou
|
video
|
KLING_API_KEY | kling/kling-v1 | api-singapore.klingai.com | State-of-the-art cinematic physics video generator (Kling v1 / v1.5 / v3). |
|
Luma AI (Dream Machine)
Luma AI
|
video
|
LUMA_API_KEY | luma/ray-2 | api.lumalabs.ai/dream-machine/v1 | Dream Machine Ray 2 high-frame-rate video synthesis. |
|
Runway
Runway
|
video
|
RUNWAY_API_KEY | runway/gen3a_turbo | api.dev.runwayml.com/v1 | Gen-3 Alpha and Gen-3 Turbo cinematic video generation. |
|
ShengShu Vidu
ShengShu Technology
|
video
|
VIDU_API_KEY | vidu/viduq1 | api.vidu.com/ent/v2 | High-definition 1080p AI video generation engine. |
|
AssemblyAI
AssemblyAI
|
stt
|
ASSEMBLYAI_API_KEY | assemblyai/conformer-2 | api.assemblyai.com/v2 | Universal-2 and Conformer-2 speech recognition with speaker diarization. |
|
Cartesia (Sonic)
Cartesia
|
tts
|
CARTESIA_API_KEY | cartesia/sonic-english | api.cartesia.ai/tts | Sub-100ms ultra-low latency streaming voice engine. |
|
DeepGram (Nova / Aura)
Deepgram
|
tts stt
|
DEEPGRAM_API_KEY | deepgram/nova-2 | api.deepgram.com/v1 | Nova-2 real-time speech transcription and Aura voice generation. |
|
ElevenLabs
ElevenLabs
|
tts stt
|
ELEVENLABS_API_KEY | elevenlabs/eleven_multilingual_v2 | api.elevenlabs.io/v1 | Hyper-realistic multi-language voice synthesis and Scribe STT. |
|
Fish Audio
Fish Audio
|
tts stt
|
FISH_AUDIO_API_KEY | fish/tts-1 | api.fish.audio/v1 | Zero-shot cross-lingual voice cloning and speech transcription. |
|
Gladia
Gladia
|
stt
|
GLADIA_API_KEY | gladia/v2 | api.gladia.io/v2 | Real-time multi-lingual speech-to-text with 99+ language coverage. |
|
PlayHT
PlayHT
|
tts
|
PLAYHT_API_KEY | playht/PlayDialog | api.play.ht/api/v2 | Ultra-realistic conversational voice engine with PlayDialog. |
|
Sarvam AI
Sarvam AI
|
tts stt
|
SARVAM_API_KEY | sarvam/bulbul:v1 | api.sarvam.ai | Indic language voice synthesis (Bulbul) and speech recognition (Saaras). |
|
Soniox
Soniox
|
tts stt
|
SONIOX_API_KEY | soniox/stt-en | api.soniox.com/v1 | Accurate enterprise AI speech recognition and real-time TTS. |
|
Speechmatics
Speechmatics
|
stt
|
SPEECHMATICS_API_KEY | speechmatics/standard | eu1.asr.api.speechmatics.com/v2 | Autonomous speech recognition across 50+ languages and accents. |
Complete Global .env Configuration File
Create a file named .env in the root of your project directory. Pyvello automatically discovers keys for any provider you select:
# ==============================================================================
# PYVELLO GLOBAL MODEL & PROVIDER CREDENTIALS
# Add the key for whichever provider you specify in ui.Agent(model="...")
# ==============================================================================
# 1. Unified Inference Aggregators
OPENROUTER_API_KEY=sk-or-v1-your_openrouter_key_here
GROQ_API_KEY=gsk_your_groq_key_here
TOGETHER_API_KEY=your_together_key_here
FIREWORKS_API_KEY=your_fireworks_key_here
SILICONFLOW_API_KEY=sk-your_siliconflow_key_here
FAL_KEY=your_fal_key_here
REPLICATE_API_TOKEN=r8_your_replicate_token_here
DEEPINFRA_API_KEY=your_deepinfra_key_here
NOVITA_API_KEY=your_novita_key_here
NEBIUS_API_KEY=your_nebius_key_here
# 2. Frontier Reasoning & LLM Providers
OPENAI_API_KEY=sk-proj-your_openai_key_here
ANTHROPIC_API_KEY=sk-ant-api03-your_anthropic_key_here
GEMINI_API_KEY=AIzaSy_your_gemini_key_here
DEEPSEEK_API_KEY=sk-your_deepseek_key_here
MISTRAL_API_KEY=your_mistral_key_here
XAI_API_KEY=xai-your_xai_key_here
# 3. Asian & Chinese Frontier Labs
ZHIPU_API_KEY=your_zhipu_glm_key_here
DASHSCOPE_API_KEY=sk-your_dashscope_qwen_key_here
MOONSHOT_API_KEY=sk-your_moonshot_kimi_key_here
QIANFAN_API_KEY=your_baidu_qianfan_key_here
HUNYUAN_API_KEY=your_tencent_hunyuan_key_here
BYTEPLUS_API_KEY=your_byteplus_doubao_key_here
MINIMAX_API_KEY=your_minimax_hailuo_key_here
# 4. Specialized Image Generation Engines
BFL_API_KEY=your_black_forest_labs_flux_key_here
IDEOGRAM_API_KEY=your_ideogram_key_here
STABILITY_API_KEY=sk-your_stability_key_here
RECRAFT_API_KEY=your_recraft_key_here
# 5. Specialized Cinematic Video Generation Engines
KLING_API_KEY=your_kuaishou_kling_key_here
RUNWAY_API_KEY=your_runway_gen3_key_here
LUMA_API_KEY=your_luma_ray2_key_here
VIDU_API_KEY=your_vidu_key_here
# 6. Specialized Voice Synthesis (TTS) & Speech-to-Text (STT)
ELEVENLABS_API_KEY=sk_your_elevenlabs_key_here
CARTESIA_API_KEY=your_cartesia_key_here
DEEPGRAM_API_KEY=your_deepgram_key_here
SARVAM_API_KEY=your_sarvam_indic_key_here
ASSEMBLYAI_API_KEY=your_assemblyai_key_here
FISH_AUDIO_API_KEY=your_fish_audio_key_here
# 7. Local Offline Execution (100% Free, Zero Key Required)
# OLLAMA_API_BASE=http://localhost:11434
# OPENAI_API_BASE=http://localhost:1234/v1
Custom Base URLs (api_base) & Direct API Keys (api_key)
You do not have to rely only on .env files. Pyvello's ui.Agent and ui.Orchestrator accept explicit api_key, api_base, and extra_headers directly in Python:
- Direct Constructor Argument:
api_key="..."orapi_base="..."takes top priority over everything else. - Environment Variable (.env): If no argument is passed, Pyvello automatically inspects the environment for provider-specific keys (e.g.
OPENROUTER_API_KEY,ANTHROPIC_API_KEY). - Custom Endpoints: Supports
OPENAI_API_BASE,OLLAMA_API_BASE, or custom proxy host URLs.
- • Ollama Local: api_base="http://localhost:11434"
- • vLLM Cluster: api_base="http://localhost:8000/v1"
- • LM Studio: api_base="http://localhost:1234/v1"
- • Corporate Proxy: api_base="https://gateway.internal/v1"
- • Custom Headers: extra_headers={"HTTP-Referer": "..."}
import pyvello as ui
# ------------------------------------------------------------------------------
# 1. Local LM Studio or vLLM Cluster with Custom URL
# ------------------------------------------------------------------------------
agent_vllm = ui.Agent(
name="ClusterAgent",
model="openai/meta-llama/Llama-3.3-70B-Instruct",
api_base="http://localhost:8000/v1", # Custom base URL endpoint
api_key="token-custom-cluster-key", # Optional custom key or token
system_prompt="You are a high-throughput cluster inference agent."
)
# ------------------------------------------------------------------------------
# 2. Local Ollama on Non-Default Port / Remote Machine
# ------------------------------------------------------------------------------
agent_remote_ollama = ui.Agent(
name="RemoteOllamaAgent",
model="ollama/deepseek-r1:32b",
api_base="http://192.168.1.100:11434", # Custom remote Ollama instance
system_prompt="Private offline reasoning on enterprise GPU node."
)
# ------------------------------------------------------------------------------
# 3. Enterprise Internal Gateway / Corporate Proxy with Custom Headers
# ------------------------------------------------------------------------------
agent_corp_proxy = ui.Agent(
name="EnterpriseGatewayAgent",
model="openai/gpt-4o",
api_base="https://internal-llm-gateway.corp.net/v1",
api_key="corp-service-account-jwt-token",
extra_headers={
"X-Department": "Risk-Engineering",
"X-Audit-ID": "audit-sec-9921"
},
system_prompt="Enterprise compliance reasoning assistant."
)
# ------------------------------------------------------------------------------
# 4. Multi-Agent Orchestrator with Custom Supervisor URL & Keys
# ------------------------------------------------------------------------------
orchestrator = ui.Orchestrator(
agents=[agent_vllm, agent_remote_ollama],
name="HybridSwarmSupervisor",
supervisor_model="openai/gpt-4o",
api_base="https://internal-llm-gateway.corp.net/v1",
api_key="corp-service-account-jwt-token",
supervisor_system_prompt="Synthesize outputs from local and remote nodes."
)
if __name__ == "__main__":
agent_vllm.to_app().launch(port=8080)
Using Different Providers in Pure Python
Once your keys are in .env, simply pass the model string to ui.Agent:
import pyvello as ui
# 1. OpenRouter (Anthropic Claude 3.7 Sonnet) - Reads OPENROUTER_API_KEY from .env
agent_claude = ui.Agent(
name="Architect",
model="openrouter/anthropic/claude-3.7-sonnet",
system_prompt="You are a high-level software architect."
)
# 2. DeepSeek R1 Reasoning Model - Reads DEEPSEEK_API_KEY from .env
agent_deepseek = ui.Agent(
name="ReasoningAgent",
model="deepseek/deepseek-reasoner",
system_prompt="Solve complex algorithmic and mathematical proofs step-by-step."
)
# 3. Google Gemini 2.0 Flash - Reads GEMINI_API_KEY from .env
agent_gemini = ui.Agent(
name="MultimodalResearcher",
model="gemini/gemini-2.0-flash",
system_prompt="Analyze multimodal inputs and research papers instantly."
)
# 4. Ollama (Local & 100% Free - Zero API Key Required)
agent_local = ui.Agent(
name="LocalCodeReviewer",
model="ollama/qwen2.5-coder",
system_prompt="Analyze code offline on local hardware with zero cloud egress."
)
# 5. Direct Code Override with Custom API Key and Base URL
agent_custom = ui.Agent(
name="CustomProxyAgent",
model="openai/my-custom-model",
api_key="sk-custom-secret-token",
api_base="http://localhost:1234/v1",
system_prompt="Custom local enterprise model."
)
# Launch in single line
if __name__ == "__main__":
agent_claude.to_app().launch(port=8000)
Structured Outputs & Token Control
Constrain model completions to strictly validated data structures using standard Pydantic v2 models (pydantic.BaseModel) or JSON Schema dictionaries, while strictly enforcing hard completion ceilings (max_tokens) to eliminate runaway inference loops and unpredictable billing.
from pydantic import BaseModel, Field
from typing import List
class LineItem(BaseModel):
description: str = Field(description="Item label")
quantity: int = Field(default=1)
unit_price: float
total: float
class FinancialInvoice(BaseModel):
vendor_name: str = Field(description="Legal entity")
invoice_number: str
subtotal: float
tax_amount: float = 0.0
grand_total: float
line_items: List[LineItem] = []
is_approved: bool = True
{
"vendor_name": "CloudScale",
"invoice_number": "INV-2026-904",
"subtotal": 160.0,
"tax_amount": 16.0,
"grand_total": 176.0,
"line_items": [
{
"description": "40 GPU hours at $3.50/hr",
"quantity": 40,
"unit_price": 3.5,
"total": 140.0
},
{
"description": "2TB NVMe storage",
"quantity": 1,
"unit_price": 20.0,
"total": 20.0
}
],
"is_approved": true
}
1. Type Safety with Pydantic v2 Models
When you provide a Pydantic model class to ui.Agent(structured_output=MyModel):
LiteLLM maps the Pydantic schema to OpenAI JSON Schema, Anthropic Tool-Use, or Gemini Structured Mode.
The completion string is validated via model_validate_json() with markdown code fence auto-cleaning.
The validated instance is stored on agent.last_structured_output with full IDE type hints.
2. Complete Python Implementation
examples/06_structured_outputs_and_tokens.pyfrom typing import List, Optional
from pydantic import BaseModel, Field
import pyvello as ui
# 1. Define target Pydantic schema for structured output extraction
class LineItem(BaseModel):
description: str = Field(description="Service or product description")
quantity: int = Field(default=1, description="Number of units")
unit_price: float = Field(description="Price per unit in USD")
total: float = Field(description="Line item subtotal")
class FinancialInvoice(BaseModel):
vendor_name: str = Field(description="Legal entity or vendor name")
invoice_number: str = Field(description="Unique invoice reference identifier")
billing_date: str = Field(description="ISO 8601 date of the transaction")
line_items: List[LineItem] = Field(default_factory=list, description="Detailed itemized breakdown")
subtotal: float = Field(description="Sum of all line items before tax")
tax_amount: float = Field(default=0.0, description="Applicable tax amount")
grand_total: float = Field(description="Final payable amount")
payment_terms: str = Field(default="Net 30", description="Contract payment conditions")
is_approved: bool = Field(default=True, description="Audit compliance validation flag")
# 2. Define Agent with Pydantic model and token limit ceiling
extractor_agent = ui.Agent(
name="FinancialExtractor",
system_prompt=(
"You are an enterprise accounting auditor. Parse incoming invoice text or receipts "
"and extract structured financial entities adhering strictly to the FinancialInvoice schema."
),
model="openrouter/z-ai/glm-5.3-flash", # Ultra low-cost ($0.05/M) or auto-prefixed 'z-ai/glm-5.3-flash'
models=[
"openrouter/z-ai/glm-5.3-flash",
"openrouter/google/gemini-2.0-flash-001",
"openrouter/deepseek/deepseek-chat",
"openrouter/meta-llama/llama-3.3-70b-instruct",
"openrouter/qwen/qwen3.7-flash",
],
max_tokens=800, # Limit completion tokens strictly (accommodates reasoning models)
structured_output=FinancialInvoice, # Enforce Pydantic BaseModel schema validation
temperature=0.0, # Zero temperature for deterministic extraction
)
# 3. Programmatic usage and typed property access
async def process_invoice(text: str):
async for chunk in extractor_agent.run(text):
print(chunk, end="")
# Access strongly typed Pydantic instance directly:
result: FinancialInvoice = extractor_agent.last_structured_output
print(f"Vendor: {result.vendor_name}, Total: ${result.grand_total}")
print(f"Line items extracted: {len(result.line_items)}")
# 4. Or launch as full interactive web application in single line:
if __name__ == "__main__":
extractor_agent.to_app(
title="Pyvello Financial Extraction & Structured Output",
description="Extract itemized invoices into Pydantic models with token ceiling controls.",
).launch()
3. Token Limit & Cost Governance (max_tokens)
Unconstrained language models can occasionally enter repetitive loops or produce unnecessarily verbose responses, dramatically increasing token costs and latency. Passing max_tokens ensures that the completion will never exceed the specified ceiling.
Passed directly to LiteLLM's max_tokens parameter during streaming and synchronous calls:
agent = ui.Agent(
name="TightSummarizer",
model="gpt-4o",
max_tokens=200, # Strict limit
temperature=0.2
)
When configured on ui.Orchestrator, the token budget cascades automatically to all worker agents:
supervisor = ui.Orchestrator(
agents=[researcher, coder],
max_tokens=500, # Cascades to workers
structured_output=ConsensusReport
)
4. Structured Output & Token Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| structured_output | Type[BaseModel] | dict | None | None | Target schema. Accepts any Pydantic BaseModel class, JSON schema dict, or {"type": "json_object"}. |
| max_tokens | int | None | None | Hard limit on output completion tokens generated by the provider model. |
| temperature | float | 0.7 | Sampling temperature. Recommend 0.0 for deterministic schema adherence and zero hallucinations. |
| timeout | float | None | 6.0 | Network request timeout in seconds passed to LiteLLM before fallback simulation. |
| last_structured_output | BaseModel | dict | None | None | Instance attribute populated after each agent run. Contains the parsed Pydantic instance or dictionary. |
Agent Core & to_app() API
The ui.Agent class encapsulates an autonomous AI agent capable of multi-turn reasoning, streaming text generation, multimodal inputs, and automated tool execution loops. The to_app() method converts any agent into an interactive, full-screen web app in a single line.
Looking for provider environment variable names for OpenRouter, OpenAI, Anthropic, Gemini, Groq, DeepSeek, or local Ollama?
ui.Agent() Constructor Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| name | str | 'AI Assistant' | Display name of the agent. |
| system_prompt | str | 'You are a helpful...' | System instruction guiding reasoning and role behavior. |
| model | str | 'gpt-4o' | Active LLM identifier supported by LiteLLM (e.g. openrouter/anthropic/claude-3.7-sonnet, openrouter/deepseek/deepseek-chat, gpt-4o). |
| models | List[str | dict] | None | Optional list of selectable models for runtime switching. |
| tools | List[Callable] | None | List of Python functions decorated with @ui.tool available for agent tool calling. |
| stream | bool | True | Whether to stream tokens in real-time over WebSocket. |
| temperature | float | 0.7 | Sampling temperature between 0.0 and 2.0. Use 0.0 for deterministic schema extraction. |
| max_tokens | int | None | None | Strict ceiling on generated completion tokens. Prevents runaway billing and infinite loops. |
| structured_output | Type[BaseModel] | dict | None | None | Constrain LLM output to a strict Pydantic class or JSON schema. Parsed instance is saved in self.last_structured_output. |
| timeout | float | None | 6.0 | Network inference timeout limit in seconds passed to LiteLLM. |
| max_tool_iterations | int | 5 | Safety guard limit on consecutive ReAct tool calling loops. |
| api_key | str | None | None | Explicit API key override for the provider. |
| api_base | str | None | None | Custom inference base URL (e.g. Ollama, vLLM, OpenRouter). |
| observability | bool | True | Enable telemetry tracing into the Langfuse-style slide-over sheet. |
| debug | bool | False | Enable developer debug notices and local simulation fallback warnings. |
| image | bool | str | False | Enable native image generation. Set to True for default (Flux Schnell) or pass a model name (e.g. openrouter/black-forest-labs/flux-schnell, openrouter/bytedance-seed/seedream-5-0-flash, kolors). |
| image_api_base | str | None | None | Custom API base URL for image generation (e.g. self-hosted GPU endpoint or Chinese model API). |
| image_api_key | str | None | None | Optional provider API key override for the image generation model. |
| video | bool | str | False | Enable native video generation. Pass True or a model identifier (e.g. openrouter/bytedance/seedance-2.0-mini, minimax/video-01, cogvideox). |
| video_api_base | str | None | None | Custom API base URL for video generation endpoints (e.g. Minimax or Kling API). |
| video_api_key | str | None | None | Optional provider API key override for video generation. |
| audio | bool | str | False | Enable native speech synthesis / TTS. Pass True (OpenAI TTS) or model name (e.g. openrouter/heygen/heygen-voice-1-turbo). |
| audio_voice | str | 'alloy' | Voice preset for synthesized audio (e.g. alloy, echo, shimmer, fable). |
| audio_api_base | str | None | None | Custom API base URL for text-to-speech voice generation endpoints. |
| audio_api_key | str | None | None | Optional provider API key override for TTS generation. |
| bool | False | Enable native executive PDF document synthesis on demand. Produces downloadable PDF base64 data URIs. | |
| multimodal | bool | False | Master toggle enabling image, video, audio, and PDF generation simultaneously on the agent. |
agent.to_app() Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| title | str | Agent name | Browser tab title and header navigation title. |
| description | str | None | None | Subtitle description displayed under the application title. |
| placeholder | str | 'Ask a question...' | Input placeholder text in prompt box. |
| examples | List[str] | None | None | Suggested prompts rendered as clickable starter pills. |
| models | List[str | dict] | None | None | Model selection dropdown options. |
| theme | str | 'light' | 'light' or 'dark' default color mode. |
| palette | str | 'red' | One of calibrated palettes ('red', 'emerald', 'indigo', 'rose', 'zinc', etc.). |
| accept_types | List[str] | None | ['text', 'image', 'pdf', 'video'] | File types allowed for multimodal upload attachments. |
| is_full_screen | bool | True | Render interface edge-to-edge with ChatGPT-style sidebar. |
| enable_graph | bool | True | Enable interactive workflow graph inspector tab. |
| debug | bool | False | Activate Developer Debug Inspector and payload logging. |
| observability | bool | True | Provide slide-over Langfuse Observability sheet button in header. |
| source_code | str | None | None | Optional source code string displayed in the 'View Code' modal. |
Code Example
import pyvello as ui
@ui.tool
def get_stock_price(ticker: str) -> dict:
"""Retrieve real-time market quote for a stock ticker.
:param ticker: Stock symbol e.g. NVDA, AAPL
"""
return {"ticker": ticker.upper(), "price": 142.50, "currency": "USD", "change": "+3.4%"}
agent = ui.Agent(
name="MarketAnalyst",
model="openrouter/anthropic/claude-3.7-sonnet",
system_prompt="You are a financial analyst. Always use tools to lookup live prices.",
tools=[get_stock_price],
stream=True,
)
# Launch with full app customization and runtime model switching
app = agent.to_app(
title="Financial Analyst Agent",
description="Real-time market intelligence powered by OpenRouter & LiteLLM",
placeholder="Ask about NVDA, AAPL, TSLA or market trends...",
examples=["What is the price of NVDA?", "Compare AAPL and TSLA quotes"],
models=[
"openrouter/anthropic/claude-3.7-sonnet",
"openrouter/deepseek/deepseek-chat",
"openrouter/openai/gpt-4o",
"openrouter/meta-llama/llama-3.3-70b-instruct",
],
palette="red",
theme="light",
observability=True,
debug=False,
)
if __name__ == "__main__":
app.launch()
Native Multimodal Omni-Agent: Plug & Play
How Pyvello enables one single agent to reason on complex logic while natively generating images, videos, speech audio, and PDF documents across OpenRouter, OpenAI, and custom Chinese / self-hosted endpoints.
Generative media models (e.g. FLUX, Kolors, Seedream, Hailuo, Seedance, HeyGen) are pure completion or custom REST endpoints. They do not support tool-calling schemas. Passing tools=[generate_image] to OpenRouter causes HTTP 404: "No endpoints found that support tool use".
In Pyvello, multimodal capabilities are native agent attributes. Simply set image=True, video=True, audio=True, or pdf=True. Pyvello seamlessly routes media creation directly to specialized engines without attaching tool schemas to completion models.
Using custom Chinese models (Minimax, Kling, CogVideoX, Kolors) or local GPU endpoints? Pyvello automatically walks arbitrary JSON payloads and extracts media URLs or base64 streams without requiring custom response schemas from the developer.
import pyvello as ui
# Single unified omni-agent handling reasoning, images, videos, audio & PDF
agent = ui.Agent(
name="UniversalMultimodalStudio",
# Primary reasoning model (OpenRouter GLM 5.3 Flash / GPT-4o)
model="openrouter/z-ai/glm-5.3-flash",
# 1. Native Image Generation (BFL FLUX, fal.ai, BytePlus Seedream, Ideogram, or DALL-E)
# E.g. image="bfl/flux-pro-1.1", "fal/flux/schnell", or "openrouter/bytedance-seed/seedream-5-0-flash"
image="openrouter/bytedance-seed/seedream-5-0-flash",
# 2. Native Video Generation (Kling AI, Runway Gen-3, Luma Ray 2, or Seedance)
# E.g. video="kling/kling-v1", "runway/gen3a_turbo", or "openrouter/bytedance/seedance-2.0-mini"
video="openrouter/bytedance/seedance-2.0-mini",
# 3. Native Audio & Voice Synthesis (ElevenLabs, Cartesia Sonic, Deepgram, or HeyGen)
# E.g. audio="elevenlabs/multilingual_v2", "cartesia/sonic-english", or "openrouter/heygen/heygen-voice-1-turbo"
audio="openrouter/heygen/heygen-voice-1-turbo",
audio_voice="alloy",
# 4. Native Executive Document & PDF Generation
pdf=True,
system_prompt=(
"You are an advanced multimodal AI assistant. Converse and reason on complex topics, "
"and natively generate images, videos, speech audio, and executive PDF documents on demand."
),
)
# Launch unified studio app with one command
app = agent.to_app(
title="Universal Multimodal Studio",
description="Single-chat multi-model AI assistant with native image, video, audio, and PDF generation.",
placeholder="Ask for an image, video, audio narration, PDF report, or reasoning query...",
)
if __name__ == "__main__":
app.launch()
ChatInterface (Full Parity Reference)
ui.ChatInterface provides 100% parameter parity with Agent.to_app(). You can pass a custom Python reply function fn, an existing agent, or pass model, system_prompt, and tools directly.
ChatInterface Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| fn | Callable | None | None | Optional streaming generator or function callback (message, history, ...). |
| agent | Agent | None | None | Optional Agent instance. If provided, overrides fn. |
| title | str | 'AI Assistant' | Browser title and top navigation header title. |
| description | str | None | None | Subtitle description displayed under the app title. |
| placeholder | str | 'Ask a question...' | Input placeholder text in prompt box. |
| examples | List[str] | None | None | Suggested prompts rendered as clickable starter pills. |
| models | List[str | dict] | None | None | List of models for the model picker dropdown. |
| model | str | None | None | Convenience parameter: auto-instantiates an Agent with this model. |
| system_prompt | str | None | None | Convenience parameter: system instruction for auto-instantiated Agent. |
| tools | List[Callable] | None | None | Convenience parameter: list of @ui.tool functions. |
| temperature | float | 0.7 | Sampling temperature. |
| palette | str | 'red' | One of calibrated theme palettes. |
| is_full_screen | bool | True | Render interface edge-to-edge with sidebar. |
| enable_graph | bool | True | Enable interactive workflow graph inspector tab. |
| observability | bool | True | Provide slide-over Langfuse Observability sheet button. |
Example: Direct Agent Configuration
import pyvello as ui
@ui.tool
def get_crypto_quote(symbol: str) -> dict:
"""Fetch live cryptocurrency prices."""
return {"symbol": symbol.upper(), "price_usd": 68420.00, "24h_change": "+4.2%"}
# Pass model, system_prompt, tools directly to ChatInterface with OpenRouter!
app = ui.ChatInterface(
model="openrouter/deepseek/deepseek-chat",
system_prompt="You are a crypto research specialist.",
tools=[get_crypto_quote],
models=[
"openrouter/deepseek/deepseek-chat",
"openrouter/google/gemini-2.0-flash-001",
"openrouter/anthropic/claude-3.7-sonnet",
],
title="Crypto Intelligence Assistant",
placeholder="Ask about BTC, ETH, SOL...",
examples=["What is the price of BTC?", "Summarize market movements"],
palette="red",
observability=True,
)
if __name__ == "__main__":
app.launch()
Document & Attachment Ingestion Matrix
Pyvello provides zero-configuration document ingestion directly in ui.ChatInterface. When users click the attachment clip or drop files into the prompt bar, Pyvello processes the file content using native extraction engines and delivers it directly to the model's context window.
| Format | Extensions | Extraction Engine | LLM Delivery Format | Capabilities |
|---|---|---|---|---|
| PDF Documents | PyPDF / Native Byte Decoder | [Attached PDF: name (pages)]\n```document...``` | Financial reports, contracts, multi-page legal filings Q&A without external OCR services. | |
| Word Documents | .docx | Native OpenXML XML Parser (Zero Dependencies) | [Attached Word Document: name]\n```document...``` | Paragraph-accurate extraction of Word specifications, requirements, and memos. |
| Structured Tables | .csv, .json, .tsv | Native UTF-8 Stream Decoder | ```csv / ```json structured code fence | Tabular query, statistical calculations, automated charting, and schema extraction. |
| Source Code | .py, .ts, .js, .rs, .go, .sql | UTF-8 File Reader | ```<lang> syntax-highlighted block | Code review, bug fixing, refactoring, unit test generation, and architecture audits. |
| Images (Vision) | .png, .jpg, .webp, .gif | Base64 Vision Payload Encoder | {"type": "image_url", "image_url": {"url": "data:..."}} | Multimodal visual reasoning, UI screenshot analysis, diagram parsing, and image editing. |
| Media Assets | .mp3, .wav, .mp4, .webm | Native Pyvello Media Storage | Interactive audio waveforms & video players | Voice transcription, media playback preview cards, and audio-to-text workflows. |
Image-to-Image Synthesis & AI Image Editing
When image=True or an explicit image model (such as "openrouter/bytedance-seed/seedream-5-0-flash" or "flux") is passed to ui.ChatInterface, Pyvello supports both Text-to-Image and Image-to-Image editing natively.
Upload any concept sketch, product photo, or existing generation via the chat attachment button.
Enter natural prompts such as: "Change the lighting to warm sunset neon", "Add futuristic cat headphones to the character", or "Render this wireframe as an Apple-style glassmorphic landing page".
import pyvello as ui
# ChatInterface with multimodal image editing and document analysis enabled
app = ui.ChatInterface(
model="openrouter/z-ai/glm-5.3-flash",
image="openrouter/bytedance-seed/seedream-5-0-flash",
video="openrouter/bytedance/seedance-2.0-mini",
audio="openrouter/heygen/heygen-voice-1-turbo",
pdf=True,
title="Multimodal Creative Studio",
placeholder="Attach an image to edit, a PDF/Docx to analyze, or ask anything...",
examples=[
"Attach photo and prompt: 'Add futuristic glowing neon visor'",
"Attach docx and prompt: 'Summarize executive milestones'",
"Create a 10-second cinematic video of a spaceship launch",
],
palette="emerald",
)
if __name__ == "__main__":
app.launch()
Orchestrator (Multi-Agent Swarms & Attached Tools)
The ui.Orchestrator coordinates specialized worker agents into an autonomous swarm. Each worker's deliverable is transferred into the context of subsequent workers, and the supervisor generates the consolidated final resolution. Each specialist's execution is tracked sequentially in the Langfuse-style Observability sheet with real-time badges in the UI.
First-Class Conditional Tool Nodes & Two-Way Edges
Specialist agents with attached tools (tools=[fn]) automatically render dedicated Tool Nodes in the workflow graph. These are connected via bidirectional execution edges (<──────>) representing tool calls and result returns. Clicking Agent Graph in the top navbar launches an expansive edge-to-edge canvas with automatic Dagre centering and zoom-to-fit.
ui.orchestrator() Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| agents | List[Agent] | required | List of specialized worker subagents. |
| supervisor_system_prompt | str | None | None | System instructions guiding supervisor on decomposing and synthesizing. |
| supervisor_model | str | 'gpt-4o' | Model ID for supervisor synthesis. |
| models | List[str | dict] | None | None | Selectable models for runtime switching. |
| temperature | float | 0.7 | Sampling temperature. |
| stream | bool | True | Whether to stream tokens in real-time. |
| name | str | 'SwarmSupervisor' | Name of the orchestrator. |
Code Example: Swarm with Attached Tools
import pyvello as ui
@ui.tool
def get_market_metrics(industry: str) -> dict:
"""Lookup market size, CAGR, and valuation multiples."""
return {"industry": industry, "market_size": "$42B", "cagr": "18.4%"}
@ui.tool
def estimate_aws_cost(clusters: int, nodes_per_cluster: int) -> dict:
"""Calculate monthly AWS EKS compute & egress costs."""
return {"nodes": clusters * nodes_per_cluster, "monthly_usd": 3850.00}
# Define Specialist Agents - Each worker has its own dedicated OpenRouter model
market_worker = ui.agent(
name="MarketResearcher",
model="openrouter/deepseek/deepseek-chat",
system_prompt="Analyze target addressable market and unit economics.",
tools=[get_market_metrics]
)
infra_worker = ui.agent(
name="InfraArchitect",
model="openrouter/meta-llama/llama-3.3-70b-instruct",
system_prompt="Specify cloud infrastructure and multi-region Kubernetes nodes.",
tools=[estimate_aws_cost]
)
risk_worker = ui.agent(
name="RiskAssessor",
model="openrouter/google/gemini-2.0-flash-001",
system_prompt="Evaluate compliance, HIPAA guidelines, and operational risk."
)
# Configure Dynamic Swarm Orchestrator with a dedicated Supervisor model
orchestrator = ui.orchestrator(
agents=[market_worker, infra_worker, risk_worker],
supervisor_model="openrouter/anthropic/claude-3.7-sonnet",
supervisor_system_prompt="""You are an enterprise software architect supervising junior engineers.
Decompose user requests and delegate only to the needed specialists.
Synthesize verified deliverables into a unified architecture proposal.""",
palette="red",
)
if __name__ == "__main__":
orchestrator.to_app().launch()
Router, Chain & LLM-As-Judge
Pyvello includes first-class implementations of modern agentic design patterns: semantic query routing, sequential prompt chaining, fan-out parallel execution, and automated LLM-as-a-judge evaluation.
ui.router()
Classifies user requests and dispatches them to optimal specialist agents or deterministic handlers.
ui.chain() & parallel()
Chains sequential reasoning prompts or runs concurrent evaluations across multiple models.
ui.judge()
Evaluates agent responses against quality rubrics, returning structured scores and critique notes.
Code Example
import pyvello as ui
# 1. Specialized worker agents with distinct OpenRouter models
coder = ui.Agent(
name="CodingSpecialist",
model="openrouter/qwen/qwen-2.5-coder-32b-instruct",
system_prompt="Write production-grade, type-annotated Python code."
)
writer = ui.Agent(
name="Copywriter",
model="openrouter/meta-llama/llama-3.3-70b-instruct",
system_prompt="Draft clear marketing copy and technical documentation."
)
# 2. Semantic Router with high-speed intent classifier
router = ui.Router(
routes={"code": coder, "marketing": writer},
classifier_model="openrouter/openai/gpt-4o-mini"
)
# 3. Sequential Chain with step-specific OpenRouter models
chain = ui.PromptChain([
ui.ChainStep(
name="Summarize",
model="openrouter/deepseek/deepseek-chat",
system_prompt="Summarize this article: {input}"
),
ui.ChainStep(
name="Translate",
model="openrouter/google/gemini-2.0-flash-001",
system_prompt="Translate summary to Spanish: {output_from_step_1}"
),
])
# 4. LLM-as-Judge Quality Gate with advanced reasoning model
judge = ui.LLMAsJudge(
name="QualityJudge",
model="openrouter/anthropic/claude-3.7-sonnet",
rubric="Evaluate code for security vulnerabilities, time complexity, and readability.",
threshold=4.5
)
# 5. Launch actionable multi-agent semantic router interface
app = router.to_app(
title="Multi-Agent Semantic Router",
description="Intelligent prompt routing across Qwen 2.5 Coder and Llama 3.3 70B with real-time graph visualization.",
placeholder="Ask to write Python code or draft product marketing copy...",
examples=[
"Write a Python async queue with worker concurrency and retry backoff",
"Draft a product launch announcement for our reactive UI framework",
],
palette="violet",
)
if __name__ == "__main__":
app.launch(port=8080)
Langfuse Real-Time Observability Sheet
Pyvello features a slide-over Observability Sheet modeled after industry-standard LLM diagnostics (such as Langfuse). Accessible anytime via the [Observability] activity button in the top navigation bar, the sheet updates in real-time over WebSockets.
Continuous Sequential Step Progression
In multi-turn conversations, execution steps do not reset. If Turn 1 completed at Step 4, then Turn 2 automatically continues at Step 5, Step 6, Step 7, and Step 8:
Dual Action Pills Below Every Message
Below each assistant message, Pyvello displays non-intrusive action pills that open an execution inspector modal:
- [Agent: Name]: Shows which agent executed the deliverable.
- [LLM called (N)]: Displays all model inferences, prompt messages, returned text, token economics, and latency.
- [Tools called (N)]: Displays all ReAct tool calls, arguments JSON, and execution return values.
Container & Columns
Ergonomic responsive grid and flexbox layout primitives. Use ui.columns(N) with python context managers to create multi-column layouts effortlessly.
import pyvello as ui
with ui.App(title="Layout Containers & Columns Demo", theme="light", palette="red") as app:
with ui.container(max_width="6xl"):
ui.title("Multi-Column Responsive Grid")
col1, col2 = ui.columns(2)
with col1:
ui.title("Left Panel")
ui.text("Configure parameters here.")
with col2:
ui.title("Right Panel")
ui.metric(label="System Health", value="99.98%", delta="+0.04%")
if __name__ == "__main__":
app.launch()
Card
Structured card container with optional title, description header, loading skeleton, and nested component slots.
Production Cluster
Active nodes: 12 · Health: Nominal
| Parameter | Type | Default | Description |
|---|---|---|---|
| title | str | None | None | Card header title text. |
| description | str | None | None | Subtitle description below the header. |
| loading | bool | False | When true, displays an animated skeleton placeholder. |
| class_name | str | None | None | Custom Tailwind CSS classes. |
import pyvello as ui
with ui.App(title="Card Container Demo", theme="light", palette="red") as app:
with ui.card(title="Server Telemetry", description="Real-time latency metrics"):
ui.metric(label="P99 Latency", value="42 ms", delta="-6 ms", delta_type="positive")
ui.button("Flush Cache", variant="outline")
if __name__ == "__main__":
app.launch()
Tabs
Tabbed navigation container with strict panel content isolation and animated transitions.
import pyvello as ui
with ui.App(title="Tabs Layout Demo", theme="light", palette="red") as app:
ui.title("Tabbed Navigation")
tab_overview, tab_settings = ui.tabs([
{"id": "overview", "label": "Overview"},
{"id": "settings", "label": "Settings"},
])
with tab_overview:
ui.text("System summary metrics and telemetry.")
ui.metric(label="Throughput", value="1,240 req/s")
with tab_settings:
ui.switch(label="Enable Notifications", value=True)
ui.button("Save Preferences", variant="default")
if __name__ == "__main__":
app.launch()
Accordion & Expander
Collapsible containers for organizing detailed content, advanced settings, and FAQ accordions.
import pyvello as ui
with ui.App(title="Accordion & Expander Demo", theme="light", palette="red") as app:
ui.title("Collapsible Content Panels")
# Single collapsible section
with ui.expander("Advanced Configuration", default_open=False):
ui.slider(label="Context Window Size", value=4096, min=1024, max=16384, step=1024)
# Multi-item accordion
ui.accordion(items=[
{"title": "How does Hot Reload work?", "content": "Pyvello uses file system watchers to stream live diffs."},
{"title": "Which LLMs are supported?", "content": "All providers supported by LiteLLM (OpenRouter, OpenAI, Anthropic, DeepSeek, etc.)."}
])
if __name__ == "__main__":
app.launch()
Dialog & Sheet (Modal & Drawer)
Overlay modals and slide-out drawers (sheets) with backdrop blur, keyboard dismissal, and customizable triggers.
import pyvello as ui
with ui.App(title="Modal Dialog & Drawer Sheet", theme="light", palette="red") as app:
ui.title("Interactive Overlays")
# Modal Dialog
with ui.dialog(title="Confirm Deployment", trigger="Deploy Model", trigger_variant="default"):
ui.text("Are you sure you want to promote v2.4 to production?")
ui.button("Confirm", variant="default")
# Slide-Over Drawer Sheet
with ui.sheet(title="Agent Inspection", trigger="Inspect Agent", side="right"):
ui.json_viewer(data={"agent": "MarketResearcher", "status": "active", "temperature": 0.7})
if __name__ == "__main__":
app.launch()
Form (Grouped Submission)
Encapsulates multiple input fields into a single reactive submission boundary with validation, confirmation modals, and unified submit handlers.
import pyvello as ui
def handle_deploy(payload: dict):
ui.toast(f"Cluster deployed: {payload.get('cluster_name')}", type="success")
with ui.App(title="Form Hub") as app:
with ui.form(title="Cluster Configuration", submit_label="Deploy Cluster", on_submit=handle_deploy):
ui.text_input(label="Cluster Name", placeholder="us-east-prod-01", id="cluster_name")
ui.slider(label="Initial Replicas", min=1, max=20, default=3, id="replicas")
ui.switch(label="Enable Zero-Trust Encryption", value=True, id="encryption")
if __name__ == "__main__":
app.launch()
Separator & Divider
Clean visual dividers with optional text badges and horizontal or vertical orientations.
import pyvello as ui
with ui.App(title="Separator Demo", theme="light", palette="red") as app:
ui.title("Section Dividers")
ui.text("Upper section content")
ui.separator()
ui.text("Middle section content")
ui.divider()
ui.text("Lower section content")
if __name__ == "__main__":
app.launch()
TextInput & TextArea
Single-line and multi-line text input fields supporting reactive change listeners and auto-sizing.
import pyvello as ui
with ui.App(title="Input Form Demo", theme="light", palette="red") as app:
ui.title("Text Inputs & TextAreas")
name = ui.text_input(label="Project Name", placeholder="e.g. quantum-gateway")
prompt = ui.text_area(label="System Prompt", rows=4, placeholder="Enter instructions for the agent...")
ui.button("Save Specification", variant="default")
if __name__ == "__main__":
app.launch()
NumberInput & Slider
Numeric inputs and interactive slider controls with min, max, and step increments.
import pyvello as ui
with ui.App(title="Numeric Controls Demo", theme="light", palette="red") as app:
ui.title("Sliders & Numeric Inputs")
temperature = ui.slider(label="Sampling Temperature", value=0.7, min=0.0, max=2.0, step=0.05)
workers = ui.number_input(label="Max Worker Agents", value=3, min=1, max=10)
if __name__ == "__main__":
app.launch()
Switch & Checkbox
Boolean toggle switches and checkboxes with accessible labels and description subtext.
import pyvello as ui
with ui.App(title="Switch & Checkbox Demo", theme="light", palette="red") as app:
ui.title("Toggles & Boolean Options")
stream_toggle = ui.switch(label="Real-Time Streaming", description="Stream LLM responses token-by-token", value=True)
agree = ui.checkbox(label="I accept terms and privacy policies", value=False)
if __name__ == "__main__":
app.launch()
Select & ToggleGroup
Dropdown selects and segment toggle button groups for selecting between discrete options.
import pyvello as ui
with ui.App(title="Select & Toggle Demo", theme="light", palette="red") as app:
ui.title("Option Selectors")
model_choice = ui.select(
label="Inference Engine",
options=[
"openrouter/anthropic/claude-3.7-sonnet",
"openrouter/deepseek/deepseek-chat",
"openrouter/openai/gpt-4o",
"openrouter/meta-llama/llama-3.3-70b-instruct",
],
value="openrouter/anthropic/claude-3.7-sonnet"
)
view_mode = ui.toggle_group(options=["List", "Grid", "Table"], value="Grid")
if __name__ == "__main__":
app.launch()
Radio
Mutually exclusive radio group choices.
import pyvello as ui
with ui.App(title="Radio Group Demo", theme="light", palette="red") as app:
ui.title("Radio Group Selection")
priority = ui.radio(label="Execution Priority", options=["Low", "Normal", "Critical"], value="Normal")
if __name__ == "__main__":
app.launch()
AutoForm (Function-to-UI)
Automatically generates validated reactive shadcn/ui input forms directly from Python type annotations, docstrings, and default arguments without writing HTML or React markup.
import pyvello as ui
def synthesize_voiceover(script: str, pitch: float = 1.0, speed: float = 1.0, high_fidelity: bool = True):
"""Synthesize high-fidelity voiceover audio with custom acoustic parameters."""
return f"Synthesized '{script}' at {speed}x speed"
with ui.App(title="AutoForm Studio") as app:
ui.title("Automatic Schema Generation")
ui.from_function(synthesize_voiceover) # Auto-generates UI!
if __name__ == "__main__":
app.launch()
FileUpload & InputOTP
Drag-and-drop file upload zone and segmented OTP code inputs for MFA verification.
import pyvello as ui
with ui.App(title="FileUpload & OTP Demo", theme="light", palette="red") as app:
ui.title("File Upload & Security Verification")
uploader = ui.file_upload(label="Upload Dataset (CSV, JSON)", accept=".csv,.json")
otp = ui.input_otp(length=6)
if __name__ == "__main__":
app.launch()
Typography (Title, Header, Subheader & Text)
Headings and body text components with responsive sizing, semantic heading levels, color accents, and alignment controls.
Application Title (H1)
Section Header (H2, Primary)
Subsection (H3)
Standard body text explaining operational procedures and reactive models.
Muted subtle annotation or timestamp label.
ui.title() & ui.text() Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| text / text_str | str | Required | The textual string to render. |
| level | int (1-6) | 1 | Semantic heading level (H1 through H6) for ui.title(). |
| variant | str | None | Typography style variant: "h1", "h2", "h3", "h4", "lead", "muted". |
| color | str | None | Accent color: "primary", "foreground", "muted", "destructive". |
| class_name | str | None | Custom Tailwind CSS utility classes (e.g. "mb-4 tracking-tight"). |
Complete Executable Code
import pyvello as ui
with ui.App(title="Typography Demo", theme="light", palette="red") as app:
# Title variations
ui.title("Main Application Title (H1)", level=1, class_name="mb-2")
ui.title("Secondary Section Header (H2)", level=2, color="primary")
ui.header("Convenience Header (H2)")
ui.subheader("Convenience Subheader (H3)")
ui.title("Minor Subsection (H4)", level=4)
# Text variations
ui.text("Standard body text explaining reactive parameters and agent workflows.")
ui.text("Lead paragraph introducing the component catalog.", variant="lead")
ui.text("Muted subtle annotation or timestamp label.", variant="muted")
if __name__ == "__main__":
app.launch()
Metric
Key performance indicator (KPI) card displaying a primary metric value, delta change, and trend direction.
| Parameter | Type | Default | Description |
|---|---|---|---|
| label | str | required | Metric title label. |
| value | Any | required | Primary metric value. |
| delta | Any | None | None | Change indicator (e.g. '+12%'). |
| delta_type | str | 'neutral' | 'positive' (green), 'negative' (red), or 'neutral'. |
| description | str | None | None | Optional footer description. |
| loading | bool | False | Render loading placeholder. |
import pyvello as ui
with ui.App(title="Metric KPI Demo", theme="light", palette="red") as app:
ui.title("KPI Telemetry Cards")
col1, col2 = ui.columns(2)
with col1:
ui.metric(label="Active Sessions", value="1,420", delta="+18%", delta_type="positive")
with col2:
ui.metric(label="Avg Latency", value="48 ms", delta="-4 ms", delta_type="positive")
if __name__ == "__main__":
app.launch()
Table (DataFrame & Records)
High-speed data grid with sorting, pagination, search filtering, and 3-Dots Action Dropdown menus. Accepts raw Python dictionaries or pandas DataFrames.
| Agent | Model | Status |
|---|---|---|
| Researcher | gpt-4o | Active |
| Architect | claude-3-5 | Idle |
import pyvello as ui
with ui.App(title="Data Table Demo", theme="light", palette="red") as app:
ui.title("Searchable Data Grid")
ui.table(
data=[
{"Agent": "MarketResearcher", "Model": "deepseek-v4.1", "Status": "Active"},
{"Agent": "InfraArchitect", "Model": "deepseek-v4.1", "Status": "Idle"},
{"Agent": "RiskAssessor", "Model": "deepseek-v4.1", "Status": "Idle"},
],
searchable=True,
page_size=5,
)
if __name__ == "__main__":
app.launch()
Charts (Bar, Line, Area, Donut)
Interactive SVG-based data visualizations calibrated to Pyvello theme palettes. Supports bar charts, time-series lines, filled areas, and donut breakdowns.
import pyvello as ui
with ui.App(title="Charts & Visualizations Demo", theme="light", palette="red") as app:
ui.title("Interactive Analytics Charts")
chart_data = [
{"label": "Mon", "value": 120},
{"label": "Tue", "value": 240},
{"label": "Wed", "value": 310},
{"label": "Thu", "value": 190},
{"label": "Fri", "value": 450},
]
ui.bar_chart(data=chart_data, title="Weekly Token Invocations (Bar)")
ui.line_chart(data=chart_data, title="Inference Latency Trend (Line)")
ui.area_chart(data=chart_data, title="Token Volume (Area)")
ui.donut_chart(data=chart_data[:3], title="Provider Allocation (Donut)")
if __name__ == "__main__":
app.launch()
Callout & Badge
Prominent notification banners (info, warning, success, error) and status badge pills.
Hot reloading active. Files are continuously monitored for changes.
import pyvello as ui
with ui.App(title="Callout & Badge Demo", theme="light", palette="red") as app:
ui.title("Alerts & Status Badges")
ui.callout("All subagent tools executed successfully.", variant="success")
ui.badge("Production Ready", variant="default")
if __name__ == "__main__":
app.launch()
Terminal (Telemetry Stream & Console)
High-tech macOS/Linux cyber terminal component for streaming agent thoughts, WebSocket telemetry, CLI standard output, and execution logs with line numbers, auto-scroll, and one-click copy.
| Parameter | Type | Default | Description |
|---|---|---|---|
| title | str | "Terminal Output" | Header title shown on top macOS traffic light window bar. |
| lines | List[str] | [] | Initial list of string log lines pre-loaded into the terminal viewport. |
| height | int | str | 220 | Viewport height in pixels (e.g. 220) or CSS height string. |
| auto_scroll | bool | True | Automatically keeps the scroll position pinned to the newest incoming log. |
| endpoint | Optional[str] | None | WebSocket endpoint identifier displayed in the terminal status badge. |
import pyvello as ui
with ui.App(title="Swarm Sentinel", theme="dark", palette="pyvello") as app:
ui.title("Reactive Telemetry Monitor")
term = ui.terminal(title="Agent Swarm Telemetry", endpoint="/ws/session_01", height=200)
@ui.button("Dispatch Agent Ping").on_click
def on_ping():
ui.stream_log("[STREAM] Telemetry packet dispatched to cluster mesh (0.42ms)")
@ui.button("Synthesize Data").on_click
def on_synth():
ui.stream_log("[SUCCESS] Synthesizing multi-modal telemetry from 82 workers...")
if __name__ == "__main__":
app.launch()
Media (Image, Audio, Video)
Native multimodal display components supporting image lightbox modal zooms, HTML5 audio waveform players, and responsive video players.
import pyvello as ui
with ui.App(title="Media Studio", theme="dark") as app:
ui.title("Multimodal Content Primitives")
col1, col2, col3 = ui.columns(3)
with col1:
ui.image(src="/images/render.png", caption="3D Neural NeRF Model")
with col2:
ui.audio(src="/audio/voiceover.mp3", caption="Synthesized Audio Track")
with col3:
ui.video(src="/video/simulation.mp4", caption="Physics Particle Simulation")
if __name__ == "__main__":
app.launch()
Markdown & Code
Rich markdown renderer supporting GitHub Flavored Markdown (GFM), math KaTeX rendering, syntax highlighted code blocks, and copy buttons.
import pyvello as ui
with ui.App(title="Markdown & Code Demo", theme="light", palette="red") as app:
ui.title("Rich Content & Syntax Highlighting")
ui.markdown("""### Architecture Specification
- **Supervisor**: Dynamic Routing
- **Workers**: 3 subagents
- **Protocol**: WebSocket JSON lines
""")
ui.code("""def compute_hash(val: str) -> str:
import hashlib
return hashlib.sha256(val.encode()).hexdigest()""", language="python")
if __name__ == "__main__":
app.launch()
JsonViewer
Interactive tree explorer for arbitrary JSON payloads with collapsible keys and copy functionality.
import pyvello as ui
with ui.App(title="JSON Inspector Demo", theme="light", palette="red") as app:
ui.title("Interactive JSON Inspector")
ui.json_viewer(data={"swarm": "KubernetesArchitect", "nodes": 9, "status": "healthy"})
if __name__ == "__main__":
app.launch()
Feedback & Utility
Toast notifications, user avatars, skeleton loaders, progress bars, tooltips, and Lucide icons.
import pyvello as ui
def trigger_toast():
ui.toast("Workflow executed successfully!", type="default")
with ui.App(title="Feedback & Utility Demo", theme="light", palette="red") as app:
ui.title("Feedback & UI Utility Components")
ui.button("Show Toast Notification", on_click=trigger_toast)
ui.avatar(fallback="AI")
ui.skeleton(width="100%", height="24px")
ui.progress(value=75, label="Optimizing weights...")
ui.icon(name="Sparkles", size=18)
if __name__ == "__main__":
app.launch()
AI Research & Tool Assistant
A comprehensive full-stack research workspace pairing a persistent navigation and telemetry control rail (ui.sidebar()), executive KPI metric cards (ui.metric()), and an autonomous streaming AI agent (ui.chat(agent=agent)) equipped with financial computation and database lookup tools powered by OpenRouter (gpt-4o-mini).
Autonomous Research & Market Intelligence Hub
Interactive multi-turn AI researcher equipped with financial computation, domain lookups, and token telemetry.
Here is the verified market research and financial breakdown for your query:
- 2026 Estimated TAM: $148 Billion
- 5-Year Compound Growth (CAGR): 34.2%
- Primary Growth Driver: Enterprise LLM inference workloads and custom dedicated silicon.
- Operating Profit: $18.00 Million
- Operating Margin: 36.0%
- Projected Revenue (+14.0%): $57.00 Million next quarter
"""Pyvello Example 01: Autonomous AI Research & Market Intelligence Assistant.
This example demonstrates how to build an executive-grade AI research workspace
combining a persistent sidebar control panel, real-time KPI metrics, and an
autonomous multi-tool agent powered by OpenRouter (gpt-4o-mini).
Key Pyvello Concepts Demonstrated:
1. ui.Agent configuration with OpenRouter models and system instructions.
2. Direct tool registration using the @agent.tool decorator.
3. ui.sidebar() for persistent navigation, telemetry metrics, and quick prompt buttons.
4. Interactive Python event handlers (on_click) displaying live ui.toast() alerts.
5. Responsive layout with ui.row() and ui.metric() for real-time status.
6. ui.chat(agent=agent) for full-screen streaming conversations with automatic tool calling.
"""
import os
from dotenv import load_dotenv
import pyvello as ui
# Load environment variables (OPENROUTER_API_KEY from .env)
load_dotenv()
# ---------------------------------------------------------------------------
# 1. Specialist Agent Definition with OpenRouter
# ---------------------------------------------------------------------------
# We initialize an autonomous agent with a fast, high-performance reasoning model.
# The agent automatically streams responses, handles chat sessions, and executes
# registered tools when it detects numerical or domain-specific questions.
agent = ui.Agent(
name="MarketResearcher",
model="openrouter/openai/gpt-4o-mini",
system_prompt=(
"You are an expert market intelligence and quantitative research specialist. "
"Provide concise, data-driven answers formatted in clean Markdown. "
"Always use the available tools whenever the user asks for financial calculations, "
"sector growth metrics, or database lookups."
),
)
# ---------------------------------------------------------------------------
# 2. Tool Registration with Python Typing & Docstrings
# ---------------------------------------------------------------------------
# Pyvello automatically converts Python type-annotated functions and docstrings
# into JSON Schema definitions for function calling.
@agent.tool
def calculate_financial_metrics(
revenue: float, cost: float, growth_rate: float
) -> str:
"""Calculate operating profit, operating margin percentage, and next-quarter projected revenue.
Args:
revenue: Current quarter revenue in USD millions.
cost: Current operating cost in USD millions.
growth_rate: Anticipated quarterly growth percentage (e.g., 12.5 for 12.5%).
"""
profit = revenue - cost
margin = (profit / revenue * 100.0) if revenue > 0 else 0.0
projected = revenue * (1.0 + growth_rate / 100.0)
return (
f"Operating Profit: ${profit:.2f}M | "
f"Operating Margin: {margin:.1f}% | "
f"Projected Revenue (at +{growth_rate:.1f}% growth): ${projected:.2f}M"
)
@agent.tool
def search_market_database(sector: str) -> str:
"""Retrieve verified industry benchmarks, market size, and CAGR metrics for a sector.
Args:
sector: The market or tech sector to look up (e.g., 'Cloud AI', 'Fintech', 'Autonomous Systems').
"""
normalized = sector.lower().strip()
benchmarks = {
"cloud ai": (
"Sector: Cloud AI Infrastructure | 2026 TAM: $148B | 5-Year CAGR: 34.2% | "
"Key Growth Driver: Enterprise inference workloads and dedicated silicon clusters."
),
"fintech": (
"Sector: Global Fintech & Embedded Finance | 2026 TAM: $320B | 5-Year CAGR: 18.5% | "
"Key Growth Driver: Real-time settlement rails and automated risk adjudication."
),
"cybersecurity": (
"Sector: Autonomous Cybersecurity & Identity | 2026 TAM: $215B | 5-Year CAGR: 22.1% | "
"Key Growth Driver: Post-quantum cryptography migration and AI-powered SOC automation."
),
}
for key, data in benchmarks.items():
if key in normalized:
return data
return (
f"Sector '{sector}': Estimated 2026 Market TAM: $85B | 5-Year CAGR: 14.8% | "
"Source: Pyvello Enterprise Intelligence Index (Verified)."
)
# ---------------------------------------------------------------------------
# 3. Reactive Event Handlers (User Actions & Alert Callbacks)
# ---------------------------------------------------------------------------
def select_cloud_ai_topic():
"""Triggered when user clicks 'Cloud AI Market Size' in the sidebar."""
ui.toast(
message="Loaded research prompt: 'What is the market size of Cloud AI and calculate profit for $50M revenue?'",
type="info",
title="Prompt Selected",
)
def select_saas_margins_topic():
"""Triggered when user clicks 'Calculate SaaS Margins' in the sidebar."""
ui.toast(
message="Loaded calculation prompt: 'Calculate profit and margin for $50M revenue with $32M operating costs.'",
type="info",
title="Calculation Selected",
)
def select_cybersecurity_topic():
"""Triggered when user clicks 'Cybersecurity TAM' in the sidebar."""
ui.toast(
message="Loaded sector prompt: 'Retrieve verified industry benchmarks, market size, and CAGR for Cybersecurity.'",
type="info",
title="Database Lookup Selected",
)
def sync_knowledge_index():
"""Triggered when user clicks 'Sync Knowledge Base' in the sidebar."""
ui.toast(
message="Knowledge vector index synchronized with 1,840 verified SEC filings and equity research reports.",
type="success",
title="Index Synchronized",
)
def export_research_dossier():
"""Triggered when user clicks 'Export Research Dossier' in the sidebar."""
ui.toast(
message="Generated executive research dossier (Markdown & PDF formats ready for download).",
type="success",
title="Dossier Exported",
)
def view_analyst_profile():
"""Triggered when user clicks the analyst profile footer."""
ui.toast(
message="Analyst: Vaibhav Singh | Clearance: Level 3 Research Lead | Workspace: Acme Global Intelligence",
type="info",
title="Analyst Profile",
)
# ---------------------------------------------------------------------------
# 4. Reactive UI Layout Architecture
# ---------------------------------------------------------------------------
# with ui.App() creates the reactive single-page application container.
# Passing palette="red" applies Pyvello's signature red theme palette.
with ui.App(title="Research Intelligence Studio", theme="light", palette="red") as app:
# 4A. Persistent Left Navigation & Telemetry Sidebar
with ui.sidebar():
# Workspace Branding Header
with ui.row(class_name="items-center justify-between w-full pb-1"):
with ui.row(class_name="items-center gap-2 min-w-0"):
ui.badge(
"AI",
variant="default",
class_name="w-6 h-6 rounded-md flex items-center justify-center font-bold text-xs p-0 shrink-0",
)
with ui.column(class_name="min-w-0 gap-0"):
ui.text("Acme Intelligence", class_name="font-bold text-xs text-foreground tracking-tight truncate leading-tight")
ui.text("Market Research Swarm", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.badge("v1.0", variant="secondary", class_name="text-[9px] font-mono px-1.5 py-0.5 shrink-0")
ui.separator()
# Agent Status Callout
ui.callout(
"Agent connected to OpenRouter (gpt-4o-mini) with 2 active tools.",
variant="info",
class_name="text-[11px] p-2.5",
)
ui.separator()
# Telemetry & Knowledge Metrics
ui.text("Knowledge Status", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.metric("Indexed Reports", "1,840", delta="+14% MoM")
ui.metric("Fact-Checking Score", "99.4%", delta="+0.8%")
ui.separator()
# Quick-Start Prompt Suggestions with on_click Handlers
ui.text("Research Topics", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.button(
"Cloud AI Market Size",
on_click=select_cloud_ai_topic,
right_icon="chevron-right",
variant="ghost",
class_name="w-full justify-between text-xs font-medium px-2.5 py-1.5 rounded-lg bg-muted/40 hover:bg-muted text-foreground h-8",
)
ui.button(
"Calculate SaaS Margins",
on_click=select_saas_margins_topic,
right_icon="chevron-right",
variant="ghost",
class_name="w-full justify-between text-xs font-medium px-2.5 py-1.5 rounded-lg bg-muted/40 hover:bg-muted text-foreground h-8",
)
ui.button(
"Cybersecurity TAM",
on_click=select_cybersecurity_topic,
right_icon="chevron-right",
variant="ghost",
class_name="w-full justify-between text-xs font-medium px-2.5 py-1.5 rounded-lg bg-muted/40 hover:bg-muted text-foreground h-8",
)
ui.separator()
# Workspace Actions Section
ui.text("Studio Actions", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.button(
"Sync Knowledge Base",
icon="refresh-cw",
on_click=sync_knowledge_index,
variant="outline",
class_name="w-full justify-start text-xs font-medium px-2.5 py-1.5 rounded-lg h-8",
)
ui.button(
"Export Research Dossier",
icon="download",
on_click=export_research_dossier,
variant="ghost",
class_name="w-full justify-start text-xs font-medium px-2.5 py-1.5 rounded-lg h-8 text-muted-foreground hover:text-foreground",
)
# User Profile Footer (Interactive)
with ui.row(class_name="pt-3 border-t border-border/80 items-center justify-between w-full mt-auto select-none"):
with ui.row(class_name="items-center gap-2 min-w-0 flex-1"):
ui.avatar(fallback="VS", class_name="w-7 h-7 rounded-full bg-primary/10 text-primary border border-primary/20 font-bold text-xs flex items-center justify-center")
with ui.column(class_name="min-w-0 flex-1 gap-0"):
ui.text("Vaibhav Singh", class_name="text-xs font-semibold text-foreground truncate leading-tight")
ui.text("Senior Analyst", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.button(
"Profile",
on_click=view_analyst_profile,
variant="ghost",
class_name="text-[10px] font-mono h-6 px-2 text-muted-foreground hover:text-foreground",
)
# 4B. Main Content Viewport
# Header summary matching docs preview typography
ui.title(
"Autonomous Research & Market Intelligence Hub",
level=4,
class_name="text-sm font-bold text-foreground tracking-tight",
)
ui.text(
"Interactive multi-turn AI researcher equipped with financial computation, "
"domain lookups, and token telemetry.",
class_name="text-[11px] text-muted-foreground leading-normal",
)
# Full-Screen Interactive Chat Component with Model badge, Tools modal button, and Observability
ui.chat(
agent=agent,
show_header=True,
placeholder="Ask a question (e.g. 'What is the market size of Cloud AI and calculate profit for $50M rev with $30M cost?')...",
examples=[
"What is the 2026 market size and growth driver for Cloud AI?",
"Calculate operating profit and margin for $45M revenue with $28M costs at 15% quarterly growth.",
"Compare the CAGR of Cloud AI vs Cybersecurity.",
],
)
# ---------------------------------------------------------------------------
# 5. Standalone Server Execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Launch on port 8080 with automatic hot-reloading enabled
app.launch(port=8080)
03. SRE Incident Command & Cluster War Room
A mission-critical operational war room application featuring full-screen kiosk support (header=False), persistent telemetry and severity navigation sidebar with pinned on-call commander profile (ui.sidebar()), 4 executive KPI metric cards for incident velocity and availability (ui.metric()), live P99 latency trajectory line chart (ui.line_chart()), service error distribution bar chart (ui.bar_chart()), critical incident callout banner (ui.callout()), searchable incident records table (ui.table()), and interactive failover traffic shedding controls (ui.slider(), ui.switch()) in the crimson incident palette (palette="red").
Kiosk Full-Screen Mode & Autonomous Swarm Control
Pyvello applications support header=False to completely hide the top navigation chrome, granting 100% viewport real estate for embedded NOC monitoring walls, incident war rooms, and dedicated kiosks. When header=False is specified, a floating slide-out control button seamlessly docks on the top-left to toggle the navigation sidebar without manual UI scaffolding.
| Incident ID | Severity | Service | Impact | Status | Mitigation |
|---|---|---|---|---|---|
| INC-8921 | P0 - Critical | Postgres Cluster A | 4.2% drop | Mitigating | Auto-failover to Replica |
| INC-8919 | P1 - High | Vector Indexer | P99 +85ms | Investigating | Worker scaling +4 |
| INC-8914 | P2 - Medium | Webhook Dispatcher | Retry backlog | Resolved | Queue buffer flushed |
| INC-8908 | P1 - High | Inference Cache | Cache miss 18% | Mitigating | Warm memory sync |
| INC-8902 | P3 - Low | Audit Log Exporter | Export delay | Resolved | Batch size tuned |
"""Example 03: Autonomous DevOps & SRE Incident Command Center.
A mission-critical operational war room application featuring:
- Full-screen or header-enabled mode (header=True by default, can be set to False)
- Persistent telemetry and severity navigation sidebar with pinned on-call commander profile
- Reactive Python callbacks (on_click, on_change) displaying live ui.toast() alert notifications
- 4 executive KPI metric cards for incident velocity, latency, and SLO availability
- Live P99 latency trajectory line chart and service error distribution bar chart (Crimson / Red palette)
- Critical incident callout banner with automated mitigation actions
- Searchable, interactive production incident records data table
- Interactive failover parameters: traffic shedding slider and auto-remediation switch
- Red / Crimson executive terminal palette (palette="red")
"""
import pyvello as ui
# ---------------------------------------------------------------------------
# 1. Dataset Definitions
# ---------------------------------------------------------------------------
# Trailing 6-interval P99 Inference & Cluster Latency (milliseconds)
latency_trajectory = [
{"interval": "10:00", "latency": 58},
{"interval": "10:15", "latency": 64},
{"interval": "10:30", "latency": 89},
{"interval": "10:45", "latency": 112},
{"interval": "11:00", "latency": 78},
{"interval": "11:15", "latency": 42},
]
# Service Error Distribution across Microservices (errors / second)
error_distribution = [
{"service": "Auth Gateway", "errors": 14.2},
{"service": "Vector DB", "errors": 8.6},
{"service": "Model Router", "errors": 4.1},
{"service": "Billing Sync", "errors": 1.2},
]
# Active Production Incident Records
incident_records = [
{
"id": "INC-8921",
"severity": "P0 - Critical",
"service": "Postgres Cluster A",
"impact": "4.2% drop",
"status": "Mitigating",
"mitigation": "Auto-failover to Replica",
},
{
"id": "INC-8919",
"severity": "P1 - High",
"service": "Vector Indexer",
"impact": "P99 +85ms",
"status": "Investigating",
"mitigation": "Worker scaling +4",
},
{
"id": "INC-8914",
"severity": "P2 - Medium",
"service": "Webhook Dispatcher",
"impact": "Retry backlog",
"status": "Resolved",
"mitigation": "Queue buffer flushed",
},
{
"id": "INC-8908",
"severity": "P1 - High",
"service": "Inference Cache",
"impact": "Cache miss 18%",
"status": "Mitigating",
"mitigation": "Warm memory sync",
},
{
"id": "INC-8902",
"severity": "P3 - Low",
"service": "Audit Log Exporter",
"impact": "Export delay",
"status": "Resolved",
"mitigation": "Batch size tuned",
},
]
# ---------------------------------------------------------------------------
# 2. Reactive Event Handlers (User Actions & Alert Callbacks)
# ---------------------------------------------------------------------------
def handle_nav_active():
"""Triggered when user clicks 'Active Incidents' in the sidebar."""
ui.toast(
message="Viewing Active P0/P1 Production Incidents & Cluster Health.",
type="info",
title="Active Incidents",
)
def handle_nav_resolved():
"""Triggered when user clicks 'Resolved Incidents' in the sidebar."""
ui.toast(
message="Viewing Historical Resolved Incidents archive and post-mortems.",
type="info",
title="Resolved Incidents",
)
def handle_nav_telemetry():
"""Triggered when user clicks 'Telemetry Feeds' in the sidebar."""
ui.toast(
message="Streaming live OpenTelemetry latency curves and ingress error rates.",
type="info",
title="Telemetry Feeds",
)
def handle_nav_runbooks():
"""Triggered when user clicks 'Runbooks & Playbooks' in the sidebar."""
ui.toast(
message="Opened SRE Automated Mitigation Runbooks & Disaster Recovery playbooks.",
type="info",
title="Runbooks & Playbooks",
)
def handle_nav_settings():
"""Triggered when user clicks 'Incident Settings' in the sidebar."""
ui.toast(
message="Incident Command & PagerDuty escalation threshold settings.",
type="info",
title="Incident Settings",
)
def handle_traffic_shed_change(value: float):
"""Triggered when user adjusts the traffic shedding slider."""
ui.toast(
message=f"Throttled non-critical asynchronous workloads to {int(value)}% capacity.",
type="warning",
title="Traffic Shed Ratio Updated",
)
def handle_rollback_toggle(enabled: bool):
"""Triggered when user toggles the autonomous rollback switch."""
status_str = "ENABLED (5xx > 1.5% auto-revert)" if enabled else "DISABLED (Manual intervention required)"
ui.toast(
message=f"Autonomous Canary Rollback is now {status_str}.",
type="info",
title="Rollback Policy Changed",
)
def handle_execute_failover():
"""Triggered when user clicks 'Execute Safe Failover' button."""
ui.toast(
message="Safe cross-region failover initiated to replica cluster (us-west-2). Read traffic rerouted.",
type="error",
title="Safe Failover Executed",
)
def handle_acknowledge_p0():
"""Triggered when user clicks 'Acknowledge P0' button."""
ui.toast(
message="Incident P0-8921 acknowledged by Incident Commander Elena Rostova. SLA clock paused.",
type="success",
title="P0 Incident Acknowledged",
)
def handle_export_postmortem():
"""Triggered when user clicks 'Export Post-Mortem' button."""
ui.toast(
message="Generated comprehensive Markdown & Timeline Post-Mortem summary for INC-8921.",
type="info",
title="Post-Mortem Exported",
)
def handle_mute_pagers():
"""Triggered when user clicks 'Mute Pagers' button."""
ui.toast(
message="Non-critical sirens and Slack alert webhooks muted for 30 minutes during active mitigation.",
type="warning",
title="Pagers Muted",
)
def handle_trigger_swarm_sync():
"""Triggered when user clicks 'Swarm Sync' button."""
ui.toast(
message="Autonomous DevOps mitigation agent swarm synchronized with live Kubernetes pods.",
type="success",
title="Swarm Synchronized",
)
def handle_view_commander():
"""Triggered when user clicks the commander profile footer."""
ui.toast(
message="Commander: Dr. Elena Rostova | Role: Principal SRE | Clearance: P0 Incident Command",
type="info",
title="Incident Commander Profile",
)
# ---------------------------------------------------------------------------
# 3. Reactive UI Layout Architecture
# ---------------------------------------------------------------------------
# with ui.App() creates the single-page application container.
# palette="red" sets the high-visibility crimson / incident red color scheme.
# header=True is the default. Pass header=False to completely hide the top navbar
# for full-screen kiosk displays or embedded NOC monitoring walls:
# with ui.App(title="...", theme="light", palette="red", header=False) as app:
with ui.App(
title="SRE Incident Command & Cluster War Room",
theme="light",
palette="red",
header=True,
) as app:
# 3A. Persistent Navigation & Dimensions Sidebar
with ui.sidebar():
# Command Center Brand Header
with ui.row(class_name="items-center justify-between w-full pb-1"):
with ui.row(class_name="items-center gap-2 min-w-0"):
ui.badge(
"SRE",
variant="default",
class_name="w-6 h-6 rounded-md flex items-center justify-center font-bold text-xs p-0 shrink-0",
)
with ui.column(class_name="min-w-0 gap-0"):
ui.text("SRE Command Central", class_name="font-bold text-xs text-foreground tracking-tight truncate leading-tight")
ui.text("Cluster War Room", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.badge("v3.2", variant="secondary", class_name="text-[9px] font-mono px-1.5 py-0.5 shrink-0")
ui.separator()
# Primary Navigation Menu with Interactive Handlers
ui.text("Incident Views", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.button(
"Active Incidents",
icon="alert-octagon",
on_click=handle_nav_active,
variant="default",
class_name="w-full justify-start text-xs font-semibold h-8 shadow-xs",
)
ui.button(
"Resolved Incidents",
icon="check-circle-2",
on_click=handle_nav_resolved,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Telemetry Feeds",
icon="activity",
on_click=handle_nav_telemetry,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Runbooks & Playbooks",
icon="book-open",
on_click=handle_nav_runbooks,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Incident Settings",
icon="settings",
on_click=handle_nav_settings,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.separator()
# Operational Cluster Scope
ui.text("Target Cluster", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("Region", class_name="text-[10px] text-muted-foreground")
ui.text("us-east-1 (Primary)", class_name="font-semibold text-foreground text-[10px]")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("Remediation", class_name="text-[10px] text-muted-foreground")
ui.text("Swarm Active", class_name="font-semibold text-emerald-500 text-[10px]")
# Pinned On-Call Incident Commander Footer (Sticks to bottom, interactive)
with ui.row(class_name="pt-3 border-t border-border/80 items-center justify-between w-full mt-auto select-none"):
with ui.row(class_name="items-center gap-2 min-w-0 flex-1"):
ui.avatar(fallback="ER", class_name="w-7 h-7 rounded-full bg-primary/20 text-primary border border-primary/30 font-bold text-xs flex items-center justify-center")
with ui.column(class_name="min-w-0 flex-1 gap-0"):
ui.text("Dr. Elena Rostova", class_name="text-xs font-semibold text-foreground truncate leading-tight")
ui.text("Principal SRE Commander", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.button(
"Profile",
on_click=handle_view_commander,
variant="ghost",
class_name="text-[10px] font-mono h-6 px-2 text-muted-foreground hover:text-foreground",
)
# 3B. Main Content Viewport
# Incident Title & War Room Status Header with Action Controls
with ui.row(class_name="flex-col sm:flex-row sm:items-center justify-between w-full pb-2 border-b border-border/60 gap-3 select-none"):
with ui.column(class_name="flex-1 min-w-0 space-y-0.5"):
ui.title(
"Production Incident Command & Service Health",
level=4,
class_name="text-sm font-bold text-foreground tracking-tight",
)
ui.text(
"Autonomous swarm incident mitigation, real-time error telemetry, and failover orchestration.",
class_name="text-[11px] text-muted-foreground",
)
with ui.row(class_name="flex-row items-center gap-2 w-auto shrink-0 flex-wrap"):
ui.button(
"Mute Pagers",
icon="bell-off",
on_click=handle_mute_pagers,
variant="outline",
class_name="text-xs font-medium h-7 px-2.5",
)
ui.button(
"Swarm Sync",
icon="refresh-cw",
on_click=handle_trigger_swarm_sync,
variant="default",
class_name="text-xs font-semibold h-7 px-2.5 shadow-xs",
)
with ui.row(class_name="flex-row items-center gap-1.5 px-2.5 py-1 rounded-full bg-rose-500/10 text-rose-500 border border-rose-500/20 text-[10px] font-mono font-semibold w-auto shrink-0"):
ui.badge("P0 War Room Active", variant="outline", class_name="border-0 p-0 text-[10px] font-semibold text-rose-500")
# Critical Active Alert Callout Banner
ui.callout(
"CRITICAL: Database connection pool exhaustion detected in us-east-1. Autonomous agent swarm is shedding 25% non-critical traffic and provisioning warm read replicas.",
variant="warning",
class_name="text-xs font-medium my-2",
)
# 4 Executive KPI Metric Cards
with ui.row(class_name="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 w-full my-1"):
ui.metric("ACTIVE P0/P1 OUTAGES", "2 Active", delta="-3 vs peak")
ui.metric("P99 INFERENCE LATENCY", "42ms", delta="-18ms nominal")
ui.metric("AUTONOMOUS MITIGATION", "94.2%", delta="+4.1% MoM")
ui.metric("SYSTEM AVAILABILITY", "99.98%", delta="Within SLO")
# 2 Visual Analytics Charts
with ui.row(class_name="grid grid-cols-1 md:grid-cols-2 gap-3 w-full my-1"):
ui.line_chart(
data=latency_trajectory,
x="interval",
y="latency",
title="Inference & Ingress Latency (ms)",
description="Trailing 6-interval P99 latency trajectory across all ingress points",
height=200,
color="#ef4444",
)
ui.bar_chart(
data=error_distribution,
x="service",
y="errors",
title="Service Error Distribution (req/s)",
description="Real-time 5xx error volume distributed across microservice endpoints",
height=200,
color="#dc2626",
)
# Active Production Incidents Data Table
ui.title("Active Production Incidents", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono mt-3 mb-1")
ui.table(
data=incident_records,
columns=["id", "severity", "service", "impact", "status", "mitigation"],
page_size=5,
searchable=True,
)
# Interactive Remediation Controls
ui.title("Remediation & Failover Controls", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono mt-3 mb-1")
with ui.row(class_name="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full p-3 rounded-xl border border-border bg-card/60 shadow-2xs my-1"):
with ui.column(class_name="space-y-1"):
ui.text("Non-Critical Traffic Shedding Ratio", class_name="text-xs font-semibold text-foreground")
ui.text("Percentage of non-essential asynchronous workers throttled during mitigation.", class_name="text-[11px] text-muted-foreground")
ui.slider(label="Traffic Shed %", value=25, min=0, max=100, step=5, on_change=handle_traffic_shed_change)
with ui.column(class_name="space-y-2 justify-center"):
ui.switch(
label="Autonomous Rollback on Failure",
description="Automatically revert canary deployments if 5xx errors exceed 1.5%",
value=True,
on_change=handle_rollback_toggle,
)
with ui.row(class_name="flex-row items-center gap-2 pt-1"):
ui.button("Execute Safe Failover", on_click=handle_execute_failover, variant="destructive", class_name="text-xs font-semibold h-8")
ui.button("Acknowledge P0", on_click=handle_acknowledge_p0, variant="outline", class_name="text-xs font-medium h-8")
ui.button("Export Post-Mortem", on_click=handle_export_postmortem, variant="ghost", class_name="text-xs font-medium h-8 text-muted-foreground hover:text-foreground")
# ---------------------------------------------------------------------------
# 4. Standalone Server Execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Launch on port 8083 for standalone or test execution
app.launch(port=8083)
04. Multimodal Document Intelligence & Extraction Studio
A comprehensive multi-tab enterprise workspace showcasing the full spectrum of Pyvello components: staged tab containers (ui.tabs()), drag-and-drop file upload (ui.file_upload()), live progress bars (ui.progress()), two-factor cryptographic authentication (ui.input_otp()), selection controls (ui.select(), ui.toggle_group(), ui.radio(), ui.checkbox()), collapsible JSON tree viewers (ui.json_viewer()), syntax-highlighted code blocks (ui.code()), regulatory framework disclosure accordions (ui.accordion()), and visual analytics (ui.donut_chart() & ui.area_chart()).
Staged Tabbed Workflows & Cryptographic Zero-Knowledge Verification
This example illustrates how to structure complex multi-stage pipelines using ui.tabs(). Operators transition between file ingestion, structured entity JSON inspection, and regulatory compliance disclosures without page refreshes or bespoke frontend state management.
Multimodal Document Intelligence & Extraction Studio
Autonomous OCR extraction, SEC/HIPAA compliance verification, and structured JSON audit logging.
Enter your 6-digit cryptographic security token to approve automated PII redaction and external export.
"""Example 04: Multimodal Document Intelligence & Compliance Verification Studio.
A mission-critical enterprise document extraction and compliance verification suite featuring:
- Full-screen or header-enabled mode (header=True by default, can be set to False)
- Persistent compliance posture navigation sidebar with pinned Chief Compliance Officer profile
- Multi-tab workflow layout (ui.tabs) for Ingestion, Structured JSON, and Regulatory Compliance
- Drag-and-drop file uploader (ui.file_upload) with dynamic OCR progress bar (ui.progress)
- Cryptographic 6-digit two-factor authentication verification (ui.input_otp)
- Rich selection and security controls (ui.select, ui.toggle_group, ui.radio, ui.checkbox)
- Interactive collapsible JSON entity inspection tree (ui.json_viewer)
- Syntax-highlighted Python transformation code (ui.code) and Markdown summary (ui.markdown)
- Regulatory framework disclosure accordion (ui.accordion)
- Visual analytics: compliance framework donut chart (ui.donut_chart) and throughput area chart (ui.area_chart)
- Reactive Python callbacks (on_click, on_change, on_upload) with live ui.toast() alerts
- Gold / Amber executive terminal palette (palette="yellow")
"""
from typing import Any
import pyvello as ui
# ---------------------------------------------------------------------------
# 1. Dataset & Schema Definitions
# ---------------------------------------------------------------------------
# Sample extracted entity hierarchy from a financial 10-K document
extracted_entity_data = {
"document_id": "SEC-10K-2026-Q3-0941",
"filing_entity": "Acme Global Technologies Inc.",
"cik_number": "0001849201",
"fiscal_period": "Q3 2026",
"verification_status": "Verified - SOC2 Type II",
"financial_metrics": {
"total_revenue_usd": 14820000.0,
"operating_income_usd": 4210000.0,
"net_retention_rate": 1.182,
"cash_and_equivalents_usd": 38400000.0,
},
"pii_redaction_log": {
"masked_tax_ids": 4,
"sanitized_routing_numbers": 2,
"redacted_signatures": 3,
"encryption_cipher": "AES-256-GCM",
},
"compliance_flags": [
{"rule": "SEC Reg S-K", "status": "Compliant", "confidence": 0.998},
{"rule": "SOX Section 404", "status": "Compliant", "confidence": 0.994},
{"rule": "HIPAA Privacy Rule", "status": "Not Applicable", "confidence": 1.0},
],
}
# Python transformation script displayed in the code viewer
sample_transformation_code = '''import json
from pydantic import BaseModel, Field
class FinancialEntity(BaseModel):
document_id: str
filing_entity: str
total_revenue_usd: float = Field(..., description="Audited GAAP revenue")
operating_income_usd: float
net_retention_rate: float
verification_hash: str
def parse_and_validate(raw_payload: dict) -> FinancialEntity:
"""Normalize extracted OCR bounding boxes into verified entity records."""
metrics = raw_payload.get("financial_metrics", {})
return FinancialEntity(
document_id=raw_payload["document_id"],
filing_entity=raw_payload["filing_entity"],
total_revenue_usd=metrics["total_revenue_usd"],
operating_income_usd=metrics["operating_income_usd"],
net_retention_rate=metrics["net_retention_rate"],
verification_hash="sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"
)
'''
# Compliance framework breakdown data for Donut Chart
compliance_framework_data = [
{"label": "SOC2 Type II", "value": 42},
{"label": "SEC Reg S-K", "value": 31},
{"label": "HIPAA & PHI", "value": 18},
{"label": "GDPR Art 17", "value": 9},
]
# Trailing 6-interval document parsing throughput for Area Chart
throughput_timeline_data = [
{"label": "08:00", "value": 180},
{"label": "09:00", "value": 340},
{"label": "10:00", "value": 580},
{"label": "11:00", "value": 720},
{"label": "12:00", "value": 650},
{"label": "13:00", "value": 890},
]
# ---------------------------------------------------------------------------
# 2. Reactive Event Handlers (User Actions & Alert Callbacks)
# ---------------------------------------------------------------------------
def handle_nav_pipeline():
"""Triggered when user clicks 'Ingestion Pipeline' in the sidebar."""
ui.toast(
message="Viewing Live Ingestion Pipeline & Multimodal OCR Queue.",
type="info",
title="Pipeline Status",
)
def handle_nav_documents():
"""Triggered when user clicks 'Document Archive' in the sidebar."""
ui.toast(
message="Loaded archive: 2,480 parsed SEC 10-K and HIPAA health records.",
type="info",
title="Document Archive",
)
def handle_nav_schemas():
"""Triggered when user clicks 'Extraction Schemas' in the sidebar."""
ui.toast(
message="Viewing JSON Schema models and Pydantic validation contracts.",
type="info",
title="Extraction Schemas",
)
def handle_nav_auditors():
"""Triggered when user clicks 'Auditor Access' in the sidebar."""
ui.toast(
message="Loaded verified auditor roster, cryptographic signatures, and access logs.",
type="info",
title="Auditor Directory",
)
def handle_nav_settings():
"""Triggered when user clicks 'Studio Settings' in the sidebar."""
ui.toast(
message="Opening OCR model weights, PII vaulting, and retention preferences.",
type="info",
title="Studio Settings",
)
def handle_file_upload(files: Any):
"""Triggered when user uploads a document package."""
ui.toast(
message="Document uploaded: 14 pages queued for LayoutLM OCR extraction.",
type="success",
title="Document Uploaded",
)
def handle_taxonomy_change(value: str):
"""Triggered when user changes the document taxonomy dropdown."""
ui.toast(
message=f"Switched document classification schema to '{value}'.",
type="info",
title="Taxonomy Updated",
)
def handle_ocr_engine_change(value: str):
"""Triggered when user selects a different OCR engine."""
ui.toast(
message=f"Active extraction engine configured to '{value}'.",
type="info",
title="OCR Engine Selected",
)
def handle_otp_change(value: str):
"""Triggered when user types a 2FA OTP security code."""
ui.toast(
message=f"Two-factor auditor verification code received: {value[:3]}***",
type="info",
title="2FA Security Token",
)
def handle_masking_toggle(checked: bool):
"""Triggered when user toggles zero-knowledge PII masking."""
status_str = "ENFORCED (Auto-redacting SSN, Tax ID, and Banking data)" if checked else "BYPASSED (Raw text retained)"
ui.toast(
message=f"Zero-Knowledge PII Masking is now {status_str}.",
type="warning",
title="Privacy Policy Updated",
)
def handle_boundary_change(value: str):
"""Triggered when user changes inference security boundary."""
ui.toast(
message=f"Inference execution boundary set to '{value}'.",
type="info",
title="Security Boundary Configured",
)
def handle_authorize_extraction():
"""Triggered when user clicks 'Authorize Document Extraction'."""
ui.toast(
message="Cryptographic signature verified. Batch OCR and entity extraction initiated.",
type="success",
title="Extraction Authorized",
)
def handle_reset_buffer():
"""Triggered when user clicks 'Reset Ingestion Buffer'."""
ui.toast(
message="Ingestion scratch buffer cleared. Ready for next document upload.",
type="info",
title="Buffer Reset",
)
def handle_reprocess_ocr():
"""Triggered when user clicks 'Reprocess OCR Layout'."""
ui.toast(
message="Re-running dense OCR layout alignment with bounding box heuristics.",
type="info",
title="OCR Reprocessing",
)
def handle_copy_json():
"""Triggered when user clicks 'Copy Extracted JSON'."""
ui.toast(
message="Parsed entity JSON tree copied to clipboard.",
type="success",
title="JSON Copied",
)
def handle_download_cert():
"""Triggered when user clicks 'Download Signed Certificate'."""
ui.toast(
message="Downloaded cryptographically signed compliance certificate (PDF).",
type="success",
title="Certificate Downloaded",
)
def handle_purge_cache():
"""Triggered when user clicks 'Purge Transient Cache'."""
ui.toast(
message="Transient GPU memory buffers and cache shredded securely.",
type="error",
title="Cache Shredded",
)
def handle_sync_rails():
"""Triggered when user clicks 'Sync Parser Rails'."""
ui.toast(
message="Synchronized extraction rails with regulatory compliance databases.",
type="success",
title="Rails Synchronized",
)
def handle_export_bundle():
"""Triggered when user clicks 'Export Audit Bundle'."""
ui.toast(
message="Exported complete extraction dossier (JSON, Python code, and audit trail).",
type="success",
title="Dossier Exported",
)
def handle_view_officer():
"""Triggered when user clicks the compliance officer profile."""
ui.toast(
message="Officer: Dr. Elena Croft | Role: Chief Compliance Officer | Cert: CISA / CISSP",
type="info",
title="Compliance Officer Profile",
)
# ---------------------------------------------------------------------------
# 3. Reactive UI Layout Architecture
# ---------------------------------------------------------------------------
# with ui.App() creates the single-page application container.
# palette="yellow" applies the gold / amber executive terminal color scheme.
# header=True is the default. Pass header=False to completely hide the top navbar
# for full-screen kiosk displays or embedded audit inspection walls:
# with ui.App(title="...", theme="light", palette="yellow", header=False) as app:
with ui.App(
title="Multimodal Document Intelligence & Extraction Studio",
theme="light",
palette="yellow",
header=True,
) as app:
# 3A. Persistent Navigation & Dimensions Sidebar
with ui.sidebar():
# Command Center Brand Header
with ui.row(class_name="items-center justify-between w-full pb-1"):
with ui.row(class_name="items-center gap-2 min-w-0"):
ui.badge(
"DOC",
variant="default",
class_name="w-6 h-6 rounded-md flex items-center justify-center font-bold text-xs p-0 shrink-0",
)
with ui.column(class_name="min-w-0 gap-0"):
ui.text("Acme Document AI", class_name="font-bold text-xs text-foreground tracking-tight truncate leading-tight")
ui.text("Compliance Studio", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.badge("v4.2", variant="secondary", class_name="text-[9px] font-mono px-1.5 py-0.5 shrink-0")
ui.separator()
# Primary Navigation Menu with Interactive Handlers
ui.text("Studio Views", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.button(
"Ingestion Pipeline",
icon="file-text",
on_click=handle_nav_pipeline,
variant="default",
class_name="w-full justify-start text-xs font-semibold h-8 shadow-xs",
)
ui.button(
"Document Archive",
icon="archive",
on_click=handle_nav_documents,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Extraction Schemas",
icon="code-2",
on_click=handle_nav_schemas,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Auditor Access",
icon="shield-check",
on_click=handle_nav_auditors,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Studio Settings",
icon="settings",
on_click=handle_nav_settings,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.separator()
# Operational Pipeline Status
ui.text("Pipeline Health", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("OCR Model", class_name="text-[10px] text-muted-foreground")
ui.text("LayoutLM-v4", class_name="font-semibold text-foreground text-[10px]")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("Integrity", class_name="text-[10px] text-muted-foreground")
ui.text("SHA-256 Signed", class_name="font-semibold text-emerald-500 text-[10px]")
# Pinned Chief Compliance Officer Profile Footer (Sticks to bottom, interactive)
with ui.row(class_name="pt-3 border-t border-border/80 items-center justify-between w-full mt-auto select-none"):
with ui.row(class_name="items-center gap-2 min-w-0 flex-1"):
ui.avatar(fallback="EC", class_name="w-7 h-7 rounded-full bg-primary/20 text-primary border border-primary/30 font-bold text-xs flex items-center justify-center")
with ui.column(class_name="min-w-0 flex-1 gap-0"):
ui.text("Dr. Elena Croft", class_name="text-xs font-semibold text-foreground truncate leading-tight")
ui.text("Chief Compliance Officer", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.button(
"Profile",
on_click=handle_view_officer,
variant="ghost",
class_name="text-[10px] font-mono h-6 px-2 text-muted-foreground hover:text-foreground",
)
# 3B. Main Content Viewport
# Header summary & Action Controls
with ui.row(class_name="flex-col sm:flex-row sm:items-center justify-between w-full pb-2 border-b border-border/60 gap-3 select-none"):
with ui.column(class_name="flex-1 min-w-0 space-y-0.5"):
ui.title(
"Multimodal Document Intelligence & Extraction Studio",
level=4,
class_name="text-sm font-bold text-foreground tracking-tight",
)
ui.text(
"Autonomous OCR extraction, SEC/HIPAA compliance verification, and structured JSON audit logging.",
class_name="text-[11px] text-muted-foreground",
)
with ui.row(class_name="flex-row items-center gap-2 w-auto shrink-0 flex-wrap"):
ui.button(
"Sync Parser Rails",
icon="refresh-cw",
on_click=handle_sync_rails,
variant="outline",
class_name="text-xs font-medium h-7 px-2.5",
)
ui.button(
"Export Audit Bundle",
icon="download",
on_click=handle_export_bundle,
variant="default",
class_name="text-xs font-semibold h-7 px-2.5 shadow-xs",
)
with ui.row(class_name="flex-row items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20 text-[10px] font-mono font-semibold w-auto shrink-0"):
ui.badge("Pipeline Healthy", variant="outline", class_name="border-0 p-0 text-[10px] font-semibold text-emerald-500")
# Multi-Tab Workflow Container (ui.tabs)
with ui.tabs(
tabs_list=[
{"id": "ingest", "label": "Document Ingestion & Security"},
{"id": "extraction", "label": "OCR & Extracted JSON"},
{"id": "compliance", "label": "Compliance Verification & Rules"},
],
class_name="w-full my-3",
):
# -------------------------------------------------------------
# TAB 1: Document Ingestion & Security Verification
# -------------------------------------------------------------
with ui.column(class_name="space-y-4 w-full"):
ui.callout(
"Upload SEC 10-K, vendor invoice, or clinical trial PDF. The extraction pipeline performs SHA-256 verification and enforces zero-knowledge PII sanitization.",
variant="info",
class_name="text-xs font-medium",
)
with ui.row(class_name="grid grid-cols-1 lg:grid-cols-2 gap-4 w-full"):
# Left Panel: File Uploader and Taxonomy Settings
with ui.column(class_name="p-4 rounded-2xl border border-border bg-card/60 space-y-3"):
ui.title("Document Upload & OCR Preprocessing", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
ui.file_upload(
label="Drop PDF, Scanned Image, or Financial Dataset",
accept=".pdf,.png,.csv,.json",
on_upload=handle_file_upload,
)
ui.progress(value=78, label="Optical Character Recognition (OCR) Parsing...", show_value=True)
ui.select(
options=["SEC 10-K Annual Filing", "Healthcare HIPAA Record", "Enterprise Vendor Invoice", "Legal M&A Contract"],
label="Document Taxonomy Classification",
value="SEC 10-K Annual Filing",
on_change=handle_taxonomy_change,
)
with ui.column(class_name="space-y-1.5"):
ui.text("Extraction Engine Mode", class_name="text-xs font-medium text-foreground")
ui.toggle_group(
options=["Fast OCR", "Dense LayoutLM", "Multimodal Vision"],
value="Dense LayoutLM",
on_change=handle_ocr_engine_change,
)
# Right Panel: Security 2FA & Privacy Boundaries
with ui.column(class_name="p-4 rounded-2xl border border-border bg-card/60 space-y-3"):
ui.title("Two-Factor Auditor Authorization (2FA)", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
ui.text(
"Enter your 6-digit cryptographic security token to approve automated PII redaction and external export.",
class_name="text-[11px] text-muted-foreground",
)
ui.input_otp(length=6, value="849201", on_change=handle_otp_change)
ui.checkbox(
label="Enforce SOC2 Zero-Knowledge PII Masking",
description="Automatically scrub Social Security Numbers, Tax IDs, and Bank Routing codes prior to indexing.",
value=True,
on_change=handle_masking_toggle,
)
ui.radio(
options=["Strict Sandbox (No External APIs)", "Hybrid LLM Inference", "Air-Gapped Local Cluster"],
label="Inference Security Boundary",
value="Strict Sandbox (No External APIs)",
on_change=handle_boundary_change,
)
with ui.row(class_name="flex-row items-center gap-2 pt-2"):
ui.button("Authorize Document Extraction", on_click=handle_authorize_extraction, variant="default", class_name="text-xs font-semibold h-8")
ui.button("Reset Ingestion Buffer", on_click=handle_reset_buffer, variant="outline", class_name="text-xs font-medium h-8")
# -------------------------------------------------------------
# TAB 2: OCR & Extracted Structured JSON Inspector
# -------------------------------------------------------------
with ui.column(class_name="space-y-4 w-full"):
with ui.row(class_name="flex-row items-center justify-between w-full select-none"):
with ui.column(class_name="space-y-0.5"):
ui.title("Extracted Structured Entities & Transformation Logic", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
ui.text("Inspect parsed JSON entity hierarchies and review the verified Pydantic transformation code.", class_name="text-[11px] text-muted-foreground")
with ui.row(class_name="flex-row items-center gap-2 w-auto shrink-0"):
ui.button("Reprocess OCR Layout", icon="refresh-cw", on_click=handle_reprocess_ocr, variant="outline", class_name="text-xs font-medium h-7 px-2.5")
ui.button("Copy Extracted JSON", icon="copy", on_click=handle_copy_json, variant="default", class_name="text-xs font-semibold h-7 px-2.5 shadow-xs")
with ui.row(class_name="grid grid-cols-1 lg:grid-cols-2 gap-4 w-full"):
# Left Column: Collapsible JSON Tree Viewer
with ui.column(class_name="space-y-2"):
ui.text("Parsed Entity Graph (JSON Tree)", class_name="text-xs font-semibold text-foreground")
ui.json_viewer(
data=extracted_entity_data,
title="SEC-10K-2026-Q3-0941.json",
default_expanded=True,
)
# Right Column: Generated Python Transformation Code & Markdown Summary
with ui.column(class_name="space-y-3"):
ui.text("Pydantic Schema Contract", class_name="text-xs font-semibold text-foreground")
ui.code(
sample_transformation_code,
language="python",
filename="transform_entities.py",
)
ui.markdown(
"### Verification Summary\n"
"- **Entities Discovered:** `42 verified tokens`\n"
"- **PII Scrubbed:** `14 confidential identifiers masked`\n"
"- **Confidence Score:** `99.2% across bounding boxes`\n"
"- **Parser Engine:** `Pyvello LayoutLM-v4`"
)
# -------------------------------------------------------------
# TAB 3: Compliance Verification & Regulatory Rules
# -------------------------------------------------------------
with ui.column(class_name="space-y-4 w-full"):
ui.callout(
"Regulatory Compliance Check complete: All 4 enterprise standards passed zero-knowledge validation.",
variant="success",
class_name="text-xs font-medium",
)
with ui.row(class_name="grid grid-cols-1 lg:grid-cols-2 gap-4 w-full"):
# Left Column: Regulatory Framework Accordion
with ui.column(class_name="space-y-2"):
ui.title("Regulatory Audit Requirements", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
ui.accordion(
items=[
{
"title": "SOC2 Type II - Data Retention & Vaulting",
"content": "All extracted artifacts are encrypted at rest with AES-256 GCM. Automated 90-day time-to-live (TTL) purging is actively enforced across all storage volumes.",
},
{
"title": "HIPAA / HITECH - Protected Health Information (PHI)",
"content": "Zero-Knowledge named entity recognizer automatically scrubs patient identifiers, Medical Record Numbers (MRN), and physician notes prior to indexing.",
},
{
"title": "SEC Regulation S-K - Material Financial Disclosure",
"content": "Reconciled GAAP revenues, EBITDA calculations, and operating margins against audited quarterly balance sheet filings with 99.8% precision.",
},
{
"title": "GDPR Article 17 - Right to Erasure & Shredding",
"content": "Cryptographic shredding hooks enabled for all transient GPU buffers, scratch arrays, and intermediate OCR embeddings.",
},
],
default_value="item-0",
)
# Right Column: Visual Compliance Analytics
with ui.column(class_name="space-y-3"):
ui.title("Compliance Analytics & Throughput", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
with ui.row(class_name="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full"):
ui.donut_chart(
data=compliance_framework_data,
title="Audit Framework Allocation",
height=180,
)
ui.area_chart(
data=throughput_timeline_data,
title="Ingestion Velocity (Pages/hr)",
height=180,
color="#eab308",
)
# Audit Action Buttons Footer
with ui.row(class_name="flex-row items-center gap-2 pt-2 border-t border-border/80"):
ui.button("Download Signed Compliance Certificate", on_click=handle_download_cert, variant="default", class_name="text-xs font-semibold h-8 shadow-xs")
ui.button("Purge Transient Cache", on_click=handle_purge_cache, variant="destructive", class_name="text-xs font-semibold h-8")
# ---------------------------------------------------------------------------
# 4. Standalone Server Execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Launch on port 8084 for standalone or test execution
app.launch(port=8084)
05. Multi-Agent Swarm & Execution DAG Studio
A mission-critical multi-agent coordination command center demonstrating structured topology graphs (app.graph / AgentGraph), hierarchical location breadcrumbs (ui.breadcrumb()), slide-over side drawers (ui.sheet()), destructive rollout confirmation modals (ui.dialog()), dynamic hover tooltips (ui.tooltip()), and automated LLM-as-a-Judge evaluation scorecards.
Hierarchical Multi-Agent Supervision with Real-Time Trace Drawers
This example illustrates how to structure complex multi-agent swarms using AgentGraph. Operators inspect real-time execution node latencies, review semantic intent router classification rules, and verify LLM benchmark evaluations before triggering production deployments.
Autonomous Multi-Agent Swarm & Execution DAG Studio
Supervisor planning, intent routing, sequential chains, and LLM-as-a-judge evaluation.
| Intent | Target Agent | Model | Confidence | Sample Query |
|---|---|---|---|---|
| architecture_plan | PlannerAgent | gpt-4o | 0.982 | Design a distributed vector ingestion worker pipeline with dead-letter queue |
| code_generation | SynthesizerAgent | claude-3-5-sonnet | 0.967 | Write async FastAPI endpoint with Redis token bucket rate limiting |
| security_audit | AuditorAgent | gpt-4o-mini | 0.941 | Check this raw SQL template for parameter injection vulnerabilities |
| llm_judge_eval | EvaluatorAgent | deepseek-r1 | 0.955 | Benchmark generated unit tests against edge cases and coverage target |
| Criteria | Weight | Score | Status | Evaluator Model |
|---|---|---|---|---|
| Code Correctness & Type Safety | 35% | 99.2% | PASSED | deepseek-r1 |
| Zero-Vulnerability Security Posture | 30% | 100.0% | PASSED | deepseek-r1 |
| Async Throughput & Latency Budget | 20% | 96.8% | PASSED | deepseek-r1 |
| Documentation & Test Suite Coverage | 15% | 97.5% | PASSED | deepseek-r1 |
"""Example 05: Autonomous Multi-Agent Swarm & Execution DAG Studio.
A mission-critical multi-agent coordination and execution DAG workspace featuring:
- Full-screen or header-enabled mode (header=True by default, can be set to False)
- Persistent swarm topology navigation sidebar with pinned AI Systems Architect profile
- Interactive breadcrumb navigation (ui.breadcrumb) and contextual tooltips (ui.tooltip)
- Top header action bar featuring slide-over trace sheets (ui.sheet) and deployment dialogs (ui.dialog)
- 4 executive KPI metric cards for worker count, swarm token economics, latency, and judge score
- Visual execution DAG representation showing supervisor and specialist agent node states
- Semantic intent router rules table and LLM-as-a-Judge quantitative evaluation scorecard
- Reactive Python callbacks (on_click) displaying live ui.toast() alert notifications
- Red / Crimson executive terminal palette (palette="red")
"""
from typing import Any
import pyvello as ui
from pyvello.graph.models import NodeKind, NodeStatus
# ---------------------------------------------------------------------------
# 1. Dataset & Swarm Topology Definitions
# ---------------------------------------------------------------------------
# Semantic Router Intent Classification Rules
router_rules = [
{
"intent": "Database Schema & Migration",
"target_agent": "Database Architect",
"model": "gpt-4o",
"confidence": "99.4%",
"sample": "Add foreign key indexing and partitioned audit log tables",
},
{
"intent": "Core Backend Code Synthesis",
"target_agent": "Code Synthesizer",
"model": "claude-3-5-sonnet",
"confidence": "98.8%",
"sample": "Refactor async connection pool with exponential backoff",
},
{
"intent": "Vulnerability & Security Audit",
"target_agent": "Security Auditor",
"model": "gpt-4o-mini",
"confidence": "99.1%",
"sample": "Scan AST for unsanitized raw SQL and timing attacks",
},
{
"intent": "Automated Quality & Verification",
"target_agent": "LLM Evaluator",
"model": "deepseek-r1",
"confidence": "97.6%",
"sample": "Grade correctness against RFC 7231 and generate pytest suite",
},
]
# LLM-as-a-Judge Evaluation Scorecard Metrics
judge_scorecard = [
{
"criteria": "Functional Correctness",
"weight": "35%",
"score": "99.2%",
"status": "Passed",
"evaluator": "deepseek-r1",
},
{
"criteria": "Security & Zero PII Leakage",
"weight": "30%",
"score": "99.8%",
"status": "Passed",
"evaluator": "gpt-4o",
},
{
"criteria": "Test Coverage & Edge Cases",
"weight": "20%",
"score": "94.6%",
"status": "Passed",
"evaluator": "claude-3-5-sonnet",
},
{
"criteria": "Code Complexity & Cyclomatic Depth",
"weight": "15%",
"score": "96.1%",
"status": "Passed",
"evaluator": "gpt-4o-mini",
},
]
# ---------------------------------------------------------------------------
# 2. Reactive Event Handlers (User Actions & Alert Callbacks)
# ---------------------------------------------------------------------------
def handle_nav_dag():
"""Triggered when user clicks 'DAG Topology' in the sidebar."""
ui.toast(
message="Viewing Live Multi-Agent Execution DAG Graph and Node Topology.",
type="info",
title="DAG Topology",
)
def handle_nav_workers():
"""Triggered when user clicks 'Worker Agents' in the sidebar."""
ui.toast(
message="Viewing 4 active specialized worker agents and prompt contexts.",
type="info",
title="Worker Agents",
)
def handle_nav_router():
"""Triggered when user clicks 'Router Rules' in the sidebar."""
ui.toast(
message="Opened Semantic Intent Router classification matrix.",
type="info",
title="Router Rules",
)
def handle_nav_judge():
"""Triggered when user clicks 'Judge Scorecards' in the sidebar."""
ui.toast(
message="Loaded automated LLM-as-a-Judge evaluation benchmarks.",
type="info",
title="Judge Scorecards",
)
def handle_nav_settings():
"""Triggered when user clicks 'Cluster Settings' in the sidebar."""
ui.toast(
message="Opened Swarm Concurrency, Token Budget, and Rate-Limiting dialog.",
type="info",
title="Cluster Settings",
)
def handle_trigger_swarm():
"""Triggered when user clicks 'Trigger Swarm' in the header."""
ui.toast(
message="Swarm execution initiated: Architecture Planner node active.",
type="success",
title="Swarm Started",
)
def handle_pause_swarm():
"""Triggered when user clicks 'Pause Execution'."""
ui.toast(
message="Swarm execution suspended. Active agent workers idling safely.",
type="warning",
title="Swarm Paused",
)
def handle_export_dag():
"""Triggered when user clicks 'Export DAG Trace'."""
ui.toast(
message="Exported OpenTelemetry execution trace and token breakdown (JSON).",
type="success",
title="DAG Trace Exported",
)
def handle_confirm_deploy():
"""Triggered when user confirms deployment inside the dialog."""
ui.toast(
message="Deployed multi-agent swarm to us-east-1 production Kubernetes pods.",
type="success",
title="Deployment Complete",
)
def handle_view_architect():
"""Triggered when user clicks the architect profile footer."""
ui.toast(
message="Architect: Dr. Aris Thorne | Role: Lead AI Systems Architect | Clearance: Swarm Supervisor",
type="info",
title="AI Architect Profile",
)
# ---------------------------------------------------------------------------
# 3. Reactive UI Layout Architecture
# ---------------------------------------------------------------------------
# with ui.App() creates the single-page application container.
# palette="red" applies the high-visibility crimson / incident red color scheme.
# header=True is the default. Pass header=False to completely hide the top navbar
# for full-screen kiosk displays or embedded NOC monitoring walls:
# with ui.App(title="...", theme="light", palette="red", header=False) as app:
with ui.App(
title="Autonomous Multi-Agent Swarm & Execution DAG Studio",
theme="light",
palette="red",
header=True,
) as app:
# Populate application execution graph nodes and edges
if app.graph:
n1 = app.graph.add_node("planner", label="Architecture Planner", kind=NodeKind.AGENT, model="gpt-4o")
n1.status = NodeStatus.COMPLETED
n2 = app.graph.add_node("coder", label="Code Synthesizer", kind=NodeKind.AGENT, model="claude-3-5-sonnet")
n2.status = NodeStatus.RUNNING
n3 = app.graph.add_node("auditor", label="Security Auditor", kind=NodeKind.AGENT, model="gpt-4o-mini")
n3.status = NodeStatus.IDLE
n4 = app.graph.add_node("judge", label="LLM Evaluator", kind=NodeKind.LLM, model="deepseek-r1")
n4.status = NodeStatus.IDLE
app.graph.add_edge("planner", "coder", animated=True)
app.graph.add_edge("coder", "auditor")
app.graph.add_edge("auditor", "judge")
# 3A. Persistent Navigation & Dimensions Sidebar
with ui.sidebar():
# Command Center Brand Header
with ui.row(class_name="items-center justify-between w-full pb-1"):
with ui.row(class_name="items-center gap-2 min-w-0"):
ui.badge(
"DAG",
variant="default",
class_name="w-6 h-6 rounded-md flex items-center justify-center font-bold text-xs p-0 shrink-0",
)
with ui.column(class_name="min-w-0 gap-0"):
ui.text("Acme Swarm Core", class_name="font-bold text-xs text-foreground tracking-tight truncate leading-tight")
ui.text("Multi-Agent Supervisor", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.badge("v5.0", variant="secondary", class_name="text-[9px] font-mono px-1.5 py-0.5 shrink-0")
ui.separator()
# Primary Navigation Menu with Interactive Handlers
ui.text("Swarm Views", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.button(
"DAG Topology",
icon="network",
on_click=handle_nav_dag,
variant="default",
class_name="w-full justify-start text-xs font-semibold h-8 shadow-xs",
)
ui.button(
"Worker Agents",
icon="bot",
on_click=handle_nav_workers,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Router Rules",
icon="split",
on_click=handle_nav_router,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Judge Scorecards",
icon="scale",
on_click=handle_nav_judge,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Cluster Settings",
icon="settings",
on_click=handle_nav_settings,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.separator()
# Operational Swarm Status
ui.text("Cluster Health", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("Supervisor", class_name="text-[10px] text-muted-foreground")
ui.text("Hierarchical Swarm", class_name="font-semibold text-foreground text-[10px]")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("Execution Mode", class_name="text-[10px] text-muted-foreground")
ui.text("Live DAG Active", class_name="font-semibold text-emerald-500 text-[10px]")
# Pinned AI Systems Architect Profile Footer (Sticks to bottom, interactive)
with ui.row(class_name="pt-3 border-t border-border/80 items-center justify-between w-full mt-auto select-none"):
with ui.row(class_name="items-center gap-2 min-w-0 flex-1"):
ui.avatar(fallback="AT", class_name="w-7 h-7 rounded-full bg-primary/20 text-primary border border-primary/30 font-bold text-xs flex items-center justify-center")
with ui.column(class_name="min-w-0 flex-1 gap-0"):
ui.text("Dr. Aris Thorne", class_name="text-xs font-semibold text-foreground truncate leading-tight")
ui.text("Lead AI Architect", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.button(
"Profile",
on_click=handle_view_architect,
variant="ghost",
class_name="text-[10px] font-mono h-6 px-2 text-muted-foreground hover:text-foreground",
)
# 3B. Main Content Viewport
# Breadcrumb Hierarchy Navigation
ui.breadcrumb(items=["Swarm Control", "Enterprise Engineering Swarm", "Production Refactor DAG"])
# Header Title & Action Controls with Slide-Over Sheet and Dialog
with ui.row(class_name="flex-col sm:flex-row sm:items-center justify-between w-full pb-2 border-b border-border/60 gap-3 select-none"):
with ui.column(class_name="flex-1 min-w-0 space-y-0.5"):
ui.title(
"Autonomous Multi-Agent Swarm & Execution DAG Studio",
level=4,
class_name="text-sm font-bold text-foreground tracking-tight",
)
ui.text(
"Supervisor planning, intent routing, sequential chains, and LLM-as-a-judge evaluation.",
class_name="text-[11px] text-muted-foreground",
)
with ui.row(class_name="flex-row items-center gap-2 w-auto shrink-0 flex-wrap"):
ui.button(
"Trigger Swarm",
icon="play",
on_click=handle_trigger_swarm,
variant="default",
class_name="text-xs font-semibold h-7 px-2.5 shadow-xs",
)
ui.button(
"Pause",
icon="pause",
on_click=handle_pause_swarm,
variant="outline",
class_name="text-xs font-medium h-7 px-2.5",
)
# Slide-over Right Drawer Panel (ui.sheet) for Detailed Node Telemetry
with ui.sheet(
title="Swarm Execution Trace & Step Latency",
description="Live execution telemetry across all worker agents, router classifications, and model token usage.",
trigger="Inspect Swarm Trace",
trigger_variant="outline",
side="right",
class_name="w-full sm:max-w-md",
):
with ui.column(class_name="space-y-3 pt-3"):
ui.callout("All 4 agent nodes communicating via zero-copy in-memory WebSocket event rails.", variant="info")
with ui.column(class_name="p-3 rounded-xl border border-border bg-card space-y-1"):
ui.text("Step 1: Architecture Planner", class_name="font-semibold text-xs text-foreground")
ui.text("Model: openrouter/openai/gpt-4o | Latency: 420ms | Tokens: 3,420", class_name="text-[10px] font-mono text-muted-foreground")
with ui.column(class_name="p-3 rounded-xl border border-border bg-card space-y-1"):
ui.text("Step 2: Code Synthesizer", class_name="font-semibold text-xs text-foreground")
ui.text("Model: anthropic/claude-3-5-sonnet | Latency: 840ms | Tokens: 6,890", class_name="text-[10px] font-mono text-muted-foreground")
with ui.column(class_name="p-3 rounded-xl border border-border bg-card space-y-1"):
ui.text("Step 3: Security Auditor", class_name="font-semibold text-xs text-foreground")
ui.text("Model: openrouter/openai/gpt-4o-mini | Latency: 290ms | Tokens: 1,840", class_name="text-[10px] font-mono text-muted-foreground")
with ui.column(class_name="p-3 rounded-xl border border-border bg-card space-y-1"):
ui.text("Step 4: LLM-as-a-Judge", class_name="font-semibold text-xs text-foreground")
ui.text("Model: deepseek/deepseek-r1 | Latency: 610ms | Score: 98.4%", class_name="text-[10px] font-mono text-muted-foreground")
# Pop-up Modal Confirmation Dialog (ui.dialog)
with ui.dialog(
title="Deploy Multi-Agent Swarm to Production",
description="Confirm deployment of verified agent weights to production cluster.",
trigger="Deploy Swarm",
trigger_variant="destructive",
):
with ui.column(class_name="space-y-3 pt-2"):
ui.callout("Target: us-east-1 Production Kubernetes Cluster. 4 worker pods will be provisioned.", variant="warning")
with ui.row(class_name="flex-row items-center gap-2 pt-2"):
ui.button("Confirm Production Rollout", on_click=handle_confirm_deploy, variant="destructive", class_name="text-xs font-semibold h-8")
# 4 Executive KPI Metric Cards with Tooltips (ui.tooltip)
with ui.row(class_name="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 w-full my-2"):
ui.metric("ACTIVE WORKER AGENTS", "4 Nodes", delta="Supervisor Mesh")
ui.metric("TOTAL SWARM TOKENS", "148,290", delta="+34.2% batch")
ui.metric("MEAN INFERENCE LATENCY", "640ms", delta="-120ms opt")
ui.metric("LLM JUDGE SCORE", "98.4%", delta="Passed Benchmark")
# Visual Swarm Execution DAG Pipeline
ui.title("Swarm Execution DAG & Agent Node Topology", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono mt-3 mb-1")
with ui.row(class_name="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 w-full p-4 rounded-2xl border border-border bg-card/60 shadow-2xs my-1"):
# Node 1: Architecture Planner
with ui.column(class_name="p-3.5 rounded-xl border border-emerald-500/30 bg-emerald-500/5 space-y-2"):
with ui.row(class_name="items-center justify-between w-full"):
ui.badge("Step 1", variant="outline", class_name="text-[9px] font-mono text-emerald-500 border-emerald-500/30")
ui.badge("Completed", variant="default", class_name="text-[9px] font-mono bg-emerald-500 text-black")
ui.text("Architecture Planner", class_name="text-xs font-bold text-foreground")
ui.text("Decomposes requirements into structured task contracts and database schemas.", class_name="text-[10px] text-muted-foreground leading-relaxed")
ui.text("Model: gpt-4o | 420ms", class_name="text-[9px] font-mono text-primary font-semibold")
# Node 2: Code Synthesizer
with ui.column(class_name="p-3.5 rounded-xl border border-amber-500/30 bg-amber-500/5 space-y-2"):
with ui.row(class_name="items-center justify-between w-full"):
ui.badge("Step 2", variant="outline", class_name="text-[9px] font-mono text-amber-500 border-amber-500/30")
ui.badge("Running", variant="default", class_name="text-[9px] font-mono bg-amber-500 text-black")
ui.text("Code Synthesizer", class_name="text-xs font-bold text-foreground")
ui.text("Synthesizes async Python backend logic and SQLAlchemy connection pools.", class_name="text-[10px] text-muted-foreground leading-relaxed")
ui.text("Model: claude-3-5-sonnet | 840ms", class_name="text-[9px] font-mono text-primary font-semibold")
# Node 3: Security Auditor
with ui.column(class_name="p-3.5 rounded-xl border border-border bg-muted/20 space-y-2"):
with ui.row(class_name="items-center justify-between w-full"):
ui.badge("Step 3", variant="outline", class_name="text-[9px] font-mono")
ui.badge("Queued", variant="secondary", class_name="text-[9px] font-mono")
ui.text("Security Auditor", class_name="text-xs font-bold text-foreground")
ui.text("Scans generated abstract syntax trees for SQL injection and timing side-channels.", class_name="text-[10px] text-muted-foreground leading-relaxed")
ui.text("Model: gpt-4o-mini | Standby", class_name="text-[9px] font-mono text-muted-foreground")
# Node 4: LLM-as-a-Judge
with ui.column(class_name="p-3.5 rounded-xl border border-border bg-muted/20 space-y-2"):
with ui.row(class_name="items-center justify-between w-full"):
ui.badge("Step 4", variant="outline", class_name="text-[9px] font-mono")
ui.badge("Queued", variant="secondary", class_name="text-[9px] font-mono")
ui.text("LLM-as-a-Judge", class_name="text-xs font-bold text-foreground")
ui.text("Rigorously evaluates synthetic code correctness and generates verification unit tests.", class_name="text-[10px] text-muted-foreground leading-relaxed")
ui.text("Model: deepseek-r1 | Standby", class_name="text-[9px] font-mono text-muted-foreground")
# Semantic Intent Router & Classification Rules Table
ui.title("Semantic Intent Router Classification Rules", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono mt-3 mb-1")
ui.table(
data=router_rules,
columns=["intent", "target_agent", "model", "confidence", "sample"],
page_size=5,
searchable=True,
)
# LLM-as-a-Judge Evaluation Scorecard Table
ui.title("LLM-as-a-Judge Evaluation Benchmark Scorecard", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono mt-3 mb-1")
ui.table(
data=judge_scorecard,
columns=["criteria", "weight", "score", "status", "evaluator"],
page_size=5,
searchable=True,
)
# ---------------------------------------------------------------------------
# 4. Standalone Server Execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Launch on port 8085 for standalone or test execution
app.launch(port=8085)
06. Multimodal Generative Studio & AutoForm
An automated Python function ingestion workspace (ui.from_function() / AutoForm) achieving complete Streamlit and Gradio parity with zero boilerplate. Paired with native multimodal media components: synthetic image previews (ui.image()), synthesized neural voiceovers (ui.audio()), video animation playback (ui.video()), latent parameter controls (ui.number_input(), ui.text_area(), ui.text_input()), and loading skeletons (ui.skeleton()).
Interactive AutoForm Generation with Multimodal Canvas Playback
Simply pass any typed Python function into ui.from_function() to automatically generate sliders, dropdowns, text areas, and live JSON response inspectors without writing any HTML or JavaScript.
Multimodal Generative Media & Automated Function Workbench
Automated Python function UI inference (AutoForm) combined with synthetic image, audio, and video preview.
"""Example 06: Multimodal Generative Media & Automated Function Workbench.
An executive-grade multimodal media studio and function runner featuring:
- Full-screen or header-enabled mode (header=True by default, can be set to False)
- Automatic web UI form generation from Python function signatures (ui.from_function / AutoForm)
- Multimodal media rendering: high-resolution image (ui.image), audio player (ui.audio), and video stream (ui.video)
- Granular freeform inputs: multi-line negative prompt (ui.text_area), numeric LoRA stepper (ui.number_input), and model endpoint (ui.text_input)
- Animated loading skeleton placeholders (ui.skeleton)
- Persistent creative studio navigation sidebar with pinned Creative Director profile
- Reactive Python callbacks (on_click, on_change) with live ui.toast() alert notifications
- Gold / Amber executive terminal palette (palette="yellow")
"""
from typing import Any, Dict
import pyvello as ui
# ---------------------------------------------------------------------------
# 1. Target Python Function for Automated Form Ingestion (ui.from_function)
# ---------------------------------------------------------------------------
def generate_synthetic_media(
prompt: str = "Cyberpunk neon city skyline reflected in rainfall, volumetric golden lighting",
style_preset: str = "Cinematic Hyper-Realism",
guidance_scale: float = 7.5,
num_inference_steps: int = 30,
aspect_ratio: str = "16:9",
seed: int = 42,
enable_hd_upscaling: bool = True,
) -> Dict[str, Any]:
"""Execute text-to-image and multimodal media synthesis with customizable sampling parameters.
Args:
prompt: Detailed creative prompt describing the visual scene and lighting.
style_preset: Visual aesthetic preset applied to the latent space.
guidance_scale: Classifier-free guidance (CFG) scale balancing creativity vs prompt fidelity.
num_inference_steps: Denoising steps executed by the diffusion scheduler.
aspect_ratio: Output canvas aspect ratio (e.g., 16:9 widescreen or 1:1 square).
seed: Random seed for deterministic reproducibility.
enable_hd_upscaling: Apply secondary 4k latent upscaler model.
"""
return {
"status": "success",
"asset_id": "ASSET-GEN-9421",
"prompt": prompt,
"style_preset": style_preset,
"guidance_scale": guidance_scale,
"num_inference_steps": num_inference_steps,
"aspect_ratio": aspect_ratio,
"seed": seed,
"hd_upscaling": enable_hd_upscaling,
"resolution": "3840x2160 (4K UHD)",
"inference_time_ms": 1420.5,
"engine": "Pyvello Diffusion & Docker Sandbox",
}
# ---------------------------------------------------------------------------
# 2. Reactive Event Handlers (User Actions & Alert Callbacks)
# ---------------------------------------------------------------------------
def handle_nav_workbench():
"""Triggered when user clicks 'Function Workbench' in the sidebar."""
ui.toast(
message="Viewing Automated Function Workbench & Diffusion Parameters.",
type="info",
title="Function Workbench",
)
def handle_nav_gallery():
"""Triggered when user clicks 'Media Gallery' in the sidebar."""
ui.toast(
message="Loaded 1,420 generated 4k images, audio narrations, and video clips.",
type="info",
title="Media Gallery",
)
def handle_nav_models():
"""Triggered when user clicks 'Model Checkpoints' in the sidebar."""
ui.toast(
message="Viewing HuggingFace, Replicate, and local ComfyUI model registry.",
type="info",
title="Model Registry",
)
def handle_nav_docker():
"""Triggered when user clicks 'Docker Sandbox' in the sidebar."""
ui.toast(
message="Connected to isolated Docker container with CUDA GPU acceleration.",
type="info",
title="Docker Sandbox",
)
def handle_nav_settings():
"""Triggered when user clicks 'Studio Settings' in the sidebar."""
ui.toast(
message="Opened GPU VRAM caching, batch queue, and storage retention settings.",
type="info",
title="Studio Settings",
)
def handle_generate_media():
"""Triggered when user clicks 'Run Multimodal Synthesis' in the header."""
ui.toast(
message="Synthesis complete: 4k image canvas, voiceover narration, and video clip generated.",
type="success",
title="Synthesis Complete",
)
def handle_download_bundle():
"""Triggered when user clicks 'Download Media Bundle'."""
ui.toast(
message="Downloaded creative media bundle (PNG image, MP3 voiceover, MP4 video).",
type="success",
title="Bundle Downloaded",
)
def handle_clear_scratch():
"""Triggered when user clicks 'Clear Scratch Buffer'."""
ui.toast(
message="Cleared latent scratch canvas and intermediate noise tensors.",
type="info",
title="Buffer Cleared",
)
def handle_export_script():
"""Triggered when user clicks 'Export PyTorch Script'."""
ui.toast(
message="Exported standalone diffusers Python script for offline GPU inference.",
type="success",
title="Script Exported",
)
def handle_view_director():
"""Triggered when user clicks the creative director profile footer."""
ui.toast(
message="Director: Chloe Bennett | Role: Principal Generative Media Architect | Clearance: Multimodal Lead",
type="info",
title="Creative Director Profile",
)
def handle_negative_change(val: str):
"""Triggered when user types in the negative prompt textarea."""
ui.toast(
message=f"Negative prompt guidance updated: '{val[:25]}...'",
type="info",
title="Negative Prompt Updated",
)
def handle_lora_change(val: float):
"""Triggered when user changes the LoRA numeric input."""
ui.toast(
message=f"LoRA fine-tuning weight calibrated to {val:.2f}.",
type="warning",
title="LoRA Calibrated",
)
def handle_checkpoint_change(val: str):
"""Triggered when user changes model checkpoint text input."""
ui.toast(
message=f"Active diffusion model checkpoint updated to '{val}'.",
type="info",
title="Checkpoint Loaded",
)
# ---------------------------------------------------------------------------
# 3. Reactive UI Layout Architecture
# ---------------------------------------------------------------------------
# with ui.App() creates the single-page application container.
# palette="yellow" sets the gold / amber executive terminal color scheme.
# header=True is the default. Pass header=False to completely hide the top navbar
# for full-screen kiosk displays or embedded creative video walls:
# with ui.App(title="...", theme="light", palette="yellow", header=False) as app:
with ui.App(
title="Multimodal Generative Media & Automated Function Workbench",
theme="light",
palette="yellow",
header=True,
) as app:
# 3A. Persistent Navigation & Dimensions Sidebar
with ui.sidebar():
# Studio Brand Header
with ui.row(class_name="items-center justify-between w-full pb-1"):
with ui.row(class_name="items-center gap-2 min-w-0"):
ui.badge(
"AI",
variant="default",
class_name="w-6 h-6 rounded-md flex items-center justify-center font-bold text-xs p-0 shrink-0",
)
with ui.column(class_name="min-w-0 gap-0"):
ui.text("Acme Media AI", class_name="font-bold text-xs text-foreground tracking-tight truncate leading-tight")
ui.text("Generative Workbench", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.badge("v6.0", variant="secondary", class_name="text-[9px] font-mono px-1.5 py-0.5 shrink-0")
ui.separator()
# Primary Navigation Menu with Interactive Handlers
ui.text("Creative Views", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
ui.button(
"Function Workbench",
icon="sliders-horizontal",
on_click=handle_nav_workbench,
variant="default",
class_name="w-full justify-start text-xs font-semibold h-8 shadow-xs",
)
ui.button(
"Media Gallery",
icon="image",
on_click=handle_nav_gallery,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Model Checkpoints",
icon="box",
on_click=handle_nav_models,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Docker Sandbox",
icon="container",
on_click=handle_nav_docker,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.button(
"Studio Settings",
icon="settings",
on_click=handle_nav_settings,
variant="ghost",
class_name="w-full justify-start text-xs font-medium h-8 text-muted-foreground hover:text-foreground",
)
ui.separator()
# Operational Pipeline Dimensions
ui.text("Inference Engine", class_name="text-[10px] font-mono text-muted-foreground uppercase tracking-wider font-semibold")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("Engine Mode", class_name="text-[10px] text-muted-foreground")
ui.text("AutoForm Inferred", class_name="font-semibold text-foreground text-[10px]")
with ui.row(class_name="w-full justify-between items-center px-2 py-1.5 rounded-lg border border-border bg-muted/40 text-[10px] font-mono text-muted-foreground"):
ui.text("GPU Cluster", class_name="text-[10px] text-muted-foreground")
ui.text("4x H100 (Online)", class_name="font-semibold text-emerald-500 text-[10px]")
# Pinned Creative Director Profile Footer (Sticks to bottom, interactive)
with ui.row(class_name="pt-3 border-t border-border/80 items-center justify-between w-full mt-auto select-none"):
with ui.row(class_name="items-center gap-2 min-w-0 flex-1"):
ui.avatar(fallback="CB", class_name="w-7 h-7 rounded-full bg-primary/20 text-primary border border-primary/30 font-bold text-xs flex items-center justify-center")
with ui.column(class_name="min-w-0 flex-1 gap-0"):
ui.text("Chloe Bennett", class_name="text-xs font-semibold text-foreground truncate leading-tight")
ui.text("Creative Director", class_name="text-[10px] text-muted-foreground truncate leading-tight")
ui.button(
"Profile",
on_click=handle_view_director,
variant="ghost",
class_name="text-[10px] font-mono h-6 px-2 text-muted-foreground hover:text-foreground",
)
# 3B. Main Content Viewport
# Header Title & Action Controls
with ui.row(class_name="flex-col sm:flex-row sm:items-center justify-between w-full pb-2 border-b border-border/60 gap-3 select-none"):
with ui.column(class_name="flex-1 min-w-0 space-y-0.5"):
ui.title(
"Multimodal Generative Media & Automated Function Workbench",
level=4,
class_name="text-sm font-bold text-foreground tracking-tight",
)
ui.text(
"Automated Python function UI inference (AutoForm) combined with synthetic image, audio, and video preview.",
class_name="text-[11px] text-muted-foreground",
)
with ui.row(class_name="flex-row items-center gap-2 w-auto shrink-0 flex-wrap"):
ui.button(
"Run Synthesis",
icon="sparkles",
on_click=handle_generate_media,
variant="default",
class_name="text-xs font-semibold h-7 px-2.5 shadow-xs",
)
ui.button(
"Download Media",
icon="download",
on_click=handle_download_bundle,
variant="outline",
class_name="text-xs font-medium h-7 px-2.5",
)
ui.button(
"Export PyTorch",
icon="code",
on_click=handle_export_script,
variant="ghost",
class_name="text-xs font-medium h-7 px-2.5 text-muted-foreground hover:text-foreground",
)
# Advisory Status Callout
ui.callout(
"AutoForm automatically parsed generate_synthetic_media() type annotations and generated interactive sliders, switches, and JSON response viewers.",
variant="info",
class_name="text-xs font-medium my-2",
)
# Two-Column Creative Studio Container
with ui.row(class_name="grid grid-cols-1 lg:grid-cols-2 gap-4 w-full my-2"):
# Left Column: Automated Function Form Inferred from Python (ui.from_function / AutoForm)
with ui.column(class_name="space-y-4"):
ui.title("Automated Function Ingestion (Streamlit / Gradio Parity)", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
# The AutoForm component generated directly from Python function
ui.from_function(
generate_synthetic_media,
title="Generative Diffusion Inference Runner",
description="Automatically inferred from Python function signature with type annotations.",
output_type="json",
)
# Additional Freeform Inputs (Textarea, NumberInput, TextInput)
with ui.column(class_name="p-4 rounded-2xl border border-border bg-card/60 space-y-3"):
ui.title("Advanced Latent Space Controls", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
ui.text_area(
label="Negative Prompt & Artifact Filtering",
placeholder="blurry, distorted anatomy, text artifacts, watermark, low resolution...",
rows=2,
value="blurry, low resolution, watermark, oversaturated artifacts",
on_change=handle_negative_change,
)
with ui.row(class_name="grid grid-cols-1 sm:grid-cols-2 gap-3 w-full"):
ui.number_input(
label="LoRA Guidance Weight",
value=0.85,
min=0.0,
max=2.0,
step=0.05,
on_change=handle_lora_change,
)
ui.text_input(
label="HuggingFace Checkpoint URL",
value="stabilityai/stable-diffusion-xl-base-1.0",
on_change=handle_checkpoint_change,
)
# Right Column: Multimodal Media Outputs (Image, Audio, Video, Skeletons)
with ui.column(class_name="space-y-4"):
ui.title("Multimodal Media Outputs & Playback", level=4, class_name="text-xs font-bold uppercase tracking-wider text-muted-foreground font-mono")
# Synthetic Image Canvas (ui.image)
with ui.column(class_name="p-4 rounded-2xl border border-border bg-card/60 space-y-2"):
ui.text("Generated 4K Visual Canvas", class_name="text-xs font-semibold text-foreground")
ui.image(
src="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=800&auto=format&fit=crop&q=80",
caption="Diffusion Render: Cyberpunk neon city in rainfall (Seed: 42, Steps: 30, CFG: 7.5)",
alt="Synthetic Cyberpunk Neon Architecture",
class_name="rounded-xl overflow-hidden border border-border/80 shadow-md",
)
# Audio Voiceover Player (ui.audio)
with ui.column(class_name="p-4 rounded-2xl border border-border bg-card/60 space-y-2"):
ui.text("Synthesized Multimodal Voiceover Narration", class_name="text-xs font-semibold text-foreground")
ui.audio(
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
caption="Voiceover: English (US) - Neural High-Fidelity Speech Model",
class_name="w-full",
)
# Video Clip Player (ui.video)
with ui.column(class_name="p-4 rounded-2xl border border-border bg-card/60 space-y-2"):
ui.text("Synthesized Animation Clip (H.264 / 60fps)", class_name="text-xs font-semibold text-foreground")
ui.video(
src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4",
caption="Motion Diffusion: Volumetric rain lighting sequence (16:9 widescreen)",
class_name="w-full rounded-xl overflow-hidden shadow-sm",
)
# Loading State Skeleton Placeholder (ui.skeleton)
with ui.column(class_name="p-4 rounded-2xl border border-dashed border-border bg-muted/20 space-y-2"):
ui.text("Background Secondary Upscaling Queue (Idle)", class_name="text-[11px] font-mono text-muted-foreground")
ui.skeleton(width="100%", height="14px")
ui.skeleton(width="60%", height="14px")
# ---------------------------------------------------------------------------
# 4. Standalone Server Execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Launch on port 8086 for standalone or test execution
app.launch(port=8086)
07. Secure Enterprise Portal & Zero-Trust Auth
Production-grade enterprise portal demonstrating built-in authentication, user registration, role policies, and session persistence in Pyvello. Supports both single-user gated tools and high-concurrency multi-user team workspaces with zero external dependencies.
Unauthenticated visitors see a centered, shadcn-styled card with 'Sign In' and 'Create Account' tabs. The application unlocks immediately upon verification.
Toggle registration via allow_registration=False for private single-user tools, or keep it enabled for open multi-user SaaS.
Python event handlers inspect active session claims via ui.current_user() to trigger user-aware alert notifications.
Security & Operations Overview
Real-time operational dashboard monitoring authenticated sessions and cryptographic status.
Your session token is cryptographically verified via SQLite persistence. The username is visible in the top header bar alongside a one-click Sign Out action.
All password hashes utilize PBKDF2-HMAC-SHA256 with 100,000 iterations and per-user 32-character hex salts.
08. Direct OpenAI & Google SDK Integration (Sessions & Messages History)
Wire official vendor Python SDKs directly into Pyvello without abstraction overhead. Learn how client.chat.completions.create(stream=True) from openai and client.models.generate_content_stream() from google.genai stream tokens reactively into ui.chat() while preserving multi-turn message history arrays and multi-session isolation.
Declare def chat(messages): and pass the full array directly to client.chat.completions.create(messages=messages, stream=True).
Convert unified message roles (user/assistant) into Gemini contents parts and stream via client.models.generate_content_stream().
Each session tab in ui.chat() maintains independent conversation history. Pyvello injects session_id for custom server stores.
Direct OpenAI & Google SDK Integration
Wire native Python SDK clients directly into Pyvello. Learn how conversation history, session tabs, and token streaming work.
When you define a chat callback with parameters (messages, model, session_id), Pyvello automatically injects the active session tab's complete conversation array in standard OpenAI schema. Simply pass it directly to client.chat.completions.create(messages=messages, stream=True) and yield tokens as they arrive.
• SDK Client:
openai.AsyncOpenAI• Target Model:
gpt-4o-mini• Active Session ID:
session_init• Delivered Messages: 1 turn in history array
Idempotency ensures that processing duplicate webhook payloads yields the same result without side-effects. Use Redis SETNX with a 24-hour TTL on the idempotency key.
• SDK Client:
openai.AsyncOpenAI• Target Model:
gpt-4o-mini• Active Session ID:
session_init• Delivered Messages: 3 turns in history array
Pyvello delivered the entire historical message array formatted for the OpenAI Chat Completions API. Each prior turn preserves user inputs, tool responses, and previous assistant completions without manual session stitching.
import os
import time
import asyncio
from typing import Any, AsyncGenerator, Dict, List, Optional
import pyvello as ui
# 1. Vendor SDK Imports
try:
from openai import AsyncOpenAI
HAS_OPENAI_SDK = True
except ImportError:
HAS_OPENAI_SDK = False
try:
from google import genai
HAS_GOOGLE_GENAI_SDK = True
except ImportError:
HAS_GOOGLE_GENAI_SDK = False
# Server-side registry for custom session analytics
SESSION_REGISTRY: Dict[str, Dict[str, Any]] = {}
# 2. Direct OpenAI SDK Streaming Handler
async def stream_openai_sdk(messages: List[Dict[str, Any]], model_name: str, session_id: Optional[str]) -> AsyncGenerator[str, None]:
api_key = os.getenv("OPENAI_API_KEY")
if HAS_OPENAI_SDK and api_key and not api_key.startswith("mock-"):
client = AsyncOpenAI(api_key=api_key)
stream = await client.chat.completions.create(
model=model_name,
messages=[{"role": m.get("role", "user"), "content": str(m.get("content", ""))} for m in messages],
stream=True,
temperature=0.7,
)
async for chunk in stream:
delta = chunk.choices[0].delta.content or ""
if delta:
yield delta
else:
# Simulated fallback preserving exact OpenAI messages payload
prompt = messages[-1].get("content", "") if messages else ""
yield f"[OpenAI SDK Stream | Model: {model_name} | Session: {session_id}]\n\n"
yield f"Received {len(messages)} historical turns in OpenAI messages format.\n\n"
yield f"Echoing prompt: {prompt}"
# 3. Direct Google GenAI SDK Streaming Handler
async def stream_google_sdk(messages: List[Dict[str, Any]], model_name: str, session_id: Optional[str]) -> AsyncGenerator[str, None]:
api_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
if HAS_GOOGLE_GENAI_SDK and api_key and not api_key.startswith("mock-"):
client = genai.Client(api_key=api_key)
# Convert unified messages to Gemini contents schema
gemini_contents = [
{"role": "user" if m.get("role") == "user" else "model", "parts": [{"text": str(m.get("content", ""))}]}
for m in messages
]
response_stream = client.models.generate_content_stream(model=model_name, contents=gemini_contents)
for chunk in response_stream:
if getattr(chunk, "text", ""):
yield chunk.text
else:
prompt = messages[-1].get("content", "") if messages else ""
yield f"[Google GenAI SDK Stream | Model: {model_name} | Session: {session_id}]\n\n"
yield f"Converted {len(messages)} turns to Google Gemini contents schema.\n\n"
yield f"Echoing prompt: {prompt}"
# 4. Master Unified Chat Handler (Auto-Injected by Pyvello)
async def unified_sdk_chat_handler(
messages: List[Dict[str, Any]],
model: str = "OpenAI (gpt-4o-mini)",
session_id: Optional[str] = None,
) -> AsyncGenerator[str, None]:
"""Pyvello automatically injects messages, model, and session_id."""
active_sid = session_id or "default"
if active_sid not in SESSION_REGISTRY:
SESSION_REGISTRY[active_sid] = {"turns": 0, "last_model": model}
SESSION_REGISTRY[active_sid]["turns"] += 1
SESSION_REGISTRY[active_sid]["message_count"] = len(messages)
if "Google" in model or "gemini" in model.lower():
gemini_model = "gemini-2.0-flash" if "2.0" in model else "gemini-1.5-pro"
async for chunk in stream_google_sdk(messages, model_name=gemini_model, session_id=session_id):
yield chunk
else:
openai_model = "gpt-4o" if "gpt-4o" in model and "mini" not in model else "gpt-4o-mini"
async for chunk in stream_openai_sdk(messages, model_name=openai_model, session_id=session_id):
yield chunk
# 5. Build Workspace Layout
with ui.App(title="Native LLM SDK Integration & Session Architecture", theme="light", palette="violet") as app:
with ui.sidebar():
ui.text("Pyvello SDK Studio", class_name="font-bold text-xs")
ui.separator()
ui.text("Supported SDK Providers", class_name="text-[10px] font-mono text-muted-foreground uppercase font-semibold")
ui.badge("AsyncOpenAI", variant="outline")
ui.badge("google.genai", variant="outline")
ui.title("Direct OpenAI & Google SDK Integration", level=4)
ui.text("Wire native Python SDK clients directly into Pyvello. Learn how conversation history, session tabs, and token streaming work.")
# Reactive Chat Interface with Multi-Session & Vendor Dropdown
ui.chat(
on_send=unified_sdk_chat_handler,
models=[
"OpenAI (gpt-4o-mini)",
"Google (gemini-2.0-flash)",
"OpenAI (gpt-4o)",
"Google (gemini-1.5-pro)",
],
placeholder="Type a message or select a test case from the sidebar...",
id="native_sdk_chat",
)
if __name__ == "__main__":
app.launch(port=8089)
09. Universal Multimodal Studio (Single Agent Omni-Chat)
One single agent natively handles complex reasoning alongside photorealistic image generation, cinematic video synthesis, neural text-to-speech voiceovers, and executive PDF document generation without fragile tool-calling schemas. Plug and play across OpenRouter, OpenAI, and custom Chinese / self-hosted models with intelligent response parsing.
Directly connect Flux, Bytedance Seedream, Kolors, Minimax Hailuo, and CogVideoX without tool schemas that fail on pure completion models.
Synthesize neural audio speech playback and generate executive PDF download data URIs right in the same conversational thread.
Intelligently searches arbitrary JSON and response payloads to extract asset URLs and base64 streams automatically.
Photorealistic render synthesized via bytedance-seed/seedream-5-0-flash.
Supported Tools (80+ Enterprise Integrations)
Comprehensive suite of enterprise tools engineered for autonomous agents, swarms, and orchestrators. Each tool features complete type annotations, automatic schema extraction for OpenAI/LiteLLM tool calling, safe simulated fallbacks for dev environments without API keys, and centralized credential management.
Unified Enterprise Credential Architecture
Configure shared credentials once. A single Google OAuth token automatically powers Gmail, Drive, Docs, Sheets, Calendar, and Maps. Similarly, a single Microsoft Graph token powers Outlook, OneDrive, Excel 365, Teams, and Planner.
import pyvello as ui
# 1. Centralized credential setup for your entire agent workspace
ui.configure_credentials(
google_token="ya29.a0AfH6...", # Powers Gmail, Drive, Docs, Sheets, Calendar, Maps
microsoft_token="EwBoA8l6BAA...", # Powers Outlook, OneDrive, Excel, Teams, Planner
tavily_key="tvly-...", # High-accuracy AI research
slack_token="xoxb-...", # Slack bot messaging
)
Authoring Custom Agent Tools (@ui.tool)
In addition to the 135+ built-in enterprise connectors, any standard Python function or async coroutine can be converted into an LLM-callable tool using the @ui.tool decorator. Pyvello automatically parses your function's docstring and type annotations into strict JSON schemas compatible with OpenAI, Anthropic, Gemini, and DeepSeek.
The function's docstring provides the semantic tool description the LLM reads to determine when to call the tool.
Primitive types (str, int, float, bool) and Pydantic models automatically enforce parameter extraction.
Supports both synchronous functions and non-blocking async def coroutines for database queries and external HTTP APIs.
import pyvello as ui
from pydantic import BaseModel, Field
from typing import Dict, Any
class TransferRequest(BaseModel):
recipient_iban: str = Field(description="Target account IBAN string")
amount_usd: float = Field(gt=0, description="Transfer amount in USD")
reference_note: str = Field(default="Automated settlement", description="Audit note")
# 1. Simple Typed Function Tool
@ui.tool
def get_account_balance(account_id: str) -> Dict[str, Any]:
"""Retrieve real-time ledger balance and status for an account."""
return {"account_id": account_id, "balance_usd": 142500.50, "status": "active"}
# 2. Advanced Validated Tool with Pydantic Schema
@ui.tool
async def execute_funds_transfer(transfer: TransferRequest) -> Dict[str, Any]:
"""Execute a validated fund transfer with transactional audit logging."""
return {
"success": True,
"transaction_id": "tx_987123",
"recipient": transfer.recipient_iban,
"amount": transfer.amount_usd,
"reference": transfer.reference_note,
}
# 3. Equip directly onto an Agent or ChatInterface
agent = ui.Agent(
name="TreasuryAgent",
model="openrouter/deepseek/deepseek-chat",
system_prompt="You are a treasury automation specialist with tool execution access.",
tools=[get_account_balance, execute_funds_transfer],
)
app = ui.ChatInterface(agent=agent, title="Treasury Operations Swarm")
if __name__ == "__main__":
app.launch()
Native API Creation & Standalone Export
Define production-ready REST endpoints and real-time Server-Sent Events (SSE) streaming routes directly on your Pyvello application using @app.api.get, @app.api.post, or @app.api.stream. When exported, Pyvello generates a self-contained Python FastAPI backend in backend/main.py that runs natively with pure uvicorn main:app without requiring Pyvello to be installed.
No separate FastAPI or Flask projects. Declare routes alongside your reactive UI and test them live via interactive Swagger UI at http://localhost:8000/swagger (with instant aliases at /api/swagger, /api/docs, and /docs/swagger).
Use @app.api.stream with standard Python generators. Yielding dicts or strings automatically streams as text/event-stream.
Declare request body models with pydantic.BaseModel. Pyvello extracts schemas and preserves validation in both live dev and exported backends.
Export generates a pure FastAPI backend + Vite React UI. Runs anywhere via Docker, Kubernetes, AWS, or Railway without Pyvello installed.
In Pyvello, /docs is dedicated to the comprehensive framework documentation. To inspect and test your registered REST and streaming routes via OpenAPI 3.1 Swagger, navigate directly to /swagger or click the Swagger API Docs icon in the top header toolbar. Aliases at /api/swagger, /api/docs, and /docs/swagger redirect automatically.
1 Defining Endpoints & In-App Interactive UI
You can register routes using @app.api.<method> or shorthand @app.<method>. Inside with app:, build a rich reactive operations console with metrics, form controls, and live payload displays that invoke and demonstrate the endpoints directly:
import json
import pyvello as ui
from pydantic import BaseModel, Field
from typing import Optional, List
app = ui.App(title="API Studio", palette="emerald")
class UserRecord(BaseModel):
username: str
email: str
role: str = Field(default="developer")
# 1. Standard Synchronous GET with Query Parameter
@app.api.get("/api/v1/health")
def health(status_code: int = 200):
return {"status": "operational", "code": status_code, "service": "api-studio"}
# 2. Asynchronous POST with Pydantic Body Validation
@app.api.post("/api/v1/users")
async def create_user(payload: UserRecord):
return {"success": True, "created_user": payload.model_dump(), "timestamp": "2026-10-30T12:00:00Z"}
# 3. Dynamic Path Parameter Lookup
@app.api.get("/api/v1/users/{user_id}")
def get_user(user_id: str):
return {"user_id": user_id, "found": True, "access_tier": "enterprise"}
# 4. Real-time Server-Sent Events (SSE) Streaming
@app.api.stream("/api/v1/ticks")
def stream_ticks(count: int = 5):
for i in range(count):
yield {"tick": i, "status": "active", "channel": "telemetry"}
# Rich In-App Operations Console & Live Interactive Tester
with app:
# 1. Header with direct link to Swagger and System Badges
with ui.row(class_name="w-full flex-row items-center justify-between pb-3 border-b border-border gap-4"):
with ui.col(class_name="flex-1 min-w-0 gap-1"):
ui.title("API Intelligence & Operations Studio", level=1)
ui.text(
"Interactive Python REST API gateway, real-time Server-Sent Events (SSE), and embedded client testing console."
)
with ui.row(class_name="shrink-0 flex-row items-center gap-2"):
ui.badge("FastAPI Engine", variant="default")
ui.badge("OpenAPI 3.1", variant="outline")
ui.button("Open Swagger UI", href="/swagger", variant="outline", size="sm")
# 2. Executive API Gateway Metrics
col1, col2, col3, col4 = ui.columns(4)
with col1:
ui.metric("Active Endpoints", 4, delta="4 registered")
with col2:
ui.metric("Gateway Protocols", "REST + SSE", delta="Streaming enabled")
with col3:
ui.metric("Average Latency", "1.2 ms", delta="-0.3 ms vs target")
with col4:
ui.metric("OpenAPI Swagger", "/swagger", delta="Interactive UI")
# 3. Interactive Route Showcase & In-App Testing Cards
ui.title("Live Endpoint Explorer & UI Dispatcher", level=2)
ui.text("Test API handlers directly from the Pyvello UI or query them externally with curl, fetch, or Swagger UI.")
col_left, col_right = ui.columns(2)
with col_left:
# Card 1: Health Check (GET)
with ui.card("1. GET /api/v1/health", description="Query gateway operational status with customizable response status code"):
ui.callout("GET /api/v1/health?status_code=200", title="Endpoint Route", variant="info")
health_code = ui.number_input("Target Status Code", value=200, min_value=200, max_value=599)
health_output = ui.code('{\n "status": "operational",\n "code": 200,\n "service": "api-studio"\n}', language="json")
def test_health():
res = health(status_code=int(health_code.value or 200))
health_output.value = json.dumps(res, indent=2)
ui.button("Execute GET Probe", variant="default", on_click=test_health)
# Card 3: Dynamic Path Parameter Lookup (GET)
with ui.card("3. GET /api/v1/users/{user_id}", description="Dynamic URL path parameter resolution and record retrieval"):
ui.callout("GET /api/v1/users/{user_id}", title="Path Parameter Route", variant="info")
user_id_input = ui.text_input("User ID", value="usr_9042")
lookup_output = ui.code('{\n "user_id": "usr_9042",\n "found": true,\n "access_tier": "enterprise"\n}', language="json")
def test_lookup():
res = get_user(user_id=user_id_input.value or "usr_9042")
lookup_output.value = json.dumps(res, indent=2)
ui.button("Lookup User by ID", variant="secondary", on_click=test_lookup)
with col_right:
# Card 2: Create User (POST)
with ui.card("2. POST /api/v1/users", description="Pydantic model validation and asynchronous user ingestion"):
ui.callout("POST /api/v1/users (Body: JSON)", title="Validated Body Route", variant="info")
uname = ui.text_input("Username", value="alice_developer")
uemail = ui.text_input("Email Address", value="alice@example.com")
urole = ui.select(["developer", "admin", "analyst", "viewer"], label="Assigned Role", value="developer")
post_output = ui.code('// Response from POST /api/v1/users will appear here', language="json")
async def test_create_user():
payload = UserRecord(username=uname.value or "guest", email=uemail.value or "guest@example.com", role=urole.value or "developer")
res = await create_user(payload=payload)
post_output.value = json.dumps(res, indent=2)
ui.button("Post User Payload", variant="default", on_click=test_create_user)
# Card 4: Real-time SSE Stream (STREAM)
with ui.card("4. STREAM /api/v1/ticks", description="Server-Sent Events (SSE) live event stream"):
ui.callout("GET /api/v1/ticks?count=5 (Content-Type: text/event-stream)", title="SSE Stream Route", variant="info")
ticks_slider = ui.slider("Stream Tick Count", min=1, max=10, value=5)
stream_output = ui.code('// Real-time SSE event stream output:\n// data: {"tick": 0, "status": "active"}\n// ...', language="json")
def test_stream():
events = list(stream_ticks(count=int(ticks_slider.value or 5)))
stream_output.value = json.dumps(events, indent=2)
ui.button("Trigger Event Stream", variant="secondary", on_click=test_stream)
# 4. OpenAPI / Swagger Documentation Card
with ui.card("Interactive OpenAPI Documentation & Swagger UI", description="Automated OpenAPI 3.1 specification, interactive test playground, and ReDoc"):
ui.callout(
"Swagger UI is automatically mounted at /swagger (with aliases at /api/swagger, /api/docs, and /docs/swagger). "
"You can execute live curl requests, download client schemas, and inspect type definitions directly.",
title="Swagger Discovery",
variant="success"
)
with ui.row(class_name="items-center gap-3 pt-2"):
ui.button("Open Swagger UI (/swagger)", href="/swagger", variant="default")
ui.button("Open ReDoc (/redoc)", href="/redoc", variant="outline")
ui.button("View OpenAPI JSON (/openapi.json)", href="/openapi.json", variant="ghost")
if __name__ == "__main__":
app.launch()
2 Standalone Export Architecture (Zero Framework Dependency)
When you click Export Fullstack Monorepo in the header or call ui.export_app_to_directory(app, output_dir), Pyvello decomposes your app into a clean production architecture:
Extracts all tools decorated with @ui.tool and all built-in production tools (query_knowledge_base, query_database, etc.). Emits mock datasets and the standalone dispatcher:
Generates a concise Pyvello application with CORS, health probes, AI chat completions, Pydantic schemas, and your custom routes mounted automatically. Exposes the ASGI instance api = app.get_fastapi_app():
3 Consuming Custom Endpoints from TypeScript / React
The exported frontend in frontend/src/api/client.ts includes typed helpers connecting the Vite React UI to your custom endpoints:
import * as api from './api/client';
// 1. Call custom GET endpoint
const health = await api.get<{ status: string }>('/api/v1/health');
console.log(health.status); // "operational"
// 2. Call custom POST endpoint with typed JSON body
const user = await api.post<{ success: boolean }>('/api/v1/users', {
username: 'sarah_architect',
email: 'sarah@enterprise.ai',
role: 'Lead Architect',
});
// 3. Generic request helper
const data = await api.apiRequest('/api/v1/records/101', { method: 'GET' });
4 Standalone ASGI Engine & Container Deployment (Cloud Run, ECS, Fly.io)
In addition to interactive development with app.launch(), Pyvello exposes the underlying high-performance FastAPI/Starlette ASGI application directly via app.get_fastapi_app() or app.to_asgi(). This allows running behind production ASGI process supervisors like Uvicorn, Gunicorn, or Granian with multiple concurrency workers.
import pyvello as ui
app = ui.App(title="Enterprise API Gateway", palette="emerald")
@app.api.get("/api/v1/health")
def health():
return {"status": "operational", "version": "1.0.0"}
with app:
ui.title("Gateway Dashboard")
ui.metric("Active Microservices", 12)
# Expose ASGI application instance for production ASGI servers
api = app.get_fastapi_app()
if __name__ == "__main__":
app.launch(port=8000)
FROM python:3.12-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PORT=8000
# Install production dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application source
COPY . .
EXPOSE 8000
# Launch with 4 ASGI async concurrency workers
CMD ["uvicorn", "main:api", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
Complete API & Universal Tool Suite (All Cases)
A comprehensive fullstack application demonstrating every native API pattern and tool execution case in Pyvello: synchronous GET with query parameters, asynchronous POST with typed Pydantic payloads, dynamic path parameters, Server-Sent Events (SSE) live streaming, full CRUD (PUT & DELETE), custom tools (@ui.tool), built-in production tools (query_knowledge_base & query_database), interactive reactive UI, and standalone one-click monorepo export.
Sync GET with filters, async POST with Pydantic validation, and dynamic /orders/{id} path parameters.
Real-time telemetry streaming endpoint yielding JSON chunks over persistent Server-Sent Events.
Financial mortgage and risk tools created with @ui.tool alongside built-in RAG and SQL tools.
Interactive UI with live metrics and one-click export generating standalone Uvicorn FastAPI backend.
Universal API & Universal Tool Studio
Explore native backend routes and autonomous agent tool execution in a single Python script.
For a $500,000 principal at 6.5% over 30 years:
- Monthly Payment: $3,160.34
- Total Interest: $637,722.40
- Total Cost: $1,137,722.40
Citation: DOC-ARCH-01 Enterprise Compliance Guidelines verified.
"""Universal Pyvello API & Agent Tool Suite — Complete All-Cases Implementation.
Demonstrates:
1. Custom Tools with @ui.tool (Sync & Async)
2. Built-in Pyvello Production Tools (RAG Vector Search & SQL Relational Database)
3. Pydantic Models & Request Validation
4. Synchronous GET with Query Parameters
5. Asynchronous POST with Pydantic JSON Body
6. Dynamic Path Parameter Lookup (/orders/{order_id})
7. CRUD Operations (PUT Update & DELETE)
8. Real-Time Server-Sent Events (SSE) Live Streaming (@app.api.stream)
9. Reactive UI with Metrics, Columns, and Autonomous Agent Chat
10. Standalone Zero-Dependency Backend Export (uvicorn main:app)
"""
import time
import asyncio
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
import pyvello as ui
# Initialize Pyvello Application
app = ui.App(title="Universal API & Tool Studio", palette="emerald")
# ============================================================================
# CASE 1: CUSTOM AGENT TOOLS (SYNC & ASYNC WITH @ui.tool)
# ============================================================================
@ui.tool(description="Calculate mortgage amortization schedule and monthly payment.")
def calculate_mortgage(principal: float, annual_rate: float, years: int) -> Dict[str, Any]:
"""Calculate loan payment given principal, rate percentage, and tenure in years."""
r = (annual_rate / 100) / 12
n = years * 12
monthly = round(principal * (r * (1 + r)**n) / ((1 + r)**n - 1), 2)
total_payment = round(monthly * n, 2)
return {
"principal": principal,
"annual_rate_pct": annual_rate,
"years": years,
"monthly_payment": monthly,
"total_interest": round(total_payment - principal, 2),
"total_payment": total_payment,
}
@ui.tool(description="Perform asynchronous financial risk assessment score lookup.")
async def evaluate_risk_score(company_ticker: str, sector: str = "Technology") -> Dict[str, Any]:
"""Asynchronously evaluate company risk metrics."""
await asyncio.sleep(0.05)
return {
"ticker": company_ticker.upper(),
"sector": sector,
"risk_score": 24,
"grade": "A- (Low Risk)",
"liquidity_ratio": 2.8,
"debt_to_equity": 0.42,
}
# ============================================================================
# CASE 2: CONNECTING AGENT WITH CUSTOM TOOLS + BUILT-IN PRODUCTION TOOLS
# ============================================================================
wealth_agent = ui.Agent(
name="Wealth & Enterprise Specialist",
system_prompt="You are a senior financial intelligence specialist. Use tools for all calculations and lookups.",
model="gpt-4o",
tools=[
calculate_mortgage, # Custom sync tool
evaluate_risk_score, # Custom async tool
ui.query_knowledge_base, # Builtin Pyvello RAG vector tool
ui.query_database, # Builtin Pyvello SQL database tool
],
)
# ============================================================================
# CASE 3: TYPED PYDANTIC REQUEST MODELS
# ============================================================================
class OrderItem(BaseModel):
item_id: str
quantity: int = Field(default=1, ge=1)
unit_price: float
class CreateOrderRequest(BaseModel):
customer_id: str
customer_email: str
items: List[OrderItem]
notes: Optional[str] = None
# In-memory store for demonstration
ORDERS_DB: Dict[str, Dict[str, Any]] = {}
# ============================================================================
# CASE 4: SYNCHRONOUS GET WITH QUERY PARAMETERS
# ============================================================================
@app.api.get("/api/v1/health")
def api_health(detailed: bool = False):
"""Health check endpoint with optional detailed flag."""
res = {"status": "healthy", "service": "pyvello-universal-api", "timestamp": time.time()}
if detailed:
res["tools_active"] = len(wealth_agent.tools)
res["orders_count"] = len(ORDERS_DB)
return res
# ============================================================================
# CASE 5: ASYNCHRONOUS POST WITH PYDANTIC BODY
# ============================================================================
@app.api.post("/api/v1/orders")
async def create_order(req: CreateOrderRequest):
"""Create a new customer order with validated Pydantic schema."""
order_id = f"ORD-{len(ORDERS_DB) + 1001}"
total_amount = sum(it.quantity * it.unit_price for it in req.items)
order_record = {
"order_id": order_id,
"customer_id": req.customer_id,
"customer_email": req.customer_email,
"total_amount": round(total_amount, 2),
"item_count": len(req.items),
"status": "confirmed",
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
ORDERS_DB[order_id] = order_record
return {"success": True, "order": order_record}
# ============================================================================
# CASE 6: DYNAMIC PATH PARAMETER LOOKUP
# ============================================================================
@app.api.get("/api/v1/orders/{order_id}")
def get_order_by_id(order_id: str):
"""Retrieve order by dynamic path parameter."""
if order_id not in ORDERS_DB:
return {"error": "Order not found", "requested_id": order_id}
return {"success": True, "order": ORDERS_DB[order_id]}
# ============================================================================
# CASE 7: FULL CRUD OPERATIONS (PUT UPDATE & DELETE)
# ============================================================================
@app.api.put("/api/v1/orders/{order_id}")
def update_order_status(order_id: str, new_status: str = "shipped"):
"""Update existing order status via PUT."""
if order_id not in ORDERS_DB:
return {"error": "Order not found"}
ORDERS_DB[order_id]["status"] = new_status
return {"success": True, "order": ORDERS_DB[order_id]}
@app.api.delete("/api/v1/orders/{order_id}")
def delete_order(order_id: str):
"""Delete an order via DELETE."""
if order_id in ORDERS_DB:
del ORDERS_DB[order_id]
return {"success": True, "deleted_id": order_id}
return {"error": "Order not found"}
# ============================================================================
# CASE 8: REAL-TIME SERVER-SENT EVENTS (SSE) STREAMING
# ============================================================================
@app.api.stream("/api/v1/telemetry-stream")
def stream_telemetry(interval_count: int = 5):
"""Real-time SSE event stream yielding JSON telemetry chunks."""
for step in range(interval_count):
time.sleep(0.1)
yield {
"step": step + 1,
"cpu_percent": round(18.5 + (step * 2.1), 1),
"memory_mb": round(142.0 + (step * 5.4), 1),
"active_connections": 12 + step,
"timestamp": time.time(),
}
# ============================================================================
# CASE 9: REACTIVE PYVELLO UI
# ============================================================================
with app:
ui.title("Universal API & Tool Studio")
ui.text("Explore native backend routes and autonomous agent tool execution in a single script.")
col1, col2, col3, col4 = ui.columns(4)
with col1:
ui.metric(label="API Routes", value="6 Endpoints", delta="REST + SSE")
with col2:
ui.metric(label="Connected Tools", value="4 Active", delta="Custom + Builtin")
with col3:
ui.metric(label="Pydantic Schemas", value="2 Models", delta="Validated")
with col4:
ui.metric(label="Backend Engine", value="Standalone FastAPI", delta="Zero Dependency")
ui.divider()
tab1, tab2 = ui.tabs(["Autonomous AI Chat & Tools", "Interactive API Client"])
with tab1:
ui.chat(agent=wealth_agent)
with tab2:
ui.text("Call custom backend endpoints natively:")
ui.button("Call GET /health", on_click=lambda: ui.toast("Health OK"))
ui.button("Trigger POST /orders", on_click=lambda: ui.toast("Order Created"))
# ============================================================================
# CASE 10: STANDALONE PRODUCTION EXPORT (ZERO PYVELLO DEPENDENCY)
# ============================================================================
def export_project():
"""Export fullstack Vite React + Python FastAPI backend to disk."""
ui.export_app_to_directory(app, output_dir="./dist_fullstack")
print("Exported production backend to ./dist_fullstack/backend")
print("Run with: cd ./dist_fullstack/backend && uvicorn main:app --reload")
if __name__ == "__main__":
app.launch()