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.2.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.2-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_agentrouter-0.1.2.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.2.tar.gz
Algorithm Hash digest
SHA256 edec6aa2e68768d80fe8e1b25d3c60f313060c265439e5bae91ee63330a40581
MD5 5582fa5ca0af165f945f5e994ba4cee9
BLAKE2b-256 3a3b60634506b9ad4b4e615903eeadad440bb5394bb23a2b435d8a4a1ecef2a0

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_agentrouter-0.1.2.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.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_agentrouter-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1fe4e4d531ebbe35438d69093eed5cb458d37f45a056665929e50c78ee9a8a17
MD5 728bbe98b355a568fb42d13f881bcd76
BLAKE2b-256 d96e7495180d9378c7eea31b21444df8997359080f2315c97cc2b64a09ffdfc9

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_agentrouter-0.1.2-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