Skip to content

Commit f2005a2

Browse files
seanzhougooglecopybara-github
authored andcommitted
chore: Add sample agent to test support of output_schema and tools at the same time for gemini model
PiperOrigin-RevId: 792694074
1 parent af63567 commit f2005a2

File tree

3 files changed

+152
-0
lines changed

3 files changed

+152
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Output Schema with Tools Sample Agent
2+
3+
This sample demonstrates how to use structured output (`output_schema`) alongside other tools in an ADK agent. Previously, this combination was not allowed, but now it's supported through a special processor that handles the interaction.
4+
5+
## How it Works
6+
7+
The agent combines:
8+
- **Tools**: `search_wikipedia` and `get_current_year` for gathering information
9+
- **Structured Output**: `PersonInfo` schema to ensure consistent response format
10+
11+
When both `output_schema` and `tools` are specified:
12+
1. ADK automatically adds a special `set_model_response` tool
13+
2. The model can use the regular tools for information gathering
14+
3. For the final response, the model uses `set_model_response` with structured data
15+
4. ADK extracts and validates the structured response
16+
17+
## Expected Response Format
18+
19+
The agent will return information in this structured format for user query "Tell me about Albert Einstein":
20+
21+
```json
22+
{
23+
"name": "Albert Einstein",
24+
"age": 76,
25+
"occupation": "Theoretical Physicist",
26+
"location": "Princeton, New Jersey, USA",
27+
"biography": "German-born theoretical physicist who developed the theory of relativity..."
28+
}
29+
```
30+
31+
## Key Features Demonstrated
32+
33+
1. **Tool Usage**: Agent can search Wikipedia and get current year
34+
2. **Structured Output**: Response follows strict PersonInfo schema
35+
3. **Validation**: ADK validates the response matches the schema
36+
4. **Flexibility**: Works with any combination of tools and output schemas
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from . import agent
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Sample agent demonstrating output_schema with tools feature.
16+
17+
This agent shows how to use structured output (output_schema) alongside
18+
other tools. Previously, this combination was not allowed, but now it's
19+
supported through a workaround that uses a special set_model_response tool.
20+
"""
21+
22+
from google.adk.agents import LlmAgent
23+
from pydantic import BaseModel
24+
from pydantic import Field
25+
import requests
26+
27+
28+
class PersonInfo(BaseModel):
29+
"""Structured information about a person."""
30+
31+
name: str = Field(description="The person's full name")
32+
age: int = Field(description="The person's age in years")
33+
occupation: str = Field(description="The person's job or profession")
34+
location: str = Field(description="The city and country where they live")
35+
biography: str = Field(description="A brief biography of the person")
36+
37+
38+
def search_wikipedia(query: str) -> str:
39+
"""Search Wikipedia for information about a topic.
40+
41+
Args:
42+
query: The search query to look up on Wikipedia
43+
44+
Returns:
45+
Summary of the Wikipedia article if found, or error message if not found
46+
"""
47+
try:
48+
# Use Wikipedia API to search for the article
49+
search_url = (
50+
"https://en.wikipedia.org/api/rest_v1/page/summary/"
51+
+ query.replace(" ", "_")
52+
)
53+
response = requests.get(search_url, timeout=10)
54+
55+
if response.status_code == 200:
56+
data = response.json()
57+
return (
58+
f"Title: {data.get('title', 'N/A')}\n\nSummary:"
59+
f" {data.get('extract', 'No summary available')}"
60+
)
61+
else:
62+
return (
63+
f"Wikipedia article not found for '{query}'. Status code:"
64+
f" {response.status_code}"
65+
)
66+
67+
except Exception as e:
68+
return f"Error searching Wikipedia: {str(e)}"
69+
70+
71+
def get_current_year() -> str:
72+
"""Get the current year.
73+
74+
Returns:
75+
The current year as a string
76+
"""
77+
from datetime import datetime
78+
79+
return str(datetime.now().year)
80+
81+
82+
# Create the agent with both output_schema and tools
83+
root_agent = LlmAgent(
84+
name="person_info_agent",
85+
model="gemini-1.5-pro",
86+
instruction="""
87+
You are a helpful assistant that gathers information about famous people.
88+
89+
When asked about a person, you should:
90+
1. Use the search_wikipedia tool to find information about them
91+
2. Use the get_current_year tool if you need to calculate ages
92+
3. Compile the information into a structured response using the PersonInfo format
93+
94+
Always use the set_model_response tool to provide your final answer in the required structured format.
95+
""".strip(),
96+
output_schema=PersonInfo,
97+
tools=[
98+
search_wikipedia,
99+
get_current_year,
100+
],
101+
)

0 commit comments

Comments
 (0)