-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathrunners.py
More file actions
2211 lines (1975 loc) · 78.9 KB
/
Copy pathrunners.py
File metadata and controls
2211 lines (1975 loc) · 78.9 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
from contextlib import aclosing
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
from typing import TYPE_CHECKING
import warnings
from google.genai import types
from .agents.base_agent import BaseAgent
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.llm.task._finish_task_tool import FINISH_TASK_SUCCESS_RESULT
from .agents.llm.task._finish_task_tool import FINISH_TASK_TOOL_NAME
from .agents.run_config import RunConfig
from .apps.app import App
from .artifacts.base_artifact_service import BaseArtifactService
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 .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.session import Session
from .telemetry.tracing import tracer
from .tools.base_toolset import BaseToolset
from .utils._debug_output import print_event
if TYPE_CHECKING:
from .apps.app import ResumabilityConfig
logger = logging.getLogger('google_adk.' + __name__)
def _find_active_task_isolation_scope(session) -> Optional[str]:
"""Walk session backwards; find the active paused task agent's scope.
Two flavors of task scope:
* FC delegation (chat coordinator → task agent via function call):
scope = ``fc.id``, opened by an unresolved task FC.
* Workflow node (task-mode LlmAgent dispatched as a graph node):
scope = ``<node_name>@<run_id>``, stamped on every event the
task agent emits.
Both close on a SUCCESSFUL ``finish_task`` FunctionResponse —
i.e., one whose response is ``FINISH_TASK_SUCCESS_RESULT``. An
error FR (validation failure) does NOT close the scope: the task
agent is still active, will see the error, and retry. Walking
backward, the first non-empty scope we encounter that hasn't been
closed by a later successful ``finish_task`` is the paused task
awaiting the user's next reply.
Used by ``Runner._append_user_event`` to scope the new user message
to that task agent's view.
"""
finished_scopes: set[str] = set()
for event in reversed(session.events):
scope = event.isolation_scope
if not scope:
continue
if event.content and event.content.parts:
for part in event.content.parts:
fr = part.function_response
if fr and fr.name == FINISH_TASK_TOOL_NAME:
response = fr.response or {}
if response.get('result') == FINISH_TASK_SUCCESS_RESULT:
finished_scopes.add(scope)
break
if scope not in finished_scopes:
return scope
return None
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 _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: Optional[BaseAgent | 'BaseNode'] = None
"""The root agent or node 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,
node: Any = 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.
Exactly one of `app`, `agent`, or `node` must be provided. When `agent`
or `node` is provided, the Runner wraps it into an `App` internally.
Providing `app` is the recommended way to create a runner. When `app` is
provided, `app_name` can optionally override the app's name.
Args:
app: An `App` instance. Mutually exclusive with `agent` and `node`.
app_name: The application name. Required when `agent` is provided.
Optional override for `app.name` when `app` is provided. Defaults to
`node.name` when only `node` is provided.
agent: The root agent to run. Mutually exclusive with `app` and `node`.
node: The root node to run. Mutually exclusive with `app` and `agent`.
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 more than one of `app`, `agent`, or `node` is provided,
or if none is provided, or if `agent` is provided without `app_name`.
"""
app = self._resolve_app(app, app_name, agent, node, plugins)
# Extract from App — single code path.
self.app = app
self.app_name = app_name or app.name
self.agent = app.root_agent
self.context_cache_config = app.context_cache_config
self.resumability_config = app.resumability_config
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=app.plugins, close_timeout=plugin_close_timeout
)
self.auto_create_session = auto_create_session
if self.agent is not None:
(
self._agent_origin_app_name,
self._agent_origin_dir,
) = self._infer_agent_origin(self.agent)
else:
self._agent_origin_app_name = None
self._agent_origin_dir = None
self._app_name_alignment_hint: Optional[str] = None
self._enforce_app_name_alignment()
@staticmethod
def _resolve_app(
app: Optional[App],
app_name: Optional[str],
agent: Optional[BaseAgent],
node: Any,
plugins: Optional[List[BasePlugin]],
) -> App:
"""Validates inputs and normalizes to an App instance.
Exactly one of ``app``, ``agent``, or ``node`` must be provided.
When ``agent`` or ``node`` is given, it is wrapped in a new ``App``.
Returns:
The resolved ``App`` instance.
Raises:
ValueError: If the combination of arguments is invalid.
"""
# Validate mutual exclusivity.
provided = sum(x is not None for x in (app, agent, node))
if provided > 1:
raise ValueError('Only one of app, agent, or node may be provided.')
if provided == 0:
raise ValueError('One of app, agent, or node must be provided.')
# Handle deprecated plugins argument.
if plugins is not None:
if app is not None:
raise ValueError(
'When app is provided, plugins should not be provided and should'
' be provided in the app instead.'
)
warnings.warn(
'The `plugins` argument is deprecated. Please use the `app` argument'
' to provide plugins instead.',
DeprecationWarning,
)
# Normalize to App — wrap bare agent or node. Uses model_construct to
# bypass App._validate for the legacy (app_name, agent) API, which v1
# accepted with arbitrary names and root_agent types. Direct App(name=...)
# construction still validates strictly.
if agent is not None:
if not app_name:
raise ValueError(
'app_name is required when agent is provided without app.'
)
return App.model_construct(
name=app_name, root_agent=agent, plugins=plugins or []
)
if node is not None:
return App.model_construct(
name=app_name or getattr(node, 'name', 'default'),
root_agent=node,
plugins=plugins or [],
)
return app
@staticmethod
def _validate_runner_params(
app: Optional[App],
app_name: Optional[str],
agent: Optional[BaseAgent],
plugins: Optional[List[BasePlugin]],
) -> tuple[
str,
BaseAgent,
Optional[ContextCacheConfig],
Optional[ResumabilityConfig],
Optional[List[BasePlugin]],
]:
"""Deprecated: use _resolve_app instead."""
resolved = Runner._resolve_app(app, app_name, agent, None, plugins)
return (
app_name or resolved.name,
resolved.root_agent,
resolved.context_cache_config,
resolved.resumability_config,
plugins if app is None else resolved.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 _run_node_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,
yield_user_message: bool = False,
node: Optional['BaseNode'] = None,
) -> AsyncGenerator[Event, None]:
"""Run a BaseNode through NodeRunner.
Events flow through ic._event_queue via NodeRunner.
"""
from .workflow._node_runner import NodeRunner
with tracer.start_as_current_span('invocation'):
# 1. Setup
session = await self._get_or_create_session(
user_id=user_id, session_id=session_id
)
# Validate and resolve resume inputs
resume_inputs = self._extract_resume_inputs(new_message)
self._validate_new_message(new_message, resume_inputs)
if not invocation_id and new_message:
invocation_id = self._resolve_invocation_id_from_fr(
session, new_message
)
ic = self._new_invocation_context(
session,
new_message=new_message,
run_config=run_config or RunConfig(),
invocation_id=invocation_id,
)
ic._event_queue = asyncio.Queue()
# 2. Append user message to session and resolve node_input
node_input = None
if resume_inputs or invocation_id:
# Resume: recover the original user content. new_message here is a
# function response (or None), so it can't populate user_content.
node_input = self._find_original_user_content(
ic.session, ic.invocation_id
)
if node_input:
ic.user_content = node_input
if not node_input:
# Fresh: use user message as node_input
node_input = new_message
# Run callbacks on user message
if new_message:
modified_user_message = (
await ic.plugin_manager.run_on_user_message_callback(
invocation_context=ic, user_message=new_message
)
)
if modified_user_message is not None:
new_message = modified_user_message
ic.user_content = new_message
# Append user message to session for history
if new_message:
user_event = await self._append_user_event(
ic, new_message, state_delta=state_delta
)
if yield_user_message and user_event:
yield user_event
# Run before_run callbacks
corrected_user_message = await ic.plugin_manager.run_before_run_callback(
invocation_context=ic
)
if corrected_user_message is not None:
if isinstance(corrected_user_message, types.Content):
node_input = corrected_user_message
ic.user_content = corrected_user_message
if hasattr(ic.session, 'events') and len(ic.session.events) > 0:
ic.session.events.pop()
user_event = await self._append_user_event(ic, corrected_user_message)
if yield_user_message and user_event:
yield user_event
# 3. Start root node in background
from .agents.base_agent import BaseAgent
from .agents.context import Context
from .workflow._dynamic_node_scheduler import DynamicNodeScheduler
from .workflow._workflow import _LoopState
root_ctx = Context(ic)
root_agent = node or self.agent
is_agent = isinstance(self.agent, BaseAgent)
has_sub_agents = is_agent and bool(
getattr(self.agent, 'sub_agents', None)
)
use_scheduler = is_agent and has_sub_agents
# The root chat coordinator's isolation_scope stays None: its own
# events (FCs, text, synthesized FRs from completed task
# delegations) are also unscoped, so the content-builder's
# isolation_scope filter lets the coordinator see all of them
# across user turns. Task sub-agents are scoped under their
# originating function-call id and so remain invisible to the
# coordinator's view.
if not use_scheduler:
root_node_runner = NodeRunner(node=root_agent, parent_ctx=root_ctx)
done_sentinel = object()
async def _drive_root_node():
try:
if use_scheduler:
# Rehydration warning: DynamicNodeScheduler relies on session.events scanning.
# Stateful live EUC/LRO streams may rehydrate freshly if not yet persisted.
scheduler = DynamicNodeScheduler(state=_LoopState())
root_ctx._workflow_scheduler = scheduler
ctx = await scheduler(
root_ctx,
root_agent,
node_input,
run_id='1',
)
else:
ctx = await root_node_runner.run(
node_input=node_input,
resume_inputs=resume_inputs,
)
if ctx.error:
raise ctx.error
finally:
await ic._event_queue.put((done_sentinel, None))
task = asyncio.create_task(_drive_root_node())
# 4. Main loop: consume events, persist, yield
try:
async with aclosing(
self._consume_event_queue(ic, done_sentinel)
) as agen:
async for event in agen:
yield event
finally:
await self._cleanup_root_task(task, self.agent.name)
await ic.plugin_manager.run_after_run_callback(invocation_context=ic)
if self.app and self.app.events_compaction_config:
logger.debug('Running event compactor.')
from google.adk.apps.compaction import _run_compaction_for_sliding_window
await _run_compaction_for_sliding_window(
self.app,
session,
self.session_service,
skip_token_compaction=ic.token_compaction_checked,
)
async def _run_node_live(
self,
*,
session: Session,
live_request_queue: LiveRequestQueue,
run_config: Optional[RunConfig] = None,
) -> AsyncGenerator[Event, None]:
"""Run a non-agent BaseNode in live mode."""
from .agents.context import Context
from .workflow._dynamic_node_scheduler import DynamicNodeScheduler
from .workflow._node_runner import NodeRunner
from .workflow._workflow import _LoopState
from .workflow._workflow import Workflow
ic = self._new_invocation_context_for_live(
session,
live_request_queue=live_request_queue,
run_config=run_config or RunConfig(),
)
ic._event_queue = asyncio.Queue()
root_ctx = Context(ic)
root_agent = self.agent
is_workflow = isinstance(root_agent, Workflow)
if not is_workflow:
root_node_runner = NodeRunner(node=root_agent, parent_ctx=root_ctx)
done_sentinel = object()
async def _drive_root_node():
try:
if is_workflow:
scheduler = DynamicNodeScheduler(state=_LoopState())
root_ctx._workflow_scheduler = scheduler
ctx = await scheduler(
root_ctx,
root_agent,
None,
run_id='1',
)
else:
ctx = await root_node_runner.run(
node_input=None,
)
if ctx.error:
raise ctx.error
finally:
await ic._event_queue.put((done_sentinel, None))
task = asyncio.create_task(_drive_root_node())
try:
async with aclosing(self._consume_event_queue(ic, done_sentinel)) as agen:
async for event in agen:
yield event
finally:
await self._cleanup_root_task(task, self.agent.name)
def _extract_resume_inputs(
self, message: Optional[types.Content]
) -> dict[str, Any] | None:
"""Extract function response payloads from a message as resume_inputs."""
if not message or not message.parts:
return None
inputs = {}
for part in message.parts:
if part.function_response and part.function_response.id:
inputs[part.function_response.id] = part.function_response.response
return inputs or None
def _validate_new_message(
self,
message: Optional[types.Content],
resume_inputs: dict[str, Any] | None,
) -> None:
"""Validate that new_message doesn't mix FR and text parts."""
if not resume_inputs or not message or not message.parts:
return
if any(p.text for p in message.parts):
raise ValueError(
'Message cannot contain both function responses and text.'
' Function responses resume an existing invocation while'
' text starts a new one.'
)
def _resolve_invocation_id_from_fr(
self,
session: Session,
new_message: types.Content,
) -> Optional[str]:
"""Infer invocation_id by matching function responses to FC events.
Raises ValueError if responses resolve to different invocations.
"""
fr_ids = {
p.function_response.id
for p in new_message.parts or []
if p.function_response and p.function_response.id
}
if not fr_ids:
return None
# Find invocation_id for each FR by matching its FC in session
invocation_ids = set()
for event in reversed(session.events):
for fc in event.get_function_calls():
if fc.id in fr_ids:
invocation_ids.add(event.invocation_id)
fr_ids.discard(fc.id)
if not fr_ids:
break
if fr_ids:
raise ValueError(
f'Function call not found for function response ids: {fr_ids}.'
)
if len(invocation_ids) > 1:
raise ValueError(
'Function responses resolve to multiple'
f' invocations: {invocation_ids}.'
)
return invocation_ids.pop()
async def _append_user_event(
self,
ic: InvocationContext,
content: types.Content,
*,
state_delta: Optional[dict[str, Any]] = None,
) -> Event:
"""Append a user message event to the session and return it."""
if state_delta:
event = Event(
invocation_id=ic.invocation_id,
author='user',
actions=EventActions(state_delta=state_delta),
content=content,
)
else:
event = Event(
invocation_id=ic.invocation_id,
author='user',
content=content,
)
# when a paused task delegation is in flight, stamp
# the new user message with that task's isolation_scope so the
# task agent's content-build (scoped to <fc_id>) sees it.
if event.isolation_scope is None:
iso = _find_active_task_isolation_scope(ic.session)
if iso is not None:
event.isolation_scope = iso
_apply_run_config_custom_metadata(event, ic.run_config)
return await self.session_service.append_event(
session=ic.session, event=event
)
def _find_original_user_content(
self, session: Session, invocation_id: str
) -> types.Content | None:
"""Find the original user text message for a given invocation_id."""
for event in session.events:
if (
event.invocation_id == invocation_id
and event.author == 'user'
and event.content
and event.content.parts
and any(p.text for p in event.content.parts)
):
return event.content
return None
async def _consume_event_queue(
self, ic: InvocationContext, done_sentinel: object
) -> AsyncGenerator[Event, None]:
"""Consume events from ic._event_queue until done_sentinel."""
while True:
event_or_done, processed_signal = await ic._event_queue.get()
if event_or_done is done_sentinel:
break
event: Event = event_or_done
# When an LlmAgent node uses ``message_as_output`` (no
# ``output_schema``), the wrapper sets both ``event.content``
# (the model's text) AND ``event.output`` (the same text) to
# signal that the message IS the node's output. Clear
# ``event.output`` on a copy here so downstream renderers don't
# surface the same text twice. Task-mode agents set
# ``event.output`` from the ``finish_task`` FC args without
# ``message_as_output``, so this clearing doesn't affect them.
if not event.partial:
if event.node_info.message_as_output and event.content is not None:
event = event.model_copy()
event.output = None
_apply_run_config_custom_metadata(event, ic.run_config)
modified_event = await ic.plugin_manager.run_on_event_callback(
invocation_context=ic, event=event
)
output_event = self._get_output_event(
original_event=event,
modified_event=modified_event,
run_config=ic.run_config,
)
if not event.partial:
await self.session_service.append_event(
session=ic.session, event=output_event
)
yield output_event
if isinstance(processed_signal, asyncio.Event):
processed_signal.set()
async def _cleanup_root_task(
self, task: asyncio.Task, node_name: str
) -> None:
"""Cancel the root task if still running, then await it.
The task may still be running if the caller stopped iterating
early (e.g., break in async for). In that case we must cancel
to avoid a leaked task.
"""
if not task.done():
logger.debug(
'Cancelling root node %s (caller stopped early).',
node_name,
)
task.cancel()
try:
await task
except asyncio.CancelledError:
logger.warning('Root node %s was cancelled.', node_name)
except Exception:
logger.error('Root node %s failed.', node_name, exc_info=True)
raise
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,
state_delta: Optional[dict[str, Any]] = None,
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.
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.
"""
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,
state_delta=state_delta,
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,
yield_user_message: bool = False,
) -> 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.
yield_user_message: If True, yield the user message event before
agent/node events.
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'
from .agents.llm_agent import LlmAgent
from .workflow._base_node import BaseNode
if isinstance(self.agent, LlmAgent):
if self.agent.mode is None:
# LlmAgent as root agent must have chat mode.
self.agent.mode = 'chat'
if self.agent.mode == 'chat':
session = await self._get_or_create_session(
user_id=user_id, session_id=session_id
)
# when the chat coordinator has task-mode sub-agents,
# the wrapper handles delegation via ctx.run_node. Don't let
# the legacy sub-agent picker bypass the coordinator on resume.