-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathagent.py
More file actions
179 lines (154 loc) · 5.48 KB
/
agent.py
File metadata and controls
179 lines (154 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# Copyright 2026 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
#
# http://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.
"""The agent to demo the session state lifecycle.
This agent illustrate how session state will be cached in context and persisted
in session state.
"""
import logging
from typing import Optional
from google.adk.agents.callback_context import CallbackContext
from google.adk.agents.llm_agent import Agent
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.genai import types
logger = logging.getLogger('google_adk.' + __name__)
async def assert_session_values(
ctx: CallbackContext,
title: str,
*,
keys_in_ctx_session: Optional[list[str]] = None,
keys_in_service_session: Optional[list[str]] = None,
keys_not_in_service_session: Optional[list[str]] = None,
):
session_in_ctx = ctx._invocation_context.session
session_in_service = (
await ctx._invocation_context.session_service.get_session(
app_name=session_in_ctx.app_name,
user_id=session_in_ctx.user_id,
session_id=session_in_ctx.id,
)
)
assert session_in_service is not None
print(f'===================== {title} ==============================')
print(
f'** Asserting keys are cached in context: {keys_in_ctx_session}', end=' '
)
for key in keys_in_ctx_session or []:
assert key in session_in_ctx.state
print('\033[92mpass ✅\033[0m')
print(
'** Asserting keys are already persisted in session:'
f' {keys_in_service_session}',
end=' ',
)
for key in keys_in_service_session or []:
assert key in session_in_service.state
print('\033[92mpass ✅\033[0m')
print(
'** Asserting keys are not persisted in session yet:'
f' {keys_not_in_service_session}',
end=' ',
)
for key in keys_not_in_service_session or []:
assert key not in session_in_service.state
print('\033[92mpass ✅\033[0m')
print('============================================================')
async def before_agent_callback(
callback_context: CallbackContext,
) -> Optional[types.Content]:
if 'before_agent_callback_state_key' in callback_context.state:
return types.ModelContent('Sorry, I can only reply once.')
callback_context.state['before_agent_callback_state_key'] = (
'before_agent_callback_state_value'
)
await assert_session_values(
callback_context,
'In before_agent_callback',
keys_in_ctx_session=['before_agent_callback_state_key'],
keys_in_service_session=[],
keys_not_in_service_session=['before_agent_callback_state_key'],
)
async def before_model_callback(
callback_context: CallbackContext, llm_request: LlmRequest
):
callback_context.state['before_model_callback_state_key'] = (
'before_model_callback_state_value'
)
await assert_session_values(
callback_context,
'In before_model_callback',
keys_in_ctx_session=[
'before_agent_callback_state_key',
'before_model_callback_state_key',
],
keys_in_service_session=['before_agent_callback_state_key'],
keys_not_in_service_session=['before_model_callback_state_key'],
)
async def after_model_callback(
callback_context: CallbackContext, llm_response: LlmResponse
):
callback_context.state['after_model_callback_state_key'] = (
'after_model_callback_state_value'
)
await assert_session_values(
callback_context,
'In after_model_callback',
keys_in_ctx_session=[
'before_agent_callback_state_key',
'before_model_callback_state_key',
'after_model_callback_state_key',
],
keys_in_service_session=[
'before_agent_callback_state_key',
],
keys_not_in_service_session=[
'before_model_callback_state_key',
'after_model_callback_state_key',
],
)
async def after_agent_callback(callback_context: CallbackContext):
callback_context.state['after_agent_callback_state_key'] = (
'after_agent_callback_state_value'
)
await assert_session_values(
callback_context,
'In after_agent_callback',
keys_in_ctx_session=[
'before_agent_callback_state_key',
'before_model_callback_state_key',
'after_model_callback_state_key',
'after_agent_callback_state_key',
],
keys_in_service_session=[
'before_agent_callback_state_key',
'before_model_callback_state_key',
'after_model_callback_state_key',
],
keys_not_in_service_session=[
'after_agent_callback_state_key',
],
)
root_agent = Agent(
name='root_agent',
description='a verification agent.',
instruction=(
'Log all users query with `log_query` tool. Must always remind user you'
' cannot answer second query because your setup.'
),
model='gemini-2.5-flash',
before_agent_callback=before_agent_callback,
before_model_callback=before_model_callback,
after_model_callback=after_model_callback,
after_agent_callback=after_agent_callback,
)