-
Notifications
You must be signed in to change notification settings - Fork 11
Add venv support for custom evals #65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -32,4 +32,3 @@ evaluators: | |
| ref: evaluators/random_evaluator/random_evaluator.py | ||
| threshold: 0.110 | ||
| executor: local | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Virtual environment management for evaluators with dependencies. | ||
|
|
||
| When an evaluator ships a ``requirements.txt`` alongside its entrypoint, we | ||
| create a cached venv, install the dependencies (plus the evaluator SDK), and | ||
| return the path to that venv's Python interpreter so the evaluator subprocess | ||
| runs in isolation. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import hashlib | ||
| import logging | ||
| import os | ||
| import shutil | ||
| import subprocess | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _VENV_CACHE_DIR = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "agentevals" / "venvs" | ||
| _HASH_FILE = ".requirements_hash" | ||
|
|
||
| # Per-evaluator locks to prevent concurrent venv creation for the same evaluator. | ||
| _venv_locks: dict[str, asyncio.Lock] = {} | ||
|
|
||
|
|
||
| def _venv_python(venv_dir: Path) -> Path: | ||
| if sys.platform == "win32": | ||
| return venv_dir / "Scripts" / "python.exe" | ||
| return venv_dir / "bin" / "python" | ||
|
|
||
|
|
||
| def _venv_key(evaluator_path: Path) -> str: | ||
| """Stable cache directory name derived from evaluator location.""" | ||
| resolved = evaluator_path.resolve() | ||
| name = resolved.parent.name | ||
| path_hash = hashlib.sha256(str(resolved.parent).encode()).hexdigest()[:8] | ||
| return f"{name}-{path_hash}" | ||
|
|
||
|
|
||
| def _is_venv_valid(venv_dir: Path, req_hash: str) -> bool: | ||
| hash_file = venv_dir / _HASH_FILE | ||
| return _venv_python(venv_dir).exists() and hash_file.exists() and hash_file.read_text().strip() == req_hash | ||
|
|
||
|
|
||
| def _create_venv(venv_dir: Path, uv: str | None) -> None: | ||
| if venv_dir.exists(): | ||
| shutil.rmtree(venv_dir) | ||
| cmd = ( | ||
| [uv, "venv", str(venv_dir), "--python", sys.executable] if uv else [sys.executable, "-m", "venv", str(venv_dir)] | ||
| ) | ||
| subprocess.run(cmd, check=True, capture_output=True) | ||
|
|
||
|
|
||
| def _install_deps(venv_dir: Path, requirements: Path, uv: str | None) -> None: | ||
| python = str(_venv_python(venv_dir)) | ||
| sdk_spec = "agentevals-evaluator-sdk" | ||
|
|
||
| if uv: | ||
| base = [uv, "pip", "install", "--python", python] | ||
| else: | ||
| base = [python, "-m", "pip", "install"] | ||
|
|
||
| subprocess.run(base + [sdk_spec], check=True, capture_output=True) | ||
| logger.info("Installing dependencies from %s ...", requirements.name) | ||
| subprocess.run(base + ["-r", str(requirements)], check=True, capture_output=True) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Public API | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
|
|
||
| def ensure_venv(evaluator_path: Path) -> Path | None: | ||
| """Ensure a cached venv exists for *evaluator_path* if it has ``requirements.txt``. | ||
|
|
||
| Returns the venv Python path, or ``None`` if no venv is needed. | ||
| """ | ||
| requirements = evaluator_path.resolve().parent / "requirements.txt" | ||
| if not requirements.exists(): | ||
| return None | ||
|
|
||
| req_hash = hashlib.sha256(requirements.read_bytes()).hexdigest() | ||
| venv_dir = _VENV_CACHE_DIR / _venv_key(evaluator_path) | ||
krisztianfekete marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if _is_venv_valid(venv_dir, req_hash): | ||
| logger.debug("Using cached venv for %s at %s", evaluator_path.name, venv_dir) | ||
| return _venv_python(venv_dir) | ||
|
|
||
| uv = shutil.which("uv") | ||
| logger.info( | ||
| "Setting up environment for evaluator '%s' (using %s). This may take a while on first run...", | ||
| evaluator_path.stem, | ||
| "uv" if uv else "venv+pip", | ||
| ) | ||
|
|
||
| try: | ||
| venv_dir.parent.mkdir(parents=True, exist_ok=True) | ||
| _create_venv(venv_dir, uv) | ||
| _install_deps(venv_dir, requirements, uv) | ||
| except subprocess.CalledProcessError as exc: | ||
| stderr = exc.stderr.decode() if isinstance(exc.stderr, bytes) else (exc.stderr or "") | ||
| raise RuntimeError(f"Failed to set up environment for evaluator '{evaluator_path.stem}': {stderr}") from exc | ||
|
|
||
| (venv_dir / _HASH_FILE).write_text(req_hash) | ||
| logger.info("Environment ready for '%s'", evaluator_path.stem) | ||
| return _venv_python(venv_dir) | ||
|
|
||
|
|
||
| async def ensure_venv_async(evaluator_path: Path) -> Path | None: | ||
| """Async wrapper around :func:`ensure_venv` with per-evaluator locking.""" | ||
| venv_key = _venv_key(evaluator_path) | ||
| if venv_key not in _venv_locks: | ||
| _venv_locks[venv_key] = asyncio.Lock() | ||
|
|
||
| async with _venv_locks[venv_key]: | ||
| return await asyncio.to_thread(ensure_venv, evaluator_path) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.