forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_tools_click.py
More file actions
1859 lines (1669 loc) · 53.4 KB
/
cli_tools_click.py
File metadata and controls
1859 lines (1669 loc) · 53.4 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
from datetime import datetime
import functools
import hashlib
import json
import logging
import os
from pathlib import Path
import tempfile
import textwrap
from typing import Optional
import click
from click.core import ParameterSource
from fastapi import FastAPI
import uvicorn
from . import cli_create
from . import cli_deploy
from .. import version
from ..evaluation.constants import MISSING_EVAL_DEPENDENCIES_MESSAGE
from ..utils.env_utils import is_env_enabled
from .cli import run_cli
from .fast_api import get_fast_api_app
from .utils import envs
from .utils import evals
from .utils import logs
LOG_LEVELS = click.Choice(
["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
case_sensitive=False,
)
class HelpfulCommand(click.Command):
"""Command that shows full help on error instead of just the error message.
A custom Click Command class that overrides the default error handling
behavior to display the full help text when a required argument is missing,
followed by the error message. This provides users with better context
about command usage without needing to run a separate --help command.
Args:
*args: Variable length argument list to pass to the parent class.
**kwargs: Arbitrary keyword arguments to pass to the parent class.
Returns:
None. Inherits behavior from the parent Click Command class.
Returns:
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@staticmethod
def _format_missing_arg_error(click_exception):
"""Format the missing argument error with uppercase parameter name.
Args:
click_exception: The MissingParameter exception from Click.
Returns:
str: Formatted error message with uppercase parameter name.
"""
name = click_exception.param.name
return f"Missing required argument: {name.upper()}"
def parse_args(self, ctx, args):
"""Override the parse_args method to show help text on error.
Args:
ctx: Click context object for the current command.
args: List of command-line arguments to parse.
Returns:
The parsed arguments as returned by the parent class's parse_args method.
Raises:
click.MissingParameter: When a required parameter is missing, but this
is caught and handled by displaying the help text before exiting.
"""
try:
return super().parse_args(ctx, args)
except click.MissingParameter as exc:
error_message = self._format_missing_arg_error(exc)
click.echo(ctx.get_help())
click.secho(f"\nError: {error_message}", fg="red", err=True)
ctx.exit(2)
logger = logging.getLogger("google_adk." + __name__)
_ADK_WEB_WARNING = (
"ADK Web is for development purposes. It has access to all data and"
" should not be used in production."
)
def _warn_if_with_ui(with_ui: bool) -> None:
"""Warn when deploying with the developer UI enabled."""
if with_ui:
click.secho(f"WARNING: {_ADK_WEB_WARNING}", fg="yellow", err=True)
@click.group(context_settings={"max_content_width": 240})
@click.version_option(version.__version__)
def main():
"""Agent Development Kit CLI tools."""
pass
@main.group()
def deploy():
"""Deploys agent to hosted environments."""
pass
@main.group()
def conformance():
"""Conformance testing tools for ADK."""
pass
@conformance.command("record", cls=HelpfulCommand)
@click.argument(
"paths",
nargs=-1,
type=click.Path(
exists=True, dir_okay=True, file_okay=False, resolve_path=True
),
)
@click.pass_context
def cli_conformance_record(
ctx,
paths: tuple[str, ...],
):
"""Generate ADK conformance test YAML files from TestCaseInput specifications.
NOTE: this is work in progress.
This command reads TestCaseInput specifications from input.yaml files,
executes the specified test cases against agents, and generates conformance
test files with recorded agent interactions as test.yaml files.
Expected directory structure:
category/name/input.yaml (TestCaseInput) -> category/name/test.yaml (TestCase)
PATHS: One or more directories containing test case specifications.
If no paths are provided, defaults to 'tests/' directory.
Examples:
Use default directory: adk conformance record
Custom directories: adk conformance record tests/core tests/tools
"""
try:
from .conformance.cli_record import run_conformance_record
except ImportError as e:
click.secho(
f"Error: Missing conformance testing dependencies: {e}",
fg="red",
err=True,
)
click.secho(
"Please install the required conformance testing package dependencies.",
fg="yellow",
err=True,
)
ctx.exit(1)
# Default to tests/ directory if no paths provided
test_paths = [Path(p) for p in paths] if paths else [Path("tests").resolve()]
asyncio.run(run_conformance_record(test_paths))
@conformance.command("test", cls=HelpfulCommand)
@click.argument(
"paths",
nargs=-1,
type=click.Path(
exists=True, file_okay=False, dir_okay=True, resolve_path=True
),
)
@click.option(
"--mode",
type=click.Choice(["replay", "live"], case_sensitive=False),
default="replay",
show_default=True,
help=(
"Test mode: 'replay' verifies against recorded interactions, 'live'"
" runs evaluation-based verification."
),
)
@click.pass_context
def cli_conformance_test(
ctx,
paths: tuple[str, ...],
mode: str,
):
"""Run conformance tests to verify agent behavior consistency.
Validates that agents produce consistent outputs by comparing against recorded
interactions or evaluating live execution results.
PATHS can be any number of folder paths. Each folder can either:
- Contain a spec.yaml file directly (single test case)
- Contain subdirectories with spec.yaml files (multiple test cases)
If no paths are provided, defaults to searching the 'tests' folder.
TEST MODES:
\b
replay : Verifies agent interactions match previously recorded behaviors
exactly. Compares LLM requests/responses and tool calls/results.
live : Runs evaluation-based verification (not yet implemented)
DIRECTORY STRUCTURE:
Test cases must follow this structure:
\b
category/
test_name/
spec.yaml # Test specification
generated-recordings.yaml # Recorded interactions (replay mode)
generated-session.yaml # Session data (replay mode)
EXAMPLES:
\b
# Run all tests in current directory's 'tests' folder
adk conformance test
\b
# Run tests from specific folders
adk conformance test tests/core tests/tools
\b
# Run a single test case
adk conformance test tests/core/description_001
\b
# Run in live mode (when available)
adk conformance test --mode=live tests/core
"""
try:
from .conformance.cli_test import run_conformance_test
except ImportError as e:
click.secho(
f"Error: Missing conformance testing dependencies: {e}",
fg="red",
err=True,
)
click.secho(
"Please install the required conformance testing package dependencies.",
fg="yellow",
err=True,
)
ctx.exit(1)
# Convert to Path objects, use default if empty (paths are already resolved by Click)
test_paths = [Path(p) for p in paths] if paths else [Path("tests").resolve()]
asyncio.run(run_conformance_test(test_paths=test_paths, mode=mode.lower()))
@main.command("create", cls=HelpfulCommand)
@click.option(
"--model",
type=str,
help="Optional. The model used for the root agent.",
)
@click.option(
"--api_key",
type=str,
help=(
"Optional. The API Key needed to access the model, e.g. Google AI API"
" Key."
),
)
@click.option(
"--project",
type=str,
help="Optional. The Google Cloud Project for using VertexAI as backend.",
)
@click.option(
"--region",
type=str,
help="Optional. The Google Cloud Region for using VertexAI as backend.",
)
@click.option(
"--type",
type=click.Choice(["CODE", "CONFIG"], case_sensitive=False),
help=(
"EXPERIMENTAL Optional. Type of agent to create: 'config' or 'code'."
" 'config' is not ready for use so it defaults to 'code'. It may change"
" later once 'config' is ready for use."
),
default="CODE",
show_default=True,
hidden=True, # Won't show in --help output. Not ready for use.
)
@click.argument("app_name", type=str, required=True)
def cli_create_cmd(
app_name: str,
model: Optional[str],
api_key: Optional[str],
project: Optional[str],
region: Optional[str],
type: Optional[str],
):
"""Creates a new app in the current folder with prepopulated agent template.
APP_NAME: required, the folder of the agent source code.
Example:
adk create path/to/my_app
"""
cli_create.run_cmd(
app_name,
model=model,
google_api_key=api_key,
google_cloud_project=project,
google_cloud_region=region,
type=type,
)
def validate_exclusive(ctx, param, value):
# Store the validated parameters in the context
if not hasattr(ctx, "exclusive_opts"):
ctx.exclusive_opts = {}
# If this option has a value and we've already seen another exclusive option
if value is not None and any(ctx.exclusive_opts.values()):
exclusive_opt = next(key for key, val in ctx.exclusive_opts.items() if val)
raise click.UsageError(
f"Options '{param.name}' and '{exclusive_opt}' cannot be set together."
)
# Record this option's value
ctx.exclusive_opts[param.name] = value is not None
return value
def adk_services_options():
"""Decorator to add ADK services options to click commands."""
def decorator(func):
@click.option(
"--session_service_uri",
help=textwrap.dedent(
"""\
Optional. The URI of the session service.
- Leave unset to use the in-memory session service (default).
- Use 'agentengine://<agent_engine>' to connect to Agent Engine
sessions. <agent_engine> can either be the full qualified resource
name 'projects/abc/locations/us-central1/reasoningEngines/123' or
the resource id '123'.
- Use 'memory://' to run with the in-memory session service.
- Use 'sqlite://<path_to_sqlite_file>' to connect to a SQLite DB.
- See https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls for more details on supported database URIs."""
),
)
@click.option(
"--artifact_service_uri",
type=str,
help=textwrap.dedent(
"""\
Optional. The URI of the artifact service.
- Leave unset to store artifacts under '.adk/artifacts' locally.
- Use 'gs://<bucket_name>' to connect to the GCS artifact service.
- Use 'memory://' to force the in-memory artifact service.
- Use 'file://<path>' to store artifacts in a custom local directory."""
),
default=None,
)
@click.option(
"--memory_service_uri",
type=str,
help=textwrap.dedent("""\
Optional. The URI of the memory service.
- Use 'rag://<rag_corpus_id>' to connect to Vertex AI Rag Memory Service.
- Use 'agentengine://<agent_engine>' to connect to Agent Engine
sessions. <agent_engine> can either be the full qualified resource
name 'projects/abc/locations/us-central1/reasoningEngines/123' or
the resource id '123'.
- Use 'memory://' to force the in-memory memory service."""),
default=None,
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
@main.command("run", cls=HelpfulCommand)
@adk_services_options()
@click.option(
"--save_session",
type=bool,
is_flag=True,
show_default=True,
default=False,
help="Optional. Whether to save the session to a json file on exit.",
)
@click.option(
"--session_id",
type=str,
help=(
"Optional. The session ID to save the session to on exit when"
" --save_session is set to true. User will be prompted to enter a"
" session ID if not set."
),
)
@click.option(
"--replay",
type=click.Path(
exists=True, dir_okay=False, file_okay=True, resolve_path=True
),
help=(
"The json file that contains the initial state of the session and user"
" queries. A new session will be created using this state. And user"
" queries are run against the newly created session. Users cannot"
" continue to interact with the agent."
),
callback=validate_exclusive,
)
@click.option(
"--resume",
type=click.Path(
exists=True, dir_okay=False, file_okay=True, resolve_path=True
),
help=(
"The json file that contains a previously saved session (by"
" --save_session option). The previous session will be re-displayed."
" And user can continue to interact with the agent."
),
callback=validate_exclusive,
)
@click.argument(
"agent",
type=click.Path(
exists=True, dir_okay=True, file_okay=False, resolve_path=True
),
)
def cli_run(
agent: str,
save_session: bool,
session_id: Optional[str],
replay: Optional[str],
resume: Optional[str],
session_service_uri: Optional[str] = None,
artifact_service_uri: Optional[str] = None,
memory_service_uri: Optional[str] = None,
):
"""Runs an interactive CLI for a certain agent.
AGENT: The path to the agent source code folder.
Example:
adk run path/to/my_agent
"""
logs.log_to_tmp_folder()
# Validation warning for memory_service_uri (not supported for adk run)
if memory_service_uri:
click.secho(
"WARNING: --memory_service_uri is not supported for adk run.",
fg="yellow",
err=True,
)
agent_parent_folder = os.path.dirname(agent)
agent_folder_name = os.path.basename(agent)
asyncio.run(
run_cli(
agent_parent_dir=agent_parent_folder,
agent_folder_name=agent_folder_name,
input_file=replay,
saved_session_file=resume,
save_session=save_session,
session_id=session_id,
session_service_uri=session_service_uri,
artifact_service_uri=artifact_service_uri,
)
)
def eval_options():
"""Decorator to add common eval options to click commands."""
def decorator(func):
@click.option(
"--eval_storage_uri",
type=str,
help=(
"Optional. The evals storage URI to store agent evals,"
" supported URIs: gs://<bucket name>."
),
default=None,
)
@click.option(
"--log_level",
type=LOG_LEVELS,
default="INFO",
help="Optional. Set the logging level",
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
@main.command("eval", cls=HelpfulCommand)
@click.argument(
"agent_module_file_path",
type=click.Path(
exists=True, dir_okay=True, file_okay=False, resolve_path=True
),
)
@click.argument("eval_set_file_path_or_id", nargs=-1)
@click.option("--config_file_path", help="Optional. The path to config file.")
@click.option(
"--print_detailed_results",
is_flag=True,
show_default=True,
default=False,
help="Optional. Whether to print detailed results on console or not.",
)
@eval_options()
def cli_eval(
agent_module_file_path: str,
eval_set_file_path_or_id: list[str],
config_file_path: str,
print_detailed_results: bool,
eval_storage_uri: Optional[str] = None,
log_level: str = "INFO",
):
"""Evaluates an agent given the eval sets.
AGENT_MODULE_FILE_PATH: The path to the __init__.py file that contains a
module by the name "agent". "agent" module contains a root_agent.
EVAL_SET_FILE_PATH_OR_ID: You can specify one or more eval set file paths or
eval set id.
Mixing of eval set file paths with eval set ids is not allowed.
*Eval Set File Path*
For each file, all evals will be run by default.
If you want to run only specific evals from an eval set, first create a comma
separated list of eval names and then add that as a suffix to the eval set
file name, demarcated by a `:`.
For example, we have `sample_eval_set_file.json` file that has following the
eval cases:
sample_eval_set_file.json:
|....... eval_1
|....... eval_2
|....... eval_3
|....... eval_4
|....... eval_5
sample_eval_set_file.json:eval_1,eval_2,eval_3
This will only run eval_1, eval_2 and eval_3 from sample_eval_set_file.json.
*Eval Set ID*
For each eval set, all evals will be run by default.
If you want to run only specific evals from an eval set, first create a comma
separated list of eval names and then add that as a suffix to the eval set
file name, demarcated by a `:`.
For example, we have `sample_eval_set_id` that has following the eval cases:
sample_eval_set_id:
|....... eval_1
|....... eval_2
|....... eval_3
|....... eval_4
|....... eval_5
If we did:
sample_eval_set_id:eval_1,eval_2,eval_3
This will only run eval_1, eval_2 and eval_3 from sample_eval_set_id.
CONFIG_FILE_PATH: The path to config file.
PRINT_DETAILED_RESULTS: Prints detailed results on the console.
"""
if not is_env_enabled("ADK_DISABLE_LOAD_DOTENV"):
envs.load_dotenv_for_agent(agent_module_file_path, ".")
logs.setup_adk_logger(getattr(logging, log_level.upper()))
try:
from ..evaluation.base_eval_service import InferenceConfig
from ..evaluation.base_eval_service import InferenceRequest
from ..evaluation.eval_config import get_eval_metrics_from_config
from ..evaluation.eval_config import get_evaluation_criteria_or_default
from ..evaluation.eval_result import EvalCaseResult
from ..evaluation.evaluator import EvalStatus
from ..evaluation.in_memory_eval_sets_manager import InMemoryEvalSetsManager
from ..evaluation.local_eval_service import LocalEvalService
from ..evaluation.local_eval_set_results_manager import LocalEvalSetResultsManager
from ..evaluation.local_eval_sets_manager import load_eval_set_from_file
from ..evaluation.local_eval_sets_manager import LocalEvalSetsManager
from ..evaluation.simulation.user_simulator_provider import UserSimulatorProvider
from .cli_eval import _collect_eval_results
from .cli_eval import _collect_inferences
from .cli_eval import get_root_agent
from .cli_eval import parse_and_get_evals_to_run
from .cli_eval import pretty_print_eval_result
except ModuleNotFoundError as mnf:
raise click.ClickException(MISSING_EVAL_DEPENDENCIES_MESSAGE) from mnf
eval_config = get_evaluation_criteria_or_default(config_file_path)
print(f"Using evaluation criteria: {eval_config}")
eval_metrics = get_eval_metrics_from_config(eval_config)
root_agent = get_root_agent(agent_module_file_path)
app_name = os.path.basename(agent_module_file_path)
agents_dir = os.path.dirname(agent_module_file_path)
eval_sets_manager = None
eval_set_results_manager = None
if eval_storage_uri:
gcs_eval_managers = evals.create_gcs_eval_managers_from_uri(
eval_storage_uri
)
eval_sets_manager = gcs_eval_managers.eval_sets_manager
eval_set_results_manager = gcs_eval_managers.eval_set_results_manager
else:
eval_set_results_manager = LocalEvalSetResultsManager(agents_dir=agents_dir)
inference_requests = []
eval_set_file_or_id_to_evals = parse_and_get_evals_to_run(
eval_set_file_path_or_id
)
# Check if the first entry is a file that exists, if it does then we assume
# rest of the entries are also files. We enforce this assumption in the if
# block.
if eval_set_file_or_id_to_evals and os.path.exists(
list(eval_set_file_or_id_to_evals.keys())[0]
):
eval_sets_manager = InMemoryEvalSetsManager()
# Read the eval_set files and get the cases.
for (
eval_set_file_path,
eval_case_ids,
) in eval_set_file_or_id_to_evals.items():
try:
eval_set = load_eval_set_from_file(
eval_set_file_path, eval_set_file_path
)
except FileNotFoundError as fne:
raise click.ClickException(
f"`{eval_set_file_path}` should be a valid eval set file."
) from fne
eval_sets_manager.create_eval_set(
app_name=app_name, eval_set_id=eval_set.eval_set_id
)
for eval_case in eval_set.eval_cases:
eval_sets_manager.add_eval_case(
app_name=app_name,
eval_set_id=eval_set.eval_set_id,
eval_case=eval_case,
)
inference_requests.append(
InferenceRequest(
app_name=app_name,
eval_set_id=eval_set.eval_set_id,
eval_case_ids=eval_case_ids,
inference_config=InferenceConfig(),
)
)
else:
# We assume that what we have are eval set ids instead.
eval_sets_manager = (
eval_sets_manager
if eval_storage_uri
else LocalEvalSetsManager(agents_dir=agents_dir)
)
for eval_set_id_key, eval_case_ids in eval_set_file_or_id_to_evals.items():
inference_requests.append(
InferenceRequest(
app_name=app_name,
eval_set_id=eval_set_id_key,
eval_case_ids=eval_case_ids,
inference_config=InferenceConfig(),
)
)
user_simulator_provider = UserSimulatorProvider(
user_simulator_config=eval_config.user_simulator_config
)
try:
eval_service = LocalEvalService(
root_agent=root_agent,
eval_sets_manager=eval_sets_manager,
eval_set_results_manager=eval_set_results_manager,
user_simulator_provider=user_simulator_provider,
)
inference_results = asyncio.run(
_collect_inferences(
inference_requests=inference_requests, eval_service=eval_service
)
)
eval_results = asyncio.run(
_collect_eval_results(
inference_results=inference_results,
eval_service=eval_service,
eval_metrics=eval_metrics,
)
)
except ModuleNotFoundError as mnf:
raise click.ClickException(MISSING_EVAL_DEPENDENCIES_MESSAGE) from mnf
click.echo(
"*********************************************************************"
)
eval_run_summary = {}
for eval_result in eval_results:
eval_result: EvalCaseResult
if eval_result.eval_set_id not in eval_run_summary:
eval_run_summary[eval_result.eval_set_id] = [0, 0]
if eval_result.final_eval_status == EvalStatus.PASSED:
eval_run_summary[eval_result.eval_set_id][0] += 1
else:
eval_run_summary[eval_result.eval_set_id][1] += 1
click.echo("Eval Run Summary")
for eval_set_id, pass_fail_count in eval_run_summary.items():
click.echo(
f"{eval_set_id}:\n Tests passed: {pass_fail_count[0]}\n Tests"
f" failed: {pass_fail_count[1]}"
)
if print_detailed_results:
for eval_result in eval_results:
eval_result: EvalCaseResult
click.echo(
"********************************************************************"
)
pretty_print_eval_result(eval_result)
@main.group("eval_set")
def eval_set():
"""Manage Eval Sets."""
pass
@eval_set.command("create", cls=HelpfulCommand)
@click.argument(
"agent_module_file_path",
type=click.Path(
exists=True, dir_okay=True, file_okay=False, resolve_path=True
),
)
@click.argument("eval_set_id", type=str, required=True)
@eval_options()
def cli_create_eval_set(
agent_module_file_path: str,
eval_set_id: str,
eval_storage_uri: Optional[str] = None,
log_level: str = "INFO",
):
"""Creates an empty EvalSet given the agent_module_file_path and eval_set_id."""
from .cli_eval import get_eval_sets_manager
logs.setup_adk_logger(getattr(logging, log_level.upper()))
app_name = os.path.basename(agent_module_file_path)
agents_dir = os.path.dirname(agent_module_file_path)
eval_sets_manager = get_eval_sets_manager(eval_storage_uri, agents_dir)
try:
eval_sets_manager.create_eval_set(
app_name=app_name, eval_set_id=eval_set_id
)
click.echo(f"Eval set '{eval_set_id}' created for app '{app_name}'.")
except ValueError as e:
raise click.ClickException(str(e))
@eval_set.command("add_eval_case", cls=HelpfulCommand)
@click.argument(
"agent_module_file_path",
type=click.Path(
exists=True, dir_okay=True, file_okay=False, resolve_path=True
),
)
@click.argument("eval_set_id", type=str, required=True)
@click.option(
"--scenarios_file",
type=click.Path(
exists=True, dir_okay=False, file_okay=True, resolve_path=True
),
help="A path to file containing JSON serialized ConversationScenarios.",
required=True,
)
@click.option(
"--session_input_file",
type=click.Path(
exists=True, dir_okay=False, file_okay=True, resolve_path=True
),
help="Path to session file containing SessionInput in JSON format.",
required=True,
)
@eval_options()
def cli_add_eval_case(
agent_module_file_path: str,
eval_set_id: str,
scenarios_file: str,
eval_storage_uri: Optional[str] = None,
session_input_file: Optional[str] = None,
log_level: str = "INFO",
):
"""Adds eval cases to the given eval set.
There are several ways that an eval case can be created, for now this method
only supports adding one using a conversation scenarios file.
If an eval case for the generated id already exists, then we skip adding it.
"""
logs.setup_adk_logger(getattr(logging, log_level.upper()))
try:
from ..evaluation.conversation_scenarios import ConversationScenarios
from ..evaluation.eval_case import EvalCase
from ..evaluation.eval_case import SessionInput
from .cli_eval import get_eval_sets_manager
except ModuleNotFoundError as mnf:
raise click.ClickException(MISSING_EVAL_DEPENDENCIES_MESSAGE) from mnf
app_name = os.path.basename(agent_module_file_path)
agents_dir = os.path.dirname(agent_module_file_path)
eval_sets_manager = get_eval_sets_manager(eval_storage_uri, agents_dir)
try:
with open(session_input_file, "r") as f:
session_input = SessionInput.model_validate_json(f.read())
with open(scenarios_file, "r") as f:
conversation_scenarios = ConversationScenarios.model_validate_json(
f.read()
)
for scenario in conversation_scenarios.scenarios:
scenario_str = json.dumps(scenario.model_dump(), sort_keys=True)
eval_id = hashlib.sha256(scenario_str.encode("utf-8")).hexdigest()[:8]
eval_case = EvalCase(
eval_id=eval_id,
conversation_scenario=scenario,
session_input=session_input,
creation_timestamp=datetime.now().timestamp(),
)
if (
eval_sets_manager.get_eval_case(
app_name=app_name, eval_set_id=eval_set_id, eval_case_id=eval_id
)
is None
):
eval_sets_manager.add_eval_case(
app_name=app_name, eval_set_id=eval_set_id, eval_case=eval_case
)
click.echo(
f"Eval case '{eval_case.eval_id}' added to eval set"
f" '{eval_set_id}'."
)
else:
click.echo(
f"Eval case '{eval_case.eval_id}' already exists in eval set"
f" '{eval_set_id}', skipped adding."
)
except Exception as e:
raise click.ClickException(f"Failed to add eval case(s): {e}") from e
def web_options():
"""Decorator to add web UI options to click commands."""
def decorator(func):
@click.option(
"--logo-text",
type=str,
help="Optional. The text to display in the logo of the web UI.",
default=None,
)
@click.option(
"--logo-image-url",
type=str,
help=(
"Optional. The URL of the image to display in the logo of the"
" web UI."
),
default=None,
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def deprecated_adk_services_options():
"""Deprecated ADK services options."""
def warn(alternative_param, ctx, param, value):
if value:
click.echo(
click.style(
f"WARNING: Deprecated option --{param.name} is used. Please use"
f" {alternative_param} instead.",
fg="yellow",
),
err=True,
)
return value
def decorator(func):
@click.option(
"--session_db_url",
help="Deprecated. Use --session_service_uri instead.",
callback=functools.partial(warn, "--session_service_uri"),
)
@click.option(
"--artifact_storage_uri",
type=str,
help="Deprecated. Use --artifact_service_uri instead.",
callback=functools.partial(warn, "--artifact_service_uri"),
default=None,
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
def fast_api_common_options():
"""Decorator to add common fast api options to click commands."""
def decorator(func):
@click.option(
"--host",
type=str,
help="Optional. The binding host of the server",
default="127.0.0.1",
show_default=True,
)
@click.option(
"--port",