forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluation_generator.py
More file actions
253 lines (212 loc) · 8.32 KB
/
evaluation_generator.py
File metadata and controls
253 lines (212 loc) · 8.32 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
# 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 importlib
from typing import Any
from typing import Optional
import uuid
from pydantic import BaseModel
from ..agents.llm_agent import Agent
from ..artifacts.base_artifact_service import BaseArtifactService
from ..artifacts.in_memory_artifact_service import InMemoryArtifactService
from ..memory.base_memory_service import BaseMemoryService
from ..memory.in_memory_memory_service import InMemoryMemoryService
from ..runners import Runner
from ..sessions.base_session_service import BaseSessionService
from ..sessions.in_memory_session_service import InMemorySessionService
from ..sessions.session import Session
from .eval_case import EvalCase
from .eval_case import IntermediateData
from .eval_case import Invocation
from .eval_case import SessionInput
from .eval_set import EvalSet
class EvalCaseResponses(BaseModel):
"""Contains multiple responses associated with an EvalCase.
Multiple responses are a result of repeated requests to genereate inferences.
"""
eval_case: EvalCase
responses: list[list[Invocation]]
class EvaluationGenerator:
"""Generates evaluation responses for agents."""
@staticmethod
async def generate_responses(
eval_set: EvalSet,
agent_module_path: str,
repeat_num: int = 3,
agent_name: str = None,
) -> list[EvalCaseResponses]:
"""Returns evaluation responses for the given dataset and agent.
Args:
eval_set: The eval set that needs to be scraped for responses.
agent_module_path: Path to the module that contains the root agent.
repeat_num: Number of time the eval dataset should be repeated. This is
usually done to remove uncertainty that a single run may bring.
agent_name: The name of the agent that should be evaluated. This is
usually the sub-agent.
"""
results = []
for eval_case in eval_set.eval_cases:
responses = []
for _ in range(repeat_num):
response_invocations = await EvaluationGenerator._process_query(
eval_case.conversation,
agent_module_path,
agent_name,
eval_case.session_input,
)
responses.append(response_invocations)
results.append(
EvalCaseResponses(eval_case=eval_case, responses=responses)
)
return results
@staticmethod
def generate_responses_from_session(session_path, eval_dataset):
"""Returns evaluation responses by combining session data with eval data.
Args:
session_path: Path to a json file that contains session data.
eval_dataset: The eval data set that should be combined with the session
data.
"""
results = []
with open(session_path, "r") as f:
session_data = Session.model_validate_json(f.read())
print("loaded session", session_path)
for data in eval_dataset:
# load session data from session_path
results.append(
EvaluationGenerator._process_query_with_session(
session_data,
data,
)
)
return results
@staticmethod
async def _process_query(
invocations: list[Invocation],
module_name: str,
agent_name: Optional[str] = None,
initial_session: Optional[SessionInput] = None,
) -> list[Invocation]:
"""Process a query using the agent and evaluation dataset."""
module_path = f"{module_name}"
agent_module = importlib.import_module(module_path)
root_agent = agent_module.agent.root_agent
reset_func = getattr(agent_module.agent, "reset_data", None)
agent_to_evaluate = root_agent
if agent_name:
agent_to_evaluate = root_agent.find_agent(agent_name)
assert agent_to_evaluate, f"Sub-Agent `{agent_name}` not found."
return await EvaluationGenerator._generate_inferences_from_root_agent(
invocations, agent_to_evaluate, reset_func, initial_session
)
@staticmethod
async def _generate_inferences_from_root_agent(
invocations: list[Invocation],
root_agent: Agent,
reset_func: Optional[Any] = None,
initial_session: Optional[SessionInput] = None,
session_id: Optional[str] = None,
session_service: Optional[BaseSessionService] = None,
artifact_service: Optional[BaseArtifactService] = None,
memory_service: Optional[BaseMemoryService] = None,
) -> list[Invocation]:
"""Scrapes the root agent given the list of Invocations."""
if not session_service:
session_service = InMemorySessionService()
if not memory_service:
memory_service = InMemoryMemoryService()
app_name = (
initial_session.app_name if initial_session else "EvaluationGenerator"
)
user_id = initial_session.user_id if initial_session else "test_user_id"
session_id = session_id if session_id else str(uuid.uuid4())
_ = await session_service.create_session(
app_name=app_name,
user_id=user_id,
state=initial_session.state if initial_session else {},
session_id=session_id,
)
if not artifact_service:
artifact_service = InMemoryArtifactService()
runner = Runner(
app_name=app_name,
agent=root_agent,
artifact_service=artifact_service,
session_service=session_service,
memory_service=memory_service,
)
# Reset agent state for each query
if callable(reset_func):
reset_func()
response_invocations = []
for invocation in invocations:
final_response = None
user_content = invocation.user_content
tool_uses = []
invocation_id = ""
async for event in runner.run_async(
user_id=user_id, session_id=session_id, new_message=user_content
):
invocation_id = (
event.invocation_id if not invocation_id else invocation_id
)
if event.is_final_response() and event.content and event.content.parts:
final_response = event.content
elif event.get_function_calls():
for call in event.get_function_calls():
tool_uses.append(call)
response_invocations.append(
Invocation(
invocation_id=invocation_id,
user_content=user_content,
final_response=final_response,
intermediate_data=IntermediateData(tool_uses=tool_uses),
)
)
return response_invocations
@staticmethod
def _process_query_with_session(session_data, data):
"""Process the queries using the existing session data without invoking the runner."""
responses = data.copy()
# Iterate through the provided queries and align them with the session
# events
for index, eval_entry in enumerate(responses):
query = eval_entry["query"]
actual_tool_uses = []
response = None
# Search for the corresponding session events
for event in session_data.events:
# Match the query to a user event
if (
event.author == "user"
and event.content
and event.content.parts
and event.content.parts[0].text == query
):
# Look for subsequent tool usage or model responses
for subsequent_event in session_data.events:
if subsequent_event.invocation_id == event.invocation_id:
# Extract tool usage
if subsequent_event.content.parts[0].function_call:
call = subsequent_event.content.parts[0].function_call
actual_tool_uses.append(
{"tool_name": call.name, "tool_input": call.args}
)
# Extract final response
elif subsequent_event.author != "user":
response = subsequent_event.content.parts[0].text
# Update the results for the current query
responses[index]["actual_tool_use"] = actual_tool_uses
responses[index]["response"] = response
return responses