Skip to main content

ft-agui

Easy AGUI (Agent GUI) integration for FastHTML applications. Build real-time chat interfaces with AI agents as simple as pydantic-ai's to_web() but with full control and flexibility for FastHTML.

Features

  • Simple Setup - One line to integrate: agui = setup_agui(app, agent, state)
  • Real-time Chat - WebSocket-based communication with streaming responses
  • Customizable UI - FastHTML components with beautiful default styles
  • State Management - Thread-safe state with automatic UI updates
  • AGUI Protocol - Full compatibility with pydantic-ai's AGUI protocol
  • Multi-threading - Support for multiple conversation threads

Installation

pip install ft-agui

Quick Start

from fasthtml.common import *
from pydantic_ai import Agent
from ft_agui import setup_agui

# Create FastHTML app with WebSocket support
app, rt = fast_app(exts='ws')

# Create your agent
agent = Agent('openai:gpt-4o-mini', instructions='Be helpful and friendly')

# Setup AGUI with one line!
agui = setup_agui(app, agent)

@rt('/')
def index():
    return Titled(
        "My AI Chat",
        Container(
            agui.chat("my-thread")
        )
    )

serve()

Advanced Usage with State Management

from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext, ToolReturn
from pydantic_ai.ui import StateDeps
from ft_agui import setup_agui
from typing import List

# Define your state model
class Note(BaseModel):
    title: str
    content: str

class ChatState(BaseModel):
    notes: List[Note] = Field(default_factory=list)
    topic: str = "General"

    def __ft__(self):
        """Custom FastHTML rendering"""
        return Card(
            H3(f"Topic: {self.topic}"),
            Ul(*[Li(f"{n.title}: {n.content}") for n in self.notes]),
            header="Session State"
        )

# Create agent with state
agent = Agent[StateDeps[ChatState]](
    'openai:gpt-4o-mini',
    instructions='You can take notes and manage topics.',
    deps_type=StateDeps[ChatState]
)

# Add tools for state management
@agent.tool
def add_note(ctx: RunContext[StateDeps[ChatState]], title: str, content: str) -> ToolReturn:
    ctx.deps.state.notes.append(Note(title=title, content=content))
    return ToolReturn(return_value=f"Added note: {title}")

# Setup AGUI with state
app, rt = fast_app(exts='ws')
agui = setup_agui(app, agent, ChatState(), ChatState)

@rt('/')
def index():
    thread_id = "main-thread"
    return Container(
        Grid(
            Div(agui.state(thread_id)),      # State display
            Div(agui.chat(thread_id, autoscroll=True))  # Chat interface
        )
    )

Thread Management

ft-agui provides flexible thread management for handling multiple conversations:

Option 1: Explicit Thread IDs

# Pass thread_id directly
agui.state(thread_id="user-123")
agui.chat(thread_id="user-123", autoscroll=True)

Option 2: Thread Instances (Recommended)

# Create a thread instance
thread = agui.thread("user-123")
return Container(
    Grid(
        Div(thread.state()),
        Div(thread.chat(autoscroll=True))
    )
)

Option 3: Multiple Threads

# Manage multiple conversations
thread1 = agui.thread("support-chat")
thread2 = agui.thread("sales-chat")

return Container(
    Div(thread1.chat()),
    Div(thread2.chat())
)

Custom State Rendering

Define custom __ft__() methods on your Pydantic models for rich UI rendering:

class TodoItem(BaseModel):
    task: str
    done: bool = False

    def __ft__(self):
        return Li(
            Input(type="checkbox", checked=self.done),
            Span(self.task, style="text-decoration: line-through;" if self.done else "")
        )

class TodoList(BaseModel):
    items: List[TodoItem] = []

    def __ft__(self):
        return Card(
            Ul(*[item.__ft__() for item in self.items]),
            header="My Todos"
        )

API Reference

setup_agui(app, agent, initial_state=None, state_type=None)

Initialize AGUI for your FastHTML application.

Parameters:

  • app: FastHTML application (must have exts='ws' enabled)
  • agent: pydantic-ai Agent instance
  • initial_state: Initial state instance (optional)
  • state_type: State type class for validation (optional)

Returns: AGUISetup instance

AGUISetup.chat(thread_id, autoscroll=False, **kwargs)

Create a chat interface component.

Parameters:

  • thread_id: Thread identifier
  • autoscroll: Auto-scroll to bottom on new messages
  • **kwargs: Additional HTML attributes

AGUISetup.state(thread_id, **kwargs)

Create a state display component.

Parameters:

  • thread_id: Thread identifier
  • **kwargs: Additional HTML attributes

AGUISetup.thread(thread_id)

Create a thread instance for cleaner component management.

Parameters:

  • thread_id: Thread identifier (auto-generated if None)

Returns: AGUIThread instance with chat() and state() methods

Requirements

  • Python 3.11+
  • FastHTML with WebSocket support
  • pydantic-ai
  • ag-ui (AGUI protocol)

Examples

Check out the /example directory for complete examples:

  • simple_agui.py - Basic chat interface
  • agui_with_state.py - State management with tools
  • thread_management.py - Multi-thread handling

License

MIT

Credits

Built using FastHTML and currently supporting pydantic-ai

Metadata

Release files for ft-agui 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ft-agui 0.1.0
File Size Uploaded Provenance
ft_agui-0.1.0.tar.gz 200.8 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for ft-agui 0.1.0
File Interpreter ABI Platform
ft_agui-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 214.1 kB

Release files / ft_agui-0.1.0.tar.gz

Download URL ft_agui-0.1.0.tar.gz
Size 200.8 kB
Tags Source
SHA-256 checksum
How to use checksums
79622a5d31a34280d27a44818f8f783965b5e530b5cd124d731cccc53e1cc478
BLAKE2b-256 checksum
How to use checksums
f84fdd81c6961f2612008382b68596592b65aeef4e3a7b85bf8502a5fa37e3c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.13

Release files / ft_agui-0.1.0-py3-none-any.whl

Download URL ft_agui-0.1.0-py3-none-any.whl
Size 13.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a14666b73e4d070c3f1362770ae267e21326810cdc89f6454385203ea1f4bc94
BLAKE2b-256 checksum
How to use checksums
7f0c56513d75c0513a59fbb58eb1c1a2e366b43df58bec2237bbed22db6edad2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.8.13

Security for ft-agui 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page