PYVELLO DOCS
Back to Website
Overview

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.

Live Reactive Runtime & Swarm Dashboard Preview
wss://127.0.0.1:8000/ws 0.42ms Delta
Swarm Status
Active
Delta Latency
0.42 ms
Confidence
82%
Concurrency Workers 82 Nodes
min=10 default=82 max=100
Terminal Stream
CONNECTED
1 [CONNECTED] ws://localhost:8000/ws/session_01
2 [SWARM] Initialized 4 autonomous agents across DAG
3 [OBSERVABILITY] Langfuse session tracing active (sample_rate=1.0)

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.

Setup

Installation & Quickstart

Install Pyvello via pip or uv:

Live Quickstart App Preview (http://127.0.0.1:8000)
Single File Python

Hello from Pyvello!

Zero full-page reruns • Fine-grained WebSocket DOM updates

Count: 42
terminal ×
# 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

quickstart.py ×
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.

reload_usage.sh ×
# 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.

notebook.py ×
# 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)
Architecture

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.
Kiosk & Headless Mode

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

custom_app.py ×
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()
Security & Auth

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).

One-Line Activation

Pass auth=True or a credential dictionary {"admin": "secret123"} to immediately gate the entire site behind an authentication card.

Built-In User Registration

Visitors can sign in or register new accounts directly through the UI. Account creation enforces length constraints, alphanumeric rules, and password confirmation.

Zero-Trust WebSocket Protocol

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=False

Ideal 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.

single_user_auth.py ×
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.

team_auth.py ×
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:

user_context_example.py ×
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

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.

reactivity_example.py
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()
Distribution

Packaging & PyPI Publishing

Complete production guide to bundling the React frontend, building the Python wheel and source distribution, verifying assets, and releasing to PyPI.

