API Reference🔗
analysis
🔗
add_group_info(df)
🔗
Add group information to a DataFrame.
Source code in src/chembench/analysis.py
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 |
|
all_correct(row, tolerance=0.01)
🔗
Check if all metrics are correct.
Source code in src/chembench/analysis.py
187 188 189 190 191 192 193 194 195 196 197 |
|
are_parsed_values_syntactically_correct(report)
🔗
Check if the parsed values in a report are syntactically correct.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
report
|
Union[dict, list]
|
The report to check. If a list, the first item is used. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
True if the parsed values are syntactically correct, False otherwise. |
Source code in src/chembench/analysis.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
|
correct_fraction_in_subset(df, subset_name)
🔗
Compute the fraction of correct answers in a subset.
Source code in src/chembench/analysis.py
490 491 492 |
|
is_group(row, terms)
🔗
Check if a row is in a group.
Source code in src/chembench/analysis.py
200 201 202 203 204 205 206 207 |
|
load_all_reports(report_dir, data_dir, batch_size=1000, max_workers=None)
🔗
Loads all reports from a given directory and processes them in batches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
report_dir
|
Path
|
The directory containing the reports to load. |
required |
data_dir
|
Path
|
The directory containing the data to use for processing. |
required |
batch_size
|
int
|
The number of reports to process in each batch. Defaults to 1000. |
1000
|
max_workers
|
Optional[int]
|
The maximum number of worker processes to use. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: A DataFrame containing the processed reports. |
Source code in src/chembench/analysis.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
load_json(file, name_to_path_dict=None)
🔗
Load a JSON file.
Source code in src/chembench/analysis.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
|
multicolumn_df_from_nested_dict(d)
🔗
Convert a nested dict to a multi-column DataFrame.
Source code in src/chembench/analysis.py
104 105 106 107 108 109 110 111 112 113 114 115 |
|
score_report(report, ground_truth_name_to_path)
🔗
This function generates a score report for a given task.
It takes two parameters: - report (dict): The report to be scored. - ground_truth_name_to_path (dict): A dictionary mapping task names to their corresponding ground truth paths.
The function returns the scored report with added 'score' and 'metrics' fields.
Source code in src/chembench/analysis.py
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
|
baseline
🔗
RandomBaseline
🔗
Class for generating random baseline answers.
Source code in src/chembench/baseline.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
|
generate(prompt)
🔗
Generates random baseline answers based on the given prompt.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
list[str]
|
list of prompts. |
required |
Returns:
Name | Type | Description |
---|---|---|
Generations |
Generations
|
list of generated answers. |
Source code in src/chembench/baseline.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
|
evaluate
🔗
BenchmarkState
🔗
Tracks the state of benchmark execution with thread safety.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_file
|
Optional[str]
|
Path to the state file for resuming progress. |
'benchmark_state.pkl'
|
Source code in src/chembench/evaluate.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
|
add_result(task_uuid, result)
🔗
Thread-safe addition of results.
Source code in src/chembench/evaluate.py
40 41 42 43 |
|
is_question_complete(topic, task_uuid)
🔗
Thread-safe check for question completion.
Source code in src/chembench/evaluate.py
59 60 61 62 63 64 |
|
is_topic_complete(topic)
🔗
Thread-safe check for topic completion.
Source code in src/chembench/evaluate.py
54 55 56 57 |
|
load()
🔗
Thread-safe state loading.
Source code in src/chembench/evaluate.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
|
mark_question_complete(topic, task_uuid)
🔗
Thread-safe marking of completed questions.
Source code in src/chembench/evaluate.py
45 46 47 48 49 50 51 52 |
|
mark_topic_complete(topic)
🔗
Thread-safe marking of completed topics.
Source code in src/chembench/evaluate.py
35 36 37 38 |
|
save()
🔗
Thread-safe state saving.
Source code in src/chembench/evaluate.py
66 67 68 69 70 |
|
ChemBenchmark
🔗
Bases: ChemBenchmarkBase
ChemBenchmark with topic-wise evaluation.
This class provides methods to evaluate benchmark tasks organized by topics. It supports state management to skip already completed tasks and topics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
report_dir
|
str
|
Directory to save reports. Defaults to "reports". |
'reports'
|
run_id
|
Optional[str]
|
Identifier for the current run. Defaults to None. |
None
|
timeout
|
Optional[int]
|
Timeout between tasks in seconds. Defaults to None. |
None
|
skip_errors
|
bool
|
Whether to skip errors during task processing. Defaults to False. |
False
|
verbose
|
bool
|
Whether to save individual reports for tasks. Defaults to True. |
True
|
state_file
|
Optional[str]
|
Path to the state file for resuming progress. Defaults to None. |
None
|
Raises:
Type | Description |
---|---|
TypeError
|
If arguments are of incorrect type. |
ValueError
|
If registry is empty or invalid. |
Source code in src/chembench/evaluate.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
|
bench(prompter, topics=None, model_kwargs=None, batch_size=8)
🔗
Run benchmarks with optional batch processing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompter
|
BasePrompter
|
Prompter instance for executing tasks |
required |
topics
|
Optional[list]
|
Optional list of topics to evaluate. If None, evaluates all topics |
None
|
model_kwargs
|
Optional[dict]
|
Optional model configuration parameters |
None
|
batch_size
|
int
|
Number of tasks to process in parallel during model inference. This parameter only affects local model inference and is not used for API calls. Setting this too high might cause memory issues depending on your model and hardware. Defaults to 8. |
8
|
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
list of all benchmark results |
Source code in src/chembench/evaluate.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
|
evaluate_topic(topic_questions, prompter, model_kwargs, batch_size=8)
🔗
Evaluate all questions in a topic.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
topic_questions
|
TopicQuestions
|
Topic and its associated tasks |
required |
prompter
|
BasePrompter
|
Prompter instance for task execution |
required |
model_kwargs
|
dict
|
Model configuration parameters |
required |
batch_size
|
int
|
Number of tasks to process in parallel during model inference. This parameter |
8
|
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
list of results for all processed tasks |
Raises:
Type | Description |
---|---|
ValueError
|
If batch_size is less than 1 |
Source code in src/chembench/evaluate.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
|
process_single_task(task, topic, prompter, model_kwargs)
🔗
Process a single task with comprehensive error handling.
Source code in src/chembench/evaluate.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
|
submit(results, submission_path=None)
🔗
Save benchmark results and provide submission instructions for the leaderboard.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results
|
list[dict[str, Any]]
|
List of benchmark results from the bench() method |
required |
submission_path
|
Optional[str]
|
Optional custom path to save the results JSON. Defaults to "submission_results.json" in the report directory. |
None
|
Source code in src/chembench/evaluate.py
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
|
ChemBenchmarkBase
🔗
Base class for evaluating models with chembench.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
report_dir
|
str
|
Directory to save reports. Defaults to "reports". |
'reports'
|
run_id
|
Optional[str]
|
Optional identifier for the run. If provided, it will be appended to the report directory name as "{timestamp}_{run_id}". If not provided, only the timestamp will be used. |
None
|
state_file
|
Optional[str]
|
Path to the state file for resuming progress. If None, a state file named "benchmark_state.pkl" will be created in the report directory under a subdirectory named with the timestamp and run_id. Defaults to None. |
None
|
timeout
|
Optional[int]
|
Timeout between tasks in seconds. Defaults to None. |
None
|
skip_errors
|
bool
|
Whether to skip errors during task execution. Defaults to False. |
False
|
verbose
|
bool
|
Whether to enable verbose mode. Defaults to True. |
True
|
Source code in src/chembench/evaluate.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
echo_topics()
🔗
Prints all topics in the registry.
Source code in src/chembench/evaluate.py
182 183 184 185 186 187 |
|
from_directory(data_dir, **kwargs)
classmethod
🔗
Creates a benchmark instance from a local directory of tasks.
Source code in src/chembench/evaluate.py
175 176 177 178 179 180 |
|
from_huggingface(dataset_name='jablonkagroup/ChemBench', **kwargs)
classmethod
🔗
Creates a benchmark instance using HuggingFace dataset.
Source code in src/chembench/evaluate.py
168 169 170 171 172 173 |
|
get_task(index)
🔗
Retrieves a task at the specified index.
Source code in src/chembench/evaluate.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
|
save_report(report, filename)
🔗
Save a report to file if verbose mode is enabled..
Source code in src/chembench/evaluate.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
_get_item_from_results(item, key, default=0)
🔗
Extract from the nested structure.
Source code in src/chembench/evaluate.py
493 494 495 496 497 498 |
|
load_old_task_results(task, state)
🔗
Load old computed results for a task.
Source code in src/chembench/evaluate.py
467 468 469 470 471 472 473 474 475 476 477 478 479 |
|
load_old_topic_results(topic_questions, state)
🔗
Load old computed results for all tasks in a topic.
Source code in src/chembench/evaluate.py
482 483 484 485 486 487 488 489 490 |
|
extractor
🔗
LLMExtractor
🔗
Extracts the correct answer from a completion using a language model. The language model is provided the completion as well as the answer options in the case of multiple choice questions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
ChemBenchModel
|
The language model to use. |
required |
seed
|
int
|
The seed to use for permuting multiple choice options. |
42
|
permute_options
|
bool
|
Whether to permute the multiple choice options. |
False
|
temperature
|
float
|
The temperature to use when sampling from the language model. |
0
|
chunk_size
|
float
|
The size of the chunks to split the input into. |
0.9
|
max_tokens
|
int
|
The maximum number of tokens the language model can process. |
8192
|
context_length
|
int
|
The maximum number of tokens the language model can process in a single input. |
8192
|
Source code in src/chembench/extractor.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
|
_chunk_text(text)
🔗
Chunk text to fit within token limit while preserving meaning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
str
|
The text to chunk. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The extracted answer. |
Source code in src/chembench/extractor.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
_count_tokens(text)
🔗
Count the number of tokens in a text using tiktoken library.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text to count the tokens in. |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The number of tokens in the text. |
Source code in src/chembench/extractor.py
71 72 73 74 75 76 77 78 79 80 81 |
|
_create_mcq_prompt(completion, example=None)
🔗
Create the extraction prompt for a multiple choice question.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completion
|
str
|
The completion to extract the answer from. |
required |
example
|
dict
|
The example containing the target scores for each answer. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The extraction prompt. |
Source code in src/chembench/extractor.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
|
_create_numeric_prompt(completion)
🔗
Create the extraction prompt for a numeric question.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completion
|
str
|
The completion to extract the answer from. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The extraction prompt. |
Source code in src/chembench/extractor.py
181 182 183 184 185 186 187 188 189 190 191 |
|
_format_mcq_options(options)
🔗
Format multiple choice options for the extraction prompt.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
options
|
Iterable[str]
|
The multiple choice options. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The formatted options. |
Source code in src/chembench/extractor.py
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
|
_process_answer(text, mcq)
🔗
Process the answer extracted from the completion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The extracted answer. |
required |
mcq
|
bool
|
Whether the completion is a multiple choice question. |
required |
Returns:
Type | Description |
---|---|
Union[float, list[str], None]
|
Union[float, List[str], None]: The processed answer. |
Source code in src/chembench/extractor.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
|
extract(completion, mcq=False, example=None)
🔗
Extract the correct answer from a completion using a language model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completion
|
list[LiteLLMMessages]
|
The completion to extract the answer from. |
required |
mcq
|
bool
|
Whether the completion is a multiple choice question. |
False
|
example
|
dict
|
The example containing the target scores for each answer. |
None
|
Returns:
Name | Type | Description |
---|---|---|
LiteLLMMessage |
LiteLLMMessage
|
The extracted answer. |
Source code in src/chembench/extractor.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
|
fatal_code(e)
🔗
Check if an error is fatal for the backoff retry.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
e
|
Exception
|
The exception to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
Whether the error is fatal. |
Source code in src/chembench/extractor.py
18 19 20 21 22 23 24 25 26 27 28 |
|
helper
🔗
clean_report_folder(data_path, reports_path, dry_run=True)
🔗
summary
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_path
|
str
|
path to questions e.g.: "data/" |
required |
reports_path
|
str
|
paths to the reports of a specific model e.g.: "reports/claude2" |
required |
dry_run
|
bool
|
description. Defaults to True. |
True
|
Source code in src/chembench/helper.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
|
clean_report_folder_cli()
🔗
cli for clean_report_folder(data_path, reports_path, dry_run) function
example: clean-reports --data_path="data" --reports_path="reports/claude2" --dry_run=True
Source code in src/chembench/helper.py
133 134 135 136 137 138 139 |
|
create_unicode_regex(unicodes)
🔗
Create a regex pattern to match unicode symbols given a dictionary of unicodes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
unicodes
|
dict
|
Dictionary of unicode symbols to replace. |
required |
Returns:
Type | Description |
---|---|
str
|
(str) Regex to match unicode symbols. |
Source code in src/chembench/helper.py
29 30 31 32 33 34 35 36 37 38 39 40 |
|
find_json_files(directory)
🔗
Find all JSON files in a directory (recursively, i.e. in subdirectories too).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
directory
|
(str, Path)
|
Directory to search. |
required |
Returns:
Type | Description |
---|---|
list[str]
|
(list) list of JSON files. |
Source code in src/chembench/helper.py
17 18 19 20 21 22 23 24 25 26 |
|
fix_unicode(text)
🔗
Fix unicode in text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
Text to fix unicode in. |
required |
Returns:
Type | Description |
---|---|
str
|
Text with fixed unicode. |
Source code in src/chembench/helper.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
|
fix_unicode_in_questions(directory, report_filename)
🔗
Fix unicode in questions and create a report CSV.
The report CSV will contain the following columns: - output: The output with fixed unicode. - input: The original input. - filename: The filename of the JSON file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
directory
|
(str, Path)
|
Path to the directory containing JSON files. |
required |
report_filename
|
str
|
Name of the output CSV report file. |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Source code in src/chembench/helper.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
replace_unicodes(match)
🔗
Replace unicode symbols with their latex equivalent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
match
|
str
|
Unicode symbol to replace. |
required |
Returns:
Type | Description |
---|---|
str
|
Latex equivalent of the unicode symbol. |
Source code in src/chembench/helper.py
43 44 45 46 47 48 49 50 51 52 |
|
metrics
🔗
_is_number_like(x)
🔗
Check if the input is float-like.
Source code in src/chembench/metrics.py
9 10 11 12 13 14 15 |
|
all_correct(found, expected)
🔗
Check if the found value(s) is/are exactly the same as the expected value(s).
If the expected value is a dictionary, the function checks if the found value(s) match the keys in the dictionary where the corresponding value is 1.
If the expected value is a number, the function checks if the mean absolute error between the found and expected values is 0.
If the expected value is a string, the function checks if the found and expected strings are exactly the same.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
found
|
Union[str, list, tuple, float, int]
|
The found value(s), can be a string, list, tuple, float, or integer. |
required |
expected
|
Union[dict, float, int, str]
|
The expected value, can be a dictionary, float, integer, or string. |
required |
Returns:
Type | Description |
---|---|
bool
|
A boolean value indicating whether the found value(s) is/are exactly the same as the expected value(s). |
Source code in src/chembench/metrics.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
calculate_topic_metrics(results)
🔗
Calculate metrics for a topic, treating empty metrics as zero values.
Source code in src/chembench/metrics.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
|
exact_str_match(found, expected)
🔗
Check if two strings are exactly the same.
Source code in src/chembench/metrics.py
125 126 127 128 129 |
|
mae(found, expected)
🔗
Compute the mean absolute error between two values.
Casts the values to float before computing the error. If the values cannot be cast to float, returns np.nan.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
found
|
Union[float, int, str]
|
The found value. |
required |
expected
|
Union[float, int, str]
|
The expected value. |
required |
Returns:
Type | Description |
---|---|
float
|
The mean absolute error. |
Source code in src/chembench/metrics.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
|
mse(found, expected)
🔗
Compute the mean squared error between two values.
Casts the values to float before computing the error. If the values cannot be cast to float, returns np.nan.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
found
|
Union[float, int, str]
|
The found value. |
required |
expected
|
Union[float, int, str]
|
The expected value. |
required |
Returns:
Type | Description |
---|---|
float
|
The mean squared error. |
Source code in src/chembench/metrics.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
multiple_choice_grade(found, expected)
🔗
Grade a multiple choice question.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
found
|
Union[str, list, tuple]
|
The found answer. |
required |
expected
|
dict
|
The expected answer. |
required |
Returns:
Type | Description |
---|---|
float
|
The grade. |
Source code in src/chembench/metrics.py
132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
try_except(func, *args, **kwargs)
🔗
Try to run a function and return np.nan if it fails.
Source code in src/chembench/metrics.py
156 157 158 159 160 161 162 |
|
model
🔗
ChemBenchModel
🔗
Wrapper class for LiteLLM completions. For models that are supported by LiteLLM, model should be the string with the model name as provided by LiteLLM. For models not supported by LiteLLM, model should be the model instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Union[str, Any]
|
The model name or instance. |
required |
**kwargs
|
Additional arguments to pass to the LiteLLM completion. |
{}
|
Source code in src/chembench/model.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
|
_batch_completion(prompt, **model_kwargs)
🔗
Generate multiple completions from the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
BatchMessages
|
The prompts to generate the completions from. |
required |
**model_kwargs
|
Additional arguments to pass to the LiteLLM completion. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
LiteLLMMessages |
LiteLLMMessages
|
The completions from the model. |
Source code in src/chembench/model.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
|
generate(prompt, **model_kwargs)
🔗
Generate a completion from the model. If logprobs_params are provided, the top logprobs will also be returned.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
BatchMessages
|
The prompt or prompts to generate the completion from. |
required |
**model_kwargs
|
Additional arguments to pass to the LiteLLM completion. Can include parameters like temperature, max_tokens, etc. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
LiteLLMMessages |
LiteLLMMessages
|
A list of model responses, where each response is a LiteLLMMessage containing the generated completion with role="assistant". |
Source code in src/chembench/model.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
|
single_completion(prompt, **model_kwargs)
🔗
Generate a single completion from the model.
Temperature should be included in model_kwargs.
model_kwargs
should only contain arguments according to LiteLLM.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
LiteLLMMessages
|
The prompt to generate the completion from. |
required |
**model_kwargs
|
Additional arguments to pass to the LiteLLM completion. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
LiteLLMMessage |
LiteLLMMessage
|
The completion from the model. |
Source code in src/chembench/model.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
LocalModelHandler
🔗
Bases: CustomLLM
Custom handler for local model instances.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_instance
|
object
|
The local model instance. |
required |
Source code in src/chembench/model.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
batch_completion(messages, **kwargs)
🔗
Generate multiple completions using a local model instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
BatchMessages
|
The messages to generate the completions from. |
required |
**kwargs
|
Additional arguments (model, temperature, max_tokens etc) |
{}
|
Returns:
Type | Description |
---|---|
list[ModelResponse]
|
list[litellm.ModelResponse]: The completions from the model. |
Source code in src/chembench/model.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
completion(messages, **kwargs)
🔗
Generate a completion using a local model instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
List[Dict[str, str]]
|
The messages to generate the completion from. |
required |
**kwargs
|
Additional arguments (model, temperature, max_tokens etc) |
{}
|
Returns:
Type | Description |
---|---|
ModelResponse
|
litellm.ModelResponse: The completion from the model. |
Source code in src/chembench/model.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
format_litellm_response(text, model='Custom-LLM')
🔗
Format the response from a local model instance into a LiteLLM response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text generated by the local model instance. |
required |
model
|
str
|
The model used to generate the completion. |
'Custom-LLM'
|
Returns:
Type | Description |
---|---|
ModelResponse
|
litellm.ModelResponse: The formatted response. |
Source code in src/chembench/model.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
prompter
🔗
BasePrompter
🔗
Bases: ABC
Base class for all prompters.
Prompters take a task and build prompts for the LLM.
For this reason, Prompters have specific methods to build prompts
that might be different for different LLMs.
The Prompters extract information from the tasks and use
it to also implement the report
method that will prompt the LLM
and compute the metrics of interest.
For this, we will parse the output in a comparatively robust way,
for example, taking into account various ways of writing scientific
numbers.
Classes that inherit from this class should implement the following
methods:
- _prompts_with_choices
- _prompts_general
And also set the following attributes:
- _mcq_regex_template
- _floatq_regex_template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Any
|
LLM model instance to use for prompting |
required |
pipeline
|
Optional[PrompterPipeline]
|
Optional pipeline for parameter configuration |
None
|
**kwargs
|
dict[str, Any]
|
Additional keyword arguments for model configuration |
{}
|
Pipeline Args
Pipeline Configuration Example
pipeline = PrompterPipeline() pipeline.add_step('use_cot', True) pipeline.add_step('seed', 123) pipeline.add_hook('post_process_ce', custom_ce_processor)
prompter = Prompter(model, pipeline=pipeline)
Source code in src/chembench/prompter.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
|
valid_refusal_types
property
🔗
Get all valid refusal detection methods.
Returns:
Type | Description |
---|---|
list[str]
|
list[str]: List of valid refusal detection methods. |
__init__(model, pipeline=None, **kwargs)
🔗
Initialize BasePrompter with pipeline configuration.
Source code in src/chembench/prompter.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
|
_calculate_metrics(result, answer, target, task, score_map)
🔗
Calculate all metrics for a single result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
dict
|
Result dictionary. |
required |
answer
|
Any
|
Answer extracted from the model output. |
required |
target
|
Any
|
Target value. |
required |
task
|
Task
|
Task object. |
required |
score_map
|
dict[str, int]
|
Mapping of answer choices to scores. |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Source code in src/chembench/prompter.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
|
_create_task_map(tasks)
🔗
Create a mapping of completion indices to tasks and their examples. This is because some tasks have multiple examples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tasks
|
list[Task]
|
List of tasks to score. |
required |
Returns:
Type | Description |
---|---|
Tuple[dict[int, TaskMapEntry], int]
|
Tuple[dict[int, TaskMapEntry], int]: - Mapping of completion indices to tasks and examples - Number of examples |
Source code in src/chembench/prompter.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
_post_process_latex(prompt)
🔗
Process the prompt with configured post-processors.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
str
|
Prompt string. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Processed prompt. |
Source code in src/chembench/prompter.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
|
_process_single_result(completion, task, example_idx, score_map, prompt, **model_kwargs)
🔗
Process a single completion result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completion
|
str
|
Completion string from the model. |
required |
task
|
Task
|
Task object. |
required |
example_idx
|
int
|
Index of the example. |
required |
score_map
|
dict
|
Mapping of answer choices to scores. |
required |
prompt
|
LiteLLMMessages
|
Prompt message. |
required |
model_kwargs
|
dict[str, Any]
|
Additional model kwargs. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
dict |
dict
|
Processed result. |
Source code in src/chembench/prompter.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
|
_prompts_general(examples)
abstractmethod
🔗
Generate prompts for general questions (i.e. non-MCQ).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
List of task examples. |
required |
Raises:
Type | Description |
---|---|
NotImplementedError
|
Method must be implemented by subclass. |
Source code in src/chembench/prompter.py
231 232 233 234 235 236 237 238 239 240 241 |
|
_prompts_with_choices(examples)
abstractmethod
🔗
Generate prompts for multiple choice questions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
List of task examples. |
required |
Raises:
Type | Description |
---|---|
NotImplementedError
|
Method must be implemented by subclass. |
Source code in src/chembench/prompter.py
219 220 221 222 223 224 225 226 227 228 229 |
|
is_mcq(task)
🔗
Check if task is a multiple choice question.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
Task object. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if task is a multiple choice question. |
Source code in src/chembench/prompter.py
243 244 245 246 247 248 249 250 251 252 |
|
report(task, model_kwargs=None)
🔗
Generate report for a single task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
Task to score. |
required |
model_kwargs
|
Optional[dict[str, Any]]
|
Additional model kwargs. |
None
|
Returns:
Name | Type | Description |
---|---|---|
Report |
Report
|
Report for the task. |
Source code in src/chembench/prompter.py
478 479 480 481 482 483 484 485 486 487 488 |
|
report_batch(tasks, model_kwargs=None)
🔗
Generate reports for multiple tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tasks
|
list[Task]
|
List of tasks to score. |
required |
model_kwargs
|
Optional[dict[str, Any]]
|
Additional model kwargs. |
None
|
Returns:
Type | Description |
---|---|
list[Report]
|
list[Report]: List of reports for each task. |
Source code in src/chembench/prompter.py
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 |
|
CompletionPrompter
🔗
Bases: BasePrompter
Source code in src/chembench/prompter.py
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
_prompts_general(examples)
🔗
Generate prompts for numeric/general questions using completion-style prompts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Name | Type | Description |
---|---|---|
BatchMessages |
BatchMessages
|
List of prompt messages. |
Source code in src/chembench/prompter.py
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
_prompts_with_choices(examples)
🔗
Generate prompts and score maps for MCQs using completion-style prompts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Type | Description |
---|---|
Tuple[BatchMessages, list[dict[str, int]]]
|
Tuple[BatchMessages, list[dict[str, int]]]: - List of prompt messages - List of score maps mapping answer choices to scores |
Source code in src/chembench/prompter.py
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
|
ConfidenceInstructionPrompter
🔗
Bases: InstructionPrompter
Create a prompter to get confidence from model.
Source code in src/chembench/prompter.py
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 |
|
_prompts_general(examples)
🔗
Generate prompts and score maps for numeric/general questions using confidence instruction style prompt template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Name | Type | Description |
---|---|---|
BatchMessages |
BatchMessages
|
List of prompt messages |
Source code in src/chembench/prompter.py
775 776 777 778 779 780 781 782 783 784 785 786 787 788 |
|
_prompts_with_choices(examples, permute=False)
🔗
Generate prompts and score maps for numeric/general questions using confidence instruction style prompt template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
permute
|
bool
|
Whether to permute the answer choices. |
False
|
Returns:
Type | Description |
---|---|
Tuple[BatchMessages, list[dict[str, int]]]
|
Tuple[BatchMessages, list[dict[str, int]]]: - List of prompt messages - List of score maps mapping answer choices to scores |
Source code in src/chembench/prompter.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 |
|
_score(task, model_kwargs=None)
🔗
Score the LLM on the task.
This method will, depending on the task, build multiple choice or general prompts and then prompt the LLM.
The results will be parsed and the metrics will be computed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
Task to score. |
required |
model_kwargs
|
Optional[dict]
|
Additional model kwargs. |
None
|
Returns:
Type | Description |
---|---|
Tuple[dict, list[dict], dict, int]
|
Tuple[dict, list[dict], dict, int]: Tuple containing: - Summarized metrics - List of results - List of prompts - Number of examples |
Source code in src/chembench/prompter.py
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 |
|
InstructionPrompter
🔗
Bases: BasePrompter
Prompter for use with models that are instruction tuned.
For background on instruction tuning, see the following blog post: https://nlpnewsletter.substack.com/p/instruction-tuning-vol-1
Source code in src/chembench/prompter.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
|
_prompts_general(examples)
🔗
Generate prompts and score maps for numeric/general questions using instruction style prompt template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Name | Type | Description |
---|---|---|
BatchMessages |
BatchMessages
|
List of prompt messages |
Source code in src/chembench/prompter.py
576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
|
_prompts_with_choices(examples)
🔗
Generate prompts and score maps for MCQs using instruction style prompt template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Type | Description |
---|---|
Tuple[BatchMessages, list[dict[str, int]]]
|
Tuple[BatchMessages, list[dict[str, int]]]: - List of prompt messages - List of score maps mapping answer choices to scores |
Source code in src/chembench/prompter.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
|
MultimodalInstructionPrompter
🔗
Bases: BasePrompter
Prompter for multimodal instruction-tuned models
Source code in src/chembench/prompter.py
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
|
_format_content(content)
🔗
Format content items for LiteLLM API consumption
Parameters:
Name | Type | Description | Default |
---|---|---|---|
content
|
list[dict[str, str]]
|
list of content items |
required |
Returns:
Type | Description |
---|---|
list[MessageContent]
|
list[dict[str, str]]: formatted text-image content |
Source code in src/chembench/prompter.py
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 |
|
_get_type_choice(example)
🔗
Determine if example contains image or text content
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
task example |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
type of content |
Source code in src/chembench/prompter.py
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 |
|
_load_templates()
🔗
Load prompt templates
Raises:
Type | Description |
---|---|
Exception
|
Error loading templates |
Source code in src/chembench/prompter.py
612 613 614 615 616 617 618 619 620 621 622 |
|
_prompts_general(examples)
🔗
Generate prompts and score maps for numeric/general questions using multimodal instruction style prompt template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Name | Type | Description |
---|---|---|
BatchMessages |
BatchMessages
|
List of prompt messages |
Source code in src/chembench/prompter.py
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
|
_prompts_with_choices(examples)
🔗
Generate prompts and score maps for MCQs using multimodal instruction style prompt template
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict]
|
list of task examples. |
required |
Returns:
Type | Description |
---|---|
Tuple[BatchMessages, list[dict[str, int]]]
|
Tuple[BatchMessages, list[dict[str, int]]]: - List of prompt messages - List of score maps mapping answer choices to scores |
Source code in src/chembench/prompter.py
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 |
|
PrompterBuilder
🔗
Factory class to create prompters.
Source code in src/chembench/prompter.py
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
|
from_model_object(model, prompt_type='instruction', pipeline=None, **kwargs)
classmethod
🔗
Create a prompter from a model object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
object
|
Model object. |
required |
prompt_type
|
Literal['instruction', 'completion', 'multimodal_instruction']
|
Type of prompter to create. |
'instruction'
|
pipeline
|
Optional[PrompterPipeline]
|
Optional pipeline for parameter configuration. |
None
|
Returns:
Name | Type | Description |
---|---|---|
Prompter |
BasePrompter
|
Prompter object. |
Source code in src/chembench/prompter.py
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
|
PrompterPipeline
🔗
Pipeline for managing configurable parameters and hooks in the prompter.
Provides a flexible way to customize parameter values and processing hooks for various prompter operations.
Source code in src/chembench/prompter.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
add_arg(name, value)
🔗
Add a configuration step to the pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name identifier for the step |
required |
value
|
Any
|
Value to store for this step |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
PrompterPipeline
|
Returns self for method chaining |
Source code in src/chembench/prompter.py
62 63 64 65 66 67 68 69 70 71 72 73 |
|
add_hook(name, hook)
🔗
Add a processing hook to the pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name identifier for the hook |
required |
hook
|
Callable
|
Callable function to use for processing |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
PrompterPipeline
|
Returns self for method chaining |
Source code in src/chembench/prompter.py
75 76 77 78 79 80 81 82 83 84 85 86 |
|
get_arg(name, default=None)
🔗
Retrieve a step value from the pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name of the step to retrieve |
required |
default
|
Any
|
Default value if step doesn't exist |
None
|
Returns:
Type | Description |
---|---|
Any
|
The step value or default if not found |
Source code in src/chembench/prompter.py
88 89 90 91 92 93 94 95 96 97 98 |
|
_base_completion_prompt(example, template, cot=False)
🔗
Generate a completion prompt based on the provided example and template.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
The example containing the input for the prompt. |
required |
template
|
str
|
The template string to be formatted with the example input. |
required |
cot
|
bool
|
Whether to include a continuation of thought (COT) prompt. Defaults to False. |
False
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The generated completion prompt. |
Source code in src/chembench/prompter.py
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 |
|
_base_multiple_choice_prompt(example, template, permute=False, cot=False, random_seed=42)
🔗
Generate a multiple-choice prompt based on the given example.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
A dictionary containing the input and target scores. |
required |
template
|
str
|
A string template for the prompt. |
required |
permute
|
bool
|
Whether to permute the order of the answers. Defaults to False. |
False
|
cot
|
bool
|
Whether to include a cot (context of task) prompt. Defaults to False. |
False
|
random_seed
|
int
|
The random seed for answer permutation. Defaults to 42. |
42
|
Returns:
Name | Type | Description |
---|---|---|
tuple |
A tuple containing the generated prompt and a dictionary mapping answer letters to scores. |
Source code in src/chembench/prompter.py
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 |
|
create_multiple_choice_confidence_prompt(example, permute=False, cot=False, random_seed=42)
🔗
Create a prompt with multiple choices.
The example is expected to be a dict with keys "input" and "target_scores". The "input" is the question and the "target_scores" is a dict with possible answers and their scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
dict with keys "input" and "target_scores" |
required |
permute
|
bool
|
whether to permute the answers |
False
|
cot
|
bool
|
whether to add a COT prompt statement |
False
|
random_seed
|
int
|
random seed for permutation |
42
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
prompt |
dict |
dict
|
mapping from answer to score |
Source code in src/chembench/prompter.py
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 |
|
create_multiple_choice_prompt(example, permute=False, cot=False, random_seed=42)
🔗
Create a prompt with multiple choices.
The example is expected to be a dict with keys "input" and "target_scores". The "input" is the question and the "target_scores" is a dict with possible answers and their scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
dict with keys "input" and "target_scores" |
required |
permute
|
bool
|
whether to permute the answers |
False
|
cot
|
bool
|
whether to add a COT prompt statement |
False
|
random_seed
|
int
|
random seed for permutation |
42
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
prompt |
dict |
dict
|
mapping from answer to score |
Source code in src/chembench/prompter.py
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 |
|
create_multiple_choice_prompt_completion(example, permute=False, cot=False, random_seed=42)
🔗
Create a prompt with multiple choices.
The example is expected to be a dict with keys "input" and "target_scores". The "input" is the question and the "target_scores" is a dict with possible answers and their scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
dict with keys "input" and "target_scores" |
required |
permute
|
bool
|
whether to permute the answers |
False
|
cot
|
bool
|
whether to add a COT prompt statement |
False
|
random_seed
|
int
|
random seed for permutation |
42
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
prompt |
dict |
dict
|
mapping from answer to score |
Source code in src/chembench/prompter.py
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 |
|
general_prompt(example, cot=False)
🔗
Create a prompt with fill in the blank questions.
The example is expected to be a dict with keys "input" and "target". The "input" is the question and the "target" is the answers.
We will covert the questions into prompts of the following form
The following is a question about chemistry. Question: {question} Answer by including the final answer within two [ANSWER] tokens without units.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
dict with keys "input" and "target" |
required |
cot
|
bool
|
whether to add a COT prompt statement |
False
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
prompt |
Source code in src/chembench/prompter.py
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 |
|
general_prompt_completion(example, cot=False)
🔗
Create a prompt with fill in the blank questions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
dict with keys "input" and "target" |
required |
cot
|
bool
|
whether to add a COT prompt statement |
False
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
prompt |
Source code in src/chembench/prompter.py
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 |
|
general_prompt_confidence(example, cot=False)
🔗
Create a prompt with fill in the blank questions.
The example is expected to be a dict with keys "input" and "target". The "input" is the question and the "target" is the answers.
We will covert the questions into prompts of the following form
The following is a question about chemistry. Question: {question} Answer by including the final answer within two [ANSWER] tokens without units.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
example
|
dict
|
dict with keys "input" and "target" |
required |
cot
|
bool
|
whether to add a COT prompt statement |
False
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
prompt |
Source code in src/chembench/prompter.py
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 |
|
prepare_general_answer(model_output, pattern=FLOATQ_REGEX_TEMPLATE_1, word_parsing_fallback=True, llm_extractor=None)
🔗
Parse scientific numbers from model output and return as a float.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_output
|
str
|
Output from the model in string format. |
required |
pattern
|
str
|
Regex pattern to match the identifier. Defaults to FLOATQ_REGEX_TEMPLATE_1. |
FLOATQ_REGEX_TEMPLATE_1
|
word_parsing_fallback
|
bool
|
If True, tries to convert words to numbers if no pattern matches. Defaults to True. |
True
|
llm_extractor
|
Optional[Union[str, ChemBenchModel]]
|
LLM extractor to use if no pattern matches. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
Optional[float]
|
Optional[float]: Scientific number in float format if found, else None. |
Source code in src/chembench/prompter.py
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 |
|
prepare_mcq_answer(text, pattern=MCQ_REGEX_TEMPLATE_1, alphabet=None, llm_extractor=None, example='')
🔗
Parse string within the identifiers defined in the mcq regex for eg: [ANSWER]A,B[ANSWER] -> A,B
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
Output from the model in string format. |
required |
pattern
|
str
|
Regex pattern to match the identifier. Defaults to MCQ_REGEX_TEMPLATE_1. |
MCQ_REGEX_TEMPLATE_1
|
alphabet
|
Optional[list[str]]
|
list of allowed letters. Defaults to None, in which case it uses A-Z. |
None
|
llm_extractor
|
Optional[Union[str, ChemBenchModel]]
|
LLM extractor to use if no pattern matches. Defaults to None. |
None
|
example
|
Optional[dict[str, Any]]
|
Example dict with keys "input" and "target_scores" if llm_fallback is True. Defaults to None. |
''
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Text within the identifier for regex matching, or the original text if no matches are found. |
Source code in src/chembench/prompter.py
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 |
|
refusal
🔗
RefusalDetector
🔗
Refusal detection model
Attributes:
Name | Type | Description |
---|---|---|
REFUSAL_TYPES |
list[str]
|
The supported refusal detection types |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
refusal_type
|
str
|
The type of refusal detection to use |
required |
Source code in src/chembench/refusal.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
__init__(refusal_type)
🔗
Initialize the sentiment analysis model
Source code in src/chembench/refusal.py
21 22 23 24 25 26 27 |
|
check_refusals(message_content)
🔗
Check for refusals using both methods
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message_content
|
BatchMessages
|
The message content to check for refusals |
required |
Returns:
Type | Description |
---|---|
Tuple[bool, str]
|
(is_refusal, detection_method) |
Source code in src/chembench/refusal.py
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
get_possible_refusal_types()
🔗
Get the possible refusal types
Returns:
Type | Description |
---|---|
list[str]: Sorted list of supported refusal detection types |
Source code in src/chembench/refusal.py
29 30 31 32 33 34 35 |
|
keyword_refusal_detection(message_content)
🔗
Check if the message content contains refusal patterns using keywords
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message_content
|
str
|
The message content to check for refusal patterns |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if refusal patterns are detected, False otherwise |
Source code in src/chembench/refusal.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
|
lazy_load_model()
🔗
Lazy load the model only when needed
Source code in src/chembench/refusal.py
37 38 39 40 41 42 43 44 45 46 |
|
refusal_sentiment_analysis(completion, overlap=128)
🔗
Perform sentiment-based refusal detection
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completion
|
str
|
The completion to check for refusal patterns |
required |
overlap
|
int
|
The overlap between chunks |
128
|
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if refusal patterns are detected, False otherwise |
Source code in src/chembench/refusal.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
|
task
🔗
Task
🔗
One benchmark task.
A benchmark task can contain multiple examples and will always contain a regex to find the output as well as a list of metrics along with some basic metadata.
Using a LLM that follows the llm.generate
API in langchain,
the report
method will prompt the LLM and compute the metrics
of interest.
Examples:
>>> from pprint import pprint
>>> from chembench.task import Task
>>> from langchain_openai import OpenAI
>>> task = Task.from_json("tests/data/task.json")
>>> report = task.report(OpenAI())
>>> pprint(report.dict())
Source code in src/chembench/task.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
|
__init__(examples, name, description, keywords, metrics, preferred_score, uuid=None, relative_tolerance=None)
🔗
Create a new task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
examples
|
list[dict[str, str]]
|
list of examples. Following the Big Bench format. |
required |
name
|
str
|
Name of the task. |
required |
description
|
str
|
Description of the task. |
required |
keywords
|
list[str]
|
list of keywords. |
required |
metrics
|
list[str]
|
list of metrics to compute. |
required |
preferred_score
|
str
|
The preferred score. |
required |
output_regex
|
Regex pattern to find the output in the completion. |
required |
Source code in src/chembench/task.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
|
TaskRegistry
🔗
Registry for managing topic-wise benchmark tasks. The registry can be initialized in two ways: 1. Using from_directory() to load from a local directory 2. Using from_huggingface() to load from a HuggingFace dataset
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir
|
Path
|
Directory containing topic data. |
None
|
topics
|
dict[str, TopicQuestions]
|
dictionary mapping topic names to their respective TopicQuestions. |
required |
Source code in src/chembench/task.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
|
__init__(data_dir=None)
🔗
Initialize registry.
Source code in src/chembench/task.py
123 124 125 |
|
_load_topics(data_dir)
🔗
Load all topics from the data directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir
|
Path
|
Path object pointing to data directory |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If no valid topics were found in the directory |
Source code in src/chembench/task.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
|
from_directory(data_dir)
classmethod
🔗
Create a TaskRegistry instance from a local directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir
|
str
|
Path to directory containing topic data |
required |
Returns:
Name | Type | Description |
---|---|---|
TaskRegistry |
TaskRegistry
|
New registry instance with loaded topics |
Raises:
Type | Description |
---|---|
ValueError
|
If data_dir is None or empty |
FileNotFoundError
|
If data_dir doesn't exist |
Source code in src/chembench/task.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
|
from_huggingface(dataset_name)
classmethod
🔗
Create a TaskRegistry instance from a HuggingFace dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name
|
str
|
Name of the dataset on HuggingFace hub |
required |
Returns:
Name | Type | Description |
---|---|---|
TaskRegistry |
TaskRegistry
|
New registry instance with loaded topics |
Source code in src/chembench/task.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
|
get_all_topics()
🔗
Get list of all available topics.
Source code in src/chembench/task.py
284 285 286 |
|
get_topic(topic)
🔗
Get questions for a specific topic.
Source code in src/chembench/task.py
280 281 282 |
|
get_topic_count(topic)
🔗
Get number of questions in a topic.
Source code in src/chembench/task.py
288 289 290 291 |
|
get_total_questions()
🔗
Get the total number of questions across all topics.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Total number of questions in all topics combined |
Source code in src/chembench/task.py
293 294 295 296 297 298 299 |
|
TopicQuestions
dataclass
🔗
Container for topic-wise questions.
Source code in src/chembench/task.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
|
task_count
property
🔗
Get the number of tasks in this topic.
__len__()
🔗
Return the number of tasks in this topic.
This allows using len(topic_questions) directly.
Source code in src/chembench/task.py
103 104 105 106 107 108 |
|
types
🔗
RefusalType
🔗
Bases: Enum
Valid refusal detection methods.
Source code in src/chembench/types.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
from_string(value)
classmethod
🔗
Get a refusal type from a string.
Source code in src/chembench/types.py
36 37 38 39 40 41 42 43 44 |
|
get_valid_values()
classmethod
🔗
Get all valid refusal type values.
Source code in src/chembench/types.py
46 47 48 49 |
|
utils
🔗
convert_to_number(matched_value)
🔗
Helper Function to convert string to number using pint
Parameters:
Name | Type | Description | Default |
---|---|---|---|
matched_value
|
str
|
String which is to be converted to number |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
converted number |
Source code in src/chembench/utils.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
create_multiple_choice_regex(allowed_letters)
🔗
Create a regex to match the multiple choice answer pattern.
The pattern is run_regex
to return the matching letter
as it uses a capture group.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
allowed_letters
|
list[str]
|
list of allowed letters. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
Regex pattern. |
Source code in src/chembench/utils.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
|
enable_caching()
🔗
Enable caching for LiteLLM using SQLite.
Source code in src/chembench/utils.py
321 322 323 324 325 326 |
|
enable_logging()
🔗
Set up the chembench logging with sane defaults.
Source code in src/chembench/utils.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
|
find_numbers(input_string)
🔗
Run regex iterator function to parse number from the input string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_string
|
str
|
String from which number to be parsed |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
parsed number |
Source code in src/chembench/utils.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
|
format_input(example, type_choice)
🔗
Format input data into question and answer format replace the type entries in json with their values in JSON/Task
Source code in src/chembench/utils.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
|
get_answer_list(example, permute=False, random_seed=42)
🔗
Generate answer list and score mapping
Source code in src/chembench/utils.py
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 |
|
join_text(prompt, types_to_join)
🔗
Join consecutive text items of specified types - no processing needed here for eg: this would join { "type": "text", "text": "is an AFM image of" }, { "type": "text", "text": "square grids on a substrate." }, into
"type": "text",
"text": "is an AFM image of square grids on a substrate."
},
if types_to_join = ["text"]
Source code in src/chembench/utils.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 |
|
parse_input_string(input_string)
🔗
Parse input string to extract placeholders and text. This is because the input string contain placeholders like {type1} or {entry1}, later used to replace with actual values in the JSON/Task.
eg:
input_string = "{type1} {entry1} is an AFM image of square grids on a substrate. What is the width of the image in micrometers?"
output = [
{"type": "placeholder", "key": "type1"},
{"type": "placeholder", "key": "entry1"},
{"type": "text", "value": "is an AFM image of square grids on a substrate. What is the width of the image in micrometers?"}
]
Source code in src/chembench/utils.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
|
parse_json_like_string(s)
🔗
Convert a JSON-like string with single quotes to valid JSON and parse it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
s
|
str
|
The JSON-like string to parse |
required |
Returns:
Name | Type | Description |
---|---|---|
dict |
dict
|
The parsed JSON data |
Source code in src/chembench/utils.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
process_text(text, post_processors)
🔗
Apply all post-processors to text
Source code in src/chembench/utils.py
538 539 540 541 542 543 544 |
|
prompt2messages(prompts, system_prompt=None)
🔗
Convert a list of prompts to a list of messages.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompts
|
Union[list[str], list[dict]]
|
The prompts to convert. list[str] for text-only and list[list[dict]] for multimodal. |
required |
system_prompt
|
Optional[str]
|
The system prompt to prepend to each message. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
list[list[LiteLLMMessage]]
|
List[List[litellm.Message]]: A list where each inner list contains the message sequence for a single conversation. |
Source code in src/chembench/utils.py
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
|
run_regex(pattern, string, return_first=True)
🔗
Run a regex pattern on a string and return the matches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str
|
The regex pattern to match. |
required |
string
|
str
|
The string to search for matches. |
required |
return_first
|
bool
|
If True, return only the first match. If False, return a list of all matches. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Union[str, list[str], None]
|
Union[str, list[str], None]: The first match if return_first is True, a list of all matches if return_first is False, or None if no matches are found. |
Source code in src/chembench/utils.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
|
run_regex_iterator(pattern, string, return_first=True, return_indices=False)
🔗
Function to parse matches given regex pattern.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
regex as per re module |
required | |
string
|
String from which pattern need to be parsed |
required | |
return_first
|
bool
|
True if only first match is required |
True
|
return_indices
|
bool
|
True to return a dict with both match and the indices in the string |
False
|
Returns:
Name | Type | Description |
---|---|---|
str |
Union[str, dict[str, str], list[dict[str, str]], None]
|
if only first matching string is require |
dict |
Union[str, dict[str, str], list[dict[str, str]], None]
|
both match and index |
list |
Union[str, dict[str, str], list[dict[str, str]], None]
|
list of dict with match and index |
Source code in src/chembench/utils.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
|
save_json(file_path, data)
🔗
Save data as JSON file.
Source code in src/chembench/utils.py
45 46 47 48 |
|
text2int(textnum, numwords={})
🔗
Converts a textual representation of a number to its corresponding integer value. Based on https://stackoverflow.com/a/493788
Parameters:
Name | Type | Description | Default |
---|---|---|---|
textnum
|
str
|
The textual representation of the number. |
required |
numwords
|
dict
|
A dictionary containing the mapping of words to their numeric values. Defaults to an empty dictionary. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
int |
The integer value of the textual representation. |
Raises:
Type | Description |
---|---|
Exception
|
If an illegal word is encountered in the textual representation. |
Example
text2int("twenty three") 23 text2int("one hundred and twenty five") 125
Source code in src/chembench/utils.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
|
watermark
🔗
Capture some basic information about the computing environment.
Taken from https://gist.github.com/tahajahangir/5275848#file-pyinfo-py