Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions samples/agent/langgraph/restaurant_finder/.env.example
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
46 changes: 46 additions & 0 deletions samples/agent/langgraph/restaurant_finder/README.md
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.
119 changes: 119 additions & 0 deletions samples/agent/langgraph/restaurant_finder/__main__.py
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The import RestaurantAgent is 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:

  • Lines 66-68: Comment about hardcoding SUPPORTED_CONTENT_TYPES.
  • Lines 103-105: Comment about the images directory.

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()
Loading