Wheel Verification & Artifact Inspector Preview
TWINE PASSED 100% Zero-Node
pyvello-0.1.0
py3-none-any.whl
1.8 MB
Format:Wheel 1.0 (purelib)
Build Backend:hatchling.build
React Assets:Included (pyvello/static)
Node.js Req:0.0 (None)
Checksum: SHA256 e89f...2d1a
Wheel Archive Structure Verified
pyvello/
static/ (React 18 SPA)
├── index.html
├── assets/index-*.js (1.6 MB)
└── assets/index-*.css (111 KB)
web_template/
├── agents/
├── auth/
├── components/
└── __init__.py
$ twine check dist/*
exit: 0
Checking dist/pyvello-0.1.0.tar.gz...
PASSED: Metadata conforms to 2.1
Checking dist/pyvello-0.1.0-py3-none-any.whl...
PASSED: Static bundle integrity verified
PASSED: Entry points registered (pyvello)
PyPI Target: production READY TO PUBLISH
Zero-Node Runtime Architecture

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:

compile_frontend.sh ×
# 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:

pyproject.toml ×
[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:

build_package.sh ×
# 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:

test_local_wheel.sh ×
# 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:

upload_to_pypi.sh ×
# 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:

publish.yml ×
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
AI Core

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 & Environment Key Inspector
Click any provider to inspect Live Key Auto-Detected
Environment Variable (.env)
OPENROUTER_API_KEY
Auto-Resolution: Auto-detected in .env
Model Format in ui.Agent()
openrouter/z-ai/glm-5.3-flash
Gateway URL: openrouter.ai/api/v1
Supported Modalities
INFERENCE + LLM + IMAGE + VIDEO + TTS
Zero-Config Routing: Automatic Prefix Stripping
> agent = ui.Agent(name="Architect", model="openrouter/z-ai/glm-5.3-flash")
Pure Python 3.10+
Global Registry 50+ Providers Supported

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.

⌘K
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:

.env ×
# ==============================================================================
# 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:

Key & URL Resolution Priority
  • Direct Constructor Argument: api_key="..." or api_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.
Supported Custom Architectures
  • • 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": "..."}
custom_urls_and_keys.py ×
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:

agent_providers.py ×
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)
AI Core & Schemas

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.

Interactive Pydantic Extraction & Token Budget Simulator
Click any schema tab to inspect Pydantic v2 Validated
Schema Enforcement
FinancialInvoice (Pydantic v2)
Auto-validated via model_validate_json
Token Ceiling (max_tokens)
450 Tokens Cap
LiteLLM call_kwargs["max_tokens"]
Sampling Temperature
0.0 (Deterministic)
Zero variance for reliable parsing
Programmatic Accessor
agent.last_structured_output
Typed instance, zero manual json.loads
Input Document / Prompt:
Invoice #INV-2026-904 from CloudScale: 40 GPU hours at $3.50/hr ($140.00) plus 2TB NVMe storage ($20.00). Subtotal $160.00, Tax $16.00, Grand Total $176.00. Payment due in Net 30 days.
Python Pydantic Schema Definition pydantic.BaseModel
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
Structured Output Result (agent.last_structured_output) JSON Schema Verified
{
  "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):

1. Provider Schema Translation

LiteLLM maps the Pydantic schema to OpenAI JSON Schema, Anthropic Tool-Use, or Gemini Structured Mode.

2. Automatic Validation

The completion string is validated via model_validate_json() with markdown code fence auto-cleaning.

3. Strongly Typed Access

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.py
structured_extractor.py
from 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.

Agent Token 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
)
Swarm Orchestrator Cascade

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.
AI Core

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.

Configuring LLM Providers & API Keys (.env)

Looking for provider environment variable names for OpenRouter, OpenAI, Anthropic, Gemini, Groq, DeepSeek, or local Ollama?

View Provider Matrix & .env →

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.
pdf 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

agent_to_app.py ×
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()
Multimodal Architecture Like ChatGPT

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.

Why Tool Calling Fails on Media Models

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".

The Native Omni-Agent Solution

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.

Universal Intelligent Response Parser

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.

multimodal_omni_agent.py
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()
Interface

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

direct_chat_interface.py ×
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()
Zero Hallucination

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 .pdf 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.
Creative Studio

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.

Uploaded Reference Canvas

Upload any concept sketch, product photo, or existing generation via the chat attachment button.

Conversational Inpainting & Style Transfer

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".

image_editing_studio.py
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()
Swarms

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.

LangGraph Parity

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

swarm_orchestrator.py ×
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()
AI Patterns

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

patterns_example.py ×
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)
Observability

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:

Turn 1: Step 1 (MarketResearcher) -> Step 2 (InfraArchitect) -> Step 3 (RiskAssessor) -> Step 4 (Supervisor)
Turn 2: Step 5 (MarketResearcher) -> Step 6 (InfraArchitect) -> Step 7 (RiskAssessor) -> Step 8 (Supervisor)

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.
Layout

Container & Columns

Ergonomic responsive grid and flexbox layout primitives. Use ui.columns(N) with python context managers to create multi-column layouts effortlessly.

Visual Preview
Column 1 Content
Column 2 Content
columns_example.py ×
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()
Layout

Card

Structured card container with optional title, description header, loading skeleton, and nested component slots.

Visual Preview

Production Cluster

Active nodes: 12 · Health: Nominal

Active
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.
card_example.py ×
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()
Layout

Tabs

Tabbed navigation container with strict panel content isolation and animated transitions.

Visual Preview
tabs_example.py ×
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()
Layout

Accordion & Expander

Collapsible containers for organizing detailed content, advanced settings, and FAQ accordions.

expander_example.py ×
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()
Layout

Dialog & Sheet (Modal & Drawer)

Overlay modals and slide-out drawers (sheets) with backdrop blur, keyboard dismissal, and customizable triggers.

dialog_sheet_example.py ×
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()
Layout

Form (Grouped Submission)

Encapsulates multiple input fields into a single reactive submission boundary with validation, confirmation modals, and unified submit handlers.

form_example.py
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()
Layout

Separator & Divider

Clean visual dividers with optional text badges and horizontal or vertical orientations.

divider_example.py ×
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()
Inputs

Button

Interactive button component with variants, loading spinners, and built-in confirmation dialogs.

Visual Preview
Parameter Type Default Description
label str required Button text.
variant str 'default' 'default', 'secondary', 'outline', 'destructive', 'ghost'.
size str 'default' 'default', 'sm', 'lg', 'icon'.
disabled bool False Disabled state.
loading bool False Render animated spinner.
confirm str | dict | None None Prompt user with confirmation modal before firing callback.
on_click Callable | None None Callback executed on click.
button_example.py ×
import pyvello as ui

def execute_action():
    print("Workflow executed successfully!")

def delete_cluster():
    print("Cluster safely removed!")

with ui.App(title="Button Component Demo", theme="light", palette="red") as app:
    ui.title("Interactive Buttons")
    ui.button("Execute Workflow", variant="default", on_click=execute_action)
    ui.button("Delete Cluster", variant="destructive", on_click=delete_cluster, confirm="Are you sure you want to delete this cluster?")

if __name__ == "__main__":
    app.launch()
Inputs

TextInput & TextArea

Single-line and multi-line text input fields supporting reactive change listeners and auto-sizing.

Visual Preview
text_inputs.py ×
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()
Inputs

NumberInput & Slider

Numeric inputs and interactive slider controls with min, max, and step increments.

number_slider.py ×
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()
Inputs

Switch & Checkbox

Boolean toggle switches and checkboxes with accessible labels and description subtext.

Visual Preview
Enable Streaming
switch_checkbox.py ×
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()
Inputs

Select & ToggleGroup

Dropdown selects and segment toggle button groups for selecting between discrete options.

select_example.py ×
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()
Inputs

Radio

Mutually exclusive radio group choices.

radio_example.py ×
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()
Inputs

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.

autoform_example.py
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()
Inputs

FileUpload & InputOTP

Drag-and-drop file upload zone and segmented OTP code inputs for MFA verification.

upload_otp.py ×
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()
Display

Typography (Title, Header, Subheader & Text)

Headings and body text components with responsive sizing, semantic heading levels, color accents, and alignment controls.

Visual Preview

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

app_typography.py ×
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()
Display

Metric

Key performance indicator (KPI) card displaying a primary metric value, delta change, and trend direction.

Visual Preview
Monthly Recurring Revenue
$128,450
+14.2% from last month
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.
metric_example.py ×
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()
Display

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.

Visual Preview
AgentModelStatus
Researchergpt-4oActive
Architectclaude-3-5Idle
table_example.py ×
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()
Display

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.

charts_example.py ×
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()
Display

Callout & Badge

Prominent notification banners (info, warning, success, error) and status badge pills.

Visual Preview
Notice

Hot reloading active. Files are continuously monitored for changes.

callout_example.py ×
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()
Display

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.
terminal_demo.py
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()
Display

Media (Image, Audio, Video)

Native multimodal display components supporting image lightbox modal zooms, HTML5 audio waveform players, and responsive video players.

media_example.py
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()
Display

Markdown & Code

Rich markdown renderer supporting GitHub Flavored Markdown (GFM), math KaTeX rendering, syntax highlighted code blocks, and copy buttons.

markdown_example.py ×
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()
Display

JsonViewer

Interactive tree explorer for arbitrary JSON payloads with collapsible keys and copy functionality.

json_viewer_example.py ×
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()
Display

Feedback & Utility

Toast notifications, user avatars, skeleton loaders, progress bars, tooltips, and Lucide icons.

utility_example.py ×
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()
Example 01

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).

https://app.pyvello.dev/research-intelligence
Interactive Preview

Autonomous Research & Market Intelligence Hub

Interactive multi-turn AI researcher equipped with financial computation, domain lookups, and token telemetry.

Active LLM Model
GPT-4o-mini OpenRouter
Registered Tools
2 Active Auto-Calling
Mean Inference Latency
320ms -18ms P95
What is the 2026 market size of Cloud AI and calculate operating profit for $50M revenue with $32M operating costs at 14% growth?
U
search_market_database(sector='Cloud AI')
calculate_financial_metrics(revenue=50, cost=32, growth_rate=14)

Here is the verified market research and financial breakdown for your query:

1. Cloud AI Infrastructure Benchmark
  • 2026 Estimated TAM: $148 Billion
  • 5-Year Compound Growth (CAGR): 34.2%
  • Primary Growth Driver: Enterprise LLM inference workloads and custom dedicated silicon.
2. Quantitative Financial Computation
  • Operating Profit: $18.00 Million
  • Operating Margin: 36.0%
  • Projected Revenue (+14.0%): $57.00 Million next quarter
MarketResearcher LLM Called (1) 2 Tools Executed
312 tokens | 340ms
Example

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").

Architecture

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.

https://app.pyvello.dev/incident-command
Interactive Preview
Production Incident Command & Service Health
Autonomous swarm incident mitigation, real-time error telemetry, and failover orchestration.
P0 War Room Active
CRITICAL: Database connection pool exhaustion detected in us-east-1. Autonomous agent swarm is shedding 25% non-critical traffic and provisioning warm read replicas.
ACTIVE P0/P1 OUTAGES
2 Active
-3 vs peak
P99 INFERENCE LATENCY
42ms
-18ms nominal
AUTONOMOUS MITIGATION
94.2%
+4.1% MoM
SYSTEM AVAILABILITY
99.98%
Within SLO
Inference & Ingress Latency (ms)
Trailing 6-interval P99 latency trajectory across all ingress points
P99 Metric
10:0010:1510:3010:4511:0011:15
Service Error Distribution (req/s)
Real-time 5xx error volume distributed across microservice endpoints
5xx Rates
14.2
Auth Gateway
8.6
Vector DB
4.1
Model Router
1.2
Billing Sync
14.2 req/s8.6 req/s4.1 req/s1.2 req/s
Active Production Incidents
Search table...
5 rows
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
Showing 1 to 5 of 5 entries
1
Remediation & Failover Controls
Non-Critical Traffic Shedding Ratio
Percentage of non-essential asynchronous workers throttled during mitigation.
Traffic Shed % 25%
Autonomous Rollback on Failure
Automatically revert canary deployments if 5xx exceeds 1.5%
Example

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()).

Full Component Spectrum

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.

V
Pyvello / Multimodal Document Intelligence & Extraction Studio
Yellow Palette Pipeline Healthy

Multimodal Document Intelligence & Extraction Studio

Autonomous OCR extraction, SEC/HIPAA compliance verification, and structured JSON audit logging.

Document Ingestion & Security OCR & Extracted JSON Compliance Verification & Rules
Upload SEC 10-K, vendor invoice, or clinical trial PDF. The extraction pipeline performs SHA-256 verification and enforces zero-knowledge PII sanitization.
Document Upload & OCR Preprocessing
Click to upload or drag & drop files
Supported types: .pdf, .png, .csv, .json
Optical Character Recognition (OCR) Parsing... 78%
SEC 10-K Annual Filing
Fast OCR Dense LayoutLM Multimodal Vision
Two-Factor Auditor Authorization (2FA)

Enter your 6-digit cryptographic security token to approve automated PII redaction and external export.

8
4
9
2
0
1
Enforce SOC2 Zero-Knowledge PII Masking
Automatically scrub Social Security Numbers, Tax IDs, and Bank Routing codes prior to indexing.
Strict Sandbox (No External APIs)
Hybrid LLM Inference
Air-Gapped Local Cluster
Example

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.

Swarm Mesh & Observability

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.

V
Pyvello / Autonomous Multi-Agent Swarm & Execution DAG Studio
Red Palette Swarm Healthy

Autonomous Multi-Agent Swarm & Execution DAG Studio

Supervisor planning, intent routing, sequential chains, and LLM-as-a-judge evaluation.

Active Worker Agents
4 Nodes
Supervisor Mesh
Total Swarm Tokens
148,290
+34.2% batch
Mean Inference Latency
640ms
-120ms opt
LLM Judge Score
98.4%
Passed Benchmark
Swarm Execution DAG & Agent Node Topology
Step 1 Completed
Architecture Planner
Decomposes requirements into structured task contracts and database schemas.
Model: gpt-4o | 420ms
Step 2 Running
Code Synthesizer
Synthesizes async Python backend logic and SQLAlchemy connection pools.
Model: claude-3-5-sonnet | 840ms
Step 3 Queued
Security Auditor
Scans generated abstract syntax trees for SQL injection and timing side-channels.
Model: gpt-4o-mini | Standby
Step 4 Queued
LLM-as-a-Judge
Rigorously evaluates synthetic code correctness and generates verification unit tests.
Model: deepseek-r1 | Standby
Semantic Intent Router Classification Rules
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
LLM-as-a-Judge Evaluation Benchmark Scorecard
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

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()).

Zero-Code Function to UI

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.

V
Pyvello / Multimodal Generative Media & Automated Function Workbench
Yellow Palette H100 Cluster Online

Multimodal Generative Media & Automated Function Workbench

Automated Python function UI inference (AutoForm) combined with synthetic image, audio, and video preview.

AutoForm automatically parsed generate_synthetic_media() type annotations and generated interactive sliders, switches, and JSON response viewers.
Automated Function Ingestion (Streamlit / Gradio Parity)
Generative Diffusion Inference Runner
Automatically inferred from Python function signature with type annotations.
cinematic-cyberpunk
Guidance Scale (float) 7.5
Inference Steps (int) 30
High Res Fix (bool)
Inference Output (JSON)
{ "status": "synthesized", "seed": 42, "inference_ms": 640 }
Advanced Latent Space Controls
Multimodal Media Outputs & Playback
Generated 4K Visual Canvas
Synthetic Cyberpunk Neon Architecture
Diffusion Render: Cyberpunk neon city in rainfall (Seed: 42, Steps: 30, CFG: 7.5)
Synthesized Multimodal Voiceover Narration
Voiceover: English (US) - Neural High-Fidelity Speech Model
Synthesized Animation Clip (H.264 / 60fps)
Motion Diffusion: Volumetric rain lighting sequence (16:9 widescreen)
Background Secondary Upscaling Queue (Idle)
Example

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.

Turnkey Auth Experience

Unauthenticated visitors see a centered, shadcn-styled card with 'Sign In' and 'Create Account' tabs. The application unlocks immediately upon verification.

Single & Multi-User Modes

Toggle registration via allow_registration=False for private single-user tools, or keep it enabled for open multi-user SaaS.

Live User Identity in Callbacks

Python event handlers inspect active session claims via ui.current_user() to trigger user-aware alert notifications.

V
Pyvello / Secure Enterprise Portal
Indigo Palette
A admin
Sign Out

Security & Operations Overview

Real-time operational dashboard monitoring authenticated sessions and cryptographic status.

Active Sessions
48
+12 today
Auth Policy Health
99.8%
+0.4%
Failed Logins
0
-3 past 24h
Storage Volume
14.2 GB
+250 MB
Current Session Profile

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.

Session: ACTIVE Storage: SQLite PBKDF2-HMAC: SHA-256
Default administrative credentials seeded on first launch: username 'admin', password 'admin123'. New accounts can be registered seamlessly via the 'Create Account' tab.
Platform Health & Cryptography

All password hashes utilize PBKDF2-HMAC-SHA256 with 100,000 iterations and per-user 32-character hex salts.

Hash Rounds
100,000
Token Entropy
256-bit
Example

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.

Direct OpenAI SDK

Declare def chat(messages): and pass the full array directly to client.chat.completions.create(messages=messages, stream=True).

Google GenAI SDK

Convert unified message roles (user/assistant) into Gemini contents parts and stream via client.models.generate_content_stream().

Multi-Session Isolation

Each session tab in ui.chat() maintains independent conversation history. Pyvello injects session_id for custom server stores.

V
Pyvello / Native LLM SDK Integration & Session Architecture
Violet Palette
WebSocket Live
SDK
Pyvello SDK Studio
OpenAI & Google Native
Supported SDK Providers
OpenAI SDK AsyncOpenAI
Accepts full messages array directly in chat.completions.create().
Google GenAI SDK google.genai
Auto-transforms history into Gemini contents parts representation.
Session Inspection
Multi-Turn Test Cases
1. Define SaaS Architecture
2. Follow-Up Refinement
3. Switch Model & Compare
AI
Direct SDK Mode
Zero Wrapper Overhead

Direct OpenAI & Google SDK Integration

Wire native Python SDK clients directly into Pyvello. Learn how conversation history, session tabs, and token streaming work.

Architecture Unified History Injection & Session Isolation

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.

Model:
OpenAI (gpt-4o-mini)
Session: session_init 3 Turns in Memory
Explain webhook idempotency with Redis.
AI
[OpenAI SDK Execution]
• 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.

How should the database schema look for idempotency keys?
AI
[OpenAI SDK Execution]
• 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.

ChatAssistant LLM called 1
Example

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.

Native Image & Video Models

Directly connect Flux, Bytedance Seedream, Kolors, Minimax Hailuo, and CogVideoX without tool schemas that fail on pure completion models.

TTS Audio & PDF Synthesis

Synthesize neural audio speech playback and generate executive PDF download data URIs right in the same conversational thread.

Universal Response Parser

Intelligently searches arbitrary JSON and response payloads to extract asset URLs and base64 streams automatically.

Universal Multimodal Studio Single Omni-Agent
Active $0.05
Active Modalities: Image: Flux / Seedream Video: Seedance / Hailuo Audio: HeyGen / TTS PDF: Executive Engine
Generate an image of an autonomous cyber exploration vehicle on Mars with dramatic sunset lighting.
UniversalMultimodalStudio • Native Image Synthesis
Mars Exploration Vehicle

Photorealistic render synthesized via bytedance-seed/seedream-5-0-flash.

View High-Resolution Image →
Generate a 5-second cinematic video teaser of this rover navigating red rock canyons.
UniversalMultimodalStudio • Native Video Synthesis
▶
rover_canyon_flight.mp4
Duration: 5.0s • 1080p 60fps • Seedance 2.0 Mini
Synthesized
Play Full Video →
Synthesize speech audio: Welcome to Pyvello Multimodal Studio. One agent handles all your media.
UniversalMultimodalStudio • Native Speech Synthesis
♪
narration_alloy.mp3
Neural Voice: alloy • HeyGen / OpenAI TTS
Synthesized
Listen to Audio Recording (MP3) →
Create an executive financial PDF document summarizing Q3 rover mission milestones.
UniversalMultimodalStudio • Native PDF Document Engine
PDF
report.pdf (14.2 KB)
PDF-1.4 Standard • Base64 Data URI • Instant Download
Generated
Download PDF Document →
Integrations & Tools 135 Production Connectors

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.

ui.configure_credentials
credentials.py ×
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
)
Custom Function Calling

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.

1. Docstring Parsing

The function's docstring provides the semantic tool description the LLM reads to determine when to call the tool.

2. Type Hint Validation

Primitive types (str, int, float, bool) and Pydantic models automatically enforce parameter extraction.

3. Native Async / Sync

Supports both synchronous functions and non-blocking async def coroutines for database queries and external HTTP APIs.

custom_tools.py
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()
Showing 135 of 135 tools
FastAPI & REST Engine Zero Framework Lock-in

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.

Zero Backend Boilerplate

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).

SSE Real-Time Streaming

Use @app.api.stream with standard Python generators. Yielding dicts or strings automatically streams as text/event-stream.

Pydantic Schema Validation

Declare request body models with pydantic.BaseModel. Pyvello extracts schemas and preserves validation in both live dev and exported backends.

Standalone Deployment

Export generates a pure FastAPI backend + Vite React UI. Runs anywhere via Docker, Kubernetes, AWS, or Railway without Pyvello installed.

Where is Swagger UI? (/swagger, /api/docs, /docs/swagger)

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:

api_studio_showcase.py
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:

backend/tools.py (Universal Tool Dispatcher)

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:

execute_tool(name: str, arguments: dict) -> str
backend/main.py (Production Pyvello Server)

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():

uvicorn main:api --host 0.0.0.0 --port 8000 --reload

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:

frontend/src/api/client.ts
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.

main.py (Direct ASGI Exposure)
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)
Dockerfile (Production Distroless/Slim)
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"]
Example 10 All Possible Cases

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.

Cases 1-3: REST Endpoints

Sync GET with filters, async POST with Pydantic validation, and dynamic /orders/{id} path parameters.

Case 4: SSE Live Stream

Real-time telemetry streaming endpoint yielding JSON chunks over persistent Server-Sent Events.

Cases 5-7: Custom & Builtin Tools

Financial mortgage and risk tools created with @ui.tool alongside built-in RAG and SQL tools.

Cases 8-10: Export & UI

Interactive UI with live metrics and one-click export generating standalone Uvicorn FastAPI backend.

https://app.pyvello.dev/universal-api-studio
Emerald Theme
FastAPI Live

Universal API & Universal Tool Studio

Explore native backend routes and autonomous agent tool execution in a single Python script.

API Routes
6 Endpoints
REST + SSE Live
Connected Tools
4 Active
Custom + Builtin RAG
Pydantic Schemas
2 Models
Auto Validated
Backend Engine
Standalone
Zero Dependency
Custom API Endpoints Console Interactive Dispatcher
GET /api/v1/health
200 OK
POST /api/v1/orders
Pydantic Body
STREAM /api/v1/telemetry-stream
SSE Chunked
// Live Response Inspector: POST /api/v1/orders
{
"success": true,
"order": {
"order_id": "ORD-1001",
"total_amount": 1420.50,
"status": "confirmed"
}
}
W
Wealth & Enterprise Agent
gpt-4o • 4 tools
Calculate mortgage for $500,000 at 6.5% for 30 years and check our enterprise policy.
Invoked: calculate_mortgage + query_knowledge_base

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.