Experiment¶
rupsycho.experiment.ExperimentDocument
¶
Class for storing an experiment and associated questionnaires along with metadata.
Extends LangChain's BaseMedia and Pydantic's BaseModel, integrating data validation and serialization capabilities with document handling features.
Example:
.. code-block:: python
from my_module import ExperimentDocument
experiment_doc = ExperimentDocument(
name="Experiment 1",
description="Test Experiment",
demographic_profiles={...},
models={...},
questionnaire=...,
metadata={"source": "Lab A"}
)
Initialize ExperimentDocument with optional conversions for nested data.
name
¶
name: str | None = Field(None, description='The name of the experiment', examples=['Generative Models for Big Five Inventory'])
description
¶
description: str | None = Field(None, description='The description of the experiment', examples=['Testing Generative Models for BFI questionnaire using Rupsycho.'])
parameters
¶
parameters: ExperimentParameters = Field(default_factory=ExperimentParameters, description='The parameters for the experiment and text generation')
prompt_template
¶
prompt_template: NormalPromptTemplateConfig | ChatPromptTemplateConfig | LangchainPromptTemplateConfig = Field(None, description='The prompt template used by the model')
models
¶
models: dict[str, LangChainModelConfig | LocalHuggingFaceModelConfig | RemoteHuggingFaceModelConfig | OllamaModelConfig | OpenAIModelConfig | GoogleModelConfig | DeepSeekModelConfig] = Field(default_factory=dict, description='The models in the experiment')
demographic_profiles
¶
demographic_profiles: dict[str, DemographicProfile] = Field(default_factory=dict, description='The demographic profiles in the experiment')
questionnaire
¶
questionnaire: Questionnaire | None = Field(None, description='The questionnaire in the experiment')
metadata
¶
metadata: dict[str, Any] = Field(default_factory=dict, description='Additional metadata for the experiment document.')
set_questionnaire
¶
Sets the questionnaire for the experiment.
rupsycho.experiment_collection.ExperimentCollection
¶
Class for storing a collection of ExperimentDocument objects along with metadata.
Example:
.. code-block:: python
from my_module import ExperimentCollection, ExperimentDocument
experiment_doc1 = ExperimentDocument(
name="Experiment 1",
description="Test Experiment",
demographic_profiles=[...],
models=[...],
questionnaire=...,
metadata={"source": "Lab A"}
)
experiment_doc2 = ExperimentDocument(
name="Experiment 2",
description="Another Test",
demographic_profiles=[...],
models=[...],
questionnaire=...,
metadata={"source": "Lab B"}
)
experiment_collection = ExperimentCollection(
experiments=[experiment_doc1, experiment_doc2],
metadata={"source": "Lab Collection"}
)
Initialize an ExperimentCollection with a list of ExperimentDocument objects.
experiments
instance-attribute
¶
List of ExperimentDocument objects representing the experiments.
is_lc_serializable
classmethod
¶
Return whether this class is serializable.
get_lc_namespace
classmethod
¶
Get the namespace of the LangChain object.
run_all
¶
Run every experiment of the collection, one after another.
| PARAMETER | DESCRIPTION |
|---|---|
**run_kwargs
|
Passed to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[RunSummary]
|
One |
Mixins¶
rupsycho.mixins.experiment_processing.ExperimentProcessingMixin
¶
Runs an experiment: models x seeds x items x personas.
The mixin relies on the attributes of ExperimentDocument (questionnaire,
demographic_profiles, runnable_models, runnable_prompt, runnable_parser,
parameters, models and name).
assemble_prompt
¶
Return the fully assembled prompt for one item and persona, exactly as sent.
| PARAMETER | DESCRIPTION |
|---|---|
item_idx
|
Index of the instruction item.
TYPE:
|
persona_idx
|
Index of the demographic profile (in configuration order).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
The prompt text; for chat prompts the messages are joined as ``"System
|
..."`` / |
``"Human
|
..."`` blocks. |
| RAISES | DESCRIPTION |
|---|---|
IndexError
|
If |
ValueError
|
If the experiment has no questionnaire or prompt. |
Note
Does not include the accumulated memory of cumulative runs.
print_assembled_prompt
¶
Print the assembled prompt of one item and persona (see assemble_prompt).
Problems (for example an out-of-range index) are reported as a warning instead of raising, which is convenient in notebooks.
| PARAMETER | DESCRIPTION |
|---|---|
item_idx
|
Index of the instruction item.
TYPE:
|
persona_idx
|
Index of the demographic profile.
TYPE:
|
process_single_experiment
¶
process_single_experiment(cumulative: bool, pbar: Any = None, callbacks: Sequence = (), *, max_concurrency: int = 1, on_error: ErrorPolicy = 'warn') -> RunSummary
Process every model of the experiment and return a :class:RunSummary.
| PARAMETER | DESCRIPTION |
|---|---|
cumulative
|
Let each persona remember its earlier answers.
TYPE:
|
pbar
|
Progress bar to update; one is created if omitted.
TYPE:
|
callbacks
|
Callbacks that receive every answer.
TYPE:
|
max_concurrency
|
Calls to run at the same time (API models only; local Hugging Face models always run sequentially).
TYPE:
|
on_error
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RunSummary
|
A summary of the calls made. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
run
¶
run(callbacks: Sequence = (), cumulative: bool = False, *, max_concurrency: int = 1, on_error: ErrorPolicy = 'warn', show_progress: bool = True) -> RunSummary
Run the experiment.
Every model is asked every question as every persona, once per seed. Answers are
stored on the questionnaire items (see get_answers / get_answers_as_dataframe)
and passed to the callbacks as soon as they are generated.
| PARAMETER | DESCRIPTION |
|---|---|
callbacks
|
Callbacks such as
TYPE:
|
cumulative
|
Let each persona remember its earlier answers ("response memory"). Needs a chat prompt whose user message is asked once per item.
TYPE:
|
max_concurrency
|
Number of calls to run in parallel. Useful for API models where the time is spent waiting; models running in this process (local Hugging Face) are always called sequentially. Results and callbacks keep their order.
TYPE:
|
on_error
|
What to do when a model call fails.
TYPE:
|
show_progress
|
Show a progress bar.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RunSummary
|
A |
RunSummary
|
of calls, failures and the elapsed time. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the experiment is incomplete (no model, prompt, questionnaire). |
rupsycho.mixins.experiment_exporting.ExperimentExportMixin
¶
Mixin providing methods to export the experiment results to a file or return the answers.
to_config
¶
Return the experiment as a plain, JSON-serialisable configuration dictionary.
Only the configuration is exported (name, description, parameters, models, prompt
template, personas, questionnaire), never runtime objects. Secrets such as API keys
are masked. The result can be passed to
experiment_from_dict, so an exported
experiment can be shared, versioned and re-loaded.
| PARAMETER | DESCRIPTION |
|---|---|
include_answers
|
Keep the answers collected so far on the questionnaire items.
Pass
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
The configuration dictionary. |
export_to_file
¶
Write the experiment configuration (and answers) to a JSON file.
| PARAMETER | DESCRIPTION |
|---|---|
filename
|
Target file; it is written as UTF-8 and overwritten if it exists.
TYPE:
|
include_answers
|
Keep the answers collected so far; see
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
OSError
|
If the file cannot be written. |
get_answers
¶
Extracts and returns the answers from the experiment in a list holding the nested answer structure.
:return: A list of dictionaries representing the answers for each instruction item.
get_answers_as_dataframe
¶
Returns a flat pandas DataFrame with the experiment's answers.
Columns include: - "Instruction ID" - "Instruction Question" - "Model ID" - "Persona ID" - "Run Seed" - "Answer"
:return: A pandas DataFrame containing the flattened answers.
rupsycho.mixins.model_managing.ModelManagementMixin
¶
Methods to manage the models of an experiment.
An experiment keeps two dictionaries under the same identifiers: models holds the
configurations (what gets exported), runnable_models holds what is run - either the
configuration itself (loaded lazily when the run reaches it) or a ready LangChain model
added with add_model.
load_model
¶
Deserialize a model from its LangChain definition.
| PARAMETER | DESCRIPTION |
|---|---|
model_definition
|
Serialized model as produced by
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any | None
|
The model, or |
add_model
¶
Add a ready LangChain model to the experiment.
The model is run as it is. Its serialized definition is stored in models so that the
experiment can be exported; models that cannot be serialized (for example local
pipelines) are exported as a placeholder and have to be added again after loading.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Any LangChain runnable (chat model, LLM, ...).
TYPE:
|
identifier
|
Name of the model in the results. Defaults to its object id.
TYPE:
|
Note
Adding a model under an identifier that exists replaces it and emits a warning.
set_runnable_models
¶
Reset runnable_models to the configured models.
Every model is then loaded from its configuration when the run reaches it. Models that were added as live objects without a loadable configuration are no longer available afterwards.
get_model
¶
Return the runnable entry of a model.
| PARAMETER | DESCRIPTION |
|---|---|
identifier
|
Identifier of the model.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any | None
|
The LangChain model, or - for models that are loaded lazily - its configuration; |
Any | None
|
|
remove_model
¶
Remove a model from the experiment.
| PARAMETER | DESCRIPTION |
|---|---|
identifier
|
Identifier of the model. Unknown identifiers only emit a warning.
TYPE:
|
replace_model
¶
Replace an existing model by a ready LangChain model.
| PARAMETER | DESCRIPTION |
|---|---|
identifier
|
Identifier of the model to replace. Unknown identifiers only emit a warning.
TYPE:
|
new_model
|
The new model.
TYPE:
|
get_all_runnable_models
¶
Return the runnable entries of all models, keyed by identifier.
rupsycho.mixins.persona_managing.PersonaManagementMixin
¶
Methods to manage the personas of an experiment.
Personas are the demographic profiles the models answer as. They are stored in
demographic_profiles under unique identifiers, which also label the rows of the results.
add_persona
¶
Add a persona to the experiment.
| PARAMETER | DESCRIPTION |
|---|---|
persona
|
The demographic profile to add.
TYPE:
|
identifier
|
Name of the persona in the results. Defaults to the object id.
TYPE:
|
Example
Note
Adding a persona under an identifier that exists replaces it and emits a warning.
get_persona
¶
Return the persona with this identifier, or None if there is none.
remove_persona
¶
Remove a persona.
| PARAMETER | DESCRIPTION |
|---|---|
identifier
|
Identifier of the persona. Unknown identifiers only emit a warning.
TYPE:
|
rupsycho.mixins.prompt_managing.PromptTemplateMixin
¶
Mixin providing methods to manage the prompt template in the experiment.
This includes setting the prompt template, loading it, and converting it into a runnable form.
load_prompt
¶
Load the prompt template from its serialized definition.
:param prompt_template: Serialized prompt template. :return: Loaded prompt, or None if an error occurs.
set_prompt
¶
Use a ready-made LangChain prompt for this experiment.
The prompt is kept as a serialized langchain prompt configuration, so it survives
export_to_file and can be loaded again.
| PARAMETER | DESCRIPTION |
|---|---|
prompt
|
A LangChain prompt template such as
TYPE:
|
get_prompt
¶
Return the current runnable prompt template.
| RETURNS | DESCRIPTION |
|---|---|
Any | None
|
The LangChain prompt, or |
get_prompt_config
¶
Return the prompt template configuration (normal, chat or langchain).
| RETURNS | DESCRIPTION |
|---|---|
Any | None
|
The configuration object, or |
set_prompt_config
¶
Set the prompt from a configuration, as it would appear in a JSON file.
| PARAMETER | DESCRIPTION |
|---|---|
prompt_template
|
A configuration dictionary (
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the configuration is not recognised. |
has_prompt
¶
Check whether a runnable prompt is set.
:return: True if a runnable prompt is set, False otherwise.
Run summary¶
rupsycho.mixins.experiment_processing.RunSummary
dataclass
¶
Outcome of :meth:ExperimentProcessingMixin.run.
| ATTRIBUTE | DESCRIPTION |
|---|---|
n_calls |
Number of model calls made.
TYPE:
|
n_failed |
Number of calls that raised; their answers are missing from the results.
TYPE:
|
elapsed |
Wall-clock seconds of the whole run.
TYPE:
|
errors |
The first distinct error messages (at most five).
TYPE:
|