fastapi-agentrouter


Namefastapi-agentrouter JSON
Version 0.3.0 PyPI version JSON
download
home_pageNone
SummaryAI Agent interface library for FastAPI with multi-platform support
upload_time2025-08-07 14:52:24
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT
keywords agent ai discord fastapi slack webhook
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastAPI AgentRouter

[![CI](https://github.com/chanyou0311/fastapi-agentrouter/actions/workflows/ci.yml/badge.svg)](https://github.com/chanyou0311/fastapi-agentrouter/actions/workflows/ci.yml)
[![PyPI version](https://badge.fury.io/py/fastapi-agentrouter.svg)](https://badge.fury.io/py/fastapi-agentrouter)
[![Python versions](https://img.shields.io/pypi/pyversions/fastapi-agentrouter.svg)](https://pypi.org/project/fastapi-agentrouter/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Simplified AI Agent integration for FastAPI with Slack support.

## 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
- 💬 **Slack Integration** - Built-in Slack Bolt integration with lazy listeners
- 🎯 **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** - Clean separation of concerns

## Installation

```bash
# Basic installation
pip install fastapi-agentrouter

# With Slack support
pip install "fastapi-agentrouter[slack]"

# With Vertex AI ADK support
pip install "fastapi-agentrouter[vertexai]"

# All extras
pip install "fastapi-agentrouter[all]"
```

## Quick Start

```python
from fastapi import FastAPI
from fastapi_agentrouter import router, get_agent_placeholder

# Your agent implementation
class MyAgent:
    def stream_query(self, *, message: str, **kwargs):
        # Process the message and yield responses
        yield f"Response to: {message}"

app = FastAPI()

# Two-line integration!
app.dependency_overrides[get_agent_placeholder] = lambda: MyAgent()
app.include_router(router)
```

That's it! Your agent is now available at:
- `/agent/slack/events` - Handle all Slack events and interactions

## Advanced Usage

### With Vertex AI Agent Development Kit (ADK)

```python
from fastapi import FastAPI
from fastapi_agentrouter import router, get_agent_placeholder
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.dependency_overrides[get_agent_placeholder] = get_adk_app
app.include_router(router)
```

### Custom Agent Implementation

```python
from fastapi import FastAPI
from fastapi_agentrouter import router, get_agent_placeholder

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

def get_custom_agent():
    return CustomAgent()

app = FastAPI()
app.dependency_overrides[get_agent_placeholder] = get_custom_agent
app.include_router(router)
```

### Disabling Slack Integration

```python
import os
from fastapi import FastAPI
from fastapi_agentrouter import router, get_agent_placeholder

# Disable Slack integration via environment variable
os.environ["DISABLE_SLACK"] = "true"  # Slack endpoints will return 404

app = FastAPI()
app.dependency_overrides[get_agent_placeholder] = lambda: YourAgent()
app.include_router(router)
```

## Configuration

### Environment Variables

Configure Slack integration via environment variables using [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/):

```bash
# Required for Slack integration
export SLACK_BOT_TOKEN="xoxb-your-bot-token"
export SLACK_SIGNING_SECRET="your-signing-secret"

# Optional: Disable Slack integration
export DISABLE_SLACK="true"
```

### Platform Setup

#### Slack Setup

1. Create a Slack App at https://api.slack.com/apps
2. Get your Bot Token and Signing Secret from Basic Information
3. Set environment variables:
   ```bash
   export SLACK_BOT_TOKEN="xoxb-your-bot-token"
   export SLACK_SIGNING_SECRET="your-signing-secret"
   ```
4. Configure Event Subscriptions URL: `https://your-domain.com/agent/slack/events`
5. Subscribe to bot events:
   - `app_mention` - When your bot is mentioned
   - `message.im` - Direct messages to your bot (optional)
6. For interactive components and slash commands, use the same URL: `https://your-domain.com/agent/slack/events`

## Agent Protocol

Your agent must implement the `stream_query` method:

```python
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 Slack integration:
- `/agent/slack/events` - Main Slack event handler

#### `fastapi_agentrouter.get_agent_placeholder`

Dependency placeholder that should be overridden with your agent:
```python
app.dependency_overrides[fastapi_agentrouter.get_agent_placeholder] = your_get_agent_function
```

### Environment Variables

The library uses [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) for configuration management:

- `SLACK_BOT_TOKEN` - Slack Bot User OAuth Token (required)
- `SLACK_SIGNING_SECRET` - Slack Signing Secret (required)
- `DISABLE_SLACK=true` - Disable Slack endpoints (return 404)

See the [Configuration Guide](https://chanyou0311.github.io/fastapi-agentrouter/getting-started/configuration/) for detailed documentation on all available settings.


Request body:
```json
{
  "message": "Your message here",
  "user_id": "optional-user-id",
  "session_id": "optional-session-id"
}
```

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

## Examples

See the [examples](examples/) directory for complete examples:
- [basic_usage.py](examples/basic_usage.py) - Basic integration patterns
- More examples coming soon!

## Development

### Setup Development Environment

```bash
# 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

```bash
# Run all tests
pytest

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

# Run specific tests
pytest tests/test_router.py
```

### Build Documentation

```bash
# 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](LICENSE) file for details.

## Links

- [Documentation](https://chanyou0311.github.io/fastapi-agentrouter)
- [PyPI Package](https://pypi.org/project/fastapi-agentrouter)
- [GitHub Repository](https://github.com/chanyou0311/fastapi-agentrouter)
- [Issue Tracker](https://github.com/chanyou0311/fastapi-agentrouter/issues)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-agentrouter",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "agent, ai, discord, fastapi, slack, webhook",
    "author": null,
    "author_email": "Yu Nakamura <chanyou0311@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/cd/62/46a3066e9223eef148a36b48f25e58f8ed79492c69dcb7b3139243ae5eb5/fastapi_agentrouter-0.3.0.tar.gz",
    "platform": null,
    "description": "# FastAPI AgentRouter\n\n[![CI](https://github.com/chanyou0311/fastapi-agentrouter/actions/workflows/ci.yml/badge.svg)](https://github.com/chanyou0311/fastapi-agentrouter/actions/workflows/ci.yml)\n[![PyPI version](https://badge.fury.io/py/fastapi-agentrouter.svg)](https://badge.fury.io/py/fastapi-agentrouter)\n[![Python versions](https://img.shields.io/pypi/pyversions/fastapi-agentrouter.svg)](https://pypi.org/project/fastapi-agentrouter/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nSimplified AI Agent integration for FastAPI with Slack support.\n\n## Features\n\n- \ud83d\ude80 **Simple Integration** - Just 2 lines to add agent to your FastAPI app\n- \ud83e\udd16 **Vertex AI ADK Support** - Native support for Google's Agent Development Kit\n- \ud83d\udcac **Slack Integration** - Built-in Slack Bolt integration with lazy listeners\n- \ud83c\udfaf **Protocol-Based** - Works with any agent implementing `stream_query` method\n- \u26a1 **Async & Streaming** - Full async support with streaming responses\n- \ud83e\udde9 **Dependency Injection** - Leverage FastAPI's DI system\n- \ud83d\udcc1 **Modular Architecture** - Clean separation of concerns\n\n## Installation\n\n```bash\n# Basic installation\npip install fastapi-agentrouter\n\n# With Slack support\npip install \"fastapi-agentrouter[slack]\"\n\n# With Vertex AI ADK support\npip install \"fastapi-agentrouter[vertexai]\"\n\n# All extras\npip install \"fastapi-agentrouter[all]\"\n```\n\n## Quick Start\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_agentrouter import router, get_agent_placeholder\n\n# Your agent implementation\nclass MyAgent:\n    def stream_query(self, *, message: str, **kwargs):\n        # Process the message and yield responses\n        yield f\"Response to: {message}\"\n\napp = FastAPI()\n\n# Two-line integration!\napp.dependency_overrides[get_agent_placeholder] = lambda: MyAgent()\napp.include_router(router)\n```\n\nThat's it! Your agent is now available at:\n- `/agent/slack/events` - Handle all Slack events and interactions\n\n## Advanced Usage\n\n### With Vertex AI Agent Development Kit (ADK)\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_agentrouter import router, get_agent_placeholder\nfrom vertexai.preview import reasoning_engines\nfrom vertexai import Agent\n\n# Define your agent with tools\ndef get_weather(city: str) -> dict:\n    \"\"\"Get weather for a city.\"\"\"\n    return {\"city\": city, \"weather\": \"sunny\", \"temperature\": 25}\n\nagent = Agent(\n    name=\"weather_agent\",\n    model=\"gemini-2.5-flash-lite\",\n    description=\"Weather information agent\",\n    tools=[get_weather],\n)\n\ndef get_adk_app():\n    return reasoning_engines.AdkApp(\n        agent=agent,\n        enable_tracing=True,\n    )\n\napp = FastAPI()\napp.dependency_overrides[get_agent_placeholder] = get_adk_app\napp.include_router(router)\n```\n\n### Custom Agent Implementation\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_agentrouter import router, get_agent_placeholder\n\nclass CustomAgent:\n    def stream_query(self, *, message: str, user_id=None, session_id=None, **kwargs):\n        # Your custom logic here\n        yield f\"Response to: {message}\"\n\ndef get_custom_agent():\n    return CustomAgent()\n\napp = FastAPI()\napp.dependency_overrides[get_agent_placeholder] = get_custom_agent\napp.include_router(router)\n```\n\n### Disabling Slack Integration\n\n```python\nimport os\nfrom fastapi import FastAPI\nfrom fastapi_agentrouter import router, get_agent_placeholder\n\n# Disable Slack integration via environment variable\nos.environ[\"DISABLE_SLACK\"] = \"true\"  # Slack endpoints will return 404\n\napp = FastAPI()\napp.dependency_overrides[get_agent_placeholder] = lambda: YourAgent()\napp.include_router(router)\n```\n\n## Configuration\n\n### Environment Variables\n\nConfigure Slack integration via environment variables using [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/):\n\n```bash\n# Required for Slack integration\nexport SLACK_BOT_TOKEN=\"xoxb-your-bot-token\"\nexport SLACK_SIGNING_SECRET=\"your-signing-secret\"\n\n# Optional: Disable Slack integration\nexport DISABLE_SLACK=\"true\"\n```\n\n### Platform Setup\n\n#### Slack Setup\n\n1. Create a Slack App at https://api.slack.com/apps\n2. Get your Bot Token and Signing Secret from Basic Information\n3. Set environment variables:\n   ```bash\n   export SLACK_BOT_TOKEN=\"xoxb-your-bot-token\"\n   export SLACK_SIGNING_SECRET=\"your-signing-secret\"\n   ```\n4. Configure Event Subscriptions URL: `https://your-domain.com/agent/slack/events`\n5. Subscribe to bot events:\n   - `app_mention` - When your bot is mentioned\n   - `message.im` - Direct messages to your bot (optional)\n6. For interactive components and slash commands, use the same URL: `https://your-domain.com/agent/slack/events`\n\n## Agent Protocol\n\nYour agent must implement the `stream_query` method:\n\n```python\nclass AgentProtocol:\n    def stream_query(\n        self,\n        *,\n        message: str,\n        user_id: Optional[str] = None,\n        session_id: Optional[str] = None,\n        **kwargs\n    ) -> Iterator[Any]:\n        \"\"\"Stream responses for a message.\"\"\"\n        ...\n```\n\nThe method should yield response events. For Vertex AI ADK, events have a `content` attribute.\n\n## API Reference\n\n### Core Components\n\n#### `fastapi_agentrouter.router`\n\nPre-configured APIRouter with Slack integration:\n- `/agent/slack/events` - Main Slack event handler\n\n#### `fastapi_agentrouter.get_agent_placeholder`\n\nDependency placeholder that should be overridden with your agent:\n```python\napp.dependency_overrides[fastapi_agentrouter.get_agent_placeholder] = your_get_agent_function\n```\n\n### Environment Variables\n\nThe library uses [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) for configuration management:\n\n- `SLACK_BOT_TOKEN` - Slack Bot User OAuth Token (required)\n- `SLACK_SIGNING_SECRET` - Slack Signing Secret (required)\n- `DISABLE_SLACK=true` - Disable Slack endpoints (return 404)\n\nSee the [Configuration Guide](https://chanyou0311.github.io/fastapi-agentrouter/getting-started/configuration/) for detailed documentation on all available settings.\n\n\nRequest body:\n```json\n{\n  \"message\": \"Your message here\",\n  \"user_id\": \"optional-user-id\",\n  \"session_id\": \"optional-session-id\"\n}\n```\n\nResponse:\n```json\n{\n  \"response\": \"Agent response\",\n  \"session_id\": \"session-id-if-provided\"\n}\n```\n\n## Examples\n\nSee the [examples](examples/) directory for complete examples:\n- [basic_usage.py](examples/basic_usage.py) - Basic integration patterns\n- More examples coming soon!\n\n## Development\n\n### Setup Development Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/chanyou0311/fastapi-agentrouter.git\ncd fastapi-agentrouter\n\n# Install with uv (recommended)\nuv sync --all-extras --dev\n\n# Or with pip\npip install -e \".[all,dev,docs]\"\n\n# Install pre-commit hooks\npre-commit install\n```\n\n### Run Tests\n\n```bash\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=src --cov-report=html\n\n# Run specific tests\npytest tests/test_router.py\n```\n\n### Build Documentation\n\n```bash\n# Serve docs locally\nmkdocs serve\n\n# Build docs\nmkdocs build\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Links\n\n- [Documentation](https://chanyou0311.github.io/fastapi-agentrouter)\n- [PyPI Package](https://pypi.org/project/fastapi-agentrouter)\n- [GitHub Repository](https://github.com/chanyou0311/fastapi-agentrouter)\n- [Issue Tracker](https://github.com/chanyou0311/fastapi-agentrouter/issues)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "AI Agent interface library for FastAPI with multi-platform support",
    "version": "0.3.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/chanyou0311/fastapi-agentrouter/issues",
        "Changelog": "https://github.com/chanyou0311/fastapi-agentrouter/releases",
        "Documentation": "https://chanyou0311.github.io/fastapi-agentrouter",
        "Homepage": "https://github.com/chanyou0311/fastapi-agentrouter",
        "Repository": "https://github.com/chanyou0311/fastapi-agentrouter"
    },
    "split_keywords": [
        "agent",
        " ai",
        " discord",
        " fastapi",
        " slack",
        " webhook"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6e024c3a648e850815765b4b4afa538ea9deaaf4b031c860ff19acfa49ff0624",
                "md5": "2b9fc9901639b6ccbdd5731c67114d05",
                "sha256": "da873c6fa21a41c8a0e44a5c85fae04139b3b7886398b8dd62acf674f64dcee8"
            },
            "downloads": -1,
            "filename": "fastapi_agentrouter-0.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2b9fc9901639b6ccbdd5731c67114d05",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 10328,
            "upload_time": "2025-08-07T14:52:22",
            "upload_time_iso_8601": "2025-08-07T14:52:22.804683Z",
            "url": "https://files.pythonhosted.org/packages/6e/02/4c3a648e850815765b4b4afa538ea9deaaf4b031c860ff19acfa49ff0624/fastapi_agentrouter-0.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "cd6246a3066e9223eef148a36b48f25e58f8ed79492c69dcb7b3139243ae5eb5",
                "md5": "d744759c22546690dbe9690c619f510d",
                "sha256": "c305e79824fba043e494c94686b7b21a1affd887b95472fb17db69f21e25473d"
            },
            "downloads": -1,
            "filename": "fastapi_agentrouter-0.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "d744759c22546690dbe9690c619f510d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 23880,
            "upload_time": "2025-08-07T14:52:24",
            "upload_time_iso_8601": "2025-08-07T14:52:24.313357Z",
            "url": "https://files.pythonhosted.org/packages/cd/62/46a3066e9223eef148a36b48f25e58f8ed79492c69dcb7b3139243ae5eb5/fastapi_agentrouter-0.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-07 14:52:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "chanyou0311",
    "github_project": "fastapi-agentrouter",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fastapi-agentrouter"
}
        
Elapsed time: 2.86014s