|
| 1 | +#!/usr/bin/env -S uv run --script |
| 2 | +# /// script |
| 3 | +# requires-python = "==3.11.11" |
| 4 | +# dependencies = [ |
| 5 | +# "pandas==2.2.3", |
| 6 | +# "openai", |
| 7 | +# "django", |
| 8 | +# ] |
| 9 | +# /// |
| 10 | + |
| 11 | +# uv script (or plain Python) to generate results to CSV, run from the terminal |
| 12 | +# Run from inside the container (working dir is /usr/src/server): |
| 13 | +# docker compose exec backend python api/views/assistant/eval_assistant.py |
| 14 | +# |
| 15 | + |
| 16 | + |
| 17 | +import os |
| 18 | +import sys |
| 19 | +import logging |
| 20 | +import datetime |
| 21 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 22 | + |
| 23 | +# Django setup must come before any imports that touch the ORM |
| 24 | +# NOTE: from api/views/assistant/, "../../../../" resolves four levels up to |
| 25 | +# /usr/src (not /usr/src/server, where balancer_backend lives). So this insert |
| 26 | +# alone does not put the settings package on sys.path — running the script |
| 27 | +# relies on the container already having /usr/src/server on PYTHONPATH. Sanity- |
| 28 | +# check this the first time the eval is run for real; the path depth may need |
| 29 | +# adjusting (e.g. "../../../"). |
| 30 | +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../"))) |
| 31 | +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "balancer_backend.settings") |
| 32 | + |
| 33 | +import django |
| 34 | +django.setup() |
| 35 | + |
| 36 | +from django.contrib.auth import get_user_model |
| 37 | + |
| 38 | +from api.views.assistant.assistant_services import run_assistant |
| 39 | +# TODO: remove unused import or use INSTRUCTIONS to record an instructions_hash column |
| 40 | +from api.views.assistant.assistant_prompts import INSTRUCTIONS |
| 41 | + |
| 42 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") |
| 43 | +logger = logging.getLogger(__name__) |
| 44 | + |
| 45 | +# Read model and INSTRUCTIONS from the source file or add a lightweight config endpoint to the backend |
| 46 | + |
| 47 | +# Read model and INSTRUCTIONS from the source file |
| 48 | +# INSTRUCTIONS is imported from assistant_prompts.py |
| 49 | +# MODEL is read from assistant_services.py MODEL_DEFAULTS |
| 50 | +# TODO: import a shared MODEL_NAME constant from assistant_services instead of hardcoding |
| 51 | +MODEL = "gpt-5-nano" |
| 52 | + |
| 53 | +# Set of representative questions to evaluate the assistant |
| 54 | +QUESTIONS = [ |
| 55 | + "What medications are recommended for bipolar depression?", |
| 56 | + "What are the risks of lithium for patients with kidney disease?", |
| 57 | + "Which mood stabilizers are safe during pregnancy?", |
| 58 | + "What is the evidence for quetiapine in bipolar disorder?", |
| 59 | + "How does valproate compare to lithium for mania?", |
| 60 | +] |
| 61 | + |
| 62 | + |
| 63 | +def run_one(question: str, user, branch: str) -> dict: |
| 64 | + """Run the assistant for a single question and return a result row. |
| 65 | +
|
| 66 | + Uses ThreadPoolExecutor (not asyncio.gather + await run_assistant) for concurrency. |
| 67 | +
|
| 68 | + Concurrency approach comparison: |
| 69 | + - ThreadPoolExecutor (this implementation): |
| 70 | + - run_assistant stays sync — views.py and the WSGI web app are unaffected |
| 71 | + - Each question runs in a thread pool worker, blocking on OpenAI + DB I/O |
| 72 | + - Django DB safe when run via `docker compose exec backend python eval_assistant.py`: |
| 73 | + this is a synchronous Django process context. Each ThreadPoolExecutor worker |
| 74 | + is a real OS thread with its own threading.local() storage, so each thread |
| 75 | + gets its own DB connection created lazily on first use. There is no shared |
| 76 | + event loop thread, so connections cannot clash or bleed between questions. |
| 77 | + The connection isolation concern only arises in ASGI contexts where multiple |
| 78 | + coroutines share one thread and therefore one threading.local() connection — |
| 79 | + which is not the case here. |
| 80 | + - Runtime: bottlenecked by OpenAI rate limits, not thread overhead |
| 81 | + - asyncio.gather + await run_assistant (alternative): |
| 82 | + - run_assistant becomes async — requires async def post in views.py, |
| 83 | + AsyncOpenAI client, and async handle_tool_calls_with_reasoning |
| 84 | + - Django DB unsafe if get_closest_embeddings is called directly in an async |
| 85 | + context without wrapping: get_closest_embeddings is a sync function that |
| 86 | + hits the ORM, so calling it on the event loop thread blocks all other |
| 87 | + coroutines until the DB responds. The fix is sync_to_async(get_closest_embeddings), |
| 88 | + which runs it in a dedicated worker thread with its own threading.local() |
| 89 | + connection. Bare await does not work at all — Django ORM querysets are not |
| 90 | + awaitables and raise TypeError immediately. |
| 91 | + - Under WSGI (manage.py runserver), async views run in a new event loop |
| 92 | + per request — adds overhead to every web request for no benefit |
| 93 | + - Cleaner call site in eval_assistant.py but wrong trade-off given WSGI |
| 94 | + """ |
| 95 | + try: |
| 96 | + response_text, response_id = run_assistant(message=question, user=user) |
| 97 | + return { |
| 98 | + "branch": branch, |
| 99 | + "model": MODEL, |
| 100 | + "question": question, |
| 101 | + "response_output_text": response_text, |
| 102 | + "error": None, |
| 103 | + } |
| 104 | + except Exception as e: |
| 105 | + logger.error(f"Error evaluating question '{question}': {e}") |
| 106 | + return { |
| 107 | + "branch": branch, |
| 108 | + "model": MODEL, |
| 109 | + "question": question, |
| 110 | + "response_output_text": None, |
| 111 | + "error": str(e), |
| 112 | + } |
| 113 | + |
| 114 | + |
| 115 | +def main(): |
| 116 | + branch = os.environ.get("EVAL_BRANCH", "develop") |
| 117 | + |
| 118 | + User = get_user_model() |
| 119 | + user = User.objects.filter(is_superuser=True).first() |
| 120 | + if not user: |
| 121 | + raise RuntimeError("No superuser found. Create one with manage.py createsuperuser.") |
| 122 | + |
| 123 | + logger.info(f"Starting evaluation: branch={branch}, model={MODEL}, questions={len(QUESTIONS)}") |
| 124 | + |
| 125 | + # ThreadPoolExecutor runs questions concurrently — see run_one docstring |
| 126 | + # for trade-off discussion vs asyncio.gather + await run_assistant. |
| 127 | + # max_workers=5 stays safely under OpenAI rate limits for gpt-5-nano. |
| 128 | + results = [] |
| 129 | + with ThreadPoolExecutor(max_workers=5) as pool: |
| 130 | + futures = { |
| 131 | + pool.submit(run_one, question, user, branch): question |
| 132 | + for question in QUESTIONS |
| 133 | + } |
| 134 | + for future in as_completed(futures): |
| 135 | + results.append(future.result()) |
| 136 | + |
| 137 | + # Import pandas here, not at module top, so that importing this module (e.g. |
| 138 | + # run_one from test_eval_assistant.py) does not require pandas. It is only |
| 139 | + # needed for the CSV output below, when this script is run directly. |
| 140 | + import pandas as pd |
| 141 | + |
| 142 | + df = pd.DataFrame(results) |
| 143 | + |
| 144 | + results_dir = os.path.join(os.path.dirname(__file__), "results") |
| 145 | + os.makedirs(results_dir, exist_ok=True) |
| 146 | + timestamp = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S") |
| 147 | + output_path = os.path.join(results_dir, f"{branch}-{timestamp}.csv") |
| 148 | + df.to_csv(output_path, index=False) |
| 149 | + |
| 150 | + logger.info(f"Results saved to {output_path}") |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + main() |
0 commit comments