Skip to main content

AI Agent interface library for FastAPI with multi-platform support

Project description

FastAPI AgentRouter

CI PyPI version Python versions License: MIT

Simplified AI Agent integration for FastAPI with multi-platform support (Slack, Discord, Webhook).

Features

  • 🚀 Simple Integration - Just 2 lines to add agent to your FastAPI app
  • 🤖 Vertex AI ADK Support - Native support for Google's Agent Development Kit
  • 🔌 Multi-Platform - Built-in Slack, Discord, and webhook endpoints
  • 🎯 Protocol-Based - Works with any agent implementing stream_query method
  • Async & Streaming - Full async support with streaming responses
  • 🧩 Dependency Injection - Leverage FastAPI's DI system
  • 📁 Modular Architecture - Separate routers for each platform

Installation

# Basic installation
pip install fastapi-agentrouter

# With platform-specific dependencies
pip install "fastapi-agentrouter[slack]"      # For Slack support
pip install "fastapi-agentrouter[discord]"    # For Discord support
pip install "fastapi-agentrouter[vertexai]"   # For Vertex AI ADK
pip install "fastapi-agentrouter[all]"        # All platforms

Quick Start

from fastapi import FastAPI
from fastapi_agentrouter import create_agent_router

# Your agent implementation (e.g., Vertex AI ADK)
def get_agent():
    # Return your agent instance
    # This could be a Vertex AI AdkApp, or any object with stream_query method
    from vertexai.preview import reasoning_engines
    return reasoning_engines.AdkApp(agent=your_agent)

app = FastAPI()

# Simple integration - just one line!
app.include_router(create_agent_router(get_agent))

That's it! Your agent is now available at:

  • /agent/webhook - Generic webhook endpoint
  • /agent/slack/events - Slack events and slash commands
  • /agent/discord/interactions - Discord interactions

Advanced Usage

With Vertex AI Agent Development Kit (ADK)

from fastapi import FastAPI
from fastapi_agentrouter import create_agent_router
from vertexai.preview import reasoning_engines
from vertexai import Agent

# Define your agent with tools
def get_weather(city: str) -> dict:
    """Get weather for a city."""
    return {"city": city, "weather": "sunny", "temperature": 25}

agent = Agent(
    name="weather_agent",
    model="gemini-2.5-flash-lite",
    description="Weather information agent",
    tools=[get_weather],
)

def get_adk_app():
    return reasoning_engines.AdkApp(
        agent=agent,
        enable_tracing=True,
    )

app = FastAPI()
app.include_router(create_agent_router(get_adk_app))

Custom Agent Implementation

class CustomAgent:
    def stream_query(self, *, message: str, user_id=None, session_id=None):
        # Your custom logic here
        yield f"Response to: {message}"

def get_custom_agent():
    return CustomAgent()

app = FastAPI()
app.include_router(create_agent_router(get_custom_agent))

Selective Platform Integration

from fastapi_agentrouter import create_agent_router

# Enable only specific platforms
def get_agent():
    return your_agent

app = FastAPI()
app.include_router(
    create_agent_router(
        get_agent,
        enable_slack=True,
        enable_discord=False,  # Discord will return 404 Not Found
        enable_webhook=True
    )
)

Configuration

Environment Variables

Configure platform integrations via environment variables:

# Slack configuration
export SLACK_SIGNING_SECRET="your-slack-signing-secret"

# Discord configuration
export DISCORD_PUBLIC_KEY="your-discord-public-key"

Platform Setup

Slack Setup

  1. Create a Slack App at https://api.slack.com/apps
  2. Get your Signing Secret from Basic Information
  3. Set environment variable: SLACK_SIGNING_SECRET
  4. Configure Event Subscriptions URL: https://your-domain.com/agent/slack/events
  5. Subscribe to events: message.channels, app_mention, etc.
  6. For slash commands, use the same URL

Discord Setup

  1. Create Discord Application at https://discord.com/developers/applications
  2. Get your Public Key from General Information
  3. Set environment variable: DISCORD_PUBLIC_KEY
  4. Set Interactions Endpoint URL: https://your-domain.com/agent/discord/interactions

Agent Protocol

Your agent must implement the stream_query method:

class AgentProtocol:
    def stream_query(
        self,
        *,
        message: str,
        user_id: Optional[str] = None,
        session_id: Optional[str] = None,
        **kwargs
    ) -> Iterator[Any]:
        """Stream responses for a message."""
        ...

The method should yield response events. For Vertex AI ADK, events have a content attribute.

API Reference

Core Components

fastapi_agentrouter.router

Pre-configured APIRouter with all platform endpoints:

  • /agent/slack/ - Slack integration endpoints
  • /agent/discord/ - Discord integration endpoints
  • /agent/webhook - Generic webhook endpoint

fastapi_agentrouter.get_agent_placeholder

Dependency placeholder that should be overridden with your agent:

app.dependency_overrides[fastapi_agentrouter.get_agent_placeholder] = your_get_agent_function

Environment Variables

  • DISABLE_SLACK=true - Disable Slack endpoints (return 404)
  • DISABLE_DISCORD=true - Disable Discord endpoints (return 404)
  • DISABLE_WEBHOOK=true - Disable webhook endpoint (return 404)

Webhook Endpoint

POST /agent/webhook

Request body:

{
  "message": "Your message here",
  "user_id": "optional-user-id",
  "session_id": "optional-session-id"
}

Response:

{
  "response": "Agent response",
  "session_id": "session-id-if-provided"
}

Examples

See the examples directory for complete examples:

  • basic_usage.py - Basic integration patterns
  • More examples coming soon!

Development

Setup Development Environment

# Clone the repository
git clone https://github.com/chanyou0311/fastapi-agentrouter.git
cd fastapi-agentrouter

# Install with uv (recommended)
uv sync --all-extras --dev

# Or with pip
pip install -e ".[all,dev,docs]"

# Install pre-commit hooks
pre-commit install

Run Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=src --cov-report=html

# Run specific tests
pytest tests/test_router.py

Build Documentation

# Serve docs locally
mkdocs serve

# Build docs
mkdocs build

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_agentrouter-0.1.1.tar.gz (13.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_agentrouter-0.1.1-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_agentrouter-0.1.1.tar.gz.

File metadata

  • Download URL: fastapi_agentrouter-0.1.1.tar.gz
  • Upload date:
  • Size: 13.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for fastapi_agentrouter-0.1.1.tar.gz
Algorithm Hash digest
SHA256 f2a77186ed2945c53d9135dc2a8a52a471e11bc794bfaacd4381322b3328287a
MD5 160eb3c64134c967544487b2e1fb6dba
BLAKE2b-256 9834c70cbbbf4c47dd6c3f3b5458fc7a3272ae50aeabcb1a955228f100eef969

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_agentrouter-0.1.1.tar.gz:

Publisher: release-please.yml on chanyou0311/fastapi-agentrouter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_agentrouter-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_agentrouter-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 416118b47c332df503b2cbbe0ec8167123de20965d03e9fe0e78641bd4987e97
MD5 6922fd8a47bf21c28efc6e8310dd2600
BLAKE2b-256 c6d7a24834a7665314c3d02449c13403ce15b0aba5b561505d416cf2cb78dd80

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_agentrouter-0.1.1-py3-none-any.whl:

Publisher: release-please.yml on chanyou0311/fastapi-agentrouter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page