-
Notifications
You must be signed in to change notification settings - Fork 778
feat: Add LangGraph Restaurant Finder sample agent #508
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
Open
faizan842
wants to merge
9
commits into
google:main
Choose a base branch
from
faizan842:feature/langgraph-restaurant-finder
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b27b243
Add Langgraph restaurant_finder sample example
faizan842 34633a3
Update readme
faizan842 5c25ce9
Fix retry model call when AI response is empty
faizan842 60eb5e2
Remove hardcoded base_url from restaurant finder tool
faizan842 f8014b4
Merge branch 'main' into feature/langgraph-restaurant-finder
faizan842 043baa4
Merge branch 'main' into feature/langgraph-restaurant-finder
faizan842 2c1b04e
Merge branch 'main' into feature/langgraph-restaurant-finder
faizan842 faab3b8
Merge branch 'main' into feature/langgraph-restaurant-finder
faizan842 2ef4b67
Merge branch 'main' into feature/langgraph-restaurant-finder
faizan842 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # Copy this file to .env and fill in your API key | ||
| # Get your API key at: https://aistudio.google.com/apikey | ||
|
|
||
| GEMINI_API_KEY=your_gemini_api_key_here | ||
|
|
||
| # Optional: Use Vertex AI instead of Gemini API | ||
| # GOOGLE_GENAI_USE_VERTEXAI=TRUE |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # A2UI Restaurant finder and table reservation agent sample (LangGraph) | ||
|
|
||
| This sample uses [LangGraph](https://github.com/langchain-ai/langgraph) along with the A2A protocol to create a simple "Restaurant finder and table reservation" agent that is hosted as an A2A server. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - Python 3.9 or higher | ||
| - [UV](https://docs.astral.sh/uv/) | ||
| - Access to an LLM and API Key (Google Gemini is used by default) | ||
|
|
||
| ## Running the Sample | ||
|
|
||
| 1. Navigate to the samples directory: | ||
|
|
||
| ```bash | ||
| cd samples/agent/langgraph/restaurant_finder | ||
| ``` | ||
|
|
||
| 2. Create an environment file with your API key: | ||
|
|
||
| ```bash | ||
| cp .env.example .env | ||
| # Edit .env with your actual API key (do not commit .env) | ||
| ``` | ||
|
|
||
| 3. Run the agent server: | ||
|
|
||
| ```bash | ||
| uv run . | ||
| ``` | ||
|
|
||
| ## Implementation Details | ||
|
|
||
| - `agent.py`: Defines the LangGraph agent, state, and tools. | ||
| - `agent_executor.py`: Adapts the LangGraph agent to the A2A server interface. | ||
| - `a2ui_examples.py`: Contains few-shot examples for A2UI generation. | ||
|
|
||
| ## Disclaimer | ||
|
|
||
| Important: The sample code provided is for demonstration purposes and illustrates the mechanics of A2UI and the Agent-to-Agent (A2A) protocol. When building production applications, it is critical to treat any agent operating outside of your direct control as a potentially untrusted entity. | ||
|
|
||
| All operational data received from an external agent—including its AgentCard, messages, artifacts, and task statuses—should be handled as untrusted input. For example, a malicious agent could provide crafted data in its fields (e.g., name, skills.description) that, if used without sanitization to construct prompts for a Large Language Model (LLM), could expose your application to prompt injection attacks. | ||
|
|
||
| Similarly, any UI definition or data stream received must be treated as untrusted. Malicious agents could attempt to spoof legitimate interfaces to deceive users (phishing), inject malicious scripts via property values (XSS), or generate excessive layout complexity to degrade client performance (DoS). If your application supports optional embedded content (such as iframes or web views), additional care must be taken to prevent exposure to malicious external sites. | ||
|
|
||
| Developer Responsibility: Failure to properly validate data and strictly sandbox rendered content can introduce severe vulnerabilities. Developers are responsible for implementing appropriate security measures—such as input sanitization, Content Security Policies (CSP), strict isolation for optional embedded content, and secure credential handling—to protect their systems and users. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # https://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import logging | ||
| import os | ||
|
|
||
| import click | ||
| from a2a.server.apps import A2AStarletteApplication | ||
| from a2a.server.request_handlers import DefaultRequestHandler | ||
| from a2a.server.tasks import InMemoryTaskStore | ||
| from a2a.types import AgentCapabilities, AgentCard, AgentSkill | ||
| from a2ui.a2ui_extension import get_a2ui_agent_extension | ||
| from agent_executor import RestaurantAgentExecutor | ||
| from agent import RestaurantAgent # To get SUPPORTED_CONTENT_TYPES ideally, but we can hardcode for now or add it to class | ||
| from dotenv import load_dotenv | ||
| from starlette.middleware.cors import CORSMiddleware | ||
| from starlette.staticfiles import StaticFiles | ||
|
|
||
| load_dotenv() | ||
|
|
||
| logging.basicConfig(level=logging.INFO) | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class MissingAPIKeyError(Exception): | ||
| """Exception for missing API key.""" | ||
|
|
||
|
|
||
| @click.command() | ||
| @click.option("--host", default="localhost") | ||
| @click.option("--port", default=10002) | ||
| def main(host, port): | ||
| try: | ||
| # Check for API key only if Vertex AI is not configured | ||
| if not os.getenv("GOOGLE_GENAI_USE_VERTEXAI") == "TRUE": | ||
| if not os.getenv("GEMINI_API_KEY"): | ||
| raise MissingAPIKeyError( | ||
| "GEMINI_API_KEY environment variable not set and GOOGLE_GENAI_USE_VERTEXAI is not TRUE." | ||
| ) | ||
|
|
||
| capabilities = AgentCapabilities( | ||
| streaming=True, | ||
| extensions=[get_a2ui_agent_extension()], | ||
| ) | ||
| skill = AgentSkill( | ||
| id="find_restaurants", | ||
| name="Find Restaurants Tool", | ||
| description="Helps find restaurants based on user criteria (e.g., cuisine, location).", | ||
| tags=["restaurant", "finder"], | ||
| examples=["Find me the top 10 chinese restaurants in the US"], | ||
| ) | ||
|
|
||
| base_url = f"http://{host}:{port}" | ||
|
|
||
| # Hardcoding supported types since I didn't add them to the class yet, | ||
| # or I can update agent.py to have them. Let's do that for consistency if I modify agent.py. | ||
| # But for now I'll just put them here. | ||
| SUPPORTED_CONTENT_TYPES = ["text", "text/plain"] | ||
|
|
||
| agent_card = AgentCard( | ||
| name="Restaurant Agent (LangGraph)", | ||
| description="This agent helps find restaurants based on user criteria.", | ||
| url=base_url, | ||
| version="1.0.0", | ||
| default_input_modes=SUPPORTED_CONTENT_TYPES, | ||
| default_output_modes=SUPPORTED_CONTENT_TYPES, | ||
| capabilities=capabilities, | ||
| skills=[skill], | ||
| ) | ||
|
|
||
| agent_executor = RestaurantAgentExecutor(base_url=base_url) | ||
|
|
||
| request_handler = DefaultRequestHandler( | ||
| agent_executor=agent_executor, | ||
| task_store=InMemoryTaskStore(), | ||
| ) | ||
| server = A2AStarletteApplication( | ||
| agent_card=agent_card, http_handler=request_handler | ||
| ) | ||
| import uvicorn | ||
|
|
||
| app = server.build() | ||
|
|
||
| app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origin_regex=r"http://localhost:\d+", | ||
| allow_credentials=True, | ||
| allow_methods=["*"], | ||
| allow_headers=["*"], | ||
| ) | ||
|
|
||
| # Ensure images dir exists or handle it. We copied the files but maybe not the dir? | ||
| # The `cp` command I used earlier: `cp ...samples/agent/adk/restaurant_finder/{tools.py,...} ...` | ||
| # It didn't copy `images` directory explicitly. I should fix that. | ||
| if os.path.isdir("images"): | ||
| app.mount("/static", StaticFiles(directory="images"), name="static") | ||
|
|
||
| uvicorn.run(app, host=host, port=port) | ||
| except MissingAPIKeyError as e: | ||
| logger.error(f"Error: {e}") | ||
| exit(1) | ||
| except Exception as e: | ||
| logger.error(f"An error occurred during server startup: {e}") | ||
| exit(1) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
The import
RestaurantAgentis not used in this file and should be removed. The associated comment appears to be a developer note that is no longer relevant.Additionally, there are other developer comments that should be cleaned up to improve code clarity:
SUPPORTED_CONTENT_TYPES.imagesdirectory.