-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Feat/fastapi modular server contribution #2952
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat/fastapi modular server contribution #2952
Conversation
- Complete modular FastAPI server implementation for ADK agents - Server-Sent Events (SSE) streaming with three optimization levels - Clean architecture with proper separation of concerns - Includes greetings agent example with streaming capabilities - Comprehensive configuration management and logging - Ready-to-use with environment configuration template - Follows ADK best practices for production deployments Features: - Real-time agent streaming via SSE endpoints - Configurable optimization levels (minimal, balanced, full compatibility) - Modular agent system with easy extensibility - Proper error handling and logging - Environment-based configuration management Files added: - Modular server structure with agents, API, config, core, and models - SSE event mapper for optimized streaming - Streaming models and request handling - Greetings agent implementation - Environment configuration template - Comprehensive README documentation
@gemini-code-assist
gemini-code-assist
bot
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @FrigaZzz, I'm Gemini Code Assist1 ! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request delivers a robust, production-ready template for extending the Google Agent Development Kit (ADK) with a modular FastAPI server. It addresses the need for a clear reference implementation following the adk_web_server.py modularization in v1.9.0, enabling developers to easily integrate custom logic, optimize real-time data streaming, and benefit from development-friendly features like hot-reloading for agents. The changes provide a structured approach to building scalable and customizable ADK-powered applications.
Highlights
- Modular FastAPI Server Template: Introduces a reference implementation for extending the ADK's modular
adk_web_server.pyinto a production-ready FastAPI server. - Customization and Extension: Provides patterns for adding custom routers, overriding ADK endpoints, and accessing ADK services and runners, enabling flexible application development.
- Optimized SSE Streaming: Implements an
SSEEventMapperwithMINIMAL,BALANCED, andFULL_COMPAToptimization levels for Server-Sent Events, reducing payload sizes and improving performance. - Agent Hot-Reload: Integrates
watchdogfor automatic agent reloading during development, significantly enhancing the developer experience. - Comprehensive Example Structure: Includes a full example project structure with agents, API routers, configuration, core utilities, and a detailed
README.mdfor clear guidance.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
Response from ADK Triaging Agent
Hello @FrigaZzz, thank you for creating this PR!
To help us review this PR more efficiently, could you please provide the following:
- Associated Issue: For new features or examples like this, please create a GitHub issue and link it to this PR.
- Testing Plan: Please add a "Testing Plan" section to your PR description, explaining how you've tested this example.
- Screenshots/Logs: Please provide screenshots or logs of the example server running to demonstrate its functionality.
This information will help reviewers to better understand and verify your contribution. Thanks!
@gemini-code-assist
gemini-code-assist
bot
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a valuable example of a modular FastAPI server for the ADK. The structure is well-organized, and the use of Pydantic for settings and dependency injection for services follows best practices. The inclusion of agent hot-reloading is a great feature for development.
My review focuses on improving the clarity and correctness of the documentation, as well as enhancing the robustness and maintainability of the Python code. I've pointed out several areas in the README.md where examples could be more accurate or clearer. In the Python code, I've suggested changes to avoid unconventional practices like __import__() and to handle JSON serialization more safely to prevent potential runtime errors.
Overall, this is a solid contribution that will serve as an excellent reference for users. Addressing the feedback will make the example even more polished and easier for developers to adopt.
contributing/samples/fastapi_modular_server/app/api/routers/agent_router.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/routers/agent_router.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/routers/agent_router.py
Show resolved
Hide resolved
Standardize time module usage across the codebase by replacing dynamic imports with direct imports. Also improve JSON error handling in SSE responses and update README numbering.
/gemini review
@gemini-code-assist
gemini-code-assist
bot
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces an excellent and comprehensive example of building a modular FastAPI server on top of the ADK. The project structure is well-designed, leveraging modern Python and FastAPI best practices such as Pydantic for settings management, dependency injection containers, and an application factory pattern. The agent hot-reloading feature is a particularly valuable addition for improving the development workflow. My review comments focus on enhancing documentation consistency, removing unused code, refining error handling for more robustness, and improving code clarity in a few areas. Overall, this is a high-quality contribution that will serve as a great reference for users.
contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/routers/agent_router.py
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/core/mapping/sse_event_mapper.py
Outdated
Show resolved
Hide resolved
- Use json.dumps for SSE event formatting in agent_router - Replace loop with list comprehension in sse_event_mapper - Remove unused variables and outdated comments in custom_adk_server - Specify ModuleNotFoundError exception for web assets loading
/gemini review
@gemini-code-assist
gemini-code-assist
bot
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces an excellent example of a modular FastAPI server, which will be a valuable resource for users extending the ADK. The code is well-structured and follows modern Python and FastAPI practices. My review focuses on improving type safety, consistency, and making the template even more robust for end-users. I've included several suggestions to enhance code clarity and maintainability.
contributing/samples/fastapi_modular_server/app/agents/greetings_agent/__init__.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/api/routers/agent_router.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/config/settings.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/config/settings.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/core/dependencies.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/core/dependencies.py
Outdated
Show resolved
Hide resolved
contributing/samples/fastapi_modular_server/app/core/logging.py
Outdated
Show resolved
Hide resolved
- Update type hints from typing.List/Dict to modern list/dict - Add TYPE_CHECKING imports where needed - Rename greetings_agent file for consistency - Expand .gitignore with common development artifacts - Clean up unused imports in multiple files
/gemini summary
Summary of Changes
This pull request provides a robust, modular FastAPI server template designed to guide users in extending the Google Agent Development Kit (ADK). It demonstrates how to integrate custom logic, optimize Server-Sent Events (SSE) for various use cases, and enable hot-reloading of agents for a more efficient development workflow. The changes aim to empower developers to build highly customizable and performant ADK-based applications.
Highlights
- Modular FastAPI Server Template: Introduces a reference implementation for extending ADK's modular
adk_web_server.pyinto a production-ready FastAPI server, showcasing best practices for customization. - Optimized SSE Streaming: Implements an
SSEEventMapperwith three optimization levels (MINIMAL,BALANCED,FULL_COMPAT) to reduce payload sizes and improve streaming performance for Server-Sent Events. - Agent Hot-Reload: Adds functionality for automatic agent reloading on file changes during development using
watchdog, enhancing developer productivity. - Customization Guide: Provides clear examples and patterns within the
README.mdfor adding custom routers, overriding ADK endpoints, and accessing ADK services, making the server highly extensible. - Comprehensive Project Structure: Organizes the example with dedicated directories for agents, API, configuration, core utilities, and models, promoting maintainability and scalability.
Changelog
- contributing/samples/fastapi_modular_server/.env.example
- Added an example environment configuration file for application, ADK, Google Gemini, and model settings.
- contributing/samples/fastapi_modular_server/.gitignore
- Added common ignore patterns for logs, environment variables, Python bytecode, test artifacts, and IDE configurations.
- contributing/samples/fastapi_modular_server/README.md
- Introduced comprehensive documentation detailing the purpose, key features (modular routers, optimized SSE, hot-reload), project structure, quick start guide, and customization instructions for the modular server.
- contributing/samples/fastapi_modular_server/app/agents/greetings_agent/init.py
- Added an
__init__.pyfile to makegreetings_agenta Python package.
- Added an
- contributing/samples/fastapi_modular_server/app/agents/greetings_agent/greetings_agent.py
- Implemented a sample
LlmAgentnamed 'greetings_agent' using the Gemini-2.5-flash model.
- Implemented a sample
- contributing/samples/fastapi_modular_server/app/api/custom_adk_server.py
- Created
CustomAdkWebServerextendingAdkWebServer, incorporating modular router initialization, agent hot-reload setup usingwatchdog, and custom diagnostic and health check endpoints. - Includes logic to remove the default
/run_sseroute for custom handling.
- Created
- contributing/samples/fastapi_modular_server/app/api/routers/agent_router.py
- Defined
AgentRouterto manage agent-related API endpoints, specifically providing a custom/run_sseendpoint that leverages the new SSE optimization levels.
- Defined
- contributing/samples/fastapi_modular_server/app/config/settings.py
- Introduced a
Settingsclass usingpydantic-settingsfor managing application configuration from environment variables, including server details, paths, ADK settings, and logging.
- Introduced a
- contributing/samples/fastapi_modular_server/app/core/dependencies.py
- Implemented dependency injection for ADK services (
AgentLoader,SessionService,MemoryService, etc.) andSSEEventMapper, ensuring these services are instantiated as singletons.
- Implemented dependency injection for ADK services (
- contributing/samples/fastapi_modular_server/app/core/logging.py
- Added a
setup_loggingfunction to configure application-wide logging, directing output to stdout and an optional file, and setting specific logger levels.
- Added a
- contributing/samples/fastapi_modular_server/app/core/mapping/sse_event_mapper.py
- Implemented
SSEEventMapperto transform ADKEventobjects into Server-Sent Event messages, offeringMINIMAL,BALANCED, andFULL_COMPAToptimization levels for payload reduction.
- Implemented
- contributing/samples/fastapi_modular_server/app/models/streaming_request.py
- Defined an
OptimizationLevelenum andRunAgentRequestOptimizedPydantic model to extend the baseRunAgentRequestwith anoptimization_levelfield for SSE streaming.
- Defined an
- contributing/samples/fastapi_modular_server/main.py
- The main entry point, responsible for initializing logging, creating ADK services, instantiating the
CustomAdkWebServer, and running the FastAPI application using Uvicorn.
- The main entry point, responsible for initializing logging, creating ADK services, instantiating the
Activity
- The
adk-botrequested an associated issue, a testing plan, and screenshots/logs for the pull request. - The author,
FrigaZzz, initiated two/gemini reviewcommands and one/gemini summarycommand. - The
gemini-code-assist[bot]provided several review comments, including a high-priority suggestion to usejson.dumpsfor safe JSON string construction in error handling. - Medium-priority suggestions from
gemini-code-assist[bot]included correcting inconsistent numbering in theREADME.md(Quick Start, Overriding Endpoints), completing an incomplete code example for accessing runners, and definingOptimizationLevel.ULTRA_MINIMALif used in examples. - Further medium-priority suggestions from
gemini-code-assist[bot]covered adding missingbase64import, aligning.env.examplewithenv_prefixdocumentation, and replacing unconventional__import__("time").time()with directtime.time()calls. - Additional medium-priority suggestions from
gemini-code-assist[bot]recommended removing unused imports (ADKServices,Dict,List), refining JSON construction for initial SSE messages, and using list comprehensions for clarity. - More medium-priority suggestions from
gemini-code-assist[bot]advised enhancing.gitignorewith more common patterns, addressing misleading docstrings, removing unused instance attributes, and catching more specific exceptions (ModuleNotFoundError). - Finally,
gemini-code-assist[bot]suggested adding type hints forweb_server_instanceandsettings, and using built-inlistanddicttypes for type hinting instead oftyping.Listandtyping.Dict. - The author,
FrigaZzz, responded to two ofgemini-code-assist[bot]'s comments, clarifying that theREADME.md's example of removing additional routes was intentional for illustrative purposes, not a strict reflection of the current code.
...utorformat.sh) Reorganize imports to follow PEP 8 guidelines by grouping standard library, third-party, and local imports separately. This improves code readability and maintainability while keeping the same functionality.
Uh oh!
There was an error while loading. Please reload this page.
PR: Example FastAPI Modular Server Usage
📖 Overview
This PR adds a reference implementation showcasing how to extend the newly modularized
adk_web_server.py(introduced in v1.9.0) into a production-ready FastAPI server.🎯 Motivation
Release v1.9.0 introduced the following change:
This PR provides a concrete template that leverages those changes, making it easier for teams to:
📚 What’s Included
fastapi_modular_server/) with routers, agents, config, and core utilities.MINIMAL,BALANCED,FULL_COMPAT).📝 Notes
v1.9.0.✅ Checklist
v1.14.0📖 Proposal for Python Docs
We should extend the ADK Python documentation with a new section.
Suggested Doc Location:
docs/runtime/fastapi_server_extensions.mdProposed Section Outline:
Why Modularization?
fast_api.pyrefactor in v1.9.0Building a Custom Server
Overriding Built-in Routes
Optimizing Streaming (straightforward example)
SSEEventMapperThis way, the docs PR will complement this usage example, turning it into a reusable guide for the community.
🔗 Associated Issue
Closes #2953
🧪 Testing Plan
The server was tested locally by running it and issuing a streaming request via
fetchin the browser console:✅ The SSE stream responded successfully with generated content.
📸 Screenshot of the running server:
Screenshot 2025年09月15日 at 22 04 49📖 Proposal for Python Docs
We should extend the ADK Python documentation with a new section.
Suggested Doc Location:
docs/runtime/fastapi_server_extensions.mdProposed Section Outline:
Why Modularization?
fast_api.pyrefactor in v1.9.0Building a Custom Server
Overriding Built-in Routes
Optimizing Streaming (straightforward example)
SSEEventMapperThis way, the docs PR will complement this usage example, turning it into a reusable guide for the community.