Datasets:
Add files using upload-large-folder tool
Browse filesFiles changed (50)
- .DS_StoreAdded
- client/.DS_StoreAdded
- client/Prompts_large/B2/B2_S.txtAdded+17
- client/Prompts_large/B2/B2_r300_n0_Q.txtAdded
- client/Prompts_large/B2/B2_r300_n10_Q.txtAdded
- client/Prompts_large/B2/B2_r300_n20_Q.txtAdded
- client/Prompts_large/B2/B2_r300_n30_Q.txtAdded
- client/Prompts_large/B2/B2_r300_n40_Q.txtAdded
- client/Prompts_large/B2/B2_r400_n0_Q.txtAdded
- client/Prompts_large/B2/B2_r400_n10_Q.txtAdded
- client/Prompts_large/B2/B2_r400_n20_Q.txtAdded
- client/Prompts_large/B2/B2_r400_n30_Q.txtAdded
- client/Prompts_large/B2/B2_r400_n40_Q.txtAdded
- client/Prompts_large/B2/B2_vF_S.txtAdded+1
- client/Prompts_large/B2/B2_vF_r300_n0_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r300_n10_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r300_n20_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r300_n30_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r400_n0_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r400_n10_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r400_n20_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r400_n30_Q.txtAdded
- client/Prompts_large/B2/B2_vF_r400_n40_Q.txtAdded
- client/Prompts_large/B2/placeholder.txtAdded
- client/Prompts_large/B5/B5_S.txtAdded+1
- client/Prompts_large/B5/B5_r300_n0_Q.txtAdded
- client/Prompts_large/B5/B5_r300_n10_Q.txtAdded
- client/Prompts_large/B5/B5_r300_n20_Q.txtAdded
- client/Prompts_large/B5/B5_r300_n30_Q.txtAdded
- client/Prompts_large/B5/B5_r300_n40_Q.txtAdded
- client/Prompts_large/B5/B5_r400_n0_Q.txtAdded
- client/Prompts_large/B5/B5_r400_n10_Q.txtAdded
- client/Prompts_large/B5/B5_r400_n20_Q.txtAdded
- client/Prompts_large/B5/B5_r400_n30_Q.txtAdded
- client/Prompts_large/B5/B5_r400_n40_Q.txtAdded
- client/Prompts_large/B5/placeholder.txtAdded
- client/ask.pyAdded
- client/call_db.pyAdded+128
- client/call_server.pyAdded+47
- client/client_requirements.txtAdded+1
- client/eval.pyAdded
- client/init.pyAdded
- readme.mdAdded+213
- serve_requirements.txtAdded+98
- server/db.pyAdded+72
- server/main.pyAdded+74
- server/query.pyAdded+1311
- server/serve.pyAdded+430
- server/setup_ngrok.shAdded+29
- server/test.pyAdded+143
1234567891011121314151617[2.5496 2.5454 2.5411 2.5368 2.5324 2.5281 2.5238 2.5194 2.515 2.5106 2.5062 2.5018 2.4974 2.493 2.4885 2.484 2.4796 2.4751 2.4706 2.466 2.4615 2.457 2.4524 2.4478 2.4432 2.4386 2.434 2.4293 2.4247 2.42 2.4153 2.4106 2.4059 2.4012 2.3964 2.3916 2.3868 2.382 2.3772 2.3724 2.3675 2.3627 2.3578 2.3528 2.3479 2.343 2.338 2.333 2.328 2.323 2.3179 2.3129 2.3078 2.3027 2.2976 2.2924 2.2872 2.282 2.2768 2.2716 2.2663 2.2611 2.2558 2.2504 2.2451 2.2397 2.2343 2.2289 2.2234 2.218 2.2125 2.2069 2.2014 2.1958 2.1902 2.1846 2.1789 2.1732 2.1675 2.1618 2.156 2.1502 2.1444 2.1385 2.1326 2.1267 2.1207 2.1147 2.1087 2.1026 2.0965 2.0904 2.0842 2.078 2.0717 2.0655 2.0591 2.0528 2.0464 2.0399 2.0334 2.0269 2.0203 2.0137 2.0071 2.0004 1.9936 1.9868 1.9799 1.973 1.9661 1.9591 1.952 1.9449 1.9377 1.9305 1.9232 1.9158 1.9084 1.9009 1.8934 1.8858 1.8781 1.8704 1.8625 1.8546 1.8466 1.8386 1.8304 1.8222 1.8139 1.8055 1.797 1.7884 1.7797 1.7709 1.762 1.753 1.7438 1.7346 1.7252 1.7157 1.706 1.6962 1.6863 1.6762 1.666 1.6555 1.6449 1.6341 1.6231 1.6119 1.6004 1.5888 1.5768 1.5646 1.5521 1.5393 1.5261 1.5126 1.4987 1.4843 1.4695 1.4541 1.4381 1.4214 1.404 1.3857]1-0.05124.97123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import requestsimport jsonimport os
DATABASE_URL = # your_URL_here
def safe_key(text): return text.replace('.', '_')
# --------------- Save results into local JSONL file ----------------
def save_result(title, model, save_file=None): key = f"{title}-{safe_key(model)}" url = f"{DATABASE_URL}/results/{key}.json" response = requests.get(url) if response.status_code != 200: raise Exception(f"Failed to fetch result: {response.status_code}, {response.text}") results = response.json() res = list(results.values()) if results else []
if save_file: with open(save_file, "w") as f: for result in res: f.write(json.dumps(result) + "\n") return res
# --------------- Get all results for a list of models ----------------
def get_all_results(title, model_list): return [{model: save_result(title, model, None)} for model in model_list]
# --------------- Save all results into local JSONL files ----------------
def save_all_results(titles, models, save_dir): os.makedirs(save_dir, exist_ok=True) for title in titles: for model in models: filename = f"{safe_key(model)}-{title}.jsonl" filepath = os.path.join(save_dir, filename) save_result(title, model, filepath)
# --------------- Get filename for model ----------------
def get_filename(titles, models, save_dir): for title in titles: for model in models: filename = f"{safe_key(model)}-{title}.jsonl" return filename
import os
def find_incomplete_prompts(save_dir, n): model_to_titles = {}
for filename in os.listdir(save_dir): if not filename.endswith('.jsonl'): continue
file_base = filename[:-6] # remove '.jsonl'
q_idx = file_base.rfind('-Q') if q_idx == -1: continue
model_name = file_base[:q_idx] title = file_base[q_idx+1:]
filepath = os.path.join(save_dir, filename) try: with open(filepath, 'r') as f: num_lines = sum(1 for _ in f) except Exception as e: print(f"Error reading {filepath}: {e}") continue
# Each line = one entry if num_lines < n: if model_name not in model_to_titles: model_to_titles[model_name] = [] model_to_titles[model_name].append(title) for model in model_to_titles: model_to_titles[model].sort(key=lambda x: int(x[1:]))
return model_to_titles
def get_attempts_left(models, titles, save_dir, n): attempts_left = []
for model in models: model_attempts = [] for title in titles: filename = f"{safe_key(model)}-{title}.jsonl" filepath = os.path.join(save_dir, filename)
# Count number of attempts already saved if os.path.exists(filepath): try: with open(filepath, 'r') as f: num_lines = sum(1 for _ in f) except Exception as e: print(f"Error reading {filepath}: {e}") num_lines = 0 else: num_lines = 0
# Compute how many more are needed remaining = max(0, n - num_lines) model_attempts.append(remaining) attempts_left.append(model_attempts)
return attempts_left
#titles=["Q" + str(i) for i in range(1, 136)]#models = ['gemini-2.5-pro-preview-03-25']# save_all_results(titles, models, '/home/joseph_tennyson/physics/physics-benchmark/client/Responses_small')# a = get_attempts_left(# models=["gemini-2.5-pro-preview-03-25"],# titles=["Q" + str(i) for i in range(1, 136)],# save_dir= "/home/joseph_tennyson/physics/physics-benchmark/client/Responses_small",# n=10# )# print(a)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import requestsimport time
BASE_URL = # your_URL_here
def run(models, prompts, titles, num_elems, num_repeats=1): payload = { "models": models, "prompts": prompts, "titles": titles, "num_elems": num_elems, "num_repeats": num_repeats } r = requests.post(f"{BASE_URL}/run", json=payload) return r.json()
def run_with_code_interpreter(models, prompts, titles, num_elems, file_paths_per_question, num_repeats=1): """ Run queries with code interpreter enabled and file access. Args: models: List of model names prompts: List of prompts/questions titles: List of question titles num_elems: List of expected return lengths (0 for scalar, >0 for array) file_paths_per_question: List of lists - each inner list contains file paths for that question num_repeats: Number of repeats (int or nested list) """ payload = { "models": models, "prompts": prompts, "titles": titles, "num_elems": num_elems, "file_paths_per_question": file_paths_per_question, "num_repeats": num_repeats } r = requests.post(f"{BASE_URL}/run_with_code_interpreter", json=payload) return r.json()
def status(): r = requests.get(f"{BASE_URL}/status") return r.json()
def cancel(): r = requests.post(f"{BASE_URL}/cancel") return r.json()
1requests123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# CME-SpectrumBench Arena
## Installation and API usage
Before using the client:
1. Install the required packages: ```bash pip install -r client_requirements.txt2. In `server/db.py`, write in your database URL after `databaseURL`. Likewise for the variable `DATABASE_URL` in `client/call_db.py`.3. Ensure that the correct API site is reflected in the variable `BASE_URL` of `client/call_server.py`.
<br><br>
## General notes, and structure of code & data
- The benhcmark codebase has two domains: the scientific-facing side, and an API-facing side.- Reflecting this dichotomy, the codebase is split into two main folders, `client` (which prepares benchmark questions, sends questions to the server, reads model responses, evaluates/plots the responses, and generates leaderboards), and `server` (which manages the database in which responses are kept, and how models are queried through APIs).- The run script with the directory set to the `client` folder.- Note the five scripts in the `client` folder. `call_server.py` and `call_db.py` queries the server and pulls results respectively (next two sections). `init.py` contains the bulk of ARPES-specific code and is understandable only by those well-versed in that subfield of condensed matter; contact the authors for more detail. Both `ask.py` and `eval.py` call upon `init.py` for their operation; `ask.py` asks the server questions and the database for responses, while `eval.py` scores these responses. These will be elaborated in later subsections.- Let us now go through the various subfolders of the `client` folder. Note that `_small`, `_med`, and `_large` appended after folders refers to the resolution sizes of questions asked; these are folders for which all questions are posed to all models. `_single` refers to single questions posed to single models, while one parameters (noise or resolution) is varied. Note that the leaderboard ranks the scores of models to `small` resolution questions only, as this was the largest approxciamte set of resolutions that fit within the smallest context windows of all models tested (somewhere on the order 100k tokens once three-shot prompting has been taken into account).- The folder `evaluation` contains summaries of all results (such as leaderboards) as well as results for individual models.- The folder `Evaluation_plots` contains the plots of all results obtained by all models, where rhe numbering of questions runs from `Q1` to `Q190` covering all categories in order (see appendix E) with five noise/convolution levels per question. Its subfolder `Evaluation_single` collects the plots of individual questions, where `_r[...]` refers to the resolution of that dataset and `_n[...]` its noise level (in percent). Here, questions are labelled by category rather than question number.- The folder `Evaluation_single` (not to be confused with the prior subfolder) contains plots for single questions with varying noise/resolution.- `Plots` contain plots for all questions, listed under their respective categories, in both .txt (spectra) and .png (images of spectra) formats. Note the format of their names, which applies in general elsewhere. Examples given here will suffice. `A1a` refers to question A1, example a (for three-shot questions, examples a, b, c and are given with answers, and d as the actual question to be asked; for one-shot, only one example a is given, and b is the actual question). `_r25` refers to a resolution of 100 pixels along the horizontal axis, `_n20` to a noise level of 20%, `_k5_e3` to a momentum convolution of 0.005 inverse Angstrom and 0.003 electron-Volts (these are the same for all questions in our benchmark, but may in principle be varied). Lastly, note that questions in the D1 category have an additional parameter in their title referring to phononic coupling strength: `_l05`, `_l075`, `_l10`, `_l20`, and `_l50` refer to coupling strengths of 0.5, 0.75, 1.0, 2.0, and 5.0 respectively.- The various folders beginning with `Prompts` contain the actual prompts given to the question (.txt files ending with `_Q`, for 'question') and their respective solutions (ending with `_S`, for 'solution'). The previous comments on resolution sizes (`_small`, `_medium`, `_large`) and single prompts (`_single`) applies.- Likewise, folders beginning with `Responses` list the responses of various models to all questions.- Users wishing to use apply the benchmark to new models may modify code in `client/ask.py` and `client/eval.py`. However, those wishing to extend existing benchmark questions to other domains of physics or science will have to modify `client/init.py`; for this purpose it is best to contact the authors for more complete documentation and an elaboration of their philosophy.
<br><br>
## Backend Server Setup
### Database Setup (Firebase)
1. Create a Firebase project and enable Firestore2. Download your Firebase service account admin file and save it to `db_admin.json` in the `server/` directory
### Server Setup
1. Install server dependencies: ```bash cd server pip install -r ../serve_requirements.txt ```
2. Set up ngrok for external access: ```bash chmod +x setup_ngrok.sh ./setup_ngrok.sh ngrok config add-authtoken YOUR_AUTHTOKEN_HERE ```
3. Start the server: ```bash uvicorn main:app --host 0.0.0.0 --port 8000 ```
4. In a separate terminal, start ngrok: ```bash ngrok http 8000 ```
### Environment Variables
Create a `.env` file in the root directory with the following variables:
#### Example API Keys```bash# OpenAI API (for GPT models, o1 models)OPENAI_API_KEY=your_openai_api_key_here
# Anthropic API (for Claude models)ANTHROPIC_API_KEY=your_anthropic_api_key_here
# Google AI API (for Gemini models)GOOGLE_API_KEY=your_google_api_key_here
# DeepSeek API (for DeepSeek models)DEEPSEEK_API_KEY=your_deepseek_api_key_here
# xAI API (for Grok models)XAI_API_KEY=your_xai_api_key_here
# OpenRouter API (for various models)OPENROUTER_API_KEY=your_openrouter_api_key_here```
#### Required URLs```bash# Firebase Database URLFIREBASE_DB_URL=https://your-project-id.firebaseio.com
# Server Base URL (your ngrok URL)BASE_URL=https://your-ngrok-url.ngrok.io```<br><br>
## Querying the Server (`client/call_server.py`)
### `run(models, prompts, titles, num_elems, num_repeats=1)`Starts a new experiment by sending prompts to the server. Only one job can run at once; additional attempts are blocked.
- `models`: list of model names to query- `prompts`: list of prompts- `titles`: list of unique titles for each prompt- `num_elems`: list of values to extract per prompt (0 for a scalar, 1+ for an array with the specified length)- `num_repeats`: how many times to repeat each query (default = 1, meaning it isn't repeated, only done once) - NOTE: can also pass in a 2D array from calling `client/call_db.py` get_attempts_left so that each model and prompt pair is repeated until a certain amount of attempts are completed
For the ith prompt in prompts, we expect it to have a title of titles[i] and to have an array length of `num_elems[i]` (or to be a scalar if `num_elems[i] == 0`)
### `status()`Returns the current server status, including whether a job is running and progress info.
### `cancel()`Sends a request to cancel the currently running job.
<br><br>
## Pulling Results (`client/call_db.py`)
### `save_result(title, model, save_file=None)`Fetches all results for a given title and model. If `save_file` is provided, saves the results to a `.jsonl` file, with one line per attempt.
### `get_all_results(title, model_list)`Fetches all results for a given title across multiple models. Returns a list of dictionaries, each containing model results.
### `save_all_results(titles, models, save_dir)`Saves results for **every** `(title, model)` pair into separate `.jsonl` files inside the specified `save_dir`. Each file is named as `title-model.jsonl`.
### `find_incomplete_prompts(find_incomplete_prompts(save_dir, n)`Takes in a save_dir where the output files reside. For every model, find prompts in which the number of recorded entries is less than a specified threshold `n`.
### `get_attempts_left(models, titles, save_dir, n):`Get the number of attempts left to get n total attempts for each title. Looks within save_directory. Outputs a 2d array whereoutput[`i`][`j`] is how many attempts model i has on title j to reach the target number.
<br><br>
## Asking questions (`client/ask.py`)
Skipping past numerous subsidiary functions, these are the ones that matter and the user is expected to call.
### `ask_batch(size, retrieve, attempts)`
- Asks all questions to all models listed.- Models to be called should be listed in the line `models = [...]`.- `size` indicates the resolution of the questions given, where 1 refers to small, 2 medium, and 3 large. Recall that the standard leaderboard reflects answers to small resolution questions only (`size=1`).- `retrieve` toggles whether previously generated spectra (saved under `Prompts_[...]`) are to be reused for the current set of questions; this frees the program from having to generate all 190 questions again from scratch (which may take several minutes), which is especially useful for debugging. Ça va sans dire that these questions should have been generated beforehand. `retrieve=0` to generate questions from scratch, and `retrieve=1` to reuse previously generated questions.- `attempts` indicates the number of times each question to be posed to each model; that is, the sample size. Note that we can 'top up' responses such that if `n` responses have already been collected for some question where `attempts = m > n`, then only `m-n` more responses will be requested for that question. This requires the existing responses to be loaded into the appropriate `client/Responses_[...]` folder using the `save_batch()` function (next point).
### `save_batch(size, attempts)`
- Saves responses for the listed models (under `model=[...]`) from the database.- `size` and `attempts` are the same parameters as before.
### `ask_resolution_iter(question_category, resolution_array, noise_ratio, attempts)` and `ask_noise_iter(question_category, resolution, noise_ratio_array, attempts)`
- Asks a single question (listed under the text variable `question_category`) for models listed in `models=[...]` for a total number of `attempts` stated.- Available text strings for `question_category` are listed within the previous function in the script, `get_single_prompt`.- Resolution sizes should be either given as an array (`resolution_array` in the first function) or fixed (`resolution` in the second function). Resolution is defined as the number of pixels along the horizontal axis of spectra.- Noise level (as a fraction of the maximum signal intensity) should be fixed (`noise_ratio` in the first function) or given as an array (`noise_ratio_array` in the second).
### `save_resolution_iter(question_category, resolution_array, noise_ratio, attempts)` and `save_noise_iter(question_category, resolution, noise_ratio_array, attempts)`
- These save responses to questions asked by the previous two functions.- Their input variables are equivalent to the ones described above.
<br><br>
## Evaluating responses and ranking models (`client/eval.py`)
Skipping past numerous subsidiary functions, these are the ones that matter and the user is expected to call.
### `score_models()`
- After testing all 190 questions a list of models in `client/ask.py` using the function `ask_batch()` and saving them from the databased using the function `save_batch()`, this function scores all models in the list `model_list_1` with accompanying names in `model_name_1`.- Responses are read off from the relevant `Responses_[...]` folder (in this case, only low resolution questions were scored).- Leaderbaords and detailed breakdowns are generated and saved under the relevant folders.
### `plot_models()`
- Similar function to the above, calls a set of `plot_model_responses(model_name, size)` for various models stated in `model_name` of resolution sizes listed (`size = 1,2,3` for small, medium, and large).- Responses are read off from the relevant `Responses_[...]` folder
Note that the following functions were written to score a small number of question categories over a range of resolutions/frequencies; the user may extend these functions at will.
### `score_A1_B1_single_resolution_iter(model, resolution_array_A1, resolution_array_B1, noise_ratio)`
- For a given `model`, plots how scores for question categories A1 and B1 vary with resolution (stated in the two respective resolution arrays), for a fixed `noise_ratio`.
### `score_four_single_noise_iter(model, resolution, noise_array)`
- For a given `model` and `resolution`, plots how scores for A1, B1, B2, and D1 (with coupling strength 1) vary with noise (stated in `noise_array`).
### `plot_noise_responses(model, resolution, noise_array, question_category)`
- Analogous to `plot_models()` but applies to noise-dependent questions given by the given function.- Input variables are self-explanatory.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798aiofiles==24.1.0annotated-types==0.7.0anthropic==0.50.0anyio==4.9.0asttokens==3.0.0CacheControl==0.14.2cachetools==5.5.2certifi==2025.1.31cffi==1.17.1charset-normalizer==3.4.1click==8.1.8comm==0.2.2contourpy==1.3.2cryptography==44.0.2cycler==0.12.1decorator==5.2.1distro==1.9.0executing==2.2.0fastapi==0.115.12firebase-admin==6.8.0fonttools==4.57.0gcloud==0.18.3google-ai-generativelanguage==0.6.15google-api-core==2.24.2google-api-python-client==2.168.0google-auth==2.39.0google-auth-httplib2==0.2.0google-cloud-core==2.4.3google-cloud-firestore==2.20.2google-cloud-storage==3.1.0google-crc32c==1.7.1google-genai==1.12.1google-generativeai==0.8.5google-resumable-media==2.7.2googleapis-common-protos==1.70.0grpcio==1.71.0grpcio-status==1.71.0h11==0.16.0httpcore==1.0.9httplib2==0.22.0httpx==0.28.1idna==3.10ipython==9.2.0ipython_pygments_lexers==1.1.1ipywidgets==8.1.6jedi==0.19.2jiter==0.9.0jupyterlab_widgets==3.0.14jws==0.1.3kiwisolver==1.4.8matplotlib==3.10.1matplotlib-inline==0.1.7msgpack==1.1.0numpy==2.2.5oauth2client==4.1.3openai==1.76.0packaging==25.0pandas==2.2.3parso==0.8.4pexpect==4.9.0pillow==11.2.1prompt_toolkit==3.0.51proto-plus==1.26.1protobuf==5.29.4ptyprocess==0.7.0pure_eval==0.2.3pyasn1==0.6.1pyasn1_modules==0.4.2pycparser==2.22pycryptodome==3.22.0pydantic==2.11.3pydantic_core==2.33.1Pygments==2.19.1PyJWT==2.10.1pyparsing==3.2.3Pyrebase4==4.8.0python-dateutil==2.9.0.post0python-dotenv==1.1.0python-jwt==2.0.1pytz==2025.2requests==2.32.3requests-toolbelt==0.10.1rsa==4.9.1six==1.17.0sniffio==1.3.1stack-data==0.6.3starlette==0.46.2tqdm==4.67.1traitlets==5.14.3typing-inspection==0.4.0typing_extensions==4.13.2tzdata==2025.2uritemplate==4.1.1urllib3==1.26.20uvicorn==0.34.2wcwidth==0.2.13websockets==15.0.1widgetsnbextension==4.0.14123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import firebase_adminfrom firebase_admin import credentials, dbimport jsonimport os
cred = credentials.Certificate("db_admin.json")firebase_admin.initialize_app(cred, { 'databaseURL': # your_URL_here})
def safe_key(text): return text.replace('.', '_')
def append_result(title, model, result): key = f"{title}-{safe_key(model)}" data = result ref = db.reference(f"results/{key}") ref.push(data)
# save with jsonl formatdef save_result(title, model, save_file=None): key = f"{title}-{safe_key(model)}" ref = db.reference(f"results/{key}") results = ref.get() res = list(results.values()) if results else [] if save_file: with open("results.jsonl", "w") as f: for result in res: f.write(json.dumps(result) + "\n") return res
def get_all_results(title, model_list): return [{model: save_result(title, model, None)} for model in model_list]
def save_all_results(titles, models, save_dir): os.makedirs(save_dir, exist_ok=True) for title in titles: for model in models: filename = f"{title}-{safe_key(model)}.jsonl" filepath = os.path.join(save_dir, filename) save_result(title, model, filepath)
def reset_db(): ref = db.reference("results") ref.delete()
def delete_model_entries(model): ref = db.reference("results") all_entries = ref.get() if not all_entries: print("No entries found.") return target_suffix = safe_key(model) keys_to_delete = [] for key in all_entries.keys(): if key.endswith(f"-{target_suffix}"): keys_to_delete.append(key) for key in keys_to_delete: print(f"Deleting {key}") db.reference(f"results/{key}").delete()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom typing import List, Optional, Unionimport asyncio
from serve import run_model_prompt_queries # your async query runner
app = FastAPI()
# Shared statestatus = { "is_running": False, "done": 0, "total": 0,}
status_lock = asyncio.Lock()lock = asyncio.Lock()running_task: Optional[asyncio.Task] = None # Reference to the active task
class QueryRequest(BaseModel): models: List[str] prompts: List[str] titles: Optional[List[str]] num_elems: List[int] num_repeats: Union[int, List[List[int]]]
@app.post("/run")async def run_queries(req: QueryRequest): global running_task
if lock.locked(): raise HTTPException(status_code=400, detail="Server is already processing a request.")
async def run_and_track(): async with lock: status["is_running"] = True status["done"] = 0 status["total"] = len(req.models) * len(req.prompts) * req.num_repeats
async def progress_callback(): async with status_lock: status["done"] += 1
try: await run_model_prompt_queries(**req.model_dump(), progress_cb=progress_callback) except asyncio.CancelledError: print("Task was cancelled.") raise finally: status["is_running"] = False
# Launch task and store reference running_task = asyncio.create_task(run_and_track()) return {"status": "started"}
@app.post("/cancel")async def cancel_query(): global running_task
if running_task is None or running_task.done(): return {"status": "no task running"}
running_task.cancel() try: await running_task except asyncio.CancelledError: pass
return {"status": "cancelled"}
@app.get("/status")async def get_status(): return status123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311import osimport jsonimport reimport timeimport asyncioimport httpxfrom typing import Any, Dictimport datetimefrom openai import AsyncOpenAIimport mathimport aiofiles
from google import genaifrom google.genai import typesimport hashlibfrom datetime import datetime, timezone, timedelta
from dotenv import load_dotenv# Load .env from server/ so it works whether you run from project root or server/_load_env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")load_dotenv(dotenv_path=_load_env_path)
from aiolimiter import AsyncLimiter
# Add rate limitersopenai_semaphore = asyncio.Semaphore(25)openai_limiter = AsyncLimiter(10, time_period=60)
qwen_semaphore = asyncio.Semaphore(25)qwen_limiter = AsyncLimiter(10, time_period=60)
gemini_flash_semaphore = asyncio.Semaphore(15)gemini_flash_limiter = AsyncLimiter(15, time_period=60)
gemini_pro_semaphore = asyncio.Semaphore(15)gemini_pro_limiter = AsyncLimiter(5, time_period=60)
claude_semaphore = asyncio.Semaphore(20)claude_limiter = AsyncLimiter(10, time_period=60)
deepseek_semaphore = asyncio.Semaphore(2)deepseek_limiter = AsyncLimiter(1, time_period=60)
TIMEOUT = 43200# 4 hours in secondsNUM_RETRIES = 2_REGISTRY: Dict[str, Any] = {}_CODE_EXECUTION_REGISTRY: Dict[str, Any] = {}
def register_model(model: str): def decorator(fn): _REGISTRY[model] = fn return fn return decorator
def register_code_execution(model: str): def decorator(fn): _CODE_EXECUTION_REGISTRY[model] = fn return fn return decorator
# ------------------------ Extract value ------------------------
def parse_answer_reasoning_tags(text: str) -> tuple[str, str]: """ Parse <answer> and <reasoning> tags from text if they exist. Returns (answer_text, reasoning_text). If tags don't exist, returns (full_text, empty_string). """ answer_match = re.search(r'<answer>(.*?)</answer>', text, re.DOTALL | re.IGNORECASE) reasoning_match = re.search(r'<reasoning>(.*?)</reasoning>', text, re.DOTALL | re.IGNORECASE) if answer_match: answer = answer_match.group(1).strip() reasoning = reasoning_match.group(1).strip() if reasoning_match else "" return answer, reasoning else: # No tags found, return full text as answer and empty reasoning return text, ""
def extract_value(text: str, length: int): if text is None: raise ValueError("Output is None") if not text.strip(): raise ValueError("Empty output detected")
# First, try to parse answer/reasoning tags answer_text, reasoning_text = parse_answer_reasoning_tags(text) # Use the answer_text for extraction, but we'll return a dict with reasoning text_to_parse = answer_text
if length > 0: # Match a list of values inside brackets match = re.search(r'\[(.*?)\]', text_to_parse, re.DOTALL) if not match: raise ValueError(f"No bracketed list found in output, value is {text_to_parse[:50]}")
raw_items = match.group(1).split(',') result = [] for x in raw_items: x = x.strip() try: val = float(x) if math.isnan(val) or math.isinf(val): result.append(None) else: result.append(val) except ValueError: result.append(None) return {"answer": result, "reasoning": reasoning_text} else: match = re.search(r'-?\d+(?:\.\d+)?', text_to_parse) if not match: raise ValueError(f"No numeric value found in output, {text_to_parse}") val = float(match.group()) answer = None if math.isnan(val) or math.isinf(val) else val return {"answer": answer, "reasoning": reasoning_text}
def check_type(output, length): # Handle new dict format with answer and reasoning if isinstance(output, dict) and "answer" in output: answer = output["answer"] cond = True if length == 0: cond = False return isinstance(answer, list) is cond # Legacy format (backward compatibility) cond = True if length == 0: cond = False return isinstance(output, list) is cond
def _provider_details(model: str): """ Pick the right endpoint + API-key env-var based on model prefix. DeepSeek is OpenAI-compatible, so same format — just different base URL and key. """ if model.startswith("deepseek"): return "https://api.deepseek.com/v1/chat/completions", "OPENAI_API_KEY" if model.startswith("grok"): # xAI / Grok models return "https://api.x.ai/v1/chat/completions", "XAI_API_KEY" return "https://api.openai.com/v1/chat/completions", "OPENAI_API_KEY"
# ------------------------ OpenAI (Tool-calling) ------------------------
async def _openai_with_tool(model: str, prompt: str, length=0, **kwargs) -> Any: async with openai_semaphore: async with openai_limiter: tools = [{ "type": "function", "function": { "name": "return_array", "description": f"Return an array of exactly {max(length, 1)} decimal numbers.", "parameters": { "type": "object", "properties": { "numbers": { "type": "array", "items": {"type": "number"}, "minItems": max(length, 1), "maxItems": max(length, 1) } }, "required": ["numbers"] } } }] reasoning = model.split("-")[-1] model_base = model[: -len(reasoning) - 1] if reasoning in ["low", "medium", "high"] else model payload = { "model": model_base, "messages": [{"role": "user", "content": prompt}], "tools": tools, "tool_choice": "auto" } if reasoning in ["low", "medium", "high"]: payload["reasoning_effort"] = reasoning url, key_env = _provider_details(model)
headers = { "Authorization": f"Bearer {os.getenv(key_env)}", "Content-Type": "application/json" }
async with httpx.AsyncClient(timeout=TIMEOUT) as client: s = time.time() resp = await client.post( url, headers=headers, json=payload ) resp.raise_for_status() data = resp.json() args_str = data["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"] res = json.loads(args_str)['numbers'] return res if length != 0 else res[0]
# ------------------------ OpenAI basic + DeepSeek (dynamic) ------------------------@register_model("o3-pro")@register_model("gpt-oss-20b")@register_model("gpt-oss-120b")@register_model("o1-mini")@register_model("o1-low")@register_model("o1-medium")@register_model("o1-high")@register_model("o3-low")@register_model("o3-medium")@register_model("o3-high")@register_model("o3-mini-low")@register_model("o3-mini-medium")@register_model("o3-mini-high")@register_model("o4-mini-low")@register_model("o4-mini-medium")@register_model("o4-mini-high")@register_model("gpt-5.4")@register_model("gpt-5")async def _openai_basic(model: str, prompt: str, length: int = 0, **kwargs) -> Any: async with openai_semaphore: async with openai_limiter: # ── 1. Derive base-model and reasoning effort ────────────────────────── reasoning = model.split("-")[-1] model_base = ( model[: -len(reasoning) - 1] if reasoning in {"low", "medium", "high"} else model )
payload = { "model": model_base, "messages": [{"role": "user", "content": prompt}], } if reasoning in {"low", "medium", "high"}: payload["reasoning_effort"] = reasoning
# ── 2. Resolve provider URL & key dynamically ────────────────────────── url, key_env = _provider_details(model) headers = { "Authorization": f"Bearer {os.getenv(key_env)}", "Content-Type": "application/json", }
# ── 3. Fire request and parse response ───────────────────────────────── async with httpx.AsyncClient(timeout=TIMEOUT) as client: resp = await client.post(url, headers=headers, json=payload) resp.raise_for_status() text = resp.json()["choices"][0]["message"]["content"]
return extract_value(text, length)
# ------------------------ DeepSeek V4 (OpenAI-compatible, own semaphore/limiter) ------------------------# Same logic as _openai_basic — DeepSeek uses the OpenAI-compatible format.# _provider_details routes deepseek-* to api.deepseek.com with OPENAI_API_KEY.# @register_model("deepseek-v4-pro") # temporarily using call_openrouter belowasync def _deepseek_v4_basic(model: str, prompt: str, length: int = 0, **kwargs) -> Any: async with deepseek_semaphore: async with deepseek_limiter: url, key_env = _provider_details(model) headers = { "Authorization": f"Bearer {os.getenv(key_env)}", "Content-Type": "application/json", } payload = { "model": model, "messages": [{"role": "user", "content": prompt}], } async with httpx.AsyncClient(timeout=TIMEOUT) as client: resp = await client.post(url, headers=headers, json=payload) resp.raise_for_status() text = resp.json()["choices"][0]["message"]["content"] return extract_value(text, length)
@register_model("deepseek-v4-pro") # temporary: testing via openrouter@register_model("deepseek-reasoner")@register_model("kimi-k2")@register_model("glm-4.5")@register_model("qwen3-235b-thinking")@register_model("grok-4")async def call_openrouter(model: str, prompt: str, length=0, **kwargs) -> Any: """ Universal OpenRouter handler with reasoning effort support for OpenAI models. Handles model name mapping and reasoning effort extraction. IMPORTANT: reasoning_effort is ONLY applied to OpenAI models (o1/o3/o4-mini variants). Other models ignore this parameter safely. """ # Model name mapping for custom aliases name_map = { "deepseek-v4-pro": "deepseek/deepseek-v4-pro", "deepseek-reasoner": "deepseek/deepseek-r1", "o3-pro": "openai/o3-pro", "kimi-k2": "moonshotai/kimi-k2", "glm-4.5": "z-ai/glm-4.5", "qwen3-235b-thinking": "qwen/qwen3-235b-a22b-thinking-2507", "gpt-oss-20b": "openai/gpt-oss-20b", "gpt-oss-120b": "openai/gpt-oss-120b", "gpt-5": "openai/gpt-5", "grok-4": "x-ai/grok-4", "claude-3-7-sonnet-20250219": "anthropic/claude-3.7-sonnet", "claude-opus-4-5": "anthropic/claude-opus-4.5", "claude-sonnet-4-5": "anthropic/claude-sonnet-4.5", "gemini-2.0-flash": "google/gemini-2.0-flash-001", "gemini-2.0-flash-lite-preview-02-05": "google/gemini-2.0-flash-lite-001", "gemini-3-pro-preview": "google/gemini-3-pro-preview", "gemini-3-flash-preview": "google/gemini-3-flash-preview", "gemini-2.5-pro": "google/gemini-2.5-pro", "gemini-2.5-flash": "google/gemini-2.5-flash", "gemini-3.1-pro": "google/gemini-3.1-pro-preview", } # Handle OpenAI reasoning models (o1, o3, o4-mini variants) # These are the ONLY models that support reasoning_effort parameter openai_reasoning_models = { "o1-mini": "openai/o1", "o1-low": "openai/o1", "o1-medium": "openai/o1", "o1-high": "openai/o1", "o3-low": "openai/o3", "o3-medium": "openai/o3", "o3-high": "openai/o3", "o3-mini-low": "openai/o3-mini", "o3-mini-medium": "openai/o3-mini", "o3-mini-high": "openai/o3-mini", "o4-mini-low": "openai/o4-mini", "o4-mini-medium": "openai/o4-mini", "o4-mini-high": "openai/o4-mini", } # Determine OpenRouter model name and reasoning effort reasoning_effort = None is_openai_reasoning = False if model in openai_reasoning_models: openrouter_model = openai_reasoning_models[model] is_openai_reasoning = True # Extract reasoning effort from suffix effort_level = model.split("-")[-1] if effort_level in ["low", "medium", "high"]: reasoning_effort = effort_level elif model in name_map: openrouter_model = name_map[model] else: # Fallback: assume model name is already in OpenRouter format openrouter_model = model # Select appropriate rate limiter based on provider if "google" in openrouter_model or "gemini" in openrouter_model.lower(): if "flash" in openrouter_model.lower(): semaphore = gemini_flash_semaphore limiter = gemini_flash_limiter else: semaphore = gemini_pro_semaphore limiter = gemini_pro_limiter elif "anthropic" in openrouter_model or "claude" in openrouter_model.lower(): semaphore = claude_semaphore limiter = claude_limiter else: # OpenAI and all others (grok, qwen, glm, kimi, deepseek) semaphore = openai_semaphore limiter = openai_limiter async with semaphore: async with limiter: client = AsyncOpenAI( base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OPENROUTER_API_KEY"), timeout=TIMEOUT # Use the same 4-hour timeout ) # Build request payload # Add cache_control for Claude models if "anthropic" in openrouter_model or "claude" in openrouter_model.lower(): request_params = { "model": openrouter_model, "messages": [{ "role": "user", "content": [{ "type": "text", "text": prompt, "cache_control": {"type": "ephemeral"} }] }] } else: request_params = { "model": openrouter_model, "messages": [{"role": "user", "content": prompt}] } # Add reasoning_effort ONLY for OpenAI reasoning models # This ensures we never accidentally pass it to non-OpenAI models if reasoning_effort and is_openai_reasoning: request_params["reasoning_effort"] = reasoning_effort response = await client.chat.completions.create(**request_params) return extract_value(response.choices[0].message.content, length)
# ------------------------ Gemini ------------------------_cache_lookup = {} # display_name -> [cache_name, expire_time]_cache_lock = asyncio.Lock()TTL_SECONDS = 300TTL_UPDATE = 20TTL_STOP_UPDATE = 10
def _make_display_name(prompt: str) -> str: return "cache-" + hashlib.sha256(prompt.encode()).hexdigest()[:16]
def to_update(expire_time) -> bool: cur_time = time.time() return cur_time + TTL_UPDATE > expire_time and cur_time < expire_time - TTL_STOP_UPDATE
def to_create(expire_time) -> bool: cur_time = time.time() return cur_time > expire_time - TTL_STOP_UPDATE
@register_code_execution("gemini-3.1-pro")@register_code_execution("gemini-3.1-pro-preview")@register_code_execution("gemini-2.0-flash")@register_code_execution("gemini-2.0-flash-lite-preview-02-05")@register_code_execution("gemini-3-pro-preview")@register_code_execution("gemini-3-flash-preview")@register_code_execution("gemini-2.5-pro")@register_code_execution("gemini-2.5-flash")async def _gemini_with_code_execution( model: str, prompt: str, file_paths: list, file_path_to_id: dict, title: str, length: int = 0) -> Any: """ Call Gemini model with code execution enabled. Accepts file_path_to_id as nested dict with 'gemini' key containing Gemini file objects. For gemini-3.1-pro variants the prompt is augmented with a 20-call budget constraint. """ _gemini_sdk_name_map = {"gemini-3.1-pro": "gemini-3.1-pro-preview"} sdk_model = _gemini_sdk_name_map.get(model, model)
if model == "gemini-2.0-flash": gemini_semaphore = gemini_flash_semaphore gemini_limiter = gemini_flash_limiter else: gemini_semaphore = gemini_pro_semaphore gemini_limiter = gemini_pro_limiter
_31_pro_models = ("gemini-3.1-pro", "gemini-3.1-pro-preview") effective_prompt = ( prompt + "\n\nConstraint: use at most 20 code execution calls. " "If you cannot finish within that limit, return an empty response." ) if model in _31_pro_models else prompt
config = types.GenerateContentConfig( tools=[types.Tool(code_execution=types.ToolCodeExecution())] )
async with gemini_semaphore: async with gemini_limiter: client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY")) aio = client.aio
try: contents = [] if file_paths and file_path_to_id and "gemini" in file_path_to_id: gemini_files = file_path_to_id["gemini"] for file_path in file_paths: if file_path in gemini_files: contents.append(gemini_files[file_path]) contents.append(effective_prompt)
response = await aio.models.generate_content( model=sdk_model, contents=contents, config=config, )
usage = getattr(response, 'usage_metadata', None) thoughts_tok = getattr(usage, 'thoughts_token_count', None) if usage else None candidates_tok = getattr(usage, 'candidates_token_count', None) if usage else None total_tok = getattr(usage, 'total_token_count', None) if usage else None
cand = response.candidates[0] if (hasattr(response, 'candidates') and response.candidates) else None finish_reason = getattr(cand, 'finish_reason', None) if cand else None safety_ratings = getattr(cand, 'safety_ratings', None) if cand else None safety_str = "" if safety_ratings: blocked = [f"{r.category.name}:{r.probability.name}" for r in safety_ratings if hasattr(r, 'blocked') and r.blocked] if blocked: safety_str = f" SAFETY_BLOCKED={blocked}"
_raw_parts = cand.content.parts if cand and cand.content else None parts = _raw_parts if _raw_parts is not None else [] n_code = sum(1 for p in parts if getattr(p, 'executable_code', None)) n_result = sum(1 for p in parts if getattr(p, 'code_execution_result', None)) n_plot = sum(1 for p in parts if getattr(p, 'inline_data', None)) n_text = sum(1 for p in parts if getattr(p, 'text', None))
print(f"Gemini {model} [{title}] finish={finish_reason} " f"tokens(thoughts={thoughts_tok} out={candidates_tok} total={total_tok}) " f"parts(code={n_code} result={n_result} plot={n_plot} text={n_text})" f"{safety_str}")
_fr_str = str(finish_reason) if "TOO_MANY_TOOL_CALLS" in _fr_str: raise ValueError(f"TOO_MANY_TOOL_CALLS for {model} on {title}") if finish_reason is not None and "STOP" not in _fr_str: raise ValueError(f"Non-STOP finish reason for {model} on {title}: {finish_reason}")
text = response.text if (hasattr(response, 'text') and response.text) else None if text is None and cand: for part in parts: part_text = getattr(part, 'text', None) if part_text: text = part_text
if not text: parts_dump = [] if hasattr(response, 'candidates') and response.candidates: finish_reason = getattr(response.candidates[0], 'finish_reason', None) for i, part in enumerate(response.candidates[0].content.parts): if getattr(part, 'text', None): parts_dump.append(f" [{i}] text: {part.text[:120]!r}") elif getattr(part, 'executable_code', None): parts_dump.append(f" [{i}] executable_code: {(getattr(part.executable_code, 'code', '') or '')[:80]!r}") elif getattr(part, 'code_execution_result', None): parts_dump.append(f" [{i}] code_execution_result output: {(getattr(part.code_execution_result, 'output', '') or '')[:80]!r}") elif getattr(part, 'inline_data', None): parts_dump.append(f" [{i}] inline_data (e.g. plot image)") else: parts_dump.append(f" [{i}] unknown part: {part}") print(f"No text in Gemini response for {model} on {title}. finish_reason={finish_reason}, parts ({len(parts_dump)}):\n" + "\n".join(parts_dump)) raise ValueError(f"No text in response for model {model}")
print(f"Gemini {model} code execution response for {title}: {text[:200]}") return extract_value(text, length)
except Exception as e: print(f"Error in Gemini code execution for {model} on {title}: {e}") raise
@register_model("gemini-3.1-pro")@register_model("gemini-3.1-pro-preview")@register_model("gemini-2.0-flash")@register_model("gemini-2.0-flash-lite-preview-02-05")@register_model("gemini-3-pro-preview")@register_model("gemini-3-flash-preview")@register_model("gemini-2.5-pro")@register_model("gemini-2.5-flash")async def _gemini_basic(model: str, prompt: str, length=0, **kwargs) -> str: # Translate user-facing aliases to actual Google SDK model names _gemini_sdk_aliases = {"gemini-3.1-pro": "gemini-3.1-pro-preview"} sdk_model = _gemini_sdk_aliases.get(model, model)
if model == "gemini-2.0-flash": gemini_semaphore = gemini_flash_semaphore gemini_limiter = gemini_flash_limiter else: gemini_semaphore = gemini_pro_semaphore gemini_limiter = gemini_pro_limiter async with gemini_semaphore: async with gemini_limiter: # Create a new client instance for this call client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY")) aio = client.aio # Try to use caching, but fall back to non-cached if it fails cache_name = None use_cache = True try: display_name = _make_display_name(prompt) key = (display_name, model)
async with _cache_lock: expire_time = None if key in _cache_lookup: cache_name, expire_time = _cache_lookup[key] if to_update(expire_time): print('update cache for', display_name + " " + model) try: await aio.caches.update( name=cache_name, config=types.UpdateCachedContentConfig(ttl=f"{TTL_SECONDS}s") ) except Exception as e: print(f"Failed to update cache for {model}: {e}") cache_name = None use_cache = False if use_cache and ((not expire_time) or to_create(expire_time)): new_expire_time = time.time() + TTL_SECONDS print("create cache for", display_name + " " + model) try: new_cache = await aio.caches.create( model=sdk_model, config=types.CreateCachedContentConfig( display_name=display_name, contents=[ types.Content( role="user", parts=[types.Part(text=prompt)] ) ], ttl=f"{TTL_SECONDS}s", ) ) cache_name = new_cache.name _cache_lookup[key] = [cache_name, new_expire_time] except Exception as e: # Cache requires minimum tokens (4096 for flash, 2048 for pro) # This is expected for small prompts - just skip the warning if "too small" not in str(e): print(f"Cache not supported for {model}, proceeding without cache: {e}") cache_name = None use_cache = False except Exception as e: print(f"Cache setup failed for {model}, proceeding without cache: {e}") cache_name = None use_cache = False # Generate content with or without cache try: if use_cache and cache_name: response = await aio.models.generate_content( model=sdk_model, contents="Give answer only.", config=types.GenerateContentConfig(cached_content=cache_name), ) else: # Fall back to non-cached request response = await aio.models.generate_content( model=sdk_model, contents=prompt, ) # Check if response has text if not hasattr(response, 'text') or response.text is None: # Try to extract text from candidates if hasattr(response, 'candidates') and response.candidates: text = response.candidates[0].content.parts[0].text else: raise ValueError(f"No text in response for model {model}") else: text = response.text return extract_value(text, length) except Exception as e: print(f"Error generating content for {model}: {e}") raise
# ------------------------ Anthropic ------------------------@register_model("claude-opus-4-7")@register_model("claude-opus-4-6")@register_model("claude-sonnet-4-6")@register_model("claude-3-7-sonnet-20250219")@register_model("claude-opus-4-5")@register_model("claude-sonnet-4-5")async def _claude_basic(model: str, prompt: str, length=0, **kwargs) -> Any: async with claude_semaphore: async with claude_limiter: headers = { "x-api-key": os.getenv("ANTHROPIC_API_KEY"), "Content-Type": "application/json", "anthropic-version": "2023-06-01" }
body = { "model": model, "max_tokens": 64000, "messages": [ { "role": "user", "content": [ { "type": "text", "text": prompt, "cache_control": { "type": "ephemeral" } } ] } ] }
async with httpx.AsyncClient(timeout=TIMEOUT) as client: resp = await client.post("https://api.anthropic.com/v1/messages", headers=headers, json=body) resp.raise_for_status() text = resp.json()["content"][0]["text"] return extract_value(text, length)
# ------------------------ Ask wrapper ------------------------rate_limited_models = set()async def ask_model(model: str, prompt: str, cache, title, return_length=0) -> Any: handler = _REGISTRY.get(model) if not handler: raise ValueError(f"No handler registered for model {model}")
result = None for attempt in range(NUM_RETRIES): if model in rate_limited_models: print(f"Rate limited for model {model}, skipping...") return None if attempt > 0: await asyncio.sleep(60) try: result = await handler(model, prompt, return_length) if check_type(result, return_length): break raise TypeError(f"Check Type failed, expected return: {return_length}, got {result}") except Exception as e: if isinstance(e, httpx.HTTPStatusError) and e.response.status_code == 429: rate_limited_models.add(model) print(f"Error calling model {model} on attempt {attempt+1} with question {title}: {e}")
return result
# ------------------------ OpenAI Code Interpreter ------------------------
@register_code_execution("gpt-5.4")@register_code_execution("gpt-5")@register_code_execution("o3-low")@register_code_execution("o3-medium")@register_code_execution("o3-high")@register_code_execution("o4-mini-low")@register_code_execution("o4-mini-medium")@register_code_execution("o4-mini-high")async def _openai_with_code_interpreter( model: str, prompt: str, file_paths: list, file_path_to_id: dict, title: str, return_length: int = 0) -> Any: """ Call OpenAI model with code interpreter enabled and file access. Uses responses API with file_ids nested in container. Supports reasoning models (e.g., o3-low, o3-medium, o3-high). Args: model: OpenAI model name (e.g., "o3-low", "o3-medium", "o3-high", "gpt-4o") For o3 models with reasoning effort suffix, the function automatically splits "o3-low" into model="o3" with reasoning={"effort": "low"} prompt: The question/prompt file_paths: List of local file paths needed for this question file_path_to_id: Dict mapping file paths to OpenAI file IDs title: Question title for logging return_length: Expected return length (0 for scalar, >0 for array) """ async with openai_semaphore: async with openai_limiter: client = AsyncOpenAI( api_key=os.getenv("OPENAI_API_KEY"), timeout=TIMEOUT # Use the same 4-hour timeout ) # Parse model name and reasoning effort # For o3 models, split "o3-low" -> model="o3", reasoning={"effort": "low"} reasoning_effort = None model_name = model effort_level = model.split("-")[-1] # Extract "low", "medium", or "high" if effort_level in ["low", "medium", "high"]: model_name = model[: -len(effort_level) - 1] reasoning_effort = effort_level # Look up file IDs from the map # file_path_to_id is now nested: {"openai": {path: id}, "gemini": {path: file_obj}} file_ids = [] if file_paths and file_path_to_id and "openai" in file_path_to_id: openai_files = file_path_to_id["openai"] for file_path in file_paths: if file_path in openai_files: file_ids.append(openai_files[file_path]) else: raise ValueError(f"File {file_path} not found in uploaded OpenAI files map") # Build request parameters request_params = { "model": model_name, "tools": [ { "type": "code_interpreter", "container": { "type": "auto", # Critical: file_ids goes INSIDE container "file_ids": file_ids, }, } ], "input": [ { "role": "user", "content": [ { "type": "input_text", "text": prompt, } ], } ], } # Add reasoning parameter for o3 models if reasoning_effort: request_params["reasoning"] = {"effort": reasoning_effort} # Use responses API with file_ids inside container try: response = await client.responses.create(**request_params) # Extract output text from response output_text = "" if hasattr(response, 'output_text') and response.output_text: output_text = response.output_text elif hasattr(response, 'output') and response.output: for item in response.output: if hasattr(item, 'content'): for content_item in item.content: if hasattr(content_item, 'text'): output_text += content_item.text print(f"Model {model} response for {title}: {output_text[:200]}") # Extract the numerical result with reasoning result = extract_value(output_text, return_length) return result except Exception as e: print(f"Error in code interpreter call for {model} on {title}: {e}") raise
# ------------------------ Unified Code Execution Interface ------------------------
# ------------------------ Claude Code Execution ------------------------
# Cache and reference counting for Claude file uploads_claude_file_cache = {} # {file_path: file_id}_claude_file_refs = {} # {file_path: ref_count}_claude_upload_lock = None
def _get_claude_upload_lock(): """Lazy init lock to avoid issues with asyncio event loop at import time""" global _claude_upload_lock if _claude_upload_lock is None: _claude_upload_lock = asyncio.Lock() return _claude_upload_lock
async def clear_claude_cache(): """ Clear Claude file cache and refs (call at start of run). Also deletes all files from Claude API to start fresh. Note: Files are deleted successfully (API returns 200), but the list may still show files due to eventual consistency or other workspace activity. This is OK - new uploads will work correctly with reference counting. """ global _claude_file_cache, _claude_file_refs headers = { "x-api-key": os.getenv("ANTHROPIC_API_KEY"), "anthropic-version": "2023-06-01", "anthropic-beta": "files-api-2025-04-14" } try: async with httpx.AsyncClient(timeout=60) as client: # List all files resp = await client.get("https://api.anthropic.com/v1/files", headers=headers) resp.raise_for_status() files = resp.json().get('data', []) if files: print(f"Clearing {len(files)} files from Claude API...") # Delete all files for f in files: file_id = f.get('id') try: await client.delete(f"https://api.anthropic.com/v1/files/{file_id}", headers=headers) except Exception as e: # Non-fatal, continue with other files pass print(f"✓ Cleared {len(files)} files from Claude API") except Exception as e: print(f"Warning: Could not clear Claude files: {e}") # Clear local cache _claude_file_cache.clear() _claude_file_refs.clear()
async def _delete_claude_file(file_id: str): """Delete a file from Claude API""" headers = { "x-api-key": os.getenv("ANTHROPIC_API_KEY"), "anthropic-version": "2023-06-01", "anthropic-beta": "files-api-2025-04-14" } try: async with httpx.AsyncClient(timeout=30) as client: await client.delete( f"https://api.anthropic.com/v1/files/{file_id}", headers=headers ) except Exception: pass # Non-fatal
async def _get_or_upload_claude_file(file_path: str) -> str: """ Get or upload a single file to Claude with reference counting. Returns file_id. """ # Check cache first (no lock needed for read) if file_path in _claude_file_cache: return _claude_file_cache[file_path] # Need to upload - acquire lock for ls/upload atomic operation async with _get_claude_upload_lock(): # Double-check cache after acquiring lock if file_path in _claude_file_cache: return _claude_file_cache[file_path] headers = { "x-api-key": os.getenv("ANTHROPIC_API_KEY"), "anthropic-version": "2023-06-01", "anthropic-beta": "files-api-2025-04-14" } file_basename = os.path.basename(file_path) file_size = os.path.getsize(file_path) try: async with httpx.AsyncClient(timeout=60) as client: # List existing files resp = await client.get("https://api.anthropic.com/v1/files", headers=headers) resp.raise_for_status() existing_files = resp.json().get('data', []) # Check if file exists for f in existing_files: if f.get('filename') == file_basename and f.get('size_bytes') == file_size: file_id = f['id'] _claude_file_cache[file_path] = file_id return file_id # File not found, upload it async with aiofiles.open(file_path, 'rb') as f: file_content = await f.read() # Upload with retry for attempt in range(3): try: files = {'file': (file_basename, file_content)} resp = await client.post( "https://api.anthropic.com/v1/files", headers=headers, files=files ) resp.raise_for_status() file_id = resp.json()['id'] _claude_file_cache[file_path] = file_id return file_id except httpx.HTTPStatusError as e: if e.response.status_code == 500 and attempt < 2: await asyncio.sleep(2 ** attempt) else: raise except Exception as e: print(f"Error uploading {file_basename} to Claude: {e}") raise
@register_code_execution("claude-opus-4-7")@register_code_execution("claude-opus-4-6")@register_code_execution("claude-sonnet-4-6")@register_code_execution("claude-3-7-sonnet-20250219")@register_code_execution("claude-opus-4-5")@register_code_execution("claude-sonnet-4-5")async def _claude_with_code_execution( model: str, prompt: str, file_paths: list, file_path_to_id: dict, title: str, return_length: int = 0) -> Any: """ Call Claude model with code execution enabled. Uses Anthropic's native code execution tool (code_execution_20250825). Does NOT reuse containers - each request gets a fresh container. Files are uploaded just-in-time with reference counting to combat 20-file FIFO eviction. """ # Increment reference counts for files we need async with _get_claude_upload_lock(): for file_path in file_paths: _claude_file_refs[file_path] = _claude_file_refs.get(file_path, 0) + 1 try: async with claude_semaphore: async with claude_limiter: headers = { "x-api-key": os.getenv("ANTHROPIC_API_KEY"), "Content-Type": "application/json", "anthropic-version": "2023-06-01", "anthropic-beta": "code-execution-2025-08-25,files-api-2025-04-14" } # Upload files just-in-time (one by one within semaphore limit) claude_files = {} for file_path in file_paths: file_id = await _get_or_upload_claude_file(file_path) claude_files[file_path] = file_id # Build message content with files and prompt content = [] # Add files for file_path in file_paths: if file_path in claude_files: content.append({ "type": "container_upload", "file_id": claude_files[file_path] }) # Add text prompt with ephemeral cache content.append({ "type": "text", "text": prompt, "cache_control": {"type": "ephemeral"} }) # Build initial messages messages = [{"role": "user", "content": content}] # Loop to handle pause_turn (max 5 pause continuations + 1 initial = 6 total) max_attempts = 9 data = None container_id = None async with httpx.AsyncClient(timeout=TIMEOUT) as client: for attempt in range(max_attempts): body = { "model": model, "max_tokens": 64000, "messages": messages, "tools": [{ "type": "code_execution_20250825", "name": "code_execution" }] } # Reuse container from previous turn so sandbox files persist if container_id: body["container"] = container_id try: resp = await client.post( "https://api.anthropic.com/v1/messages", headers=headers, json=body ) resp.raise_for_status() data = resp.json() stop_reason = data.get("stop_reason", "unknown") usage = data.get("usage", {}) # If pause_turn and not last attempt, continue with same container if stop_reason == "pause_turn" and attempt < max_attempts - 1: container_id = (data.get("container") or {}).get("id") or container_id content_blocks = data.get("content", []) block_types = [b.get("type") for b in content_blocks] text_snippets = [ b.get("text", "")[:120] for b in content_blocks if b.get("type") == "text" ] print( f"[{title}] Claude paused (attempt {attempt + 1}/{max_attempts}) " f"container={container_id} " f"tokens(in={usage.get('input_tokens')} out={usage.get('output_tokens')}) " f"block_types={block_types}" ) for i, snippet in enumerate(text_snippets): print(f" text[{i}]: {snippet!r}") # On continuation turns, omit container_upload blocks — # files are already present in the existing container. continuation_content = [ block for block in content if block.get("type") != "container_upload" ] messages = [ {"role": "user", "content": continuation_content}, {"role": "assistant", "content": content_blocks} ] continue else: # end_turn, max_tokens, or max attempts reached break except httpx.HTTPStatusError as http_err: if attempt == max_attempts - 1: raise print(f"HTTP error on attempt {attempt + 1}, retrying...") await asyncio.sleep(2) continue if data is None: raise ValueError("No response from Claude after all attempts") # Check stop reason for debugging stop_reason = data.get("stop_reason", "unknown") # Extract all content blocks content_blocks = data.get("content", []) # Extract text from content blocks (Claude returns multiple blocks with code execution) # Pattern: text → tool_use → tool_result → text → ... → text (final answer) text_blocks = [block.get("text", "") for block in content_blocks if block.get("type") == "text"] if not text_blocks: raise ValueError("No text blocks found in Claude response") # Use the last text block which contains the final answer text = text_blocks[-1] print(f"Claude {model} code execution response for {title}: {text[:200]}") return extract_value(text, return_length) except Exception as e: print(f"\n{'!'*80}") print(f"ERROR in Claude code execution for {model} on {title}: {type(e).__name__}: {e}") print(f"{'!'*80}") # Print traceback for debugging import traceback print("\nTraceback:") traceback.print_exc() # Print stop reason and usage (only if data exists) if 'data' in locals() and data is not None: try: stop_reason = data.get("stop_reason", "unknown") print(f"\nStop reason: {stop_reason}") usage = data.get("usage", {}) if usage: print(f"Usage: {usage}") except: print("\nStop reason/usage: (error accessing)") else: print("\nStop reason/usage: (data not available - error before API response)") # Print all text blocks in full (only if text_blocks exists) if 'text_blocks' in locals() and text_blocks: try: print(f"\nTotal text blocks: {len(text_blocks)}") for i, tb in enumerate(text_blocks): print(f"\n--- TEXT BLOCK {i+1} (full content) ---") print(tb) print(f"--- END TEXT BLOCK {i+1} ---") except: print("\nText blocks: (error printing)") else: print("\nText blocks: (not available - error before text extraction)") print(f"{'!'*80}\n") raise finally: # Decrement reference counts and cleanup cache if no longer needed async with _get_claude_upload_lock(): for file_path in file_paths: if file_path in _claude_file_refs: _claude_file_refs[file_path] -= 1 if _claude_file_refs[file_path] <= 0: # Delete from API and remove from cache file_id = _claude_file_cache.get(file_path) if file_id: await _delete_claude_file(file_id) _claude_file_refs.pop(file_path, None) _claude_file_cache.pop(file_path, None)
# ------------------------ Qwen Agent Code Execution ------------------------
@register_code_execution("qwen3-235b-thinking")async def _qwen_agent_with_code_execution( model: str, prompt: str, file_paths: list, file_path_to_id: dict, title: str, return_length: int = 0) -> Any: """ Call Qwen model with code execution using Qwen Agent framework. Qwen Agent provides sandboxed Python environment with configurable packages. Uses local file paths directly (no pre-upload needed). """ from qwen_agent.agents import Assistant from qwen_agent.tools.code_interpreter import CodeInterpreter async with qwen_semaphore: async with qwen_limiter: def _run_qwen_agent_sync(): # Configure code interpreter # Note: CodeInterpreter doesn't accept extra_packages parameter in current version # It uses default Python environment with standard packages tools = [CodeInterpreter()] # Map model name to OpenRouter model ID # Use the same mapping as call_openrouter function model_map = { "qwen3-235b-thinking": "qwen/qwen3-235b-a22b-thinking-2507" } agent_model = model_map.get(model, model) # Create agent with code execution capability # Configure for OpenRouter (OpenAI-compatible API) agent = Assistant( llm={ 'model': agent_model, 'model_server': 'https://openrouter.ai/api/v1', # OpenRouter endpoint 'api_key': os.getenv('OPENROUTER_API_KEY') }, function_list=tools ) # Build message # Include file paths in the prompt text instead of using 'file' type # to avoid triggering RAG features if file_paths: file_paths_text = '\n'.join([f"File: {fp}" for fp in file_paths]) full_prompt = f"{file_paths_text}\n\n{prompt}" else: full_prompt = prompt messages = [{'role': 'user', 'content': full_prompt}] # Run agent and collect response responses = [] for response in agent.run(messages): responses.append(response) # Extract final text response if responses: final_response = responses[-1] if isinstance(final_response, list): text = final_response[-1].get('content', '') else: text = final_response.get('content', '') else: raise ValueError("No response from Qwen Agent") return text try: # Run synchronous Qwen Agent in thread pool text = await asyncio.to_thread(_run_qwen_agent_sync) print(f"Qwen Agent {model} code execution response for {title}: {text[:200]}") return extract_value(text, return_length) except Exception as e: print(f"Error in Qwen Agent code execution for {model} on {title}: {e}") raise
async def ask_model_with_code_interpreter( model: str, prompt: str, file_paths: list, file_path_to_id: dict, title: str, return_length: int = 0) -> Any: """ Unified interface for code execution across all models. Routes to appropriate provider-specific implementation using registry. Args: model: Model name prompt: The question/prompt file_paths: List of local file paths needed for this question file_path_to_id: Dict mapping file paths to file IDs (provider-specific) title: Question title for logging return_length: Expected return length (0 for scalar, >0 for array) """ handler = _CODE_EXECUTION_REGISTRY.get(model) if not handler: # Default to OpenAI code interpreter for unknown models handler = _openai_with_code_interpreter return await handler(model, prompt, file_paths, file_path_to_id, title, return_length)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430import asynciofrom tqdm import tqdmfrom query import ask_model, ask_model_with_code_interpreter # now an async functionfrom db import append_result, safe_keyimport osimport jsonimport aiofilesimport httpx
async def run_model_prompt_queries( models: list, prompts: list, titles: list, num_elems: list, num_repeats, progress_cb = None, error_cb = None, max_workers: int = 100000,): prompt_to_title = dict(zip(prompts, titles)) cache = {}
# semaphore to cap concurrent ask_model calls sem = asyncio.Semaphore(max_workers)
async def bound_ask(model, prompt, num_elem, title): async with sem: try: out = await ask_model(model, prompt, cache, title, num_elem) except Exception as e: print(f"Error for model={model}, {e}, {title}") return None, model, prompt print(f"Model: {model}, out: {out}, title: {title}") return out, model, prompt
# prepare all (model, prompt, num_elem) triples if isinstance(num_repeats, list): all_tasks = [ (m, p, n, t) for j, (p, n, t) in enumerate(zip(prompts, num_elems, titles)) for i, m in enumerate(models) for _ in range(num_repeats[i][j]) ] else: all_tasks = [ (m, p, n, t) for p, n, t in zip(prompts, num_elems, titles) for _ in range(num_repeats) for m in models ] tasks = [] for idx, (model, prompt, num_elem, title) in enumerate(all_tasks): # buffer initial semaphore load tasks.append(asyncio.create_task(bound_ask(model, prompt, num_elem, title)))
for fut in tqdm(asyncio.as_completed(tasks), total=len(tasks), desc="Processing"): output, model, prompt = await fut if output: title = prompt_to_title[prompt] try: # Firebase append_result(title, model, output)
# Local disk save_dir = "./outputs" os.makedirs(save_dir, exist_ok=True) filename = f"{title}-{safe_key(model)}.jsonl" filepath = os.path.join(save_dir, filename)
async with aiofiles.open(filepath, mode="a") as f: await f.write(json.dumps(output) + "\n")
except Exception as e: print(f"Error saving output for {title} - {model}: {e}") if progress_cb: await progress_cb() else: if error_cb: await error_cb()
return cache
def resolve_file_path(file_path: str) -> str: """ Resolve file paths to absolute paths. Relative paths are placed under server_dir/Data_csv/Plots/ Args: file_path: Relative (e.g., "A1/file.csv") or absolute file path Returns: Absolute file path """ # If already absolute, return as-is if os.path.isabs(file_path): return file_path # Get the directory where serve.py is located (server/) server_dir = os.path.dirname(os.path.abspath(__file__)) # Prepend Data_csv/Plots/ to relative paths, then make absolute return os.path.join(server_dir, "Data_csv", "Plots", file_path)
# Define model sets for checking which APIs need file uploadsGEMINI_MODELS = { "gemini-2.0-flash", "gemini-2.0-flash-lite-preview-02-05", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-2.5-flash",}
OPENAI_CODE_INTERPRETER_MODELS = { "gpt-5", "o3-low", "o3-medium", "o3-high", "o4-mini-low", "o4-mini-medium", "o4-mini-high", "gpt-4o", "gpt-4o-mini", "gpt-4-turbo"}
QWEN_AGENT_MODELS = { "qwen3-235b-thinking",}
CLAUDE_CODE_EXECUTION_MODELS = { "claude-3-7-sonnet-20250219", "claude-opus-4-5", "claude-sonnet-4-5",}
async def run_model_prompt_queries_with_code_interpreter( models: list, prompts: list, titles: list, num_elems: list, file_paths_per_question: list, # Array of arrays - one file list per question num_repeats, progress_cb = None, error_cb = None, max_workers: int = 100000,): """ Run queries with code interpreter enabled and file access. Files are uploaded once at the beginning and reused across all attempts. Each attempt still gets a fresh container (auto mode ensures isolation). Args: file_paths_per_question: List where each element is a list of file paths for that question Paths can be: - Absolute: /full/path/to/file.csv - Relative to server directory: Data_csv/Plots/A1/file.csv """ from openai import AsyncOpenAI from google import genai prompt_to_title = dict(zip(prompts, titles)) prompt_to_files = dict(zip(prompts, file_paths_per_question))
# Step 1: Collect all unique file paths across all questions and resolve them all_file_paths = set() for file_list in file_paths_per_question: for file_path in file_list: resolved_path = resolve_file_path(file_path) all_file_paths.add(resolved_path) # Check if files exist for file_path in all_file_paths: if not os.path.exists(file_path): print(f"✗ File does not exist: {file_path}") raise FileNotFoundError(f"File not found: {file_path}") # Step 2: Determine which APIs need file uploads has_gemini_models = any(model in GEMINI_MODELS for model in models) has_openai_models = any(model in OPENAI_CODE_INTERPRETER_MODELS for model in models) has_qwen_models = any(model in QWEN_AGENT_MODELS for model in models) has_claude_models = any(model in CLAUDE_CODE_EXECUTION_MODELS for model in models) print(f"Models requiring file uploads: Gemini={has_gemini_models}, OpenAI={has_openai_models}, Qwen={has_qwen_models}, Claude={has_claude_models}") # Create nested dictionary structure file_path_to_id = {} # Step 3: Upload files to OpenAI if needed if has_openai_models: print("\n" + "="*60) print("Uploading files to OpenAI...") print("="*60) client = AsyncOpenAI( api_key=os.getenv("OPENAI_API_KEY"), timeout=14400 # 4 hours in seconds ) # List existing uploaded files to avoid re-uploading try: existing_files_response = await client.files.list(purpose="user_data", limit=10000) existing_files = existing_files_response.data existing_file_map = { (f.filename, f.bytes): f.id for f in existing_files } print(f"Found {len(existing_file_map)} existing OpenAI files") except Exception as e: print(f"Warning: Could not list existing files: {e}") existing_file_map = {} openai_file_map = {} files_to_upload = [] for file_path in all_file_paths: file_size = os.path.getsize(file_path) file_basename = os.path.basename(file_path) file_key = (file_basename, file_size) if file_key in existing_file_map: openai_file_map[file_path] = existing_file_map[file_key] else: files_to_upload.append(file_path) print(f"Found {len(openai_file_map)} existing, need to upload {len(files_to_upload)} new files") if files_to_upload: FILE_UPLOAD_TIMEOUT = 600 MAX_CONCURRENT_UPLOADS = 40 upload_semaphore = asyncio.Semaphore(MAX_CONCURRENT_UPLOADS) async def upload_openai_file(file_path: str): async with upload_semaphore: try: file_basename = os.path.basename(file_path) async with aiofiles.open(file_path, 'rb') as f: file_content = await f.read() from io import BytesIO file_obj = await asyncio.wait_for( client.files.create( file=(file_basename, BytesIO(file_content)), purpose="user_data" ), timeout=FILE_UPLOAD_TIMEOUT ) return file_path, file_obj.id except Exception as e: print(f"✗ Error uploading {file_path} to OpenAI: {e}") raise upload_tasks = [upload_openai_file(fp) for fp in files_to_upload] upload_results = await asyncio.gather(*upload_tasks) for file_path, file_id in upload_results: openai_file_map[file_path] = file_id file_path_to_id["openai"] = openai_file_map print(f"✓ All {len(openai_file_map)} OpenAI files ready") # Step 4: Upload files to Gemini if needed if has_gemini_models: print("\n" + "="*60) print("Uploading files to Gemini...") print("="*60) gemini_client = genai.Client() # List existing Gemini files try: existing_gemini_files = list(gemini_client.files.list()) existing_gemini_map = { f.display_name: f for f in existing_gemini_files } print(f"Found {len(existing_gemini_map)} existing Gemini files") except Exception as e: print(f"Warning: Could not list existing Gemini files: {e}") existing_gemini_map = {} gemini_file_map = {} for file_path in all_file_paths: file_basename = os.path.basename(file_path) # Check if file already exists in Gemini if file_basename in existing_gemini_map: gemini_file_map[file_path] = existing_gemini_map[file_basename] print(f" ✓ Using existing Gemini file: {file_basename}") else: try: # Upload new file to Gemini uploaded_file = gemini_client.files.upload(file=file_path) gemini_file_map[file_path] = uploaded_file print(f" ✓ Uploaded to Gemini: {file_basename}") except Exception as e: print(f" ✗ Error uploading {file_basename} to Gemini: {e}") raise file_path_to_id["gemini"] = gemini_file_map print(f"✓ All {len(gemini_file_map)} Gemini files ready") # Step 5: Upload files to Claude if needed if has_claude_models: print("\n" + "="*60) print("Uploading files to Claude (Anthropic Files API)...") print("="*60) headers = { "x-api-key": os.getenv("ANTHROPIC_API_KEY"), "anthropic-version": "2023-06-01", "anthropic-beta": "files-api-2025-04-14" } claude_file_map = {} async def upload_claude_file(file_path: str): try: file_basename = os.path.basename(file_path) async with aiofiles.open(file_path, 'rb') as f: file_content = await f.read() # Use httpx for file upload async with httpx.AsyncClient(timeout=600) as client: files = {'file': (file_basename, file_content)} resp = await client.post( "https://api.anthropic.com/v1/files", headers=headers, files=files ) resp.raise_for_status() file_data = resp.json() return file_path, file_data['id'] except Exception as e: print(f"✗ Error uploading {file_basename} to Claude: {e}") raise upload_tasks = [upload_claude_file(fp) for fp in all_file_paths] upload_results = await asyncio.gather(*upload_tasks) for file_path, file_id in upload_results: claude_file_map[file_path] = file_id print(f" ✓ Uploaded to Claude: {os.path.basename(file_path)}") file_path_to_id["claude"] = claude_file_map print(f"✓ All {len(claude_file_map)} Claude files ready") # Step 6: Handle Qwen Agent (uses local file paths, no upload needed) if has_qwen_models: print("\n" + "="*60) print("Qwen Agent will use local file paths (no upload needed)") print("="*60) # Qwen Agent uses local file paths directly, so just map paths to themselves qwen_file_map = {file_path: file_path for file_path in all_file_paths} file_path_to_id["qwen"] = qwen_file_map print(f"✓ {len(qwen_file_map)} files ready for Qwen Agent") # Step 7: Run queries with pre-uploaded files # semaphore to cap concurrent ask_model calls sem = asyncio.Semaphore(max_workers)
async def bound_ask(model, prompt, num_elem, title, file_paths): async with sem: try: # Resolve file paths before passing to ask_model_with_code_interpreter resolved_file_paths = [resolve_file_path(fp) for fp in file_paths] out = await ask_model_with_code_interpreter( model, prompt, resolved_file_paths, file_path_to_id, title, num_elem ) except Exception as e: print(f"Error for model={model}, {e}, {title}") return None, model, prompt print(f"Model: {model}, out: {out}, title: {title}") return out, model, prompt
# prepare all (model, prompt, num_elem, file_paths) tuples if isinstance(num_repeats, list): all_tasks = [ (m, p, n, t, prompt_to_files[p]) for j, (p, n, t) in enumerate(zip(prompts, num_elems, titles)) for i, m in enumerate(models) for _ in range(num_repeats[i][j]) ] else: all_tasks = [ (m, p, n, t, prompt_to_files[p]) for p, n, t in zip(prompts, num_elems, titles) for _ in range(num_repeats) for m in models ] tasks = [] for idx, (model, prompt, num_elem, title, file_paths) in enumerate(all_tasks): tasks.append(asyncio.create_task(bound_ask(model, prompt, num_elem, title, file_paths)))
for fut in tqdm(asyncio.as_completed(tasks), total=len(tasks), desc="Processing with Code Interpreter"): output, model, prompt = await fut if output: title = prompt_to_title[prompt] try: # Firebase append_result(title, model, output)
# Local disk save_dir = "./outputs" os.makedirs(save_dir, exist_ok=True) filename = f"{title}-{safe_key(model)}.jsonl" filepath = os.path.join(save_dir, filename)
async with aiofiles.open(filepath, mode="a") as f: await f.write(json.dumps(output) + "\n")
except Exception as e: print(f"Error saving output for {title} - {model}: {e}") if progress_cb: await progress_cb() else: if error_cb: await error_cb() # Files are kept in OpenAI storage for future reuse print(f"✓ Completed all queries. {len(file_path_to_id)} files remain in storage for future use.")1234567891011121314151617181920212223242526272829#!/bin/bash
# Set install dirINSTALL_DIR="$HOME/bin"
# Download ngrok v3echo "Downloading ngrok v3..."wget -q https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.tgz -O ngrok.tgz
# Unpack and move to ~/binecho "Installing to $INSTALL_DIR..."mkdir -p "$INSTALL_DIR"tar -xzf ngrok.tgz || { echo "❌ Failed to extract ngrok.tgz"; exit 1; }
mv ngrok "$INSTALL_DIR/ngrok"rm ngrok.tgz
# Add to PATH if not already thereif ! grep -q 'export PATH="$HOME/bin:$PATH"' "$HOME/.bashrc"; then echo 'export PATH="$HOME/bin:$PATH"' >> "$HOME/.bashrc" echo "Added ngrok to PATH in .bashrc"fi
# Source the new path for this sessionexport PATH="$HOME/bin:$PATH"
# Verify installecho "Installed ngrok version:"ngrok version123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143from serve import run_model_prompt_queriesimport random, numpy as npfrom db import get_all_results, reset_db, save_resultimport asyncio
def array2string(array): return '\n'.join(['\t'.join(map(str, row)) for row in array])
E_pnts = 51k_pnts = 101
E_min_0 = 2; E_max_0 = 3k_min_0 = -1; k_max_0 = 1tau_0 = 3noise_0 = 0.3
E_min_1 = 5; E_max_1 = 7k_min_1 = -1; k_max_1 = 1tau_1 = 1noise_1 = 0.2
dE_0 = (E_max_0 - E_min_0)/(E_pnts - 1)dk_0 = (k_max_0 - k_min_0)/(k_pnts - 1)Ex_0 = 2.5
dE_1 = (E_max_1 - E_min_1)/(E_pnts - 1)dk_1 = (k_max_1 - k_min_1)/(k_pnts - 1)Ex_1 = 5.0
E_array_0 = np.linspace(E_min_0, E_max_0, E_pnts, endpoint = True)k_array_0 = np.linspace(k_min_0, k_max_0, k_pnts, endpoint = True)
E_array_1 = np.linspace(E_min_1, E_max_1, E_pnts, endpoint = True)k_array_1 = np.linspace(k_min_1, k_max_1, k_pnts, endpoint = True)
spectrum_array_0 = np.zeros((E_pnts, k_pnts))spectrum_array_1 = np.zeros((E_pnts, k_pnts))
def Ek_0(k, Ex): E = k + Ex return E
def Ek_1(k, Ex): E = 3*k + Ex return E
def Ak_0(E, k, tau, Ex): A = 1/(1 + ((E - Ek_0(k, Ex))**2)*((2*tau)**2)) return A
def Ak_1(E, k, tau, Ex): A = 1/(1 + ((E - Ek_1(k, Ex))**2)*((2*tau)**2)) return A
k_dispersion_array_0 = np.zeros(E_pnts)k_dispersion_array_1 = np.zeros(E_pnts)k_trace_array_1 = np.zeros(E_pnts)
for num in range(E_pnts): k_dispersion_array_0[num] = E_array_0[num] - Ex_0 k_dispersion_array_1[num] = (E_array_1[num] - Ex_1)/3
for E_num in range(E_pnts): k_trace_array_1[E_num] = (E_array_1[E_num] - Ex_1)/3 for k_num in range(k_pnts): spectrum_array_0[E_num,k_num] = Ak_0(E_array_0[E_num], k_array_0[k_num], tau_0, Ex_0) + random.random()*noise_0 spectrum_array_1[E_num,k_num] = Ak_1(E_array_1[E_num], k_array_1[k_num], tau_1, Ex_1) + random.random()*noise_1
temp_0 = np.array(E_array_0)[:, np.newaxis]temp_1 = np.array(E_array_1)[:, np.newaxis]
data_0 = array2string(np.concatenate((np.round(temp_0, decimals = 3), np.round(spectrum_array_0, decimals = 3)), axis = 1))data_1 = array2string(np.concatenate((np.round(temp_1, decimals = 3), np.round(spectrum_array_1, decimals = 3)), axis = 1))
content = "Dataset A:\nEnergy (eV) \t Intensity \n" + "Spectrum:\t" + '\t'.join(map(str, k_array_1)) + "\n" + data_1 + "Dataset B:\nEnergy (eV) \t Intensity \n" + "Spectrum:\t" + '\t'.join(map(str, k_array_0)) + "\n" + data_0
prompt = 'You are given two ARPES datasets in the form of tables.' \ 'Their bandstructure is the set of momenta corresponding to the maximum spectral intensity at each energy. Here is an example. '\ 'Read Dataset A. Its bandstructure is given by the array: [' + ','.join(str(x) for x in k_trace_array_1) + f']. '\ 'Now read Dataset B. What are the momenta of the bandstructure for each energy? '\ 'Do not print any files read, or code written. Return only an array of {E_pnts} numbers}, with no text.'
message = [f"{content}\n\n{prompt}"]num_elems = [E_pnts] message = [f"return [2 for _ in range(3)] as array of three numbers.]"]num_elems = [3]
title = ["test"]
models = [ # "o1-low", # "o1-medium", # "o1-high", # "o3-low", # "o3-medium", # "o3-high", # "o3-mini-low", # "o3-mini-medium", # "o3-mini-high", # "o4-mini-low", # "o4-mini-medium", # "o4-mini-high", # "o1-mini", # "deepseek-reasoner", # "gemini-2.0-flash", # "gemini-1.5-flash", # "gemini-2.5-pro-exp-03-25", # "gemini-2.0-flash-lite-preview-02-05", # "claude-3-7-sonnet-20250219"]
# num_repeats = 1
# cache = asyncio.run(# run_model_prompt_queries(# models=models,# prompts=message,# titles=title,# num_elems=num_elems,# num_repeats=[[1]]# )# )
# cache = asyncio.run(# run_model_prompt_queries(# models=models,# prompts=message,# titles=titles,# num_elems=num_elems,# num_repeats=1# )# )# reset_db() # now we know it’s done:
# print(get_all_results("test", models))# for model in models:# get_results("ARPES Bandstructure", model, save_file="model.jsonl")
.DS_StoreAdded
client/.DS_StoreAdded
client/Prompts_large/B2/B2_S.txtAdded+17
client/Prompts_large/B2/B2_r300_n0_Q.txtAdded
client/Prompts_large/B2/B2_r300_n10_Q.txtAdded
client/Prompts_large/B2/B2_r300_n20_Q.txtAdded
client/Prompts_large/B2/B2_r300_n30_Q.txtAdded
client/Prompts_large/B2/B2_r300_n40_Q.txtAdded
client/Prompts_large/B2/B2_r400_n0_Q.txtAdded
client/Prompts_large/B2/B2_r400_n10_Q.txtAdded
client/Prompts_large/B2/B2_r400_n20_Q.txtAdded
client/Prompts_large/B2/B2_r400_n30_Q.txtAdded
client/Prompts_large/B2/B2_r400_n40_Q.txtAdded
client/Prompts_large/B2/B2_vF_S.txtAdded+1
client/Prompts_large/B2/B2_vF_r300_n0_Q.txtAdded
client/Prompts_large/B2/B2_vF_r300_n10_Q.txtAdded
client/Prompts_large/B2/B2_vF_r300_n20_Q.txtAdded
client/Prompts_large/B2/B2_vF_r300_n30_Q.txtAdded
client/Prompts_large/B2/B2_vF_r400_n0_Q.txtAdded
client/Prompts_large/B2/B2_vF_r400_n10_Q.txtAdded
client/Prompts_large/B2/B2_vF_r400_n20_Q.txtAdded
client/Prompts_large/B2/B2_vF_r400_n30_Q.txtAdded
client/Prompts_large/B2/B2_vF_r400_n40_Q.txtAdded
client/Prompts_large/B2/placeholder.txtAdded
client/Prompts_large/B5/B5_S.txtAdded+1
client/Prompts_large/B5/B5_r300_n0_Q.txtAdded
client/Prompts_large/B5/B5_r300_n10_Q.txtAdded
client/Prompts_large/B5/B5_r300_n20_Q.txtAdded
client/Prompts_large/B5/B5_r300_n30_Q.txtAdded
client/Prompts_large/B5/B5_r300_n40_Q.txtAdded
client/Prompts_large/B5/B5_r400_n0_Q.txtAdded
client/Prompts_large/B5/B5_r400_n10_Q.txtAdded
client/Prompts_large/B5/B5_r400_n20_Q.txtAdded
client/Prompts_large/B5/B5_r400_n30_Q.txtAdded
client/Prompts_large/B5/B5_r400_n40_Q.txtAdded
client/Prompts_large/B5/placeholder.txtAdded
client/ask.pyAdded
client/call_db.pyAdded+128
client/call_server.pyAdded+47
client/client_requirements.txtAdded+1
client/eval.pyAdded
client/init.pyAdded
readme.mdAdded+213
serve_requirements.txtAdded+98
server/db.pyAdded+72
server/main.pyAdded+74
server/query.pyAdded+1311
server/serve.pyAdded+430
server/setup_ngrok.shAdded+29
server/test.pyAdded+143