Utils
promptolution.utils
Module for utility functions and classes.
BestPromptCallback
Bases: BaseCallback
Callback for tracking the best prompt during optimization.
This callback keeps track of the prompt with the highest score.
Attributes:
| Name | Type | Description |
|---|---|---|
best_prompt |
str
|
The prompt with the highest score so far. |
best_score |
float
|
The highest score achieved so far. |
Source code in promptolution/utils/callbacks.py
__init__()
get_best_prompt()
Get the best prompt and score achieved during optimization.
Returns: Tuple[str, float]: The best prompt and score.
on_step_end(optimizer)
Update the best prompt and score if a new high score is achieved.
Args: optimizer: The optimizer object that called the callback.
Source code in promptolution/utils/callbacks.py
FileOutputCallback
Bases: BaseCallback
Callback for saving optimization progress to a specified file type.
This callback saves information about each step to a file.
Attributes:
| Name | Type | Description |
|---|---|---|
dir |
Union[str, Path]
|
Directory the file is saved to. |
step |
int
|
The current step number. |
file_type |
str
|
The type of file to save the output to. |
Source code in promptolution/utils/callbacks.py
__init__(dir, file_type='parquet')
Initialize the FileOutputCallback.
Args: dir (Union[str, Path]): Directory the CSV file is saved to. file_type (str): The type of file to save the output to.
Source code in promptolution/utils/callbacks.py
on_step_end(optimizer)
Append this step's rows and rewrite the results file.
Args: optimizer: The optimizer object that called the callback
Source code in promptolution/utils/callbacks.py
LoggerCallback
Bases: BaseCallback
Callback for logging optimization progress.
This callback logs information about each step, epoch, and the end of training.
Attributes:
| Name | Type | Description |
|---|---|---|
logger |
The logger object to use for logging. |
|
step |
int
|
The current step number. |
Source code in promptolution/utils/callbacks.py
__init__(logger)
on_step_end(optimizer)
Log information about the current step.
Source code in promptolution/utils/callbacks.py
on_train_end(optimizer, logs=None)
Log information at the end of training.
Args: optimizer: The optimizer object that called the callback. logs: Additional information to log.
Source code in promptolution/utils/callbacks.py
ProgressBarCallback
Bases: BaseCallback
Callback for displaying a progress bar during optimization.
This callback uses tqdm to display a progress bar that updates at each step.
Attributes:
| Name | Type | Description |
|---|---|---|
pbar |
tqdm
|
The tqdm progress bar object. |
Source code in promptolution/utils/callbacks.py
__init__(total_steps)
Initialize the ProgressBarCallback.
Args: total_steps (int): The total number of steps in the optimization process.
on_step_end(optimizer)
Update the progress bar at the end of each step.
Args: optimizer: The optimizer object that called the callback.
on_train_end(optimizer)
Close the progress bar at the end of training.
Args: optimizer: The optimizer object that called the callback.
Prompt
Represent a prompt consisting of an instruction and few-shot examples.
Source code in promptolution/utils/prompt.py
__eq__(other)
Structural equality for use in lists, sets, and dict keys.
Source code in promptolution/utils/prompt.py
__hash__()
__init__(instruction, few_shots=None, downstream_template=None)
Initialize the Prompt with an instruction and associated examples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
str
|
The instruction or prompt text. |
required |
few_shots
|
List[str]
|
List of examples as string. |
None
|
downstream_template
|
str
|
Template for formatting the full prompt. |
None
|
Source code in promptolution/utils/prompt.py
__str__()
construct_prompt()
Construct the full prompt string by replacing placeholders in the template with the instruction and formatted examples.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The constructed prompt string. |
Source code in promptolution/utils/prompt.py
TokenCountCallback
Bases: BaseCallback
Callback for stopping optimization based on the total token count.
Source code in promptolution/utils/callbacks.py
__init__(max_tokens_for_termination, token_type_for_termination)
Initialize the TokenCountCallback.
Args: max_tokens_for_termination (int): Maximum number of tokens which is allowed befor the algorithm is stopped. token_type_for_termination (str): Can be one of either "input_tokens", "output_tokens" or "total_tokens".
Source code in promptolution/utils/callbacks.py
on_step_end(optimizer)
Check if the total token count exceeds the maximum allowed. If so, stop the optimization.
Source code in promptolution/utils/callbacks.py
create_prompt_variation(prompt, llm, meta_prompt=None)
Generate a variation of the given prompt(s) while keeping the semantic meaning.
Idea taken from the paper Zhou et al. (2021) https://arxiv.org/pdf/2211.01910
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
Union[List[str], str]
|
The prompt(s) to generate variations of. |
required |
llm
|
BaseLLM
|
The language model to use for generating the variations. |
required |
meta_prompt
|
str
|
The meta prompt to use for generating the variations.
If None, a default meta prompt is used. Should contain |
None
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of generated variations of the input prompt(s). |
Source code in promptolution/utils/prompt_creation.py
create_prompts_from_samples(task, llm, meta_prompt=None, n_samples=3, task_description=None, n_prompts=1, get_uniform_labels=False)
Generate a set of prompts from dataset examples sampled from a given task.
Idea taken from the paper Zhou et al. (2021) https://arxiv.org/pdf/2211.01910 Samples are selected, such that (1) all possible classes are represented (2) the samples are as representative as possible
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
BaseTask
|
The task to generate prompts for. Xs and Ys from this object are used to generate the prompts. |
required |
llm
|
BaseLLM
|
The language model to use for generating the prompts. |
required |
meta_prompt
|
str
|
The meta prompt to use for generating the prompts. If None, a default meta prompt is used. |
None
|
n_samples
|
int
|
The number of samples to use for generating prompts. |
3
|
task_description
|
str
|
The description of the task to include in the prompt. |
None
|
n_prompts
|
int
|
The number of prompts to generate. |
1
|
get_uniform_labels
|
bool
|
If True, samples are selected such that all classes are represented. |
False
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of generated prompts. |
Source code in promptolution/utils/prompt_creation.py
create_prompts_from_task_description(task_description, llm, meta_prompt=None, n_prompts=10, n_retries=3)
Generate a set of prompts from a given task description.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_description
|
str
|
The description of the task to generate prompts for. |
required |
llm
|
BaseLLM
|
The language model to use for generating the prompts. |
required |
meta_prompt
|
str
|
The meta prompt to use for generating the prompts. If None, a default meta prompt is used. |
None
|
n_prompts
|
int
|
The number of prompts to generate. |
10
|
n_retries
|
int
|
The number of retries to attempt if prompt generation fails. |
3
|
Source code in promptolution/utils/prompt_creation.py
dev_test_split(df, test_frac=0.2, seed=42)
Split a DataFrame into a dev and test set.
The optimizer selects prompts on the dev set. The test set is held out for the final evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The data to split (or a df-like with |
required |
test_frac
|
float
|
Fraction of rows held out for the test split. |
0.2
|
seed
|
int
|
Random seed for the split. |
42
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, DataFrame]
|
Tuple[pd.DataFrame, pd.DataFrame]: |
Source code in promptolution/utils/evaluation.py
evaluate_prompts(prompts, task, predictor)
Score prompts on a task and return a sorted prompt/score table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
Union[List[Prompt], List[str]]
|
Prompts to score. |
required |
task
|
BaseTask
|
The task to score on (its full dataset is used). |
required |
predictor
|
BasePredictor
|
The predictor that runs the prompts. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Columns |
Source code in promptolution/utils/evaluation.py
get_logger(name, level=None)
Get a logger with the specified name and level.
This function provides a standardized way to get loggers throughout the library, ensuring consistent formatting and behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the logger, typically name of the module. |
required |
level
|
int
|
Logging level. Defaults to None, which uses the root logger's level. |
None
|
Returns:
| Type | Description |
|---|---|
Logger
|
logging.Logger: Configured logger instance. |
Source code in promptolution/utils/logging.py
get_test_statistic_func(name)
Get the test statistic function based on the name provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the test statistic function. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
callable |
Callable[..., bool]
|
The corresponding test statistic function. |
Source code in promptolution/utils/test_statistics.py
get_token_counter(llm)
Get a token counter function for the given LLM.
This function returns a callable that counts tokens based on the LLM's tokenizer or a simple split method if no tokenizer is available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
BaseLLM
|
The language model object that may have a tokenizer. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[str], float]
|
A callable that takes a text input and returns the token count. |
Source code in promptolution/utils/token_counter.py
paired_t_test(scores_a, scores_b, alpha=0.05)
Uses a paired t-test to test if candidate A's accuracy is significantly higher than candidate B's accuracy within a confidence interval of 1-lpha. Assumptions: - The samples are paired. - The differences between the pairs are normally distributed (-> n > 30).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores_a
|
List[float]
|
Array of accuracy scores for candidate A. |
required |
scores_b
|
List[float]
|
Array of accuracy scores for candidate B. |
required |
alpha
|
float
|
Significance level (default 0.05 for 95% confidence). |
0.05
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if candidate A is significantly better than candidate B, False otherwise. |
Source code in promptolution/utils/test_statistics.py
setup_logging(level=logging.INFO)
Set up logging for the promptolution library.
This function configures the root logger for the library with appropriate formatting and level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int
|
Logging level. Defaults to logging.INFO. |
INFO
|
Source code in promptolution/utils/logging.py
sort_prompts_by_scores(prompts, scores, top_k=None)
Sort prompts by score, accepting scalar, 1D, or multi-dimensional scores.
Scores can be provided as Python lists or NumPy arrays. If scores are multi-
dimensional (e.g., per-subsample results), they are aggregated with a
nanmean across all non-leading axes before sorting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
List[Prompt]
|
Prompt objects to sort. |
required |
scores
|
Sequence[float] | ndarray
|
Corresponding scores; can be nested lists or arrays. |
required |
top_k
|
Optional[int]
|
Limit the result to the top_k prompts. |
None
|
Returns:
| Type | Description |
|---|---|
List[Prompt]
|
Tuple[List[Prompt], List[float]]: Prompts and their aggregated scores, |
List[float]
|
sorted in descending order. |
Source code in promptolution/utils/prompt.py
callbacks
Callback classes for logging, saving, and tracking optimization progress.
BaseCallback
Bases: ABC
Base class for optimization callbacks.
Callbacks can be used to monitor the optimization process, save checkpoints, log metrics, or implement early stopping criteria.
Source code in promptolution/utils/callbacks.py
__init__(**kwargs)
Initialize the callback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
on_epoch_end(optimizer)
Call at the end of each optimization epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
BaseOptimizer
|
The optimizer object that called the callback. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Bool |
bool
|
True if the optimization should continue, False if it should stop. |
Source code in promptolution/utils/callbacks.py
on_step_end(optimizer)
Call at the end of each optimization step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
BaseOptimizer
|
The optimizer object that called the callback. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Bool |
bool
|
True if the optimization should continue, False if it should stop. |
Source code in promptolution/utils/callbacks.py
on_train_end(optimizer)
Call at the end of the entire optimization process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
BaseOptimizer
|
The optimizer object that called the callback. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Bool |
bool
|
True if the optimization should continue, False if it should stop. |
Source code in promptolution/utils/callbacks.py
BestPromptCallback
Bases: BaseCallback
Callback for tracking the best prompt during optimization.
This callback keeps track of the prompt with the highest score.
Attributes:
| Name | Type | Description |
|---|---|---|
best_prompt |
str
|
The prompt with the highest score so far. |
best_score |
float
|
The highest score achieved so far. |
Source code in promptolution/utils/callbacks.py
__init__()
get_best_prompt()
Get the best prompt and score achieved during optimization.
Returns: Tuple[str, float]: The best prompt and score.
on_step_end(optimizer)
Update the best prompt and score if a new high score is achieved.
Args: optimizer: The optimizer object that called the callback.
Source code in promptolution/utils/callbacks.py
FileOutputCallback
Bases: BaseCallback
Callback for saving optimization progress to a specified file type.
This callback saves information about each step to a file.
Attributes:
| Name | Type | Description |
|---|---|---|
dir |
Union[str, Path]
|
Directory the file is saved to. |
step |
int
|
The current step number. |
file_type |
str
|
The type of file to save the output to. |
Source code in promptolution/utils/callbacks.py
__init__(dir, file_type='parquet')
Initialize the FileOutputCallback.
Args: dir (Union[str, Path]): Directory the CSV file is saved to. file_type (str): The type of file to save the output to.
Source code in promptolution/utils/callbacks.py
on_step_end(optimizer)
Append this step's rows and rewrite the results file.
Args: optimizer: The optimizer object that called the callback
Source code in promptolution/utils/callbacks.py
LoggerCallback
Bases: BaseCallback
Callback for logging optimization progress.
This callback logs information about each step, epoch, and the end of training.
Attributes:
| Name | Type | Description |
|---|---|---|
logger |
The logger object to use for logging. |
|
step |
int
|
The current step number. |
Source code in promptolution/utils/callbacks.py
__init__(logger)
on_step_end(optimizer)
Log information about the current step.
Source code in promptolution/utils/callbacks.py
on_train_end(optimizer, logs=None)
Log information at the end of training.
Args: optimizer: The optimizer object that called the callback. logs: Additional information to log.
Source code in promptolution/utils/callbacks.py
ProgressBarCallback
Bases: BaseCallback
Callback for displaying a progress bar during optimization.
This callback uses tqdm to display a progress bar that updates at each step.
Attributes:
| Name | Type | Description |
|---|---|---|
pbar |
tqdm
|
The tqdm progress bar object. |
Source code in promptolution/utils/callbacks.py
__init__(total_steps)
Initialize the ProgressBarCallback.
Args: total_steps (int): The total number of steps in the optimization process.
on_step_end(optimizer)
Update the progress bar at the end of each step.
Args: optimizer: The optimizer object that called the callback.
on_train_end(optimizer)
Close the progress bar at the end of training.
Args: optimizer: The optimizer object that called the callback.
TokenCountCallback
Bases: BaseCallback
Callback for stopping optimization based on the total token count.
Source code in promptolution/utils/callbacks.py
__init__(max_tokens_for_termination, token_type_for_termination)
Initialize the TokenCountCallback.
Args: max_tokens_for_termination (int): Maximum number of tokens which is allowed befor the algorithm is stopped. token_type_for_termination (str): Can be one of either "input_tokens", "output_tokens" or "total_tokens".
Source code in promptolution/utils/callbacks.py
on_step_end(optimizer)
Check if the total token count exceeds the maximum allowed. If so, stop the optimization.
Source code in promptolution/utils/callbacks.py
capo_utils
Shared utilities for CAPO-style optimizers.
build_few_shot_examples(instruction, num_examples, optimizer)
Create few-shot examples with optional reasoning replacement.
Source code in promptolution/utils/capo_utils.py
perform_crossover(parents, optimizer, parent_select_func=None)
Generate crossover offspring prompts.
Source code in promptolution/utils/capo_utils.py
perform_mutation(offsprings, optimizer)
Mutate offspring prompts.
Source code in promptolution/utils/capo_utils.py
evaluation
Component-level evaluation helpers: split off a held-out set, score prompts on a task.
dev_test_split(df, test_frac=0.2, seed=42)
Split a DataFrame into a dev and test set.
The optimizer selects prompts on the dev set. The test set is held out for the final evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The data to split (or a df-like with |
required |
test_frac
|
float
|
Fraction of rows held out for the test split. |
0.2
|
seed
|
int
|
Random seed for the split. |
42
|
Returns:
| Type | Description |
|---|---|
Tuple[DataFrame, DataFrame]
|
Tuple[pd.DataFrame, pd.DataFrame]: |
Source code in promptolution/utils/evaluation.py
evaluate_prompts(prompts, task, predictor)
Score prompts on a task and return a sorted prompt/score table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
Union[List[Prompt], List[str]]
|
Prompts to score. |
required |
task
|
BaseTask
|
The task to score on (its full dataset is used). |
required |
predictor
|
BasePredictor
|
The predictor that runs the prompts. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Columns |
Source code in promptolution/utils/evaluation.py
formatting
Utils for formatting prompts and outputs.
extract_from_tag(text, start_tag, end_tag)
Extract content from a string between specified start and end tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The input text to extract from. |
required |
start_tag
|
str
|
The start tag to look for. |
required |
end_tag
|
str
|
The end tag to look for. |
required |
Returns:
| Type | Description |
|---|---|
Union[List[str], str]
|
Union[List[str], str]: The extracted content, either as a list or a single string. |
Source code in promptolution/utils/formatting.py
logging
Logging configuration for the promptolution library.
get_logger(name, level=None)
Get a logger with the specified name and level.
This function provides a standardized way to get loggers throughout the library, ensuring consistent formatting and behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the logger, typically name of the module. |
required |
level
|
int
|
Logging level. Defaults to None, which uses the root logger's level. |
None
|
Returns:
| Type | Description |
|---|---|
Logger
|
logging.Logger: Configured logger instance. |
Source code in promptolution/utils/logging.py
setup_logging(level=logging.INFO)
Set up logging for the promptolution library.
This function configures the root logger for the library with appropriate formatting and level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int
|
Logging level. Defaults to logging.INFO. |
INFO
|
Source code in promptolution/utils/logging.py
optimize
The lightweight entry points: optimize prompts on a dataset, and score them on another.
evaluate(prompts, data, task_description, task_type='classification', *, model_id='gpt-4o-mini', api_key=None, api_url=None, x_column='x', y_column='y')
Score prompts on a dataset and return a sorted prompt/score table.
The counterpart to :func:optimize: pass the prompts it returned and your held-out split.
Evaluation runs on all of data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
Union[List[Prompt], List[str]]
|
Prompts to score, e.g. the output of :func: |
required |
data
|
Union[DataFrame, str, Path]
|
A DataFrame, or anything |
required |
task_description
|
str
|
Description of the task. |
required |
task_type
|
str
|
Only |
'classification'
|
model_id
|
str
|
Model id of the LLM used for predictions. |
'gpt-4o-mini'
|
api_key
|
Optional[str]
|
API key. If omitted, resolved from the environment. |
None
|
api_url
|
Optional[str]
|
API base URL, for providers other than OpenAI. |
None
|
x_column
|
str
|
Input column name in |
'x'
|
y_column
|
str
|
Label column name in |
'y'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Columns |
Source code in promptolution/utils/optimize.py
optimize(data, task_description, task_type='classification', *, model_id='gpt-4o-mini', api_key=None, api_url=None, x_column='x', y_column='y', optimizer='capo', n_steps=10, initial_prompts=None, output_dir=None)
Optimize prompts on a dataset, with sensible defaults.
Builds the components for you (an API LLM, a marker-based predictor, a classification task and the chosen optimizer), asking only for what the library cannot know: your data, an LLM and its credentials, and a description of the task.
All of data is used to select prompts, so pass your dev split here and keep a held-out split
for :func:evaluate. Nothing is fitted on this data in the gradient sense; the optimizer only
uses it to score and select candidate prompts.
Only classification is supported. For judge or reward tasks, or for full control over the
components, build them yourself and call optimizer.optimize() (see the README). For
config-driven runs, grids, SLURM and restart, use the promptolution-experiment CLI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[DataFrame, str, Path]
|
A DataFrame, or anything |
required |
task_description
|
str
|
Description of the task, used to generate initial prompts and passed to the meta-LLM during optimization. |
required |
task_type
|
str
|
Only |
'classification'
|
model_id
|
str
|
Model id of the LLM used for both predictions and prompt proposals. |
'gpt-4o-mini'
|
api_key
|
Optional[str]
|
API key. If omitted, the underlying OpenAI client resolves it from
the environment (e.g. |
None
|
api_url
|
Optional[str]
|
API base URL, for providers other than OpenAI. |
None
|
x_column
|
str
|
Input column name in |
'x'
|
y_column
|
str
|
Label column name in |
'y'
|
optimizer
|
str
|
One of |
'capo'
|
n_steps
|
int
|
Number of optimization steps. |
10
|
initial_prompts
|
Optional[List[str]]
|
Prompts to start from. If omitted, they are generated
from |
None
|
output_dir
|
Optional[Union[str, Path]]
|
If set, write the per-step trace and run info here. If omitted (the default), nothing is written to disk. |
None
|
Returns:
| Type | Description |
|---|---|
List[Prompt]
|
List[Prompt]: The optimized prompts. Pass them to :func: |
Source code in promptolution/utils/optimize.py
prompt
Module defining the Prompt class and related utilities.
Prompt
Represent a prompt consisting of an instruction and few-shot examples.
Source code in promptolution/utils/prompt.py
__eq__(other)
Structural equality for use in lists, sets, and dict keys.
Source code in promptolution/utils/prompt.py
__hash__()
__init__(instruction, few_shots=None, downstream_template=None)
Initialize the Prompt with an instruction and associated examples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instruction
|
str
|
The instruction or prompt text. |
required |
few_shots
|
List[str]
|
List of examples as string. |
None
|
downstream_template
|
str
|
Template for formatting the full prompt. |
None
|
Source code in promptolution/utils/prompt.py
__str__()
construct_prompt()
Construct the full prompt string by replacing placeholders in the template with the instruction and formatted examples.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The constructed prompt string. |
Source code in promptolution/utils/prompt.py
sort_prompts_by_scores(prompts, scores, top_k=None)
Sort prompts by score, accepting scalar, 1D, or multi-dimensional scores.
Scores can be provided as Python lists or NumPy arrays. If scores are multi-
dimensional (e.g., per-subsample results), they are aggregated with a
nanmean across all non-leading axes before sorting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompts
|
List[Prompt]
|
Prompt objects to sort. |
required |
scores
|
Sequence[float] | ndarray
|
Corresponding scores; can be nested lists or arrays. |
required |
top_k
|
Optional[int]
|
Limit the result to the top_k prompts. |
None
|
Returns:
| Type | Description |
|---|---|
List[Prompt]
|
Tuple[List[Prompt], List[float]]: Prompts and their aggregated scores, |
List[float]
|
sorted in descending order. |
Source code in promptolution/utils/prompt.py
prompt_creation
Utility functions for prompt creation.
create_prompt_variation(prompt, llm, meta_prompt=None)
Generate a variation of the given prompt(s) while keeping the semantic meaning.
Idea taken from the paper Zhou et al. (2021) https://arxiv.org/pdf/2211.01910
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
Union[List[str], str]
|
The prompt(s) to generate variations of. |
required |
llm
|
BaseLLM
|
The language model to use for generating the variations. |
required |
meta_prompt
|
str
|
The meta prompt to use for generating the variations.
If None, a default meta prompt is used. Should contain |
None
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of generated variations of the input prompt(s). |
Source code in promptolution/utils/prompt_creation.py
create_prompts_from_samples(task, llm, meta_prompt=None, n_samples=3, task_description=None, n_prompts=1, get_uniform_labels=False)
Generate a set of prompts from dataset examples sampled from a given task.
Idea taken from the paper Zhou et al. (2021) https://arxiv.org/pdf/2211.01910 Samples are selected, such that (1) all possible classes are represented (2) the samples are as representative as possible
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
BaseTask
|
The task to generate prompts for. Xs and Ys from this object are used to generate the prompts. |
required |
llm
|
BaseLLM
|
The language model to use for generating the prompts. |
required |
meta_prompt
|
str
|
The meta prompt to use for generating the prompts. If None, a default meta prompt is used. |
None
|
n_samples
|
int
|
The number of samples to use for generating prompts. |
3
|
task_description
|
str
|
The description of the task to include in the prompt. |
None
|
n_prompts
|
int
|
The number of prompts to generate. |
1
|
get_uniform_labels
|
bool
|
If True, samples are selected such that all classes are represented. |
False
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of generated prompts. |
Source code in promptolution/utils/prompt_creation.py
create_prompts_from_task_description(task_description, llm, meta_prompt=None, n_prompts=10, n_retries=3)
Generate a set of prompts from a given task description.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_description
|
str
|
The description of the task to generate prompts for. |
required |
llm
|
BaseLLM
|
The language model to use for generating the prompts. |
required |
meta_prompt
|
str
|
The meta prompt to use for generating the prompts. If None, a default meta prompt is used. |
None
|
n_prompts
|
int
|
The number of prompts to generate. |
10
|
n_retries
|
int
|
The number of retries to attempt if prompt generation fails. |
3
|
Source code in promptolution/utils/prompt_creation.py
runinfo
Persist a run's status and timestamps to runinfo.json (part of the experiment output contract).
finish_runinfo(out_dir, info, status, **extra)
Update info with a finished/failed status and the current UTC timestamp, and rewrite runinfo.json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_dir
|
Union[str, Path]
|
Directory runinfo.json is written to. |
required |
info
|
Dict[str, Any]
|
The dict returned by :func: |
required |
status
|
str
|
The run's final status, e.g. "finished" or "failed". |
required |
**extra
|
Any
|
Extra fields to record, e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: The updated info dict. |
Source code in promptolution/utils/runinfo.py
start_runinfo(out_dir, name)
Write a "running" runinfo.json with the current UTC timestamp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_dir
|
Union[str, Path]
|
Directory runinfo.json is written to. |
required |
name
|
str
|
The run's name. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: The info dict, to be passed to :func: |
Source code in promptolution/utils/runinfo.py
write_to_file(out_dir, info)
Write the run info to runinfo.json in out_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_dir
|
Union[str, Path]
|
Directory runinfo.json is written to. |
required |
info
|
Dict[str, Any]
|
The run info to serialize. |
required |
Source code in promptolution/utils/runinfo.py
templates
Meta-prompt templates for different prompt optimization methods.
test_statistics
Implementation of statistical significance tests used in the racing algorithm. Contains paired t-test functionality to compare prompt performance and determine statistical significance between candidates.
get_test_statistic_func(name)
Get the test statistic function based on the name provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the test statistic function. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
callable |
Callable[..., bool]
|
The corresponding test statistic function. |
Source code in promptolution/utils/test_statistics.py
paired_t_test(scores_a, scores_b, alpha=0.05)
Uses a paired t-test to test if candidate A's accuracy is significantly higher than candidate B's accuracy within a confidence interval of 1-lpha. Assumptions: - The samples are paired. - The differences between the pairs are normally distributed (-> n > 30).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores_a
|
List[float]
|
Array of accuracy scores for candidate A. |
required |
scores_b
|
List[float]
|
Array of accuracy scores for candidate B. |
required |
alpha
|
float
|
Significance level (default 0.05 for 95% confidence). |
0.05
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if candidate A is significantly better than candidate B, False otherwise. |
Source code in promptolution/utils/test_statistics.py
token_counter
Token counter for LLMs.
This module provides a function to count the number of tokens in a given text.
get_token_counter(llm)
Get a token counter function for the given LLM.
This function returns a callable that counts tokens based on the LLM's tokenizer or a simple split method if no tokenizer is available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
BaseLLM
|
The language model object that may have a tokenizer. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[str], float]
|
A callable that takes a text input and returns the token count. |