agent_evaluator 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of agent_evaluator might be problematic. Click here for more details.

@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent_evaluator
3
+ Version: 0.1.0
4
+ Requires-Dist: google-adk
5
+ Requires-Dist: opik
6
+ Requires-Dist: google-generativeai
7
+ Requires-Dist: python-dotenv
8
+ Requires-Dist: litellm
9
+ Requires-Dist: opik-optimizer
10
+ Requires-Dist: numpy
11
+ Requires-Dist: scipy
12
+ Requires-Dist: sentence-transformers
13
+ Requires-Dist: openai
@@ -0,0 +1,115 @@
1
+ # Agent Evaluator
2
+
3
+ A lightweight utility for comparing agents or models using datasets, with support for model, agent, and dataset evaluation modes. Built on top of `opik`, `google-adk`, and related libraries.
4
+
5
+ ## Features
6
+
7
+ - Compare LLM agents or models on custom datasets
8
+ - Evaluate agent performance, answer relevance, hallucination, and more
9
+ - Flexible configuration via JSON files
10
+ - CLI interface for easy usage
11
+
12
+ ## Installation
13
+
14
+ 1. **Clone the repository:**
15
+ ```bash
16
+ git clone <your-repo-url>
17
+ cd agent_evaluator
18
+ ```
19
+
20
+ 2. **Install dependencies:**
21
+ - Using pip (recommended for most users):
22
+ ```bash
23
+ pip install .
24
+ ```
25
+ - Or, using the included `pyproject.toml`:
26
+ ```bash
27
+ pip install .
28
+ ```
29
+
30
+ > **Note:** You may want to use a virtual environment:
31
+ > ```bash
32
+ > python -m venv .venv
33
+ > source .venv/bin/activate
34
+ > ```
35
+
36
+ ## Configuration
37
+
38
+ 1. **Create a configuration file:**
39
+ - Copy `config_template.json` to `config.json` and edit as needed:
40
+ ```bash
41
+ cp config_template.json config.json
42
+ ```
43
+ - Fill in the required fields for your agents, models, datasets, and judge model.
44
+
45
+ 2. **Prepare your agent and dataset files:**
46
+ - Implement your agent(s) in a Python file (e.g., `agent.py`).
47
+ - Prepare your dataset(s) in JSONL format, where each line is a JSON object with at least a `user_question` field.
48
+
49
+ ## Usage
50
+
51
+ Run the evaluator in one of three modes: `model`, `agent`, or `dataset`.
52
+
53
+ ```bash
54
+ python agent_evaluator/evaluator.py <mode>
55
+ ```
56
+
57
+ Where `<mode>` is one of:
58
+ - `model` &mdash; Compare different models using a single agent and dataset.
59
+ - `agent` &mdash; Compare different agents on the same dataset.
60
+ - `dataset` &mdash; Compare different datasets using a single agent.
61
+
62
+ **Example:**
63
+ ```bash
64
+ python agent_evaluator/evaluator.py model
65
+ ```
66
+
67
+ ## Configuration Example
68
+
69
+ Here is a sample `config.json` structure:
70
+
71
+ ```json
72
+ {
73
+ "model_comparison": {
74
+ "delay_seconds": 0.0,
75
+ "baseline_model": "your_baseline_model_name",
76
+ "candidate_models": ["your_candidate_model_name"],
77
+ "agent": {
78
+ "class_name": "YourAgentClass",
79
+ "module_path": "path/to/your/agent.py"
80
+ },
81
+ "dataset": "path/to/your/dataset.jsonl",
82
+ "judge_model": "your_judge_model_name"
83
+ },
84
+ "agent_comparison": {
85
+ "delay_seconds": 0.0,
86
+ "baseline_agent": {
87
+ "name": "your_baseline_agent_name",
88
+ "module_path": "path/to/your/agent.py"
89
+ },
90
+ "candidate_agents": [
91
+ {
92
+ "name": "your_candidate_agent_name",
93
+ "module_path": "path/to/your/agent.py"
94
+ }
95
+ ],
96
+ "dataset": "path/to/your/dataset.jsonl",
97
+ "judge_model": "your_judge_model_name"
98
+ },
99
+ "dataset_comparison": {
100
+ "baseline_dataset": "path/to/your/baseline_dataset.jsonl",
101
+ "candidate_datasets": ["path/to/your/candidate_dataset.jsonl"],
102
+ "agent": {
103
+ "name": "your_agent_name",
104
+ "module_path": "path/to/your/agent.py"
105
+ },
106
+ "judge_model": "your_judge_model_name"
107
+ }
108
+ }
109
+ ```
110
+
111
+ ## Notes
112
+
113
+ - Make sure your agent and judge model implementations are accessible via the paths specified in the config.
114
+ - Datasets should be in JSONL format, with each line containing at least a `user_question` field.
115
+ - For advanced usage, see the docstrings in `agent_evaluator/evaluator.py`.
@@ -0,0 +1 @@
1
+ """This package contains the agent evaluator modules."""
@@ -0,0 +1,615 @@
1
+ #!/usr/bin/env python3
2
+ """Lightweight agent / model comparison utility."""
3
+
4
+ import json
5
+ import sys
6
+ import os
7
+ import importlib.util
8
+
9
+ # Add project root to the Python path to allow running as a script
10
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
11
+
12
+ # Unconditionally disable OpenTelemetry automatic instrumentation.
13
+ # This prevents connection errors if an OTLP collector is not running.
14
+ # The manual opik.trace() calls will still function correctly.
15
+ os.environ["OTEL_SDK_DISABLED"] = "true"
16
+
17
+ import asyncio
18
+ from typing import Dict, Any, Tuple
19
+ from google.genai import types
20
+ import opik
21
+ import copy
22
+ import numpy as np
23
+
24
+ from scipy.spatial.distance import pdist, squareform
25
+ from sentence_transformers import SentenceTransformer
26
+ from google.adk.agents import Agent
27
+ from src import agent as agent_definitions
28
+ from src.opik_setup import setup_opik_tracing
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Environment helpers
32
+ # ---------------------------------------------------------------------------
33
+
34
+ try:
35
+ from google.adk.runners import Runner
36
+ from google.adk.sessions import InMemorySessionService
37
+ from dotenv import load_dotenv # type: ignore
38
+
39
+ load_dotenv()
40
+ except ImportError:
41
+ # Either python-dotenv is missing or an unexpected error occurred. We simply
42
+ # continue and rely on the variable being set in the environment.
43
+ pass
44
+
45
+
46
+ class AgentEvaluator:
47
+ """Compare agents or models against datasets defined in a JSON config."""
48
+
49
+ def __init__(self, config_file: str = "config.json"):
50
+ """Initialize with path to JSON config file."""
51
+ self.config = self._load_config(config_file)
52
+
53
+ # ------------------------------------------------------------------
54
+ # Internal helpers
55
+ # ------------------------------------------------------------------
56
+
57
+ async def _call_agent(self, runner, user_question: str, session_id: str, delay_seconds: float = 0.0):
58
+ """Call agent and return response."""
59
+ if delay_seconds > 0:
60
+ print(f"--- Throttling: Waiting {delay_seconds} seconds before request ---")
61
+ await asyncio.sleep(delay_seconds)
62
+
63
+ content = types.Content(role='user', parts=[types.Part(text=user_question)])
64
+
65
+ response = None
66
+ try:
67
+ async for event in runner.run_async(user_id="eval_user", session_id=session_id, new_message=content):
68
+ if event.is_final_response():
69
+ if event.content and event.content.parts and len(event.content.parts) > 0:
70
+ response = event.content.parts[0].text
71
+ elif event.actions and event.actions.escalate:
72
+ response = f"Agent escalated: {event.error_message or 'No message'}"
73
+ except Exception as e:
74
+ return f"Error calling agent: {str(e)}"
75
+
76
+ return response or "No response"
77
+
78
+ async def _setup_session(self, session_service, app_name: str, session_id: str):
79
+ """Setup evaluation session with cleanup."""
80
+ await session_service.delete_session(app_name=app_name, user_id="eval_user", session_id=session_id)
81
+ await session_service.create_session(app_name=app_name, user_id="eval_user", session_id=session_id, state={})
82
+
83
+ def _load_config(self, config_file: str) -> Dict:
84
+ """Load configuration from JSON file"""
85
+ try:
86
+ with open(config_file, 'r') as f:
87
+ return json.load(f)
88
+ except FileNotFoundError:
89
+ print(f"ERROR: Configuration file not found at '{config_file}'")
90
+ sys.exit(1)
91
+ except json.JSONDecodeError:
92
+ print(f"ERROR: Invalid JSON in configuration file at '{config_file}'")
93
+ sys.exit(1)
94
+ except Exception as e:
95
+ print(f"ERROR: Unexpected error loading configuration file '{config_file}': {e}")
96
+ sys.exit(1)
97
+
98
+ def _import_agent_module(self, agent_module_path: str):
99
+ """Dynamically import agent module"""
100
+ spec = importlib.util.spec_from_file_location("agent_module", agent_module_path)
101
+ if spec is None or spec.loader is None:
102
+ print(f"ERROR: Could not create module spec from '{agent_module_path}'")
103
+ sys.exit(1)
104
+ agent_module = importlib.util.module_from_spec(spec)
105
+ spec.loader.exec_module(agent_module)
106
+ return agent_module
107
+
108
+ def _create_agent_from_config(self, agent_config: Dict, model=None):
109
+ """Create agent from configuration"""
110
+ # Import the agent module
111
+ agent_module = self._import_agent_module(agent_config["module_path"])
112
+
113
+ # Get the agent class from the module
114
+ agent_class = getattr(agent_module, agent_config["class_name"])
115
+
116
+ # Create a copy of the agent to avoid modifying the original
117
+ agent = copy.deepcopy(agent_class)
118
+
119
+ # Create agent with specified model (if provided)
120
+ if model:
121
+ agent.model = model
122
+
123
+ return agent
124
+
125
+ def _get_agent_from_config(self, agent_config: Dict):
126
+ """Dynamically load an agent variable from a module and return a copy."""
127
+ module_path = agent_config["module_path"]
128
+ agent_name = agent_config["name"]
129
+
130
+ # Re-use the agent module if already imported
131
+ agent_module = self._import_agent_module(module_path)
132
+ agent_variable = getattr(agent_module, agent_name)
133
+ return copy.deepcopy(agent_variable)
134
+
135
+ def _get_model_from_config(self, model_config: Dict):
136
+ """Return model string or predefined object based on config entry"""
137
+ name = model_config["name"]
138
+
139
+ # If the model is a dictionary, it's a pre-configured LiteLLM model
140
+ if isinstance(model_config, dict):
141
+ name = model_config["name"]
142
+ if name == "gpt_llm":
143
+ return agent_definitions.gpt_llm
144
+ elif name == "claude_llm":
145
+ return agent_definitions.claude_llm
146
+
147
+ # Otherwise, treat the name as the raw model identifier string (Gemini etc.)
148
+ return name
149
+
150
+ async def _get_pairwise_judgment(self, judge_runner, question: str, response_a: str, response_b: str, context_prefix: str = "judge") -> Tuple[str, str]:
151
+ """Get a pairwise judgment from a judge model."""
152
+ prompt = f"""[Question]
153
+ {question}
154
+
155
+ [Response A]
156
+ {response_a}
157
+
158
+ [Response B]
159
+ {response_b}
160
+
161
+ [Instructions]
162
+ You are a helpful and harmless AI assistant. Your task is to evaluate the quality of two responses (A and B) to the user's question.
163
+ Consider correctness, completeness, and helpfulness.
164
+ Respond ONLY with a valid JSON object, and do NOT include any extra text, markdown, or code fences. Your entire response must be a single line of JSON, like: {{\"verdict\": \"A\", \"reasoning\": \"your explanation here\"}}
165
+ """
166
+
167
+ session_id = f"{context_prefix}_session"
168
+ await self._setup_session(judge_runner.session_service, "judge_app", session_id)
169
+
170
+ verdict_text = await self._call_agent(judge_runner, prompt, session_id)
171
+
172
+ # Parse verdict
173
+ verdict = "TIE" # default
174
+ reasoning = "No reasoning provided."
175
+
176
+ if verdict_text:
177
+ parsed = json.loads(verdict_text)
178
+ verdict = parsed.get("verdict", "TIE")
179
+ reasoning = parsed.get("reasoning", "No reasoning provided.")
180
+
181
+ return verdict, reasoning
182
+
183
+ async def _get_complexity_judgment(self, judge_runner, question: str, context_prefix: str = "complexity_judge") -> int:
184
+ """Get a complexity judgment from a judge model."""
185
+ prompt = f"""[Question]
186
+ {question}
187
+
188
+ [Instructions]
189
+ You are a helpful and harmless AI assistant. Your task is to evaluate the complexity of the user's question.
190
+ Rate the complexity on a scale from 1 to 5, where 1 is very simple and 5 is very complex.
191
+ Your decision must be a single number on the first line, enclosed in double square brackets. For example: [[3]]."""
192
+
193
+ session_id = f"{context_prefix}_session"
194
+ await self._setup_session(judge_runner.session_service, "judge_app", session_id)
195
+
196
+ response_text = await self._call_agent(judge_runner, prompt, session_id)
197
+
198
+ try:
199
+ return int(response_text.strip().replace("[[", "").replace("]]", ""))
200
+ except (ValueError, TypeError):
201
+ return 0 # Default to 0 if parsing fails
202
+
203
+ def _calculate_semantic_diversity(self, questions: list[str], model) -> float:
204
+ """Calculate semantic diversity of questions."""
205
+ if len(questions) < 2:
206
+ return 0.0
207
+ embeddings = model.encode(questions)
208
+ # Calculate pairwise cosine distances, and take the mean
209
+ distance_matrix = pdist(embeddings, 'cosine')
210
+ return np.mean(distance_matrix)
211
+
212
+ def _calculate_redundancy(self, questions: list[str], model, threshold=0.95) -> float:
213
+ """Calculate the percentage of redundant questions."""
214
+ if len(questions) < 2:
215
+ return 0.0
216
+ embeddings = model.encode(questions)
217
+ # Calculate pairwise cosine similarities
218
+ similarity_matrix = 1 - squareform(pdist(embeddings, 'cosine'))
219
+ # Find pairs with similarity > threshold (excluding self-similarity)
220
+ redundant_pairs = np.sum(np.triu(similarity_matrix, k=1) > threshold)
221
+ return (redundant_pairs / (len(questions) * (len(questions) - 1) / 2)) * 100
222
+
223
+ async def _analyze_single_dataset(
224
+ self, dataset_path: str, runner, judge_runner, embedding_model, opik_client
225
+ ) -> Dict:
226
+ """Analyzes a single dataset and returns a dictionary of quality metrics."""
227
+ with open(dataset_path, 'r') as f:
228
+ dataset = [json.loads(line) for line in f]
229
+
230
+ questions = [ex.get("user_question", "") for ex in dataset]
231
+ num_examples = len(questions)
232
+ print(f"Found {num_examples} examples.")
233
+
234
+ # 1. Agent Performance (Difficulty)
235
+ success_count = 0
236
+ for i, example in enumerate(dataset, 1):
237
+ session_id = f"dataset_comparison_{os.path.basename(dataset_path)}_example_{i}"
238
+ await self._setup_session(runner.session_service, runner.app_name, session_id)
239
+ response = await self._call_agent(runner, example["user_question"], session_id)
240
+ if not response.startswith("Error") and not response.startswith("Agent escalated"):
241
+ success_count += 1
242
+
243
+ agent_performance = (success_count / num_examples) * 100 if num_examples > 0 else 0
244
+ print(f" - Agent Performance (Success Rate): {agent_performance:.2f}%")
245
+
246
+ # 2. Complexity Analysis
247
+ complexities = []
248
+ for i, q in enumerate(questions, 1):
249
+ context = f"dataset_comparison_{os.path.basename(dataset_path)}_complexity_example_{i}"
250
+ complexities.append(await self._get_complexity_judgment(judge_runner, q, context_prefix=context))
251
+ avg_complexity = np.mean(complexities) if complexities else 0
252
+ print(f" - Average Complexity (1-5): {avg_complexity:.2f}")
253
+
254
+ # 3. Semantic Diversity
255
+ diversity_score = self._calculate_semantic_diversity(questions, embedding_model)
256
+ print(f" - Semantic Diversity Score: {diversity_score:.4f}")
257
+
258
+ # 4. Redundancy Check
259
+ redundancy_score = self._calculate_redundancy(questions, embedding_model)
260
+ print(f" - Redundancy Score (% near-duplicates): {redundancy_score:.2f}%")
261
+
262
+ dataset_results = {
263
+ "agent_performance_success_rate": agent_performance,
264
+ "average_complexity": avg_complexity,
265
+ "semantic_diversity_score": diversity_score,
266
+ "redundancy_percentage": redundancy_score,
267
+ "total_examples": num_examples
268
+ }
269
+
270
+ opik_client.trace(
271
+ name=f"dataset_comparison:analysis:{os.path.basename(dataset_path)}",
272
+ input={"dataset_path": dataset_path},
273
+ output=dataset_results
274
+ ).end()
275
+
276
+ return dataset_results
277
+
278
+ async def compare_models(self) -> Dict:
279
+ """Compare different models using the same agent and dataset"""
280
+ print("🚀 MODEL COMPARISON (Pairwise)")
281
+ config = self.config["model_comparison"]
282
+
283
+ baseline_model_name = config["baseline_model"]
284
+ judge_model_name = config.get("judge_model", baseline_model_name) # Default to baseline if not set
285
+
286
+ print(f"Agent: {config['agent']['class_name']} | Dataset: {config['dataset']}")
287
+ print(f"Baseline Model: {baseline_model_name}")
288
+ print(f"Judge Model: {judge_model_name}")
289
+
290
+ results = {}
291
+
292
+ # Create the agent and model instances
293
+ baseline_model_obj = self._get_model_from_config({"name": baseline_model_name})
294
+ baseline_agent = self._create_agent_from_config(config["agent"], baseline_model_obj)
295
+ setup_opik_tracing(baseline_agent)
296
+
297
+ session_service = InMemorySessionService()
298
+
299
+ judge_model_obj = self._get_model_from_config({"name": judge_model_name})
300
+ judge_agent = Agent(model=judge_model_obj, name="judge_agent", instruction="You are an expert evaluator.")
301
+ judge_runner = Runner(agent=judge_agent, app_name="judge_app", session_service=session_service)
302
+
303
+ print("--- Initializing Opik client for tracing ---")
304
+ project_name = os.getenv("OPIK_PROJECT_NAME", "adk-evaluator")
305
+ opik_client = opik.Opik(project_name=project_name)
306
+
307
+ for candidate_model_name in config["candidate_models"]:
308
+ comparison_name = f"{baseline_model_name}_vs_{candidate_model_name}"
309
+ print("-" * 60)
310
+ print(f"Comparing: '{baseline_model_name}' (Baseline) vs. '{candidate_model_name}' (Candidate)")
311
+
312
+ app_name = config["agent"]["class_name"]
313
+ baseline_runner = Runner(agent=baseline_agent, app_name=app_name, session_service=session_service)
314
+
315
+ candidate_model_obj = self._get_model_from_config({"name": candidate_model_name})
316
+ candidate_agent = self._create_agent_from_config(config["agent"], candidate_model_obj)
317
+ setup_opik_tracing(candidate_agent)
318
+ candidate_runner = Runner(agent=candidate_agent, app_name=app_name, session_service=session_service)
319
+
320
+ # Load the dataset
321
+ dataset_path = config["dataset"]
322
+ with open(dataset_path, 'r') as f:
323
+ dataset = [json.loads(line) for line in f]
324
+
325
+ print(f"Found {len(dataset)} examples in {dataset_path}")
326
+
327
+ # Track scores
328
+ scores = {"wins": 0, "losses": 0, "ties": 0}
329
+
330
+ for i, example in enumerate(dataset, 1):
331
+ question = example.get("user_question", "")
332
+ print(f"\n--- Example {i} ---")
333
+
334
+ # Setup unique sessions for this comparison
335
+ baseline_session_id = f"model_comparison_{comparison_name}_baseline_example_{i}"
336
+ candidate_session_id = f"model_comparison_{comparison_name}_candidate_example_{i}"
337
+ await self._setup_session(session_service, app_name, baseline_session_id)
338
+ await self._setup_session(session_service, app_name, candidate_session_id)
339
+
340
+ # Get responses from both agents
341
+ delay = self.config.get("model_comparison", {}).get("delay_seconds", 0.0)
342
+ baseline_response = await self._call_agent(baseline_runner, question, baseline_session_id)
343
+ candidate_response = await self._call_agent(candidate_runner, question, candidate_session_id, delay_seconds=delay)
344
+
345
+ print(f" - Baseline response: {baseline_response[:50].strip()}...")
346
+ print(f" - Candidate response: {candidate_response[:50].strip()}...")
347
+
348
+ # Get the verdict
349
+ judge_context = f"model_comparison_{comparison_name}_judge_example_{i}"
350
+ verdict, reasoning = await self._get_pairwise_judgment(
351
+ judge_runner, question, baseline_response, candidate_response, context_prefix=judge_context
352
+ )
353
+
354
+ trace_name = f"model_comparison:{comparison_name}:example_{i}"
355
+ trace = opik_client.trace(
356
+ name=trace_name,
357
+ input={"question": question, "baseline": baseline_response, "candidate": candidate_response},
358
+ output={"verdict": verdict, "reasoning": reasoning}
359
+ )
360
+ trace.end()
361
+
362
+ print(f" - Verdict: {verdict}")
363
+ print(f" - Reasoning: {reasoning}")
364
+
365
+ if verdict == "A":
366
+ scores["wins"] += 1
367
+ elif verdict == "B":
368
+ scores["losses"] += 1
369
+ elif verdict == "TIE":
370
+ scores["ties"] += 1
371
+
372
+ # Store and print results for this comparison
373
+ print("\n" + "=" * 60)
374
+ print(f"FINAL SCORE for {comparison_name}:")
375
+ print(f"Baseline ({baseline_model_name}) Wins: {scores['wins']}/{len(dataset)}")
376
+ print(f"Candidate ({candidate_model_name}) Wins: {scores['losses']}/{len(dataset)}")
377
+ print(f"Ties: {scores['ties']}/{len(dataset)}")
378
+ print("=" * 60)
379
+
380
+ results[comparison_name] = {
381
+ "baseline_wins": scores["wins"],
382
+ "candidate_wins": scores['losses'],
383
+ "ties": scores['ties'],
384
+ "total": len(dataset)
385
+ }
386
+
387
+ return results
388
+
389
+ async def compare_datasets(self) -> Dict:
390
+ """Compare a baseline dataset against candidate datasets."""
391
+ print("🚀 DATASET COMPARISON (Pairwise)")
392
+ config = self.config["dataset_comparison"]
393
+
394
+ agent_config = config["agent"]
395
+ judge_model_name = config["judge_model"]
396
+
397
+ print(f"Agent: {agent_config['name']}")
398
+ print(f"Judge Model: {judge_model_name}")
399
+
400
+ results = {}
401
+
402
+ # Initial Setup
403
+ print("--- Initializing services and agent ---")
404
+ project_name = os.getenv("OPIK_PROJECT_NAME", "adk-evaluator")
405
+ opik_client = opik.Opik(project_name=project_name)
406
+ session_service = InMemorySessionService()
407
+ judge_model_obj = self._get_model_from_config({"name": judge_model_name})
408
+ judge_agent = Agent(model=judge_model_obj, name="judge_agent", instruction="You are an expert evaluator.")
409
+ judge_runner = Runner(agent=judge_agent, app_name="judge_app", session_service=session_service)
410
+ agent_to_test = self._get_agent_from_config(agent_config)
411
+ setup_opik_tracing(agent_to_test)
412
+ runner = Runner(agent=agent_to_test, app_name=f"app_{agent_config['name']}", session_service=session_service)
413
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
414
+
415
+ # Analyze Baseline Dataset
416
+ baseline_dataset_path = config["baseline_dataset"]
417
+ print("-" * 60)
418
+ print(f"Analyzing Baseline Dataset: {baseline_dataset_path}")
419
+ baseline_results = await self._analyze_single_dataset(
420
+ baseline_dataset_path, runner, judge_runner, embedding_model, opik_client
421
+ )
422
+ results["baseline"] = {"path": baseline_dataset_path, "metrics": baseline_results}
423
+
424
+ # Compare against each Candidate Dataset
425
+ for candidate_dataset_path in config.get("candidate_datasets", []):
426
+ comparison_name = f"{os.path.basename(baseline_dataset_path)}_vs_{os.path.basename(candidate_dataset_path)}"
427
+ print("\n" + "=" * 60)
428
+ print(f"Comparing: '{os.path.basename(baseline_dataset_path)}' (Baseline) vs. '{os.path.basename(candidate_dataset_path)}' (Candidate)")
429
+
430
+ # Analyze Candidate
431
+ candidate_results = await self._analyze_single_dataset(
432
+ candidate_dataset_path, runner, judge_runner, embedding_model, opik_client
433
+ )
434
+
435
+ # Store results
436
+ results[comparison_name] = {
437
+ "baseline": {"path": baseline_dataset_path, "metrics": baseline_results},
438
+ "candidate": {"path": candidate_dataset_path, "metrics": candidate_results}
439
+ }
440
+
441
+ # Print comparison report
442
+ print("\n--- COMPARISON REPORT ---")
443
+ self._print_dataset_comparison_report(baseline_results, candidate_results)
444
+
445
+ print("\n\n" + "=" * 60)
446
+ print("FULL DATASET ANALYSIS COMPLETE")
447
+ print("=" * 60)
448
+
449
+ return results
450
+
451
+ def _print_dataset_comparison_report(self, baseline: Dict, candidate: Dict):
452
+ """Prints a side-by-side comparison of two dataset analysis results."""
453
+ print(f"{'Metric':<35} | {'Baseline':<15} | {'Candidate':<15}")
454
+ print("-" * 70)
455
+
456
+ def format_val(val, is_percent=False):
457
+ if isinstance(val, float):
458
+ return f"{val:.2f}%" if is_percent else f"{val:.4f}"
459
+ return str(val)
460
+
461
+ metrics_map = {
462
+ "Total Examples": ("total_examples", False),
463
+ "Agent Success Rate": ("agent_performance_success_rate", True),
464
+ "Avg. Complexity (1-5)": ("average_complexity", False),
465
+ "Semantic Diversity Score": ("semantic_diversity_score", False),
466
+ "Redundancy (%)": ("redundancy_percentage", True)
467
+ }
468
+
469
+ for name, (key, is_percent) in metrics_map.items():
470
+ b_val = format_val(baseline.get(key, 'N/A'), is_percent)
471
+ c_val = format_val(candidate.get(key, 'N/A'), is_percent)
472
+ print(f"{name:<35} | {b_val:<15} | {c_val:<15}")
473
+
474
+ async def compare_agents(self) -> Dict:
475
+ """Compare different agents using the same dataset in a pairwise fashion."""
476
+ print("🚀 AGENT COMPARISON (Pairwise)")
477
+ config = self.config["agent_comparison"]
478
+
479
+ baseline_agent_config = config["baseline_agent"]
480
+ judge_model_name = config.get("judge_model")
481
+
482
+ if not judge_model_name:
483
+ print("ERROR: 'judge_model' must be specified in 'agent_comparison' config.")
484
+ sys.exit(1)
485
+
486
+ print(f"Dataset: {config['dataset']}")
487
+ print(f"Baseline Agent: {baseline_agent_config['name']}")
488
+ print(f"Judge Model: {judge_model_name}")
489
+
490
+ results = {}
491
+
492
+ # Setup services and judge
493
+ session_service = InMemorySessionService()
494
+ judge_model_obj = self._get_model_from_config({"name": judge_model_name})
495
+ judge_agent = Agent(model=judge_model_obj, name="judge_agent", instruction="You are an expert evaluator.")
496
+ judge_runner = Runner(agent=judge_agent, app_name="judge_app", session_service=session_service)
497
+
498
+ print("--- Initializing Opik client for tracing ---")
499
+ project_name = os.getenv("OPIK_PROJECT_NAME", "adk-evaluator")
500
+ opik_client = opik.Opik(project_name=project_name)
501
+
502
+ # Create baseline agent
503
+ baseline_agent_config = config["baseline_agent"]
504
+ baseline_agent = self._get_agent_from_config(baseline_agent_config)
505
+ setup_opik_tracing(baseline_agent)
506
+
507
+ for candidate_agent_config in config.get("candidate_agents", []):
508
+ comparison_name = f"{baseline_agent_config['name']}_vs_{candidate_agent_config['name']}"
509
+ print("-" * 60)
510
+ print(f"Comparing: '{baseline_agent_config['name']}' (Baseline) vs. '{candidate_agent_config['name']}' (Candidate)")
511
+
512
+ baseline_app_name = f"app_{baseline_agent_config['name']}"
513
+ baseline_runner = Runner(agent=baseline_agent, app_name=baseline_app_name, session_service=session_service)
514
+
515
+ candidate_agent = self._get_agent_from_config(candidate_agent_config)
516
+ setup_opik_tracing(candidate_agent)
517
+ candidate_app_name = f"app_{candidate_agent_config['name']}"
518
+ candidate_runner = Runner(agent=candidate_agent, app_name=candidate_app_name, session_service=session_service)
519
+
520
+ # Load the dataset
521
+ dataset_path = config["dataset"]
522
+ with open(dataset_path, 'r') as f:
523
+ dataset = [json.loads(line) for line in f]
524
+
525
+ print(f"Found {len(dataset)} examples in {dataset_path}")
526
+
527
+ scores = {"wins": 0, "losses": 0, "ties": 0}
528
+
529
+ for i, example in enumerate(dataset, 1):
530
+ question = example.get("user_question", "")
531
+ print(f"\n--- Example {i} ---")
532
+
533
+ # Setup unique sessions
534
+ baseline_session_id = f"agent_comparison_{comparison_name}_baseline_example_{i}"
535
+ candidate_session_id = f"agent_comparison_{comparison_name}_candidate_example_{i}"
536
+ await self._setup_session(session_service, baseline_runner.app_name, baseline_session_id)
537
+ await self._setup_session(session_service, candidate_runner.app_name, candidate_session_id)
538
+
539
+ # Get responses
540
+ delay = config.get("delay_seconds", 0.0)
541
+ baseline_response = await self._call_agent(baseline_runner, question, baseline_session_id)
542
+ candidate_response = await self._call_agent(candidate_runner, question, candidate_session_id, delay_seconds=delay)
543
+
544
+ print(f" - Baseline response: {baseline_response[:50].strip()}...")
545
+ print(f" - Candidate response: {candidate_response[:50].strip()}...")
546
+
547
+ # Get the verdict
548
+ judge_context = f"agent_comparison_{comparison_name}_judge_example_{i}"
549
+ verdict, reasoning = await self._get_pairwise_judgment(
550
+ judge_runner, question, baseline_response, candidate_response, context_prefix=judge_context
551
+ )
552
+
553
+ trace_name = f"agent_comparison:{comparison_name}:example_{i}"
554
+ trace = opik_client.trace(
555
+ name=trace_name,
556
+ input={"question": question, "baseline": baseline_response, "candidate": candidate_response},
557
+ output={"verdict": verdict, "reasoning": reasoning}
558
+ )
559
+ trace.end()
560
+
561
+ print(f" - Verdict: {verdict}")
562
+ print(f" - Reasoning: {reasoning}")
563
+
564
+ if verdict == "A":
565
+ scores["wins"] += 1
566
+ elif verdict == "B":
567
+ scores["losses"] += 1
568
+ elif verdict == "TIE":
569
+ scores["ties"] += 1
570
+
571
+ # Store and print results for this comparison
572
+ print("\n" + "=" * 60)
573
+ print(f"FINAL SCORE for {comparison_name}:")
574
+ print(f"Baseline ({baseline_agent_config['name']}) Wins: {scores['wins']}/{len(dataset)}")
575
+ print(f"Candidate ({candidate_agent_config['name']}) Wins: {scores['losses']}/{len(dataset)}")
576
+ print(f"Ties: {scores['ties']}/{len(dataset)}")
577
+ print("=" * 60)
578
+
579
+ results[comparison_name] = {
580
+ "baseline_wins": scores["wins"],
581
+ "candidate_wins": scores['losses'],
582
+ "ties": scores['ties'],
583
+ "total": len(dataset)
584
+ }
585
+
586
+ return results
587
+
588
+
589
+ # ===========================================================================
590
+ # Main
591
+ # ===========================================================================
592
+
593
+ def main():
594
+ """CLI entry point."""
595
+ if len(sys.argv) < 2:
596
+ print("Usage: python src/evaluator.py <mode>")
597
+ print("Modes: model, agent, dataset")
598
+ sys.exit(1)
599
+
600
+ mode = sys.argv[1].lower()
601
+ evaluator = AgentEvaluator()
602
+
603
+ if mode == "model":
604
+ asyncio.run(evaluator.compare_models())
605
+ elif mode == "agent":
606
+ asyncio.run(evaluator.compare_agents())
607
+ elif mode == "dataset":
608
+ asyncio.run(evaluator.compare_datasets())
609
+ else:
610
+ print(f"Unknown mode: {mode}")
611
+ print("Available modes: model, agent, dataset")
612
+ sys.exit(1)
613
+
614
+ if __name__ == "__main__":
615
+ main()
@@ -0,0 +1,162 @@
1
+ import os
2
+ import asyncio
3
+ import hashlib
4
+ import time
5
+ from typing import Optional, Dict, Any
6
+ from google.adk.sessions import InMemorySessionService
7
+ from google.adk.runners import Runner
8
+ from google.genai import types
9
+ import opik
10
+ from opik.evaluation.metrics import Hallucination, AnswerRelevance, ContextRecall, ContextPrecision
11
+ from opik.evaluation import evaluate
12
+
13
+
14
+ def load_dataset_smartly(client, dataset_name: str, jsonl_file: str):
15
+ """Load dataset, recreating if content changed. Hashes are now stored inside the
16
+ dedicated 'dataset_hash' directory to avoid cluttering the project root."""
17
+ # Ensure the hash directory exists
18
+ hash_dir = "dataset_hash"
19
+ os.makedirs(hash_dir, exist_ok=True)
20
+
21
+ # Location for this dataset's hash file
22
+ hash_file = os.path.join(hash_dir, f"{dataset_name}_hash.txt")
23
+
24
+ try:
25
+ with open(jsonl_file, 'r') as f:
26
+ current_hash = hashlib.md5(f.read().strip().encode()).hexdigest()
27
+ except FileNotFoundError:
28
+ return client.get_or_create_dataset(name=dataset_name)
29
+
30
+ # Check if hash matches existing
31
+ try:
32
+ with open(hash_file, 'r') as f:
33
+ if f.read().strip() == current_hash:
34
+ return client.get_dataset(name=dataset_name)
35
+ except FileNotFoundError:
36
+ pass
37
+
38
+ # Content changed - recreate dataset
39
+ try:
40
+ client.delete_dataset(name=dataset_name)
41
+ except:
42
+ pass
43
+
44
+ dataset = client.get_or_create_dataset(name=dataset_name)
45
+ dataset.read_jsonl_from_file(jsonl_file)
46
+
47
+ with open(hash_file, 'w') as f:
48
+ f.write(current_hash)
49
+
50
+ return dataset
51
+
52
+
53
+ async def call_agent(runner, user_question: str, session_id: str, delay_seconds: float = 0.0):
54
+ """Call agent and return response."""
55
+ if delay_seconds > 0:
56
+ print(f"--- Throttling: Waiting {delay_seconds} seconds before request ---")
57
+ await asyncio.sleep(delay_seconds)
58
+
59
+ content = types.Content(role='user', parts=[types.Part(text=user_question)])
60
+
61
+ try:
62
+ async for event in runner.run_async(user_id="eval_user", session_id=session_id, new_message=content):
63
+ if event.is_final_response():
64
+ if event.content and event.content.parts and len(event.content.parts) > 0:
65
+ return event.content.parts[0].text
66
+ elif event.actions and event.actions.escalate:
67
+ return f"Agent escalated: {event.error_message or 'No message'}"
68
+ break
69
+ except Exception as e:
70
+ return f"Error calling agent: {str(e)}"
71
+
72
+ return "No response"
73
+
74
+
75
+ def create_task(runner, session_id: str, delay_seconds: float = 0.0):
76
+ """Create evaluation task function."""
77
+ def task(x):
78
+ question = x['user_question']
79
+ expected = x.get('expected_output', {})
80
+ expected_answer = expected.get('assistant_answer', '') if isinstance(expected, dict) else str(expected)
81
+
82
+ try:
83
+ response = asyncio.run(call_agent(runner, question, session_id, delay_seconds))
84
+ except Exception as e:
85
+ response = f"Error: {str(e)}"
86
+
87
+ return {
88
+ "input": question,
89
+ "output": response,
90
+ "context": expected_answer,
91
+ "expected_output": expected_answer
92
+ }
93
+
94
+ return task
95
+
96
+
97
+ async def setup_session(session_service, app_name: str, session_id: str, state: Optional[Dict] = None):
98
+ """Setup evaluation session with cleanup."""
99
+ await session_service.delete_session(app_name=app_name, user_id="eval_user", session_id=session_id)
100
+ await session_service.create_session(app_name=app_name, user_id="eval_user", session_id=session_id, state=state or {})
101
+ print(f"--- Session cleanup: Created fresh session '{session_id}' for evaluation ---")
102
+
103
+
104
+ def run_evaluation(agent, app_name: str, project_name: str, dataset_name: str, jsonl_file: str,
105
+ session_state: Optional[Dict] = None, delay_seconds: float = 0.0):
106
+ """Run complete evaluation with optional throttling."""
107
+ if delay_seconds > 0:
108
+ print(f"--- Starting evaluation with {delay_seconds}s delay between requests ---")
109
+
110
+ # Setup components
111
+ client = opik.Opik()
112
+ session_service = InMemorySessionService()
113
+ runner = Runner(agent=agent, app_name=app_name, session_service=session_service)
114
+
115
+ # Load dataset and setup session
116
+ dataset = load_dataset_smartly(client, dataset_name, jsonl_file)
117
+ asyncio.run(setup_session(session_service, app_name, "eval_session", session_state))
118
+
119
+ # Run evaluation
120
+ start_time = time.time()
121
+ result = evaluate(
122
+ dataset=dataset,
123
+ task=create_task(runner, "eval_session", delay_seconds),
124
+ scoring_metrics=[Hallucination(), AnswerRelevance(), ContextRecall(), ContextPrecision()],
125
+ project_name=project_name,
126
+ task_threads=1
127
+ )
128
+
129
+ # Attach extracted metrics for downstream use (non-breaking patch)
130
+ try:
131
+ if hasattr(result, 'test_results') and result.test_results:
132
+ # Aggregate metrics across all test_results
133
+ metric_sums = {}
134
+ metric_counts = {}
135
+ n = len(result.test_results)
136
+ for test_result in result.test_results:
137
+ if hasattr(test_result, 'score_results') and test_result.score_results:
138
+ for score_result in test_result.score_results:
139
+ if hasattr(score_result, 'name') and hasattr(score_result, 'value'):
140
+ name = score_result.name
141
+ value = score_result.value
142
+ metric_sums[name] = metric_sums.get(name, 0) + value
143
+ # Average each metric over all test_results (use 0 if missing in a test_result)
144
+ avg_metrics = {}
145
+ key_map = {
146
+ 'hallucination_metric': 'hallucination',
147
+ 'answer_relevance_metric': 'answer_relevance',
148
+ 'context_recall_metric': 'context_recall',
149
+ 'context_precision_metric': 'context_precision',
150
+ }
151
+ for name in metric_sums:
152
+ avg = metric_sums[name] / n
153
+ norm_name = key_map.get(name, name)
154
+ avg_metrics[norm_name] = avg
155
+ result._extracted_metrics = avg_metrics
156
+ except Exception as e:
157
+ print(f"[WARN] Could not attach extracted metrics: {e}")
158
+
159
+ if delay_seconds > 0:
160
+ print(f"--- Evaluation completed in {time.time() - start_time:.2f} seconds ---")
161
+
162
+ return result
@@ -0,0 +1,18 @@
1
+ """
2
+ Opik Tracing Setup Module
3
+
4
+ This module provides utilities for setting up Opik tracing on Google ADK agents
5
+ using the RecursiveCallbackInjector for automatic recursive injection.
6
+ """
7
+
8
+ from google.adk.agents import Agent
9
+ from opik.integrations.adk.recursive_callback_injector import RecursiveCallbackInjector
10
+ from opik.integrations.adk import OpikTracer
11
+
12
+
13
+ def setup_opik_tracing(agent: Agent) -> OpikTracer:
14
+ """Set up Opik tracing on an agent and all its sub-agents/tools recursively."""
15
+ tracer = OpikTracer()
16
+ injector = RecursiveCallbackInjector(tracer=tracer)
17
+ injector.inject(agent)
18
+ return tracer
@@ -0,0 +1,68 @@
1
+ """Concise prompt optimization using EvolutionaryOptimizer."""
2
+
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ if os.path.exists("src") and "src" not in sys.path:
8
+ sys.path.insert(0, "src")
9
+
10
+ from opik_evaluation import load_dataset_smartly
11
+ from opik_optimizer import EvolutionaryOptimizer, ChatPrompt
12
+ from opik.evaluation.metrics import LevenshteinRatio
13
+ import opik
14
+
15
+ def optimize_prompt(agent, current_prompt: str, jsonl_file: str,
16
+ optimizer_model: str = "gpt-4o-mini"):
17
+ """Optimize a prompt using EvolutionaryOptimizer with genetic algorithms."""
18
+
19
+ # Setup
20
+ file_name = Path(jsonl_file).stem
21
+ dataset_name = file_name if file_name.endswith('_dataset') else f"{file_name}_dataset"
22
+
23
+ # Load data
24
+ client = opik.Opik()
25
+ dataset = load_dataset_smartly(client, dataset_name, jsonl_file)
26
+
27
+ # Configured optimizer for multi-agent system
28
+ optimizer = EvolutionaryOptimizer(
29
+ model=optimizer_model,
30
+ population_size=30,
31
+ num_generations=15,
32
+ mutation_rate=0.4,
33
+ enable_moo=True,
34
+ enable_llm_crossover=True,
35
+ adaptive_mutation=True,
36
+ output_style_guidance=None,
37
+ infer_output_style=True,
38
+ n_threads=6,
39
+ seed=42,
40
+ temperature=0.3
41
+ )
42
+
43
+ # Create ChatPrompt object (required by EvolutionaryOptimizer)
44
+ chat_prompt = ChatPrompt(
45
+ name="optimized_prompt",
46
+ system=current_prompt,
47
+ user="{user_question}"
48
+ )
49
+
50
+ # Evaluation function
51
+ def evaluate_output(dataset_item, llm_output):
52
+ reference = dataset_item.get("expected_output", "")
53
+ if isinstance(reference, dict):
54
+ reference = reference.get("assistant_answer", str(reference))
55
+ return LevenshteinRatio().score(reference=str(reference), output=str(llm_output))
56
+
57
+ # Run optimization
58
+ result = optimizer.optimize_prompt(
59
+ prompt=chat_prompt,
60
+ dataset=dataset,
61
+ metric=evaluate_output,
62
+ n_samples=25
63
+ )
64
+
65
+ result.display()
66
+ return result
67
+
68
+
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent_evaluator
3
+ Version: 0.1.0
4
+ Requires-Dist: google-adk
5
+ Requires-Dist: opik
6
+ Requires-Dist: google-generativeai
7
+ Requires-Dist: python-dotenv
8
+ Requires-Dist: litellm
9
+ Requires-Dist: opik-optimizer
10
+ Requires-Dist: numpy
11
+ Requires-Dist: scipy
12
+ Requires-Dist: sentence-transformers
13
+ Requires-Dist: openai
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ agent_evaluator/__init__.py
4
+ agent_evaluator/evaluator.py
5
+ agent_evaluator/opik_evaluation.py
6
+ agent_evaluator/opik_setup.py
7
+ agent_evaluator/optimizer.py
8
+ agent_evaluator.egg-info/PKG-INFO
9
+ agent_evaluator.egg-info/SOURCES.txt
10
+ agent_evaluator.egg-info/dependency_links.txt
11
+ agent_evaluator.egg-info/requires.txt
12
+ agent_evaluator.egg-info/top_level.txt
@@ -0,0 +1,10 @@
1
+ google-adk
2
+ opik
3
+ google-generativeai
4
+ python-dotenv
5
+ litellm
6
+ opik-optimizer
7
+ numpy
8
+ scipy
9
+ sentence-transformers
10
+ openai
@@ -0,0 +1 @@
1
+ agent_evaluator
@@ -0,0 +1,19 @@
1
+ [project]
2
+ name = "agent_evaluator"
3
+ version = "0.1.0"
4
+ dependencies = [
5
+ "google-adk",
6
+ "opik",
7
+ "google-generativeai",
8
+ "python-dotenv",
9
+ "litellm",
10
+ "opik-optimizer",
11
+ "numpy",
12
+ "scipy",
13
+ "sentence-transformers",
14
+ "openai"
15
+ ]
16
+
17
+ [build-system]
18
+ requires = ["setuptools>=61.0"]
19
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+