-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathrunners.py
More file actions
1711 lines (1522 loc) · 61.8 KB
/
runners.py
File metadata and controls
1711 lines (1522 loc) · 61.8 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
from __future__ import annotations
import asyncio
import inspect
import logging
from pathlib import Path
import queue
import sys
from typing import Any
from typing import AsyncGenerator
from typing import Callable
from typing import Generator
from typing import List
from typing import Optional
import warnings
from google.adk.apps.compaction import _run_compaction_for_sliding_window
from google.genai import types
from .agents.base_agent import BaseAgent
from .agents.base_agent import BaseAgentState
from .agents.context_cache_config import ContextCacheConfig
from .agents.invocation_context import InvocationContext
from .agents.invocation_context import new_invocation_context_id
from .agents.live_request_queue import LiveRequestQueue
from .agents.run_config import RunConfig
from .apps.app import App
from .apps.app import ResumabilityConfig
from .artifacts.base_artifact_service import BaseArtifactService
from .artifacts.in_memory_artifact_service import InMemoryArtifactService
from .auth.credential_service.base_credential_service import BaseCredentialService
from .code_executors.built_in_code_executor import BuiltInCodeExecutor
from .errors.session_not_found_error import SessionNotFoundError
from .events.event import Event
from .events.event import EventActions
from .flows.llm_flows import contents
from .flows.llm_flows.functions import find_event_by_function_call_id
from .flows.llm_flows.functions import find_matching_function_call
from .memory.base_memory_service import BaseMemoryService
from .memory.in_memory_memory_service import InMemoryMemoryService
from .platform.thread import create_thread
from .plugins.base_plugin import BasePlugin
from .plugins.plugin_manager import PluginManager
from .sessions.base_session_service import BaseSessionService
from .sessions.base_session_service import GetSessionConfig
from .sessions.in_memory_session_service import InMemorySessionService
from .sessions.session import Session
from .telemetry.tracing import tracer
from .tools.base_toolset import BaseToolset
from .utils._debug_output import print_event
from .utils.context_utils import Aclosing
logger = logging.getLogger('google_adk.' + __name__)
class StopSignal:
def __init__(self) -> None:
self.stopped = False
def stop(self) -> None:
self.stopped = True
def reset(self) -> None:
self.stopped = False
def is_set(self) -> bool:
return self.stopped
def _is_tool_call_or_response(event: Event) -> bool:
return bool(event.get_function_calls() or event.get_function_responses())
def _get_function_responses_from_content(
content: types.Content,
) -> list[types.FunctionResponse]:
if not content:
return []
return [
part.function_response for part in content.parts if part.function_response
]
def _is_transcription(event: Event) -> bool:
return (
event.input_transcription is not None
or event.output_transcription is not None
)
def _has_non_empty_transcription_text(
transcription: types.Transcription,
) -> bool:
return bool(
transcription and transcription.text and transcription.text.strip()
)
def _apply_run_config_custom_metadata(
event: Event, run_config: RunConfig | None
) -> None:
"""Merges run-level custom metadata into the event, if present."""
if not run_config or not run_config.custom_metadata:
return
event.custom_metadata = {
**run_config.custom_metadata,
**(event.custom_metadata or {}),
}
class Runner:
"""The Runner class is used to run agents.
It manages the execution of an agent within a session, handling message
processing, event generation, and interaction with various services like
artifact storage, session management, and memory.
Attributes:
app_name: The application name of the runner.
agent: The root agent to run.
artifact_service: The artifact service for the runner.
plugin_manager: The plugin manager for the runner.
session_service: The session service for the runner.
memory_service: The memory service for the runner.
credential_service: The credential service for the runner.
context_cache_config: The context cache config for the runner.
resumability_config: The resumability config for the application.
"""
app_name: str
"""The app name of the runner."""
agent: BaseAgent
"""The root agent to run."""
artifact_service: Optional[BaseArtifactService] = None
"""The artifact service for the runner."""
plugin_manager: PluginManager
"""The plugin manager for the runner."""
session_service: BaseSessionService
"""The session service for the runner."""
memory_service: Optional[BaseMemoryService] = None
"""The memory service for the runner."""
credential_service: Optional[BaseCredentialService] = None
"""The credential service for the runner."""
context_cache_config: Optional[ContextCacheConfig] = None
"""The context cache config for the runner."""
resumability_config: Optional[ResumabilityConfig] = None
"""The resumability config for the application."""
def __init__(
self,
*,
app: Optional[App] = None,
app_name: Optional[str] = None,
agent: Optional[BaseAgent] = None,
plugins: Optional[List[BasePlugin]] = None,
artifact_service: Optional[BaseArtifactService] = None,
session_service: BaseSessionService,
memory_service: Optional[BaseMemoryService] = None,
credential_service: Optional[BaseCredentialService] = None,
plugin_close_timeout: float = 5.0,
auto_create_session: bool = False,
):
"""Initializes the Runner.
Developers should provide either an `app` instance or both `app_name` and
`agent`. When `app` is provided, `app_name` can optionally override the
app's name (useful for deployment scenarios like Agent Engine where the
resource name differs from the app's identifier). However, `agent` should
not be provided when `app` is provided. Providing `app` is the recommended
way to create a runner.
Args:
app: An optional `App` instance. If provided, `agent` should not be
specified. `app_name` can optionally override `app.name`.
app_name: The application name of the runner. Required if `app` is not
provided. If `app` is provided, this can optionally override `app.name`
(e.g., for deployment scenarios where a resource name differs from the
app identifier).
agent: The root agent to run. Required if `app` is not provided. Should
not be provided when `app` is provided.
plugins: Deprecated. A list of plugins for the runner. Please use the
`app` argument to provide plugins instead.
artifact_service: The artifact service for the runner.
session_service: The session service for the runner.
memory_service: The memory service for the runner.
credential_service: The credential service for the runner.
plugin_close_timeout: The timeout in seconds for plugin close methods.
auto_create_session: Whether to automatically create a session when
not found. Defaults to False. If False, a missing session raises
ValueError with a helpful message.
Raises:
ValueError: If `app` is provided along with `agent` or `plugins`, or if
`app` is not provided but either `app_name` or `agent` is missing.
"""
self.app = app
(
self.app_name,
self.agent,
self.context_cache_config,
self.resumability_config,
plugins,
) = self._validate_runner_params(app, app_name, agent, plugins)
self.artifact_service = artifact_service
self.session_service = session_service
self.memory_service = memory_service
self.credential_service = credential_service
self.plugin_manager = PluginManager(
plugins=plugins, close_timeout=plugin_close_timeout
)
self.auto_create_session = auto_create_session
(
self._agent_origin_app_name,
self._agent_origin_dir,
) = self._infer_agent_origin(self.agent)
self._app_name_alignment_hint: Optional[str] = None
self._enforce_app_name_alignment()
def _validate_runner_params(
self,
app: Optional[App],
app_name: Optional[str],
agent: Optional[BaseAgent],
plugins: Optional[List[BasePlugin]],
) -> tuple[
str,
BaseAgent,
Optional[ContextCacheConfig],
Optional[ResumabilityConfig],
Optional[List[BasePlugin]],
]:
"""Validates and extracts runner parameters.
Args:
app: An optional `App` instance.
app_name: The application name of the runner. Can override app.name when
app is provided.
agent: The root agent to run.
plugins: A list of plugins for the runner.
Returns:
A tuple containing (app_name, agent, context_cache_config,
resumability_config, plugins).
Raises:
ValueError: If parameters are invalid.
"""
if plugins is not None:
warnings.warn(
'The `plugins` argument is deprecated. Please use the `app` argument'
' to provide plugins instead.',
DeprecationWarning,
)
if app:
if agent:
raise ValueError('When app is provided, agent should not be provided.')
if plugins:
raise ValueError(
'When app is provided, plugins should not be provided and should be'
' provided in the app instead.'
)
# Allow app_name to override app.name (useful for deployment scenarios
# like Agent Engine where resource names differ from app identifiers)
app_name = app_name or app.name
agent = app.root_agent
plugins = app.plugins
context_cache_config = app.context_cache_config
resumability_config = app.resumability_config
elif not app_name or not agent:
raise ValueError(
'Either app or both app_name and agent must be provided.'
)
else:
context_cache_config = None
resumability_config = None
return app_name, agent, context_cache_config, resumability_config, plugins
def _infer_agent_origin(
self, agent: BaseAgent
) -> tuple[Optional[str], Optional[Path]]:
"""Infer the origin app name and directory from an agent's module location.
Returns:
A tuple of (origin_app_name, origin_path):
- origin_app_name: The inferred app name (directory name containing the
agent), or None if inference is not possible/applicable.
- origin_path: The directory path where the agent is defined, or None
if the path cannot be determined.
Both values are None when:
- The agent has no associated module
- The agent is defined in google.adk.* (ADK internal modules)
- The module has no __file__ attribute
"""
# First, check for metadata set by AgentLoader (most reliable source).
# AgentLoader sets these attributes when loading agents.
origin_app_name = getattr(agent, '_adk_origin_app_name', None)
origin_path = getattr(agent, '_adk_origin_path', None)
if origin_app_name is not None and origin_path is not None:
return origin_app_name, origin_path
# Fall back to heuristic inference for programmatic usage.
module = inspect.getmodule(agent.__class__)
if not module:
return None, None
# Skip ADK internal modules. When users instantiate LlmAgent directly
# (not subclassed), inspect.getmodule() returns the ADK module. This
# could falsely match 'agents' in 'google/adk/agents/' path.
if module.__name__.startswith('google.adk.'):
return None, None
module_file = getattr(module, '__file__', None)
if not module_file:
return None, None
module_path = Path(module_file).resolve()
project_root = Path.cwd()
try:
relative_path = module_path.relative_to(project_root)
except ValueError:
return None, module_path.parent
origin_dir = module_path.parent
if 'agents' not in relative_path.parts:
return None, origin_dir
origin_name = origin_dir.name
if origin_name.startswith('.'):
return None, origin_dir
return origin_name, origin_dir
def _enforce_app_name_alignment(self) -> None:
origin_name = self._agent_origin_app_name
origin_dir = self._agent_origin_dir
if not origin_name or origin_name.startswith('__'):
self._app_name_alignment_hint = None
return
if origin_name == self.app_name:
self._app_name_alignment_hint = None
return
origin_location = str(origin_dir) if origin_dir else origin_name
mismatch_details = (
'The runner is configured with app name '
f'"{self.app_name}", but the root agent was loaded from '
f'"{origin_location}", which implies app name "{origin_name}".'
)
resolution = (
'Ensure the runner app_name matches that directory or pass app_name '
'explicitly when constructing the runner.'
)
self._app_name_alignment_hint = f'{mismatch_details} {resolution}'
logger.warning('App name mismatch detected. %s', mismatch_details)
def _resolve_invocation_id(
self,
session: Session,
new_message: Optional[types.Content],
invocation_id: Optional[str],
) -> Optional[str]:
"""Infers invocation_id from new_message if it is a function response."""
function_responses = _get_function_responses_from_content(new_message)
if not function_responses:
return invocation_id
fc_event = find_event_by_function_call_id(
session.events, function_responses[0].id
)
if not fc_event:
raise ValueError(
'Function call event not found for function response id:'
f' {function_responses[0].id}'
)
if invocation_id and invocation_id != fc_event.invocation_id:
logger.warning(
'Provided invocation_id %s is ignored because new_message has a '
'function response with invocation_id %s.',
invocation_id,
fc_event.invocation_id,
)
return fc_event.invocation_id
def _format_session_not_found_message(self, session_id: str) -> str:
message = f'Session not found: {session_id}'
if not self._app_name_alignment_hint:
return message
return (
f'{message}. {self._app_name_alignment_hint} '
'The mismatch prevents the runner from locating the session. '
'To automatically create a session when missing, set '
'auto_create_session=True when constructing the runner.'
)
async def _get_or_create_session(
self,
*,
user_id: str,
session_id: str,
get_session_config: Optional[GetSessionConfig] = None,
) -> Session:
"""Gets the session or creates it if auto-creation is enabled.
This helper first attempts to retrieve the session. If not found and
auto_create_session is True, it creates a new session with the provided
identifiers. Otherwise, it raises a SessionNotFoundError.
Args:
user_id: The user ID of the session.
session_id: The session ID of the session.
get_session_config: Optional configuration for controlling which events
are fetched from session storage.
Returns:
The existing or newly created `Session`.
Raises:
SessionNotFoundError: If the session is not found and
auto_create_session is False.
"""
session = await self.session_service.get_session(
app_name=self.app_name,
user_id=user_id,
session_id=session_id,
config=get_session_config,
)
if not session:
if self.auto_create_session:
session = await self.session_service.create_session(
app_name=self.app_name, user_id=user_id, session_id=session_id
)
else:
message = self._format_session_not_found_message(session_id)
raise SessionNotFoundError(message)
return session
def run(
self,
*,
user_id: str,
session_id: str,
new_message: types.Content,
run_config: Optional[RunConfig] = None,
) -> Generator[Event, None, None]:
"""Runs the agent.
NOTE:
This sync interface is only for local testing and convenience purpose.
Consider using `run_async` for production usage.
If event compaction is enabled in the App configuration, it will be
performed after all agent events for the current invocation have been
yielded. The generator will only finish iterating after event
compaction is complete.
Args:
user_id: The user ID of the session.
session_id: The session ID of the session.
new_message: A new message to append to the session.
run_config: The run config for the agent.
Yields:
The events generated by the agent.
"""
run_config = run_config or RunConfig()
event_queue = queue.Queue()
async def _invoke_run_async():
try:
async with Aclosing(
self.run_async(
user_id=user_id,
session_id=session_id,
new_message=new_message,
run_config=run_config,
)
) as agen:
async for event in agen:
event_queue.put(event)
finally:
event_queue.put(None)
def _asyncio_thread_main():
try:
asyncio.run(_invoke_run_async())
finally:
event_queue.put(None)
thread = create_thread(target=_asyncio_thread_main)
thread.start()
# consumes and re-yield the events from background thread.
while True:
event = event_queue.get()
if event is None:
break
else:
yield event
thread.join()
async def run_async(
self,
*,
user_id: str,
session_id: str,
invocation_id: Optional[str] = None,
new_message: Optional[types.Content] = None,
state_delta: Optional[dict[str, Any]] = None,
run_config: Optional[RunConfig] = None,
stop_signal: Optional[StopSignal] = None,
) -> AsyncGenerator[Event, None]:
"""Main entry method to run the agent in this runner.
If event compaction is enabled in the App configuration, it will be
performed after all agent events for the current invocation have been
yielded. The async generator will only finish iterating after event
compaction is complete. However, this does not block new `run_async`
calls for subsequent user queries, which can be started concurrently.
Args:
user_id: The user ID of the session.
session_id: The session ID of the session.
invocation_id: The invocation ID of the session, set this to resume an
interrupted invocation.
new_message: A new message to append to the session.
state_delta: Optional state changes to apply to the session.
run_config: The run config for the agent.
Yields:
The events generated by the agent.
Raises:
ValueError: If the session is not found; If both invocation_id and
new_message are None.
"""
run_config = run_config or RunConfig()
if new_message and not new_message.role:
new_message.role = 'user'
async def _run_with_trace(
new_message: Optional[types.Content] = None,
invocation_id: Optional[str] = None,
) -> AsyncGenerator[Event, None]:
with tracer.start_as_current_span('invocation'):
session = await self._get_or_create_session(
user_id=user_id,
session_id=session_id,
get_session_config=run_config.get_session_config,
)
if not invocation_id and not new_message:
raise ValueError(
'Running an agent requires either a new_message or an '
'invocation_id to resume a previous invocation. '
f'Session: {session_id}, User: {user_id}'
)
is_resumable = (
self.resumability_config and self.resumability_config.is_resumable
)
if not is_resumable and not new_message:
raise ValueError(
'Running an agent requires a new_message or a resumable app. '
f'Session: {session_id}, User: {user_id}'
)
if not is_resumable:
invocation_context = await self._setup_context_for_new_invocation(
session=session,
new_message=new_message,
run_config=run_config,
state_delta=state_delta,
)
else:
invocation_id = self._resolve_invocation_id(
session, new_message, invocation_id
)
if not invocation_id:
invocation_context = await self._setup_context_for_new_invocation(
session=session,
new_message=new_message,
run_config=run_config,
state_delta=state_delta,
)
else:
invocation_context = (
await self._setup_context_for_resumed_invocation(
session=session,
new_message=new_message,
invocation_id=invocation_id,
run_config=run_config,
state_delta=state_delta,
)
)
if invocation_context.end_of_agents.get(
invocation_context.agent.name
):
# Directly return if the current agent in invocation context is
# already final.
return
async def execute(ctx: InvocationContext) -> AsyncGenerator[Event]:
async with Aclosing(ctx.agent.run_async(ctx)) as agen:
async for event in agen:
yield event
async with Aclosing(
self._exec_with_plugin(
invocation_context=invocation_context,
session=session,
execute_fn=execute,
is_live_call=False,
stop_signal=stop_signal,
)
) as agen:
async for event in agen:
yield event
if event.interrupted:
return
# Run compaction after all events are yielded from the agent.
# (We don't compact in the middle of an invocation, we only compact at
# the end of an invocation.)
if self.app and self.app.events_compaction_config:
logger.debug('Running event compactor.')
await _run_compaction_for_sliding_window(
self.app,
session,
self.session_service,
skip_token_compaction=invocation_context.token_compaction_checked,
)
async with Aclosing(_run_with_trace(new_message, invocation_id)) as agen:
async for event in agen:
yield event
async def rewind_async(
self,
*,
user_id: str,
session_id: str,
rewind_before_invocation_id: str,
run_config: Optional[RunConfig] = None,
) -> None:
"""Rewinds the session to before the specified invocation."""
run_config = run_config or RunConfig()
session = await self._get_or_create_session(
user_id=user_id,
session_id=session_id,
get_session_config=run_config.get_session_config,
)
rewind_event_index = -1
for i, event in enumerate(session.events):
if event.invocation_id == rewind_before_invocation_id:
rewind_event_index = i
break
if rewind_event_index == -1:
raise ValueError(
f'Invocation ID not found: {rewind_before_invocation_id}'
)
# Compute state delta to reverse changes
state_delta = await self._compute_state_delta_for_rewind(
session, rewind_event_index
)
# Compute artifact delta to reverse changes
artifact_delta = await self._compute_artifact_delta_for_rewind(
session, rewind_event_index
)
# Create rewind event
rewind_event = Event(
invocation_id=new_invocation_context_id(),
author='user',
actions=EventActions(
rewind_before_invocation_id=rewind_before_invocation_id,
state_delta=state_delta,
artifact_delta=artifact_delta,
),
)
logger.info('Rewinding session to invocation: %s', rewind_event)
await self.session_service.append_event(session=session, event=rewind_event)
async def _compute_state_delta_for_rewind(
self, session: Session, rewind_event_index: int
) -> dict[str, Any]:
"""Computes the state delta to reverse changes."""
state_at_rewind_point: dict[str, Any] = {}
for i in range(rewind_event_index):
if session.events[i].actions.state_delta:
for k, v in session.events[i].actions.state_delta.items():
if k.startswith('app:') or k.startswith('user:'):
continue
if v is None:
state_at_rewind_point.pop(k, None)
else:
state_at_rewind_point[k] = v
current_state = session.state
rewind_state_delta = {}
# 1. Add/update keys in rewind_state_delta to match state_at_rewind_point.
for key, value_at_rewind in state_at_rewind_point.items():
if key not in current_state or current_state[key] != value_at_rewind:
rewind_state_delta[key] = value_at_rewind
# 2. Set keys to None in rewind_state_delta if they are in current_state
# but not in state_at_rewind_point. These keys were added after the
# rewind point and need to be removed.
for key in current_state:
if key.startswith('app:') or key.startswith('user:'):
continue
if key not in state_at_rewind_point:
rewind_state_delta[key] = None
return rewind_state_delta
async def _compute_artifact_delta_for_rewind(
self, session: Session, rewind_event_index: int
) -> dict[str, int]:
"""Computes the artifact delta to reverse changes."""
if not self.artifact_service:
return {}
versions_at_rewind_point: dict[str, int] = {}
for i in range(rewind_event_index):
event = session.events[i]
if event.actions.artifact_delta:
versions_at_rewind_point.update(event.actions.artifact_delta)
current_versions: dict[str, int] = {}
for event in session.events:
if event.actions.artifact_delta:
current_versions.update(event.actions.artifact_delta)
rewind_artifact_delta = {}
for filename, vn in current_versions.items():
if filename.startswith('user:'):
# User artifacts are not restored on rewind.
continue
vt = versions_at_rewind_point.get(filename)
if vt == vn:
continue
rewind_artifact_delta[filename] = vn + 1
if vt is None:
# Artifact did not exist at rewind point. Mark it as inaccessible.
artifact = types.Part(
inline_data=types.Blob(
mime_type='application/octet-stream', data=b''
)
)
else:
# Artifact version changed after rewind point. Restore to version at
# rewind point by loading the actual data via the artifact service.
artifact = await self.artifact_service.load_artifact(
app_name=self.app_name,
user_id=session.user_id,
session_id=session.id,
filename=filename,
version=vt,
)
if artifact is None:
logger.warning(
'Artifact %s version %d not found during rewind for'
' session %s. Replacing with empty data.',
filename,
vt,
session.id,
)
artifact = types.Part(
inline_data=types.Blob(
mime_type='application/octet-stream', data=b''
)
)
await self.artifact_service.save_artifact(
app_name=self.app_name,
user_id=session.user_id,
session_id=session.id,
filename=filename,
artifact=artifact,
)
return rewind_artifact_delta
def _should_append_event(self, event: Event, is_live_call: bool) -> bool:
"""Checks if an event should be appended to the session."""
# Don't append audio response from model in live mode to session.
# The data is appended to artifacts with a reference in file_data in the
# event.
# We should append non-partial events only.For example, non-finished(partial)
# transcription events should not be appended.
# Function call and function response events should be appended.
# Other control events should be appended.
if is_live_call and contents._is_live_model_audio_event_with_inline_data(
event
):
# We don't append live model audio events with inline data to avoid
# storing large blobs in the session. However, events with file_data
# (references to artifacts) should be appended.
return False
return True
def _get_output_event(
self,
*,
original_event: Event,
modified_event: Event | None,
run_config: RunConfig | None,
) -> Event:
"""Returns the event that should be persisted and yielded.
Plugins may return a replacement event that only overrides a subset of
fields. Merge those changes onto the original event so the streamed event
and the persisted event stay aligned without losing the original event
identity.
"""
if modified_event is None:
return original_event
_apply_run_config_custom_metadata(modified_event, run_config)
update = {}
for field_name in modified_event.model_fields_set:
if field_name in {'id', 'invocation_id', 'timestamp'}:
continue
update[field_name] = modified_event.__dict__[field_name]
output_event = original_event.model_copy(update=update)
if not output_event.author:
output_event.author = original_event.author
return output_event
async def _exec_with_plugin(
self,
invocation_context: InvocationContext,
session: Session,
execute_fn: Callable[[InvocationContext], AsyncGenerator[Event, None]],
is_live_call: bool = False,
*,
stop_signal: Optional[StopSignal] = None,
) -> AsyncGenerator[Event, None]:
"""Wraps execution with plugin callbacks.
Args:
invocation_context: The invocation context
session: The current session
execute_fn: A callable that returns an AsyncGenerator of Events
is_live_call: Whether this is a live call
Yields:
Events from the execution, including any generated by plugins
"""
plugin_manager = invocation_context.plugin_manager
# Step 1: Run the before_run callbacks to see if we should early exit.
early_exit_result = await plugin_manager.run_before_run_callback(
invocation_context=invocation_context
)
if isinstance(early_exit_result, types.Content):
early_exit_event = Event(
invocation_id=invocation_context.invocation_id,
author='model',
content=early_exit_result,
)
_apply_run_config_custom_metadata(
early_exit_event, invocation_context.run_config
)
if self._should_append_event(early_exit_event, is_live_call):
await self.session_service.append_event(
session=session,
event=early_exit_event,
)
yield early_exit_event
else:
# Step 2: Otherwise continue with normal execution
# Note for live/bidi:
# the transcription may arrive later than the action(function call
# event and thus function response event). In this case, the order of
# transcription and function call event will be wrong if we just
# append as it arrives. To address this, we should check if there is
# transcription going on. If there is transcription going on, we
# should hold on appending the function call event until the
# transcription is finished. The transcription in progress can be
# identified by checking if the transcription event is partial. When
# the next transcription event is not partial, it means the previous
# transcription is finished. Then if there is any buffered function
# call event, we should append them after this finished(non-partial)
# transcription event.
buffered_events: list[Event] = []
is_transcribing: bool = False
async with Aclosing(execute_fn(invocation_context)) as agen:
async for event in agen:
if stop_signal and stop_signal.is_set():
# See if the run_async execution is interrupted
# If an interruption is called, return an event that signifies as such
interrupted_event = Event(
invocation_id=invocation_context.invocation_id,
author='model',
interrupted=True,
content=types.Content(role='model', parts=[]),
)
yield interrupted_event
_apply_run_config_custom_metadata(
event, invocation_context.run_config
)
# Step 3: Run the on_event callbacks before persisting so callback
# changes are stored in the session and match the streamed event.
modified_event = await plugin_manager.run_on_event_callback(
invocation_context=invocation_context, event=event
)
output_event = self._get_output_event(
original_event=event,
modified_event=modified_event,
run_config=invocation_context.run_config,
)
if is_live_call:
if event.partial and _is_transcription(event):
is_transcribing = True
if is_transcribing and _is_tool_call_or_response(event):
# only buffer function call and function response event which is
# non-partial
buffered_events.append(output_event)
continue
# Note for live/bidi: for audio response, it's considered as
# non-partial event(event.partial=None)
# event.partial=False and event.partial=None are considered as
# non-partial event; event.partial=True is considered as partial
# event.
if event.partial is not True:
if _is_transcription(event) and (
_has_non_empty_transcription_text(event.input_transcription)
or _has_non_empty_transcription_text(
event.output_transcription
)
):
# transcription end signal, append buffered events
is_transcribing = False
logger.debug(
'Appending transcription finished event: %s', event
)
if self._should_append_event(event, is_live_call):
await self.session_service.append_event(
session=session, event=output_event
)
for buffered_event in buffered_events:
logger.debug('Appending buffered event: %s', buffered_event)
await self.session_service.append_event(
session=session, event=buffered_event
)
yield buffered_event # yield buffered events to caller
buffered_events = []
else:
# non-transcription event or empty transcription event, for
# example, event that stores blob reference, should be appended.
if self._should_append_event(event, is_live_call):
logger.debug('Appending non-buffered event: %s', event)
await self.session_service.append_event(
session=session, event=output_event
)
else:
if event.partial is not True:
await self.session_service.append_event(
session=session, event=output_event
)
yield output_event
# Step 4: Run the after_run callbacks to perform global cleanup tasks or
# finalizing logs and metrics data.
# This does NOT emit any event.
await plugin_manager.run_after_run_callback(
invocation_context=invocation_context
)
async def _append_new_message_to_session(
self,