forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadk_web_server.py
More file actions
1736 lines (1530 loc) · 57.8 KB
/
adk_web_server.py
File metadata and controls
1736 lines (1530 loc) · 57.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 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
#
# 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 asynccontextmanager
import importlib
import json
import logging
import os
import time
import traceback
import typing
from typing import Any
from typing import Callable
from typing import List
from typing import Literal
from typing import Optional
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi import Query
from fastapi import Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.websockets import WebSocket
from fastapi.websockets import WebSocketDisconnect
from google.genai import types
import graphviz
from opentelemetry import trace
import opentelemetry.sdk.environment_variables as otel_env
from opentelemetry.sdk.trace import export as export_lib
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace import SpanProcessor
from opentelemetry.sdk.trace import TracerProvider
from pydantic import Field
from pydantic import ValidationError
from starlette.types import Lifespan
from typing_extensions import deprecated
from typing_extensions import override
from watchdog.observers import Observer
from . import agent_graph
from ..agents.base_agent import BaseAgent
from ..agents.live_request_queue import LiveRequest
from ..agents.live_request_queue import LiveRequestQueue
from ..agents.run_config import RunConfig
from ..agents.run_config import StreamingMode
from ..apps.app import App
from ..artifacts.base_artifact_service import ArtifactVersion
from ..artifacts.base_artifact_service import BaseArtifactService
from ..auth.credential_service.base_credential_service import BaseCredentialService
from ..errors.already_exists_error import AlreadyExistsError
from ..errors.input_validation_error import InputValidationError
from ..errors.not_found_error import NotFoundError
from ..evaluation.base_eval_service import InferenceConfig
from ..evaluation.base_eval_service import InferenceRequest
from ..evaluation.constants import MISSING_EVAL_DEPENDENCIES_MESSAGE
from ..evaluation.eval_case import EvalCase
from ..evaluation.eval_case import SessionInput
from ..evaluation.eval_metrics import EvalMetric
from ..evaluation.eval_metrics import EvalMetricResult
from ..evaluation.eval_metrics import EvalMetricResultPerInvocation
from ..evaluation.eval_metrics import EvalStatus
from ..evaluation.eval_metrics import MetricInfo
from ..evaluation.eval_result import EvalSetResult
from ..evaluation.eval_set import EvalSet
from ..evaluation.eval_set_results_manager import EvalSetResultsManager
from ..evaluation.eval_sets_manager import EvalSetsManager
from ..events.event import Event
from ..memory.base_memory_service import BaseMemoryService
from ..plugins.base_plugin import BasePlugin
from ..runners import Runner
from ..sessions.base_session_service import BaseSessionService
from ..sessions.session import Session
from ..utils.context_utils import Aclosing
from .cli_eval import EVAL_SESSION_ID_PREFIX
from .utils import cleanup
from .utils import common
from .utils import envs
from .utils import evals
from .utils.base_agent_loader import BaseAgentLoader
from .utils.shared_value import SharedValue
from .utils.state import create_empty_state
logger = logging.getLogger("google_adk." + __name__)
_EVAL_SET_FILE_EXTENSION = ".evalset.json"
TAG_DEBUG = "Debug"
TAG_EVALUATION = "Evaluation"
_REGEX_PREFIX = "regex:"
def _parse_cors_origins(
allow_origins: list[str],
) -> tuple[list[str], Optional[str]]:
"""Parse allow_origins into literal origins and a combined regex pattern.
Args:
allow_origins: List of origin strings. Entries prefixed with 'regex:' are
treated as regex patterns; all others are treated as literal origins.
Returns:
A tuple of (literal_origins, combined_regex) where combined_regex is None
if no regex patterns were provided, or a single pattern joining all regex
patterns with '|'.
"""
literal_origins = []
regex_patterns = []
for origin in allow_origins:
if origin.startswith(_REGEX_PREFIX):
pattern = origin[len(_REGEX_PREFIX) :]
if pattern:
regex_patterns.append(pattern)
else:
literal_origins.append(origin)
combined_regex = "|".join(regex_patterns) if regex_patterns else None
return literal_origins, combined_regex
class ApiServerSpanExporter(export_lib.SpanExporter):
def __init__(self, trace_dict):
self.trace_dict = trace_dict
def export(
self, spans: typing.Sequence[ReadableSpan]
) -> export_lib.SpanExportResult:
for span in spans:
if (
span.name == "call_llm"
or span.name == "send_data"
or span.name.startswith("execute_tool")
):
attributes = dict(span.attributes)
attributes["trace_id"] = span.get_span_context().trace_id
attributes["span_id"] = span.get_span_context().span_id
if attributes.get("gcp.vertex.agent.event_id", None):
self.trace_dict[attributes["gcp.vertex.agent.event_id"]] = attributes
return export_lib.SpanExportResult.SUCCESS
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
class InMemoryExporter(export_lib.SpanExporter):
def __init__(self, trace_dict):
super().__init__()
self._spans = []
self.trace_dict = trace_dict
@override
def export(
self, spans: typing.Sequence[ReadableSpan]
) -> export_lib.SpanExportResult:
for span in spans:
trace_id = span.context.trace_id
if span.name == "call_llm":
attributes = dict(span.attributes)
session_id = attributes.get("gcp.vertex.agent.session_id", None)
if session_id:
if session_id not in self.trace_dict:
self.trace_dict[session_id] = [trace_id]
else:
self.trace_dict[session_id] += [trace_id]
self._spans.extend(spans)
return export_lib.SpanExportResult.SUCCESS
@override
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
def get_finished_spans(self, session_id: str):
trace_ids = self.trace_dict.get(session_id, None)
if trace_ids is None or not trace_ids:
return []
return [x for x in self._spans if x.context.trace_id in trace_ids]
def clear(self):
self._spans.clear()
class RunAgentRequest(common.BaseModel):
app_name: str
user_id: str
session_id: str
new_message: types.Content
streaming: bool = False
state_delta: Optional[dict[str, Any]] = None
# for resume long-running functions
invocation_id: Optional[str] = None
class CreateSessionRequest(common.BaseModel):
session_id: Optional[str] = Field(
default=None,
description=(
"The ID of the session to create. If not provided, a random session"
" ID will be generated."
),
)
state: Optional[dict[str, Any]] = Field(
default=None, description="The initial state of the session."
)
events: Optional[list[Event]] = Field(
default=None,
description="A list of events to initialize the session with.",
)
class SaveArtifactRequest(common.BaseModel):
"""Request payload for saving a new artifact."""
filename: str = Field(description="Artifact filename.")
artifact: types.Part = Field(
description="Artifact payload encoded as google.genai.types.Part."
)
custom_metadata: Optional[dict[str, Any]] = Field(
default=None,
description="Optional metadata to associate with the artifact version.",
)
class AddSessionToEvalSetRequest(common.BaseModel):
eval_id: str
session_id: str
user_id: str
class RunEvalRequest(common.BaseModel):
eval_ids: list[str] = Field(
deprecated=True,
default_factory=list,
description="This field is deprecated, use eval_case_ids instead.",
)
eval_case_ids: list[str] = Field(
default_factory=list,
description=(
"List of eval case ids to evaluate. if empty, then all eval cases in"
" the eval set are run."
),
)
eval_metrics: list[EvalMetric]
class UpdateMemoryRequest(common.BaseModel):
"""Request to add a session to the memory service."""
session_id: str
"""The ID of the session to add to memory."""
class UpdateSessionRequest(common.BaseModel):
"""Request to update session state without running the agent."""
state_delta: dict[str, Any]
"""The state changes to apply to the session."""
class RunEvalResult(common.BaseModel):
eval_set_file: str
eval_set_id: str
eval_id: str
final_eval_status: EvalStatus
eval_metric_results: list[tuple[EvalMetric, EvalMetricResult]] = Field(
deprecated=True,
default=[],
description=(
"This field is deprecated, use overall_eval_metric_results instead."
),
)
overall_eval_metric_results: list[EvalMetricResult]
eval_metric_result_per_invocation: list[EvalMetricResultPerInvocation]
user_id: str
session_id: str
class RunEvalResponse(common.BaseModel):
run_eval_results: list[RunEvalResult]
class GetEventGraphResult(common.BaseModel):
dot_src: str
class CreateEvalSetRequest(common.BaseModel):
eval_set: EvalSet
class ListEvalSetsResponse(common.BaseModel):
eval_set_ids: list[str]
class EvalResult(EvalSetResult):
"""This class has no field intentionally.
The goal here is to just give a new name to the class to align with the API
endpoint.
"""
class ListEvalResultsResponse(common.BaseModel):
eval_result_ids: list[str]
class ListMetricsInfoResponse(common.BaseModel):
metrics_info: list[MetricInfo]
class AppInfo(common.BaseModel):
name: str
root_agent_name: str
description: str
language: Literal["yaml", "python"]
is_computer_use: bool = False
class ListAppsResponse(common.BaseModel):
apps: list[AppInfo]
def _setup_telemetry(
otel_to_cloud: bool = False,
internal_exporters: Optional[list[SpanProcessor]] = None,
):
# TODO - remove the else branch here once maybe_set_otel_providers is no
# longer experimental.
if otel_to_cloud:
_setup_gcp_telemetry(internal_exporters=internal_exporters)
elif _otel_env_vars_enabled():
_setup_telemetry_from_env(internal_exporters=internal_exporters)
else:
# Old logic - to be removed when above leaves experimental.
tracer_provider = TracerProvider()
if internal_exporters is not None:
for exporter in internal_exporters:
tracer_provider.add_span_processor(exporter)
trace.set_tracer_provider(tracer_provider=tracer_provider)
def _otel_env_vars_enabled() -> bool:
return any([
os.getenv(endpoint_var)
for endpoint_var in [
otel_env.OTEL_EXPORTER_OTLP_ENDPOINT,
otel_env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,
otel_env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT,
otel_env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT,
]
])
def _setup_gcp_telemetry(
internal_exporters: list[SpanProcessor] = None,
):
if typing.TYPE_CHECKING:
from ..telemetry.setup import OTelHooks
otel_hooks_to_add: list[OTelHooks] = []
if internal_exporters:
from ..telemetry.setup import OTelHooks
# Register ADK-specific exporters in trace provider.
otel_hooks_to_add.append(OTelHooks(span_processors=internal_exporters))
import google.auth
from ..telemetry.google_cloud import get_gcp_exporters
from ..telemetry.google_cloud import get_gcp_resource
from ..telemetry.setup import maybe_set_otel_providers
credentials, project_id = google.auth.default()
otel_hooks_to_add.append(
get_gcp_exporters(
# TODO - use trace_to_cloud here as well once otel_to_cloud is no
# longer experimental.
enable_cloud_tracing=True,
# TODO - reenable metrics once errors during shutdown are fixed.
enable_cloud_metrics=False,
enable_cloud_logging=True,
google_auth=(credentials, project_id),
)
)
otel_resource = get_gcp_resource(project_id)
maybe_set_otel_providers(
otel_hooks_to_setup=otel_hooks_to_add,
otel_resource=otel_resource,
)
_setup_instrumentation_lib_if_installed()
def _setup_telemetry_from_env(
internal_exporters: list[SpanProcessor] = None,
):
from ..telemetry.setup import maybe_set_otel_providers
otel_hooks_to_add = []
if internal_exporters:
from ..telemetry.setup import OTelHooks
# Register ADK-specific exporters in trace provider.
otel_hooks_to_add.append(OTelHooks(span_processors=internal_exporters))
maybe_set_otel_providers(otel_hooks_to_setup=otel_hooks_to_add)
_setup_instrumentation_lib_if_installed()
def _setup_instrumentation_lib_if_installed():
# Set instrumentation to enable emitting OTel data from GenAISDK
# Currently the instrumentation lib is in extras dependencies, make sure to
# warn the user if it's not installed.
try:
from opentelemetry.instrumentation.google_genai import GoogleGenAiSdkInstrumentor
GoogleGenAiSdkInstrumentor().instrument()
except ImportError:
logger.warning(
"Unable to import GoogleGenAiSdkInstrumentor - some"
" telemetry will be disabled. Make sure to install google-adk[otel-gcp]"
)
class AdkWebServer:
"""Helper class for setting up and running the ADK web server on FastAPI.
You construct this class with all the Services required to run ADK agents and
can then call the get_fast_api_app method to get a FastAPI app instance that
can will use your provided service instances, static assets, and agent loader.
If you pass in a web_assets_dir, the static assets will be served under
/dev-ui in addition to the API endpoints created by default.
You can add additional API endpoints by modifying the FastAPI app
instance returned by get_fast_api_app as this class exposes the agent runners
and most other bits of state retained during the lifetime of the server.
Attributes:
agent_loader: An instance of BaseAgentLoader for loading agents.
session_service: An instance of BaseSessionService for managing sessions.
memory_service: An instance of BaseMemoryService for managing memory.
artifact_service: An instance of BaseArtifactService for managing
artifacts.
credential_service: An instance of BaseCredentialService for managing
credentials.
eval_sets_manager: An instance of EvalSetsManager for managing evaluation
sets.
eval_set_results_manager: An instance of EvalSetResultsManager for
managing evaluation set results.
agents_dir: Root directory containing subdirs for agents with those
containing resources (e.g. .env files, eval sets, etc.) for the agents.
extra_plugins: A list of fully qualified names of extra plugins to load.
logo_text: Text to display in the logo of the UI.
logo_image_url: URL of an image to display as logo of the UI.
runners_to_clean: Set of runner names marked for cleanup.
current_app_name_ref: A shared reference to the latest ran app name.
runner_dict: A dict of instantiated runners for each app.
"""
def __init__(
self,
*,
agent_loader: BaseAgentLoader,
session_service: BaseSessionService,
memory_service: BaseMemoryService,
artifact_service: BaseArtifactService,
credential_service: BaseCredentialService,
eval_sets_manager: EvalSetsManager,
eval_set_results_manager: EvalSetResultsManager,
agents_dir: str,
extra_plugins: Optional[list[str]] = None,
logo_text: Optional[str] = None,
logo_image_url: Optional[str] = None,
url_prefix: Optional[str] = None,
):
self.agent_loader = agent_loader
self.session_service = session_service
self.memory_service = memory_service
self.artifact_service = artifact_service
self.credential_service = credential_service
self.eval_sets_manager = eval_sets_manager
self.eval_set_results_manager = eval_set_results_manager
self.agents_dir = agents_dir
self.extra_plugins = extra_plugins or []
self.logo_text = logo_text
self.logo_image_url = logo_image_url
# Internal properties we want to allow being modified from callbacks.
self.runners_to_clean: set[str] = set()
self.current_app_name_ref: SharedValue[str] = SharedValue(value="")
self.runner_dict = {}
self.url_prefix = url_prefix
async def get_runner_async(self, app_name: str) -> Runner:
"""Returns the cached runner for the given app."""
# Handle cleanup
if app_name in self.runners_to_clean:
self.runners_to_clean.remove(app_name)
runner = self.runner_dict.pop(app_name, None)
await cleanup.close_runners(list([runner]))
# Return cached runner if exists
if app_name in self.runner_dict:
return self.runner_dict[app_name]
# Create new runner
envs.load_dotenv_for_agent(os.path.basename(app_name), self.agents_dir)
agent_or_app = self.agent_loader.load_agent(app_name)
# Instantiate extra plugins if configured
extra_plugins_instances = self._instantiate_extra_plugins()
if isinstance(agent_or_app, BaseAgent):
agentic_app = App(
name=app_name,
root_agent=agent_or_app,
plugins=extra_plugins_instances,
)
else:
# Combine existing plugins with extra plugins
agent_or_app.plugins = agent_or_app.plugins + extra_plugins_instances
agentic_app = agent_or_app
runner = self._create_runner(agentic_app)
self.runner_dict[app_name] = runner
return runner
def _get_root_agent(self, agent_or_app: BaseAgent | App) -> BaseAgent:
"""Extract root agent from either a BaseAgent or App object."""
if isinstance(agent_or_app, App):
return agent_or_app.root_agent
return agent_or_app
def _create_runner(self, agentic_app: App) -> Runner:
"""Create a runner with common services."""
return Runner(
app=agentic_app,
artifact_service=self.artifact_service,
session_service=self.session_service,
memory_service=self.memory_service,
credential_service=self.credential_service,
)
def _instantiate_extra_plugins(self) -> list[BasePlugin]:
"""Instantiate extra plugins from the configured list.
Returns:
List of instantiated BasePlugin objects.
"""
extra_plugins_instances = []
for qualified_name in self.extra_plugins:
try:
plugin_obj = self._import_plugin_object(qualified_name)
if isinstance(plugin_obj, BasePlugin):
extra_plugins_instances.append(plugin_obj)
elif issubclass(plugin_obj, BasePlugin):
extra_plugins_instances.append(plugin_obj(name=qualified_name))
except Exception as e:
logger.error("Failed to load plugin %s: %s", qualified_name, e)
return extra_plugins_instances
def _import_plugin_object(self, qualified_name: str) -> Any:
"""Import a plugin object (class or instance) from a fully qualified name.
Args:
qualified_name: Fully qualified name (e.g., 'my_package.my_plugin.MyPlugin')
Returns:
The imported object, which can be either a class or an instance.
Raises:
ImportError: If the module cannot be imported.
AttributeError: If the object doesn't exist in the module.
"""
module_name, obj_name = qualified_name.rsplit(".", 1)
module = importlib.import_module(module_name)
return getattr(module, obj_name)
def _setup_runtime_config(self, web_assets_dir: str):
"""Sets up the runtime config for the web server."""
# Read existing runtime config file.
runtime_config_path = os.path.join(
web_assets_dir, "assets", "config", "runtime-config.json"
)
runtime_config = {}
try:
with open(runtime_config_path, "r") as f:
runtime_config = json.load(f)
except FileNotFoundError:
logger.info(
"File not found: %s. A new runtime config file will be created.",
runtime_config_path,
)
except json.JSONDecodeError:
logger.warning(
"Failed to decode JSON from %s. The file content will be"
" overwritten.",
runtime_config_path,
)
runtime_config["backendUrl"] = self.url_prefix if self.url_prefix else ""
# Set custom logo config.
if self.logo_text or self.logo_image_url:
if not self.logo_text or not self.logo_image_url:
raise ValueError(
"Both --logo-text and --logo-image-url must be defined when using"
" logo config."
)
runtime_config["logo"] = {
"text": self.logo_text,
"imageUrl": self.logo_image_url,
}
elif "logo" in runtime_config:
del runtime_config["logo"]
# Write the runtime config file.
try:
os.makedirs(os.path.dirname(runtime_config_path), exist_ok=True)
with open(runtime_config_path, "w") as f:
json.dump(runtime_config, f, indent=2)
except IOError as e:
logger.error(
"Failed to write runtime config file %s: %s", runtime_config_path, e
)
async def _create_session(
self,
*,
app_name: str,
user_id: str,
session_id: Optional[str] = None,
state: Optional[dict[str, Any]] = None,
) -> Session:
try:
session = await self.session_service.create_session(
app_name=app_name,
user_id=user_id,
state=state,
session_id=session_id,
)
logger.info("New session created: %s", session.id)
return session
except AlreadyExistsError as e:
raise HTTPException(
status_code=409, detail=f"Session already exists: {session_id}"
) from e
except Exception as e:
logger.error(
"Internal server error during session creation: %s", e, exc_info=True
)
raise HTTPException(status_code=500, detail=str(e)) from e
def get_fast_api_app(
self,
lifespan: Optional[Lifespan[FastAPI]] = None,
allow_origins: Optional[list[str]] = None,
web_assets_dir: Optional[str] = None,
setup_observer: Callable[
[Observer, "AdkWebServer"], None
] = lambda o, s: None,
tear_down_observer: Callable[
[Observer, "AdkWebServer"], None
] = lambda o, s: None,
register_processors: Callable[[TracerProvider], None] = lambda o: None,
otel_to_cloud: bool = False,
):
"""Creates a FastAPI app for the ADK web server.
By default it'll just return a FastAPI instance with the API server
endpoints,
but if you specify a web_assets_dir, it'll also serve the static web assets
from that directory.
Args:
lifespan: The lifespan of the FastAPI app.
allow_origins: The origins that are allowed to make cross-origin requests.
Entries can be literal origins (e.g., 'https://example.com') or regex
patterns prefixed with 'regex:' (e.g., 'regex:https://.*\\.example\\.com').
web_assets_dir: The directory containing the web assets to serve.
setup_observer: Callback for setting up the file system observer.
tear_down_observer: Callback for cleaning up the file system observer.
register_processors: Callback for additional Span processors to be added
to the TracerProvider.
otel_to_cloud: Whether to enable Cloud Trace and Cloud Logging
integrations.
Returns:
A FastAPI app instance.
"""
# Properties we don't need to modify from callbacks
trace_dict = {}
session_trace_dict = {}
# Set up a file system watcher to detect changes in the agents directory.
observer = Observer()
setup_observer(observer, self)
@asynccontextmanager
async def internal_lifespan(app: FastAPI):
try:
if lifespan:
async with lifespan(app) as lifespan_context:
yield lifespan_context
else:
yield
finally:
tear_down_observer(observer, self)
# Create tasks for all runner closures to run concurrently
await cleanup.close_runners(list(self.runner_dict.values()))
memory_exporter = InMemoryExporter(session_trace_dict)
_setup_telemetry(
otel_to_cloud=otel_to_cloud,
internal_exporters=[
export_lib.SimpleSpanProcessor(ApiServerSpanExporter(trace_dict)),
export_lib.SimpleSpanProcessor(memory_exporter),
],
)
if web_assets_dir:
self._setup_runtime_config(web_assets_dir)
# TODO - register_processors to be removed once --otel_to_cloud is no
# longer experimental.
tracer_provider = trace.get_tracer_provider()
register_processors(tracer_provider)
# Run the FastAPI server.
app = FastAPI(lifespan=internal_lifespan)
if allow_origins:
literal_origins, combined_regex = _parse_cors_origins(allow_origins)
app.add_middleware(
CORSMiddleware,
allow_origins=literal_origins,
allow_origin_regex=combined_regex,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/list-apps")
async def list_apps(
detailed: bool = Query(
default=False, description="Return detailed app information"
)
) -> list[str] | ListAppsResponse:
if detailed:
apps_info = self.agent_loader.list_agents_detailed()
return ListAppsResponse(apps=[AppInfo(**app) for app in apps_info])
return self.agent_loader.list_agents()
@app.get("/debug/trace/{event_id}", tags=[TAG_DEBUG])
async def get_trace_dict(event_id: str) -> Any:
event_dict = trace_dict.get(event_id, None)
if event_dict is None:
raise HTTPException(status_code=404, detail="Trace not found")
return event_dict
@app.get("/debug/trace/session/{session_id}", tags=[TAG_DEBUG])
async def get_session_trace(session_id: str) -> Any:
spans = memory_exporter.get_finished_spans(session_id)
if not spans:
return []
return [
{
"name": s.name,
"span_id": s.context.span_id,
"trace_id": s.context.trace_id,
"start_time": s.start_time,
"end_time": s.end_time,
"attributes": dict(s.attributes),
"parent_span_id": s.parent.span_id if s.parent else None,
}
for s in spans
]
@app.get(
"/apps/{app_name}/users/{user_id}/sessions/{session_id}",
response_model_exclude_none=True,
)
async def get_session(
app_name: str, user_id: str, session_id: str
) -> Session:
session = await self.session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
self.current_app_name_ref.value = app_name
return session
@app.get(
"/apps/{app_name}/users/{user_id}/sessions",
response_model_exclude_none=True,
)
async def list_sessions(app_name: str, user_id: str) -> list[Session]:
list_sessions_response = await self.session_service.list_sessions(
app_name=app_name, user_id=user_id
)
return [
session
for session in list_sessions_response.sessions
# Remove sessions that were generated as a part of Eval.
if not session.id.startswith(EVAL_SESSION_ID_PREFIX)
]
@deprecated(
"Please use create_session instead. This will be removed in future"
" releases."
)
@app.post(
"/apps/{app_name}/users/{user_id}/sessions/{session_id}",
response_model_exclude_none=True,
)
async def create_session_with_id(
app_name: str,
user_id: str,
session_id: str,
state: Optional[dict[str, Any]] = None,
) -> Session:
return await self._create_session(
app_name=app_name,
user_id=user_id,
state=state,
session_id=session_id,
)
@app.post(
"/apps/{app_name}/users/{user_id}/sessions",
response_model_exclude_none=True,
)
async def create_session(
app_name: str,
user_id: str,
req: Optional[CreateSessionRequest] = None,
) -> Session:
if not req:
return await self._create_session(app_name=app_name, user_id=user_id)
session = await self._create_session(
app_name=app_name,
user_id=user_id,
state=req.state,
session_id=req.session_id,
)
if req.events:
for event in req.events:
await self.session_service.append_event(session=session, event=event)
return session
@app.delete("/apps/{app_name}/users/{user_id}/sessions/{session_id}")
async def delete_session(
app_name: str, user_id: str, session_id: str
) -> None:
await self.session_service.delete_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
@app.patch(
"/apps/{app_name}/users/{user_id}/sessions/{session_id}",
response_model_exclude_none=True,
)
async def update_session(
app_name: str,
user_id: str,
session_id: str,
req: UpdateSessionRequest,
) -> Session:
"""Updates session state without running the agent.
Args:
app_name: The name of the application.
user_id: The ID of the user.
session_id: The ID of the session to update.
req: The patch request containing state changes.
Returns:
The updated session.
Raises:
HTTPException: If the session is not found.
"""
session = await self.session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
# Create an event to record the state change
import uuid
from ..events.event import Event
from ..events.event import EventActions
state_update_event = Event(
invocation_id="p-" + str(uuid.uuid4()),
author="user",
actions=EventActions(state_delta=req.state_delta),
)
# Append the event to the session
# This will automatically update the session state through __update_session_state
await self.session_service.append_event(
session=session, event=state_update_event
)
return session
@app.post(
"/apps/{app_name}/eval-sets",
response_model_exclude_none=True,
tags=[TAG_EVALUATION],
)
async def create_eval_set(
app_name: str, create_eval_set_request: CreateEvalSetRequest
) -> EvalSet:
try:
return self.eval_sets_manager.create_eval_set(
app_name=app_name,
eval_set_id=create_eval_set_request.eval_set.eval_set_id,
)
except ValueError as ve:
raise HTTPException(
status_code=400,
detail=str(ve),
) from ve
@deprecated(
"Please use create_eval_set instead. This will be removed in future"
" releases."
)
@app.post(
"/apps/{app_name}/eval_sets/{eval_set_id}",
response_model_exclude_none=True,
tags=[TAG_EVALUATION],
)
async def create_eval_set_legacy(
app_name: str,
eval_set_id: str,
):
"""Creates an eval set, given the id."""
await create_eval_set(
app_name=app_name,
create_eval_set_request=CreateEvalSetRequest(
eval_set=EvalSet(eval_set_id=eval_set_id, eval_cases=[])
),
)
@app.get(
"/apps/{app_name}/eval-sets",
response_model_exclude_none=True,
tags=[TAG_EVALUATION],
)
async def list_eval_sets(app_name: str) -> ListEvalSetsResponse:
"""Lists all eval sets for the given app."""
eval_sets = []
try:
eval_sets = self.eval_sets_manager.list_eval_sets(app_name)
except NotFoundError as e:
logger.warning(e)
return ListEvalSetsResponse(eval_set_ids=eval_sets)
@deprecated(
"Please use list_eval_sets instead. This will be removed in future"
" releases."
)
@app.get(
"/apps/{app_name}/eval_sets",
response_model_exclude_none=True,
tags=[TAG_EVALUATION],
)
async def list_eval_sets_legacy(app_name: str) -> list[str]:
list_eval_sets_response = await list_eval_sets(app_name)
return list_eval_sets_response.eval_set_ids
@app.post(
"/apps/{app_name}/eval-sets/{eval_set_id}/add-session",
response_model_exclude_none=True,