edsl 0.1.37.dev6__py3-none-any.whl → 0.1.38.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- edsl/Base.py +303 -303
- edsl/BaseDiff.py +260 -260
- edsl/TemplateLoader.py +24 -24
- edsl/__init__.py +48 -48
- edsl/__version__.py +1 -1
- edsl/agents/Agent.py +855 -855
- edsl/agents/AgentList.py +350 -350
- edsl/agents/Invigilator.py +222 -222
- edsl/agents/InvigilatorBase.py +284 -284
- edsl/agents/PromptConstructor.py +353 -353
- edsl/agents/__init__.py +3 -3
- edsl/agents/descriptors.py +99 -99
- edsl/agents/prompt_helpers.py +129 -129
- edsl/auto/AutoStudy.py +117 -117
- edsl/auto/StageBase.py +230 -230
- edsl/auto/StageGenerateSurvey.py +178 -178
- edsl/auto/StageLabelQuestions.py +125 -125
- edsl/auto/StagePersona.py +61 -61
- edsl/auto/StagePersonaDimensionValueRanges.py +88 -88
- edsl/auto/StagePersonaDimensionValues.py +74 -74
- edsl/auto/StagePersonaDimensions.py +69 -69
- edsl/auto/StageQuestions.py +73 -73
- edsl/auto/SurveyCreatorPipeline.py +21 -21
- edsl/auto/utilities.py +224 -224
- edsl/base/Base.py +289 -289
- edsl/config.py +149 -149
- edsl/conjure/AgentConstructionMixin.py +160 -160
- edsl/conjure/Conjure.py +62 -62
- edsl/conjure/InputData.py +659 -659
- edsl/conjure/InputDataCSV.py +48 -48
- edsl/conjure/InputDataMixinQuestionStats.py +182 -182
- edsl/conjure/InputDataPyRead.py +91 -91
- edsl/conjure/InputDataSPSS.py +8 -8
- edsl/conjure/InputDataStata.py +8 -8
- edsl/conjure/QuestionOptionMixin.py +76 -76
- edsl/conjure/QuestionTypeMixin.py +23 -23
- edsl/conjure/RawQuestion.py +65 -65
- edsl/conjure/SurveyResponses.py +7 -7
- edsl/conjure/__init__.py +9 -9
- edsl/conjure/naming_utilities.py +263 -263
- edsl/conjure/utilities.py +201 -201
- edsl/conversation/Conversation.py +290 -290
- edsl/conversation/car_buying.py +58 -58
- edsl/conversation/chips.py +95 -95
- edsl/conversation/mug_negotiation.py +81 -81
- edsl/conversation/next_speaker_utilities.py +93 -93
- edsl/coop/PriceFetcher.py +54 -54
- edsl/coop/__init__.py +2 -2
- edsl/coop/coop.py +958 -958
- edsl/coop/utils.py +131 -131
- edsl/data/Cache.py +527 -527
- edsl/data/CacheEntry.py +228 -228
- edsl/data/CacheHandler.py +149 -149
- edsl/data/RemoteCacheSync.py +97 -97
- edsl/data/SQLiteDict.py +292 -292
- edsl/data/__init__.py +4 -4
- edsl/data/orm.py +10 -10
- edsl/data_transfer_models.py +73 -73
- edsl/enums.py +173 -173
- edsl/exceptions/BaseException.py +21 -21
- edsl/exceptions/__init__.py +54 -54
- edsl/exceptions/agents.py +38 -38
- edsl/exceptions/configuration.py +16 -16
- edsl/exceptions/coop.py +10 -10
- edsl/exceptions/data.py +14 -14
- edsl/exceptions/general.py +34 -34
- edsl/exceptions/jobs.py +33 -33
- edsl/exceptions/language_models.py +63 -63
- edsl/exceptions/prompts.py +15 -15
- edsl/exceptions/questions.py +91 -91
- edsl/exceptions/results.py +29 -29
- edsl/exceptions/scenarios.py +22 -22
- edsl/exceptions/surveys.py +37 -37
- edsl/inference_services/AnthropicService.py +87 -87
- edsl/inference_services/AwsBedrock.py +120 -120
- edsl/inference_services/AzureAI.py +217 -217
- edsl/inference_services/DeepInfraService.py +18 -18
- edsl/inference_services/GoogleService.py +156 -156
- edsl/inference_services/GroqService.py +20 -20
- edsl/inference_services/InferenceServiceABC.py +147 -147
- edsl/inference_services/InferenceServicesCollection.py +97 -97
- edsl/inference_services/MistralAIService.py +123 -123
- edsl/inference_services/OllamaService.py +18 -18
- edsl/inference_services/OpenAIService.py +224 -224
- edsl/inference_services/TestService.py +89 -89
- edsl/inference_services/TogetherAIService.py +170 -170
- edsl/inference_services/models_available_cache.py +118 -118
- edsl/inference_services/rate_limits_cache.py +25 -25
- edsl/inference_services/registry.py +39 -39
- edsl/inference_services/write_available.py +10 -10
- edsl/jobs/Answers.py +56 -56
- edsl/jobs/Jobs.py +1347 -1347
- edsl/jobs/__init__.py +1 -1
- edsl/jobs/buckets/BucketCollection.py +63 -63
- edsl/jobs/buckets/ModelBuckets.py +65 -65
- edsl/jobs/buckets/TokenBucket.py +248 -248
- edsl/jobs/interviews/Interview.py +661 -661
- edsl/jobs/interviews/InterviewExceptionCollection.py +99 -99
- edsl/jobs/interviews/InterviewExceptionEntry.py +186 -186
- edsl/jobs/interviews/InterviewStatistic.py +63 -63
- edsl/jobs/interviews/InterviewStatisticsCollection.py +25 -25
- edsl/jobs/interviews/InterviewStatusDictionary.py +78 -78
- edsl/jobs/interviews/InterviewStatusLog.py +92 -92
- edsl/jobs/interviews/ReportErrors.py +66 -66
- edsl/jobs/interviews/interview_status_enum.py +9 -9
- edsl/jobs/runners/JobsRunnerAsyncio.py +338 -338
- edsl/jobs/runners/JobsRunnerStatus.py +332 -332
- edsl/jobs/tasks/QuestionTaskCreator.py +242 -242
- edsl/jobs/tasks/TaskCreators.py +64 -64
- edsl/jobs/tasks/TaskHistory.py +442 -442
- edsl/jobs/tasks/TaskStatusLog.py +23 -23
- edsl/jobs/tasks/task_status_enum.py +163 -163
- edsl/jobs/tokens/InterviewTokenUsage.py +27 -27
- edsl/jobs/tokens/TokenUsage.py +34 -34
- edsl/language_models/KeyLookup.py +30 -30
- edsl/language_models/LanguageModel.py +706 -706
- edsl/language_models/ModelList.py +102 -102
- edsl/language_models/RegisterLanguageModelsMeta.py +184 -184
- edsl/language_models/__init__.py +3 -3
- edsl/language_models/fake_openai_call.py +15 -15
- edsl/language_models/fake_openai_service.py +61 -61
- edsl/language_models/registry.py +137 -137
- edsl/language_models/repair.py +156 -156
- edsl/language_models/unused/ReplicateBase.py +83 -83
- edsl/language_models/utilities.py +64 -64
- edsl/notebooks/Notebook.py +259 -259
- edsl/notebooks/__init__.py +1 -1
- edsl/prompts/Prompt.py +357 -357
- edsl/prompts/__init__.py +2 -2
- edsl/questions/AnswerValidatorMixin.py +289 -289
- edsl/questions/QuestionBase.py +656 -656
- edsl/questions/QuestionBaseGenMixin.py +161 -161
- edsl/questions/QuestionBasePromptsMixin.py +234 -234
- edsl/questions/QuestionBudget.py +227 -227
- edsl/questions/QuestionCheckBox.py +359 -359
- edsl/questions/QuestionExtract.py +183 -183
- edsl/questions/QuestionFreeText.py +114 -114
- edsl/questions/QuestionFunctional.py +159 -159
- edsl/questions/QuestionList.py +231 -231
- edsl/questions/QuestionMultipleChoice.py +286 -286
- edsl/questions/QuestionNumerical.py +153 -153
- edsl/questions/QuestionRank.py +324 -324
- edsl/questions/Quick.py +41 -41
- edsl/questions/RegisterQuestionsMeta.py +71 -71
- edsl/questions/ResponseValidatorABC.py +174 -174
- edsl/questions/SimpleAskMixin.py +73 -73
- edsl/questions/__init__.py +26 -26
- edsl/questions/compose_questions.py +98 -98
- edsl/questions/decorators.py +21 -21
- edsl/questions/derived/QuestionLikertFive.py +76 -76
- edsl/questions/derived/QuestionLinearScale.py +87 -87
- edsl/questions/derived/QuestionTopK.py +91 -91
- edsl/questions/derived/QuestionYesNo.py +82 -82
- edsl/questions/descriptors.py +413 -413
- edsl/questions/prompt_templates/question_budget.jinja +13 -13
- edsl/questions/prompt_templates/question_checkbox.jinja +32 -32
- edsl/questions/prompt_templates/question_extract.jinja +11 -11
- edsl/questions/prompt_templates/question_free_text.jinja +3 -3
- edsl/questions/prompt_templates/question_linear_scale.jinja +11 -11
- edsl/questions/prompt_templates/question_list.jinja +17 -17
- edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -33
- edsl/questions/prompt_templates/question_numerical.jinja +36 -36
- edsl/questions/question_registry.py +147 -147
- edsl/questions/settings.py +12 -12
- edsl/questions/templates/budget/answering_instructions.jinja +7 -7
- edsl/questions/templates/budget/question_presentation.jinja +7 -7
- edsl/questions/templates/checkbox/answering_instructions.jinja +10 -10
- edsl/questions/templates/checkbox/question_presentation.jinja +22 -22
- edsl/questions/templates/extract/answering_instructions.jinja +7 -7
- edsl/questions/templates/likert_five/answering_instructions.jinja +10 -10
- edsl/questions/templates/likert_five/question_presentation.jinja +11 -11
- edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -5
- edsl/questions/templates/linear_scale/question_presentation.jinja +5 -5
- edsl/questions/templates/list/answering_instructions.jinja +3 -3
- edsl/questions/templates/list/question_presentation.jinja +5 -5
- edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -9
- edsl/questions/templates/multiple_choice/question_presentation.jinja +11 -11
- edsl/questions/templates/numerical/answering_instructions.jinja +6 -6
- edsl/questions/templates/numerical/question_presentation.jinja +6 -6
- edsl/questions/templates/rank/answering_instructions.jinja +11 -11
- edsl/questions/templates/rank/question_presentation.jinja +15 -15
- edsl/questions/templates/top_k/answering_instructions.jinja +8 -8
- edsl/questions/templates/top_k/question_presentation.jinja +22 -22
- edsl/questions/templates/yes_no/answering_instructions.jinja +6 -6
- edsl/questions/templates/yes_no/question_presentation.jinja +11 -11
- edsl/results/Dataset.py +293 -293
- edsl/results/DatasetExportMixin.py +717 -717
- edsl/results/DatasetTree.py +145 -145
- edsl/results/Result.py +450 -450
- edsl/results/Results.py +1071 -1071
- edsl/results/ResultsDBMixin.py +238 -238
- edsl/results/ResultsExportMixin.py +43 -43
- edsl/results/ResultsFetchMixin.py +33 -33
- edsl/results/ResultsGGMixin.py +121 -121
- edsl/results/ResultsToolsMixin.py +98 -98
- edsl/results/Selector.py +135 -135
- edsl/results/__init__.py +2 -2
- edsl/results/tree_explore.py +115 -115
- edsl/scenarios/FileStore.py +458 -458
- edsl/scenarios/Scenario.py +546 -546
- edsl/scenarios/ScenarioHtmlMixin.py +64 -64
- edsl/scenarios/ScenarioList.py +1112 -1112
- edsl/scenarios/ScenarioListExportMixin.py +52 -52
- edsl/scenarios/ScenarioListPdfMixin.py +261 -261
- edsl/scenarios/__init__.py +4 -4
- edsl/shared.py +1 -1
- edsl/study/ObjectEntry.py +173 -173
- edsl/study/ProofOfWork.py +113 -113
- edsl/study/SnapShot.py +80 -80
- edsl/study/Study.py +528 -528
- edsl/study/__init__.py +4 -4
- edsl/surveys/DAG.py +148 -148
- edsl/surveys/Memory.py +31 -31
- edsl/surveys/MemoryPlan.py +244 -244
- edsl/surveys/Rule.py +330 -330
- edsl/surveys/RuleCollection.py +387 -387
- edsl/surveys/Survey.py +1795 -1795
- edsl/surveys/SurveyCSS.py +261 -261
- edsl/surveys/SurveyExportMixin.py +259 -259
- edsl/surveys/SurveyFlowVisualizationMixin.py +121 -121
- edsl/surveys/SurveyQualtricsImport.py +284 -284
- edsl/surveys/__init__.py +3 -3
- edsl/surveys/base.py +53 -53
- edsl/surveys/descriptors.py +56 -56
- edsl/surveys/instructions/ChangeInstruction.py +47 -47
- edsl/surveys/instructions/Instruction.py +51 -51
- edsl/surveys/instructions/InstructionCollection.py +77 -77
- edsl/templates/error_reporting/base.html +23 -23
- edsl/templates/error_reporting/exceptions_by_model.html +34 -34
- edsl/templates/error_reporting/exceptions_by_question_name.html +16 -16
- edsl/templates/error_reporting/exceptions_by_type.html +16 -16
- edsl/templates/error_reporting/interview_details.html +115 -115
- edsl/templates/error_reporting/interviews.html +9 -9
- edsl/templates/error_reporting/overview.html +4 -4
- edsl/templates/error_reporting/performance_plot.html +1 -1
- edsl/templates/error_reporting/report.css +73 -73
- edsl/templates/error_reporting/report.html +117 -117
- edsl/templates/error_reporting/report.js +25 -25
- edsl/tools/__init__.py +1 -1
- edsl/tools/clusters.py +192 -192
- edsl/tools/embeddings.py +27 -27
- edsl/tools/embeddings_plotting.py +118 -118
- edsl/tools/plotting.py +112 -112
- edsl/tools/summarize.py +18 -18
- edsl/utilities/SystemInfo.py +28 -28
- edsl/utilities/__init__.py +22 -22
- edsl/utilities/ast_utilities.py +25 -25
- edsl/utilities/data/Registry.py +6 -6
- edsl/utilities/data/__init__.py +1 -1
- edsl/utilities/data/scooter_results.json +1 -1
- edsl/utilities/decorators.py +77 -77
- edsl/utilities/gcp_bucket/cloud_storage.py +96 -96
- edsl/utilities/interface.py +627 -627
- edsl/utilities/repair_functions.py +28 -28
- edsl/utilities/restricted_python.py +70 -70
- edsl/utilities/utilities.py +409 -409
- {edsl-0.1.37.dev6.dist-info → edsl-0.1.38.dev1.dist-info}/LICENSE +21 -21
- {edsl-0.1.37.dev6.dist-info → edsl-0.1.38.dev1.dist-info}/METADATA +1 -1
- edsl-0.1.38.dev1.dist-info/RECORD +283 -0
- edsl-0.1.37.dev6.dist-info/RECORD +0 -283
- {edsl-0.1.37.dev6.dist-info → edsl-0.1.38.dev1.dist-info}/WHEEL +0 -0
edsl/questions/QuestionBase.py
CHANGED
@@ -1,656 +1,656 @@
|
|
1
|
-
"""This module contains the Question class, which is the base class for all questions in EDSL."""
|
2
|
-
|
3
|
-
from __future__ import annotations
|
4
|
-
from abc import ABC, abstractmethod
|
5
|
-
from typing import Any, Type, Optional, List, Callable, Union, TypedDict
|
6
|
-
import copy
|
7
|
-
|
8
|
-
from edsl.exceptions import (
|
9
|
-
QuestionResponseValidationError,
|
10
|
-
QuestionAnswerValidationError,
|
11
|
-
QuestionSerializationError,
|
12
|
-
)
|
13
|
-
from edsl.questions.descriptors import QuestionNameDescriptor, QuestionTextDescriptor
|
14
|
-
|
15
|
-
|
16
|
-
from edsl.questions.AnswerValidatorMixin import AnswerValidatorMixin
|
17
|
-
from edsl.questions.RegisterQuestionsMeta import RegisterQuestionsMeta
|
18
|
-
from edsl.Base import PersistenceMixin, RichPrintingMixin
|
19
|
-
from edsl.BaseDiff import BaseDiff, BaseDiffCollection
|
20
|
-
|
21
|
-
from edsl.questions.SimpleAskMixin import SimpleAskMixin
|
22
|
-
from edsl.questions.QuestionBasePromptsMixin import QuestionBasePromptsMixin
|
23
|
-
from edsl.questions.QuestionBaseGenMixin import QuestionBaseGenMixin
|
24
|
-
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
|
25
|
-
|
26
|
-
|
27
|
-
class QuestionBase(
|
28
|
-
PersistenceMixin,
|
29
|
-
RichPrintingMixin,
|
30
|
-
SimpleAskMixin,
|
31
|
-
QuestionBasePromptsMixin,
|
32
|
-
QuestionBaseGenMixin,
|
33
|
-
ABC,
|
34
|
-
AnswerValidatorMixin,
|
35
|
-
metaclass=RegisterQuestionsMeta,
|
36
|
-
):
|
37
|
-
"""ABC for the Question class. All questions inherit from this class.
|
38
|
-
Some of the constraints on child questions are defined in the RegisterQuestionsMeta metaclass.
|
39
|
-
"""
|
40
|
-
|
41
|
-
question_name: str = QuestionNameDescriptor()
|
42
|
-
question_text: str = QuestionTextDescriptor()
|
43
|
-
|
44
|
-
_answering_instructions = None
|
45
|
-
_question_presentation = None
|
46
|
-
|
47
|
-
@property
|
48
|
-
def response_model(self) -> type["BaseModel"]:
|
49
|
-
if self._response_model is not None:
|
50
|
-
return self._response_model
|
51
|
-
else:
|
52
|
-
return self.create_response_model()
|
53
|
-
|
54
|
-
# region: Validation and simulation methods
|
55
|
-
@property
|
56
|
-
def response_validator(self) -> "ResponseValidatorBase":
|
57
|
-
"""Return the response validator."""
|
58
|
-
params = (
|
59
|
-
{
|
60
|
-
"response_model": self.response_model,
|
61
|
-
}
|
62
|
-
| {k: getattr(self, k) for k in self.validator_parameters}
|
63
|
-
| {"exception_to_throw": getattr(self, "exception_to_throw", None)}
|
64
|
-
| {"override_answer": getattr(self, "override_answer", None)}
|
65
|
-
)
|
66
|
-
return self.response_validator_class(**params)
|
67
|
-
|
68
|
-
@property
|
69
|
-
def validator_parameters(self) -> list[str]:
|
70
|
-
"""Return the parameters required for the response validator.
|
71
|
-
|
72
|
-
>>> from edsl import QuestionMultipleChoice as Q
|
73
|
-
>>> Q.example().validator_parameters
|
74
|
-
['question_options', 'use_code']
|
75
|
-
|
76
|
-
"""
|
77
|
-
return self.response_validator_class.required_params
|
78
|
-
|
79
|
-
@property
|
80
|
-
def fake_data_factory(self):
|
81
|
-
"""Return the fake data factory."""
|
82
|
-
if not hasattr(self, "_fake_data_factory"):
|
83
|
-
from polyfactory.factories.pydantic_factory import ModelFactory
|
84
|
-
|
85
|
-
class FakeData(ModelFactory[self.response_model]):
|
86
|
-
...
|
87
|
-
|
88
|
-
self._fake_data_factory = FakeData
|
89
|
-
return self._fake_data_factory
|
90
|
-
|
91
|
-
def _simulate_answer(self, human_readable: bool = False) -> dict:
|
92
|
-
"""Simulate a valid answer for debugging purposes (what the validator expects).
|
93
|
-
>>> from edsl import QuestionFreeText as Q
|
94
|
-
>>> Q.example()._simulate_answer()
|
95
|
-
{'answer': '...', 'generated_tokens': ...}
|
96
|
-
"""
|
97
|
-
simulated_answer = self.fake_data_factory.build().dict()
|
98
|
-
if human_readable and hasattr(self, "question_options") and self.use_code:
|
99
|
-
simulated_answer["answer"] = [
|
100
|
-
self.question_options[index] for index in simulated_answer["answer"]
|
101
|
-
]
|
102
|
-
return simulated_answer
|
103
|
-
|
104
|
-
class ValidatedAnswer(TypedDict):
|
105
|
-
answer: Any
|
106
|
-
comment: Optional[str]
|
107
|
-
generated_tokens: Optional[str]
|
108
|
-
|
109
|
-
def _validate_answer(
|
110
|
-
self, answer: dict, replacement_dict: dict = None
|
111
|
-
) -> ValidatedAnswer:
|
112
|
-
"""Validate the answer.
|
113
|
-
>>> from edsl.exceptions import QuestionAnswerValidationError
|
114
|
-
>>> from edsl import QuestionFreeText as Q
|
115
|
-
>>> Q.example()._validate_answer({'answer': 'Hello', 'generated_tokens': 'Hello'})
|
116
|
-
{'answer': 'Hello', 'generated_tokens': 'Hello'}
|
117
|
-
"""
|
118
|
-
|
119
|
-
return self.response_validator.validate(answer, replacement_dict)
|
120
|
-
|
121
|
-
# endregion
|
122
|
-
|
123
|
-
# region: Serialization methods
|
124
|
-
@property
|
125
|
-
def name(self) -> str:
|
126
|
-
"Helper function so questions and instructions can use the same access method"
|
127
|
-
return self.question_name
|
128
|
-
|
129
|
-
def __hash__(self) -> int:
|
130
|
-
"""Return a hash of the question.
|
131
|
-
|
132
|
-
>>> from edsl import QuestionFreeText as Q
|
133
|
-
>>> hash(Q.example())
|
134
|
-
1144312636257752766
|
135
|
-
"""
|
136
|
-
from edsl.utilities.utilities import dict_hash
|
137
|
-
|
138
|
-
return dict_hash(self._to_dict())
|
139
|
-
|
140
|
-
@property
|
141
|
-
def data(self) -> dict:
|
142
|
-
"""Return a dictionary of question attributes **except** for question_type.
|
143
|
-
|
144
|
-
>>> from edsl import QuestionFreeText as Q
|
145
|
-
>>> Q.example().data
|
146
|
-
{'question_name': 'how_are_you', 'question_text': 'How are you?'}
|
147
|
-
"""
|
148
|
-
exclude_list = [
|
149
|
-
"question_type",
|
150
|
-
"_include_comment",
|
151
|
-
"_fake_data_factory",
|
152
|
-
"_use_code",
|
153
|
-
"_model_instructions",
|
154
|
-
]
|
155
|
-
only_if_not_na_list = ["_answering_instructions", "_question_presentation"]
|
156
|
-
|
157
|
-
def ok(key, value):
|
158
|
-
if not key.startswith("_"):
|
159
|
-
return False
|
160
|
-
if key in exclude_list:
|
161
|
-
return False
|
162
|
-
if key in only_if_not_na_list and value is None:
|
163
|
-
return False
|
164
|
-
return True
|
165
|
-
|
166
|
-
candidate_data = {
|
167
|
-
k.replace("_", "", 1): v for k, v in self.__dict__.items() if ok(k, v)
|
168
|
-
}
|
169
|
-
|
170
|
-
if "func" in candidate_data:
|
171
|
-
func = candidate_data.pop("func")
|
172
|
-
import inspect
|
173
|
-
|
174
|
-
candidate_data["function_source_code"] = inspect.getsource(func)
|
175
|
-
|
176
|
-
return candidate_data
|
177
|
-
|
178
|
-
def _to_dict(self):
|
179
|
-
"""Convert the question to a dictionary that includes the question type (used in deserialization).
|
180
|
-
|
181
|
-
>>> from edsl import QuestionFreeText as Q; Q.example()._to_dict()
|
182
|
-
{'question_name': 'how_are_you', 'question_text': 'How are you?', 'question_type': 'free_text'}
|
183
|
-
"""
|
184
|
-
candidate_data = self.data.copy()
|
185
|
-
candidate_data["question_type"] = self.question_type
|
186
|
-
return {
|
187
|
-
key: value for key, value in candidate_data.items() if value is not None
|
188
|
-
}
|
189
|
-
|
190
|
-
@add_edsl_version
|
191
|
-
def to_dict(self) -> dict[str, Any]:
|
192
|
-
"""Convert the question to a dictionary that includes the question type (used in deserialization).
|
193
|
-
>>> from edsl import QuestionFreeText as Q; Q.example().to_dict()
|
194
|
-
{'question_name': 'how_are_you', 'question_text': 'How are you?', 'question_type': 'free_text', 'edsl_version': '...'}
|
195
|
-
"""
|
196
|
-
return self._to_dict()
|
197
|
-
|
198
|
-
@classmethod
|
199
|
-
@remove_edsl_version
|
200
|
-
def from_dict(cls, data: dict) -> Type[QuestionBase]:
|
201
|
-
"""Construct a question object from a dictionary created by that question's `to_dict` method."""
|
202
|
-
local_data = data.copy()
|
203
|
-
|
204
|
-
try:
|
205
|
-
question_type = local_data.pop("question_type")
|
206
|
-
if question_type == "linear_scale":
|
207
|
-
# This is a fix for issue https://github.com/expectedparrot/edsl/issues/165
|
208
|
-
options_labels = local_data.get("option_labels", None)
|
209
|
-
if options_labels:
|
210
|
-
options_labels = {
|
211
|
-
int(key): value for key, value in options_labels.items()
|
212
|
-
}
|
213
|
-
local_data["option_labels"] = options_labels
|
214
|
-
except:
|
215
|
-
raise QuestionSerializationError(
|
216
|
-
f"Data does not have a 'question_type' field (got {data})."
|
217
|
-
)
|
218
|
-
from edsl.questions.question_registry import get_question_class
|
219
|
-
|
220
|
-
try:
|
221
|
-
question_class = get_question_class(question_type)
|
222
|
-
except ValueError:
|
223
|
-
raise QuestionSerializationError(
|
224
|
-
f"No question registered with question_type {question_type}"
|
225
|
-
)
|
226
|
-
|
227
|
-
if "model_instructions" in local_data:
|
228
|
-
model_instructions = local_data.pop("model_instructions")
|
229
|
-
new_q = question_class(**local_data)
|
230
|
-
new_q.model_instructions = model_instructions
|
231
|
-
return new_q
|
232
|
-
|
233
|
-
return question_class(**local_data)
|
234
|
-
|
235
|
-
# endregion
|
236
|
-
|
237
|
-
# region: Running methods
|
238
|
-
@classmethod
|
239
|
-
def _get_test_model(self, canned_response: Optional[str] = None) -> "LanguageModel":
|
240
|
-
"""Get a test model for the question."""
|
241
|
-
from edsl.language_models import LanguageModel
|
242
|
-
|
243
|
-
return LanguageModel.example(canned_response=canned_response, test_model=True)
|
244
|
-
|
245
|
-
@classmethod
|
246
|
-
def run_example(
|
247
|
-
cls,
|
248
|
-
show_answer: bool = True,
|
249
|
-
model: Optional["LanguageModel"] = None,
|
250
|
-
cache=False,
|
251
|
-
disable_remote_cache: bool = False,
|
252
|
-
disable_remote_inference: bool = False,
|
253
|
-
**kwargs,
|
254
|
-
):
|
255
|
-
"""Run an example of the question.
|
256
|
-
>>> from edsl.language_models import LanguageModel
|
257
|
-
>>> from edsl import QuestionFreeText as Q
|
258
|
-
>>> m = Q._get_test_model(canned_response = "Yo, what's up?")
|
259
|
-
>>> m.execute_model_call("", "")
|
260
|
-
{'message': [{'text': "Yo, what's up?"}], 'usage': {'prompt_tokens': 1, 'completion_tokens': 1}}
|
261
|
-
>>> Q.run_example(show_answer = True, model = m, disable_remote_cache = True, disable_remote_inference = True)
|
262
|
-
┏━━━━━━━━━━━━━━━━┓
|
263
|
-
┃ answer ┃
|
264
|
-
┃ .how_are_you ┃
|
265
|
-
┡━━━━━━━━━━━━━━━━┩
|
266
|
-
│ Yo, what's up? │
|
267
|
-
└────────────────┘
|
268
|
-
"""
|
269
|
-
if model is None:
|
270
|
-
from edsl import Model
|
271
|
-
|
272
|
-
model = Model()
|
273
|
-
results = (
|
274
|
-
cls.example(**kwargs)
|
275
|
-
.by(model)
|
276
|
-
.run(
|
277
|
-
cache=cache,
|
278
|
-
disable_remote_cache=disable_remote_cache,
|
279
|
-
disable_remote_inference=disable_remote_inference,
|
280
|
-
)
|
281
|
-
)
|
282
|
-
if show_answer:
|
283
|
-
results.select("answer.*").print()
|
284
|
-
else:
|
285
|
-
return results
|
286
|
-
|
287
|
-
def __call__(
|
288
|
-
self,
|
289
|
-
just_answer=True,
|
290
|
-
model=None,
|
291
|
-
agent=None,
|
292
|
-
disable_remote_cache: bool = False,
|
293
|
-
disable_remote_inference: bool = False,
|
294
|
-
**kwargs,
|
295
|
-
):
|
296
|
-
"""Call the question.
|
297
|
-
|
298
|
-
|
299
|
-
>>> from edsl import QuestionFreeText as Q
|
300
|
-
>>> m = Q._get_test_model(canned_response = "Yo, what's up?")
|
301
|
-
>>> q = Q(question_name = "color", question_text = "What is your favorite color?")
|
302
|
-
>>> q(model = m, disable_remote_cache = True, disable_remote_inference = True)
|
303
|
-
"Yo, what's up?"
|
304
|
-
|
305
|
-
"""
|
306
|
-
survey = self.to_survey()
|
307
|
-
results = survey(
|
308
|
-
model=model,
|
309
|
-
agent=agent,
|
310
|
-
**kwargs,
|
311
|
-
cache=False,
|
312
|
-
disable_remote_cache=disable_remote_cache,
|
313
|
-
disable_remote_inference=disable_remote_inference,
|
314
|
-
)
|
315
|
-
if just_answer:
|
316
|
-
return results.select(f"answer.{self.question_name}").first()
|
317
|
-
else:
|
318
|
-
return results
|
319
|
-
|
320
|
-
def run(self, *args, **kwargs) -> "Results":
|
321
|
-
"""Turn a single question into a survey and runs it."""
|
322
|
-
from edsl.surveys.Survey import Survey
|
323
|
-
|
324
|
-
s = self.to_survey()
|
325
|
-
return s.run(*args, **kwargs)
|
326
|
-
|
327
|
-
async def run_async(
|
328
|
-
self,
|
329
|
-
just_answer: bool = True,
|
330
|
-
model: Optional["Model"] = None,
|
331
|
-
agent: Optional["Agent"] = None,
|
332
|
-
disable_remote_inference: bool = False,
|
333
|
-
**kwargs,
|
334
|
-
) -> Union[Any, "Results"]:
|
335
|
-
"""Call the question asynchronously.
|
336
|
-
|
337
|
-
>>> import asyncio
|
338
|
-
>>> from edsl import QuestionFreeText as Q
|
339
|
-
>>> m = Q._get_test_model(canned_response = "Blue")
|
340
|
-
>>> q = Q(question_name = "color", question_text = "What is your favorite color?")
|
341
|
-
>>> async def test_run_async(): result = await q.run_async(model=m, disable_remote_inference = True); print(result)
|
342
|
-
>>> asyncio.run(test_run_async())
|
343
|
-
Blue
|
344
|
-
"""
|
345
|
-
survey = self.to_survey()
|
346
|
-
results = await survey.run_async(
|
347
|
-
model=model,
|
348
|
-
agent=agent,
|
349
|
-
disable_remote_inference=disable_remote_inference,
|
350
|
-
**kwargs,
|
351
|
-
)
|
352
|
-
if just_answer:
|
353
|
-
return results.select(f"answer.{self.question_name}").first()
|
354
|
-
else:
|
355
|
-
return results
|
356
|
-
|
357
|
-
# endregion
|
358
|
-
|
359
|
-
# region: Magic methods
|
360
|
-
def _repr_html_(self):
|
361
|
-
from edsl.utilities.utilities import data_to_html
|
362
|
-
|
363
|
-
data = self.to_dict()
|
364
|
-
try:
|
365
|
-
_ = data.pop("edsl_version")
|
366
|
-
_ = data.pop("edsl_class_name")
|
367
|
-
except KeyError:
|
368
|
-
print("Serialized question lacks edsl version, but is should have it.")
|
369
|
-
|
370
|
-
return data_to_html(data)
|
371
|
-
|
372
|
-
def __getitem__(self, key: str) -> Any:
|
373
|
-
"""Get an attribute of the question so it can be treated like a dictionary.
|
374
|
-
|
375
|
-
>>> from edsl.questions import QuestionFreeText as Q
|
376
|
-
>>> Q.example()['question_text']
|
377
|
-
'How are you?'
|
378
|
-
"""
|
379
|
-
return getattr(self, key)
|
380
|
-
|
381
|
-
def __repr__(self) -> str:
|
382
|
-
"""Return a string representation of the question. Should be able to be used to reconstruct the question.
|
383
|
-
|
384
|
-
>>> from edsl import QuestionFreeText as Q
|
385
|
-
>>> repr(Q.example())
|
386
|
-
'Question(\\'free_text\\', question_name = \"""how_are_you\""", question_text = \"""How are you?\""")'
|
387
|
-
"""
|
388
|
-
items = [
|
389
|
-
f'{k} = """{v}"""' if isinstance(v, str) else f"{k} = {v}"
|
390
|
-
for k, v in self.data.items()
|
391
|
-
if k != "question_type"
|
392
|
-
]
|
393
|
-
question_type = self.to_dict().get("question_type", "None")
|
394
|
-
return f"Question('{question_type}', {', '.join(items)})"
|
395
|
-
|
396
|
-
def __eq__(self, other: Union[Any, Type[QuestionBase]]) -> bool:
|
397
|
-
"""Check if two questions are equal. Equality is defined as having the .to_dict().
|
398
|
-
|
399
|
-
>>> from edsl import QuestionFreeText as Q
|
400
|
-
>>> q1 = Q.example()
|
401
|
-
>>> q2 = Q.example()
|
402
|
-
>>> q1 == q2
|
403
|
-
True
|
404
|
-
>>> q1.question_text = "How are you John?"
|
405
|
-
>>> q1 == q2
|
406
|
-
False
|
407
|
-
|
408
|
-
"""
|
409
|
-
if not isinstance(other, QuestionBase):
|
410
|
-
return False
|
411
|
-
return self.to_dict() == other.to_dict()
|
412
|
-
|
413
|
-
def __sub__(self, other) -> BaseDiff:
|
414
|
-
"""Return the difference between two objects.
|
415
|
-
>>> from edsl import QuestionFreeText as Q
|
416
|
-
>>> q1 = Q.example()
|
417
|
-
>>> q2 = q1.copy()
|
418
|
-
>>> q2.question_text = "How are you John?"
|
419
|
-
>>> diff = q1 - q2
|
420
|
-
"""
|
421
|
-
|
422
|
-
return BaseDiff(other, self)
|
423
|
-
|
424
|
-
# TODO: Throws an error that should be addressed at QuestionFunctional
|
425
|
-
def __add__(self, other_question_or_diff):
|
426
|
-
"""
|
427
|
-
Compose two questions into a single question.
|
428
|
-
|
429
|
-
TODO: Probably getting deprecated.
|
430
|
-
|
431
|
-
"""
|
432
|
-
if isinstance(other_question_or_diff, BaseDiff) or isinstance(
|
433
|
-
other_question_or_diff, BaseDiffCollection
|
434
|
-
):
|
435
|
-
return other_question_or_diff.apply(self)
|
436
|
-
|
437
|
-
# from edsl.questions import compose_questions
|
438
|
-
# return compose_questions(self, other_question_or_diff)
|
439
|
-
|
440
|
-
# def _validate_response(self, response):
|
441
|
-
# """Validate the response from the LLM. Behavior depends on the question type."""
|
442
|
-
# if "answer" not in response:
|
443
|
-
# raise QuestionResponseValidationError(
|
444
|
-
# "Response from LLM does not have an answer"
|
445
|
-
# )
|
446
|
-
# return response
|
447
|
-
|
448
|
-
def _translate_answer_code_to_answer(
|
449
|
-
self, answer, scenario: Optional["Scenario"] = None
|
450
|
-
):
|
451
|
-
"""There is over-ridden by child classes that ask for codes."""
|
452
|
-
return answer
|
453
|
-
|
454
|
-
# endregion
|
455
|
-
|
456
|
-
# region: Forward methods
|
457
|
-
def add_question(self, other: QuestionBase) -> "Survey":
|
458
|
-
"""Add a question to this question by turning them into a survey with two questions.
|
459
|
-
|
460
|
-
>>> from edsl.questions import QuestionFreeText as Q
|
461
|
-
>>> from edsl.questions import QuestionMultipleChoice as QMC
|
462
|
-
>>> s = Q.example().add_question(QMC.example())
|
463
|
-
>>> len(s.questions)
|
464
|
-
2
|
465
|
-
"""
|
466
|
-
from edsl.surveys.Survey import Survey
|
467
|
-
|
468
|
-
s = Survey([self, other])
|
469
|
-
return s
|
470
|
-
|
471
|
-
def to_survey(self) -> "Survey":
|
472
|
-
"""Turn a single question into a survey.
|
473
|
-
>>> from edsl import QuestionFreeText as Q
|
474
|
-
>>> Q.example().to_survey().questions[0].question_name
|
475
|
-
'how_are_you'
|
476
|
-
"""
|
477
|
-
from edsl.surveys.Survey import Survey
|
478
|
-
|
479
|
-
s = Survey([self])
|
480
|
-
return s
|
481
|
-
|
482
|
-
def by(self, *args) -> "Jobs":
|
483
|
-
"""Turn a single question into a survey and then a Job."""
|
484
|
-
from edsl.surveys.Survey import Survey
|
485
|
-
|
486
|
-
s = Survey([self])
|
487
|
-
return s.by(*args)
|
488
|
-
|
489
|
-
# endregion
|
490
|
-
|
491
|
-
# region: Display methods
|
492
|
-
def print(self):
|
493
|
-
from rich import print_json
|
494
|
-
import json
|
495
|
-
|
496
|
-
print_json(json.dumps(self.to_dict()))
|
497
|
-
|
498
|
-
def human_readable(self) -> str:
|
499
|
-
"""Print the question in a human readable format.
|
500
|
-
|
501
|
-
>>> from edsl.questions import QuestionFreeText
|
502
|
-
>>> QuestionFreeText.example().human_readable()
|
503
|
-
'Question Type: free_text\\nQuestion: How are you?'
|
504
|
-
"""
|
505
|
-
lines = []
|
506
|
-
lines.append(f"Question Type: {self.question_type}")
|
507
|
-
lines.append(f"Question: {self.question_text}")
|
508
|
-
if hasattr(self, "question_options"):
|
509
|
-
lines.append("Please name the option you choose from the following.:")
|
510
|
-
for index, option in enumerate(self.question_options):
|
511
|
-
lines.append(f"{option}")
|
512
|
-
return "\n".join(lines)
|
513
|
-
|
514
|
-
def html(
|
515
|
-
self,
|
516
|
-
scenario: Optional[dict] = None,
|
517
|
-
agent: Optional[dict] = {},
|
518
|
-
answers: Optional[dict] = None,
|
519
|
-
include_question_name: bool = False,
|
520
|
-
height: Optional[int] = None,
|
521
|
-
width: Optional[int] = None,
|
522
|
-
iframe=False,
|
523
|
-
):
|
524
|
-
"""Return the question in HTML format."""
|
525
|
-
from jinja2 import Template
|
526
|
-
|
527
|
-
if scenario is None:
|
528
|
-
scenario = {}
|
529
|
-
|
530
|
-
prior_answers_dict = {}
|
531
|
-
|
532
|
-
if isinstance(answers, dict):
|
533
|
-
for key, value in answers.items():
|
534
|
-
if not key.endswith("_comment") and not key.endswith(
|
535
|
-
"_generated_tokens"
|
536
|
-
):
|
537
|
-
prior_answers_dict[key] = {"answer": value}
|
538
|
-
|
539
|
-
# breakpoint()
|
540
|
-
|
541
|
-
base_template = """
|
542
|
-
<div id="{{ question_name }}" class="survey_question" data-type="{{ question_type }}">
|
543
|
-
{% if include_question_name %}
|
544
|
-
<p>question_name: {{ question_name }}</p>
|
545
|
-
{% endif %}
|
546
|
-
<p class="question_text">{{ question_text }}</p>
|
547
|
-
{{ question_content }}
|
548
|
-
</div>
|
549
|
-
"""
|
550
|
-
if not hasattr(self, "question_type"):
|
551
|
-
self.question_type = "unknown"
|
552
|
-
|
553
|
-
if hasattr(self, "question_html_content"):
|
554
|
-
question_content = self.question_html_content
|
555
|
-
else:
|
556
|
-
question_content = Template("")
|
557
|
-
|
558
|
-
base_template = Template(base_template)
|
559
|
-
|
560
|
-
context = {
|
561
|
-
"scenario": scenario,
|
562
|
-
"agent": agent,
|
563
|
-
} | prior_answers_dict
|
564
|
-
|
565
|
-
# Render the question text
|
566
|
-
try:
|
567
|
-
question_text = Template(self.question_text).render(context)
|
568
|
-
except Exception as e:
|
569
|
-
print(
|
570
|
-
f"Error rendering question: question_text = {self.question_text}, error = {e}"
|
571
|
-
)
|
572
|
-
question_text = self.question_text
|
573
|
-
|
574
|
-
try:
|
575
|
-
question_content = Template(question_content).render(context)
|
576
|
-
except Exception as e:
|
577
|
-
print(
|
578
|
-
f"Error rendering question: question_content = {question_content}, error = {e}"
|
579
|
-
)
|
580
|
-
question_content = question_content
|
581
|
-
|
582
|
-
try:
|
583
|
-
params = {
|
584
|
-
"question_name": self.question_name,
|
585
|
-
"question_text": question_text,
|
586
|
-
"question_type": self.question_type,
|
587
|
-
"question_content": question_content,
|
588
|
-
"include_question_name": include_question_name,
|
589
|
-
}
|
590
|
-
except Exception as e:
|
591
|
-
raise ValueError(
|
592
|
-
f"Error rendering question: params = {params}, error = {e}"
|
593
|
-
)
|
594
|
-
rendered_html = base_template.render(**params)
|
595
|
-
|
596
|
-
if iframe:
|
597
|
-
import html
|
598
|
-
from IPython.display import display, HTML
|
599
|
-
|
600
|
-
height = height or 200
|
601
|
-
width = width or 600
|
602
|
-
escaped_output = html.escape(rendered_html)
|
603
|
-
# escaped_output = rendered_html
|
604
|
-
iframe = f""""
|
605
|
-
<iframe srcdoc="{ escaped_output }" style="width: {width}px; height: {height}px;"></iframe>
|
606
|
-
"""
|
607
|
-
display(HTML(iframe))
|
608
|
-
return None
|
609
|
-
|
610
|
-
return rendered_html
|
611
|
-
|
612
|
-
@classmethod
|
613
|
-
def example_model(cls):
|
614
|
-
from edsl import Model
|
615
|
-
|
616
|
-
q = cls.example()
|
617
|
-
m = Model("test", canned_response=cls._simulate_answer(q)["answer"])
|
618
|
-
|
619
|
-
return m
|
620
|
-
|
621
|
-
@classmethod
|
622
|
-
def example_results(cls):
|
623
|
-
m = cls.example_model()
|
624
|
-
q = cls.example()
|
625
|
-
return q.by(m).run(cache=False)
|
626
|
-
|
627
|
-
def rich_print(self):
|
628
|
-
"""Print the question in a rich format."""
|
629
|
-
from rich.table import Table
|
630
|
-
|
631
|
-
table = Table(show_header=True, header_style="bold magenta")
|
632
|
-
table.add_column("Question Name", style="dim")
|
633
|
-
table.add_column("Question Type")
|
634
|
-
table.add_column("Question Text")
|
635
|
-
table.add_column("Options")
|
636
|
-
|
637
|
-
question = self
|
638
|
-
if hasattr(question, "question_options"):
|
639
|
-
options = ", ".join([str(o) for o in question.question_options])
|
640
|
-
else:
|
641
|
-
options = "None"
|
642
|
-
table.add_row(
|
643
|
-
question.question_name,
|
644
|
-
question.question_type,
|
645
|
-
question.question_text,
|
646
|
-
options,
|
647
|
-
)
|
648
|
-
return table
|
649
|
-
|
650
|
-
# endregion
|
651
|
-
|
652
|
-
|
653
|
-
if __name__ == "__main__":
|
654
|
-
import doctest
|
655
|
-
|
656
|
-
doctest.testmod(optionflags=doctest.ELLIPSIS)
|
1
|
+
"""This module contains the Question class, which is the base class for all questions in EDSL."""
|
2
|
+
|
3
|
+
from __future__ import annotations
|
4
|
+
from abc import ABC, abstractmethod
|
5
|
+
from typing import Any, Type, Optional, List, Callable, Union, TypedDict
|
6
|
+
import copy
|
7
|
+
|
8
|
+
from edsl.exceptions import (
|
9
|
+
QuestionResponseValidationError,
|
10
|
+
QuestionAnswerValidationError,
|
11
|
+
QuestionSerializationError,
|
12
|
+
)
|
13
|
+
from edsl.questions.descriptors import QuestionNameDescriptor, QuestionTextDescriptor
|
14
|
+
|
15
|
+
|
16
|
+
from edsl.questions.AnswerValidatorMixin import AnswerValidatorMixin
|
17
|
+
from edsl.questions.RegisterQuestionsMeta import RegisterQuestionsMeta
|
18
|
+
from edsl.Base import PersistenceMixin, RichPrintingMixin
|
19
|
+
from edsl.BaseDiff import BaseDiff, BaseDiffCollection
|
20
|
+
|
21
|
+
from edsl.questions.SimpleAskMixin import SimpleAskMixin
|
22
|
+
from edsl.questions.QuestionBasePromptsMixin import QuestionBasePromptsMixin
|
23
|
+
from edsl.questions.QuestionBaseGenMixin import QuestionBaseGenMixin
|
24
|
+
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
|
25
|
+
|
26
|
+
|
27
|
+
class QuestionBase(
|
28
|
+
PersistenceMixin,
|
29
|
+
RichPrintingMixin,
|
30
|
+
SimpleAskMixin,
|
31
|
+
QuestionBasePromptsMixin,
|
32
|
+
QuestionBaseGenMixin,
|
33
|
+
ABC,
|
34
|
+
AnswerValidatorMixin,
|
35
|
+
metaclass=RegisterQuestionsMeta,
|
36
|
+
):
|
37
|
+
"""ABC for the Question class. All questions inherit from this class.
|
38
|
+
Some of the constraints on child questions are defined in the RegisterQuestionsMeta metaclass.
|
39
|
+
"""
|
40
|
+
|
41
|
+
question_name: str = QuestionNameDescriptor()
|
42
|
+
question_text: str = QuestionTextDescriptor()
|
43
|
+
|
44
|
+
_answering_instructions = None
|
45
|
+
_question_presentation = None
|
46
|
+
|
47
|
+
@property
|
48
|
+
def response_model(self) -> type["BaseModel"]:
|
49
|
+
if self._response_model is not None:
|
50
|
+
return self._response_model
|
51
|
+
else:
|
52
|
+
return self.create_response_model()
|
53
|
+
|
54
|
+
# region: Validation and simulation methods
|
55
|
+
@property
|
56
|
+
def response_validator(self) -> "ResponseValidatorBase":
|
57
|
+
"""Return the response validator."""
|
58
|
+
params = (
|
59
|
+
{
|
60
|
+
"response_model": self.response_model,
|
61
|
+
}
|
62
|
+
| {k: getattr(self, k) for k in self.validator_parameters}
|
63
|
+
| {"exception_to_throw": getattr(self, "exception_to_throw", None)}
|
64
|
+
| {"override_answer": getattr(self, "override_answer", None)}
|
65
|
+
)
|
66
|
+
return self.response_validator_class(**params)
|
67
|
+
|
68
|
+
@property
|
69
|
+
def validator_parameters(self) -> list[str]:
|
70
|
+
"""Return the parameters required for the response validator.
|
71
|
+
|
72
|
+
>>> from edsl import QuestionMultipleChoice as Q
|
73
|
+
>>> Q.example().validator_parameters
|
74
|
+
['question_options', 'use_code']
|
75
|
+
|
76
|
+
"""
|
77
|
+
return self.response_validator_class.required_params
|
78
|
+
|
79
|
+
@property
|
80
|
+
def fake_data_factory(self):
|
81
|
+
"""Return the fake data factory."""
|
82
|
+
if not hasattr(self, "_fake_data_factory"):
|
83
|
+
from polyfactory.factories.pydantic_factory import ModelFactory
|
84
|
+
|
85
|
+
class FakeData(ModelFactory[self.response_model]):
|
86
|
+
...
|
87
|
+
|
88
|
+
self._fake_data_factory = FakeData
|
89
|
+
return self._fake_data_factory
|
90
|
+
|
91
|
+
def _simulate_answer(self, human_readable: bool = False) -> dict:
|
92
|
+
"""Simulate a valid answer for debugging purposes (what the validator expects).
|
93
|
+
>>> from edsl import QuestionFreeText as Q
|
94
|
+
>>> Q.example()._simulate_answer()
|
95
|
+
{'answer': '...', 'generated_tokens': ...}
|
96
|
+
"""
|
97
|
+
simulated_answer = self.fake_data_factory.build().dict()
|
98
|
+
if human_readable and hasattr(self, "question_options") and self.use_code:
|
99
|
+
simulated_answer["answer"] = [
|
100
|
+
self.question_options[index] for index in simulated_answer["answer"]
|
101
|
+
]
|
102
|
+
return simulated_answer
|
103
|
+
|
104
|
+
class ValidatedAnswer(TypedDict):
|
105
|
+
answer: Any
|
106
|
+
comment: Optional[str]
|
107
|
+
generated_tokens: Optional[str]
|
108
|
+
|
109
|
+
def _validate_answer(
|
110
|
+
self, answer: dict, replacement_dict: dict = None
|
111
|
+
) -> ValidatedAnswer:
|
112
|
+
"""Validate the answer.
|
113
|
+
>>> from edsl.exceptions import QuestionAnswerValidationError
|
114
|
+
>>> from edsl import QuestionFreeText as Q
|
115
|
+
>>> Q.example()._validate_answer({'answer': 'Hello', 'generated_tokens': 'Hello'})
|
116
|
+
{'answer': 'Hello', 'generated_tokens': 'Hello'}
|
117
|
+
"""
|
118
|
+
|
119
|
+
return self.response_validator.validate(answer, replacement_dict)
|
120
|
+
|
121
|
+
# endregion
|
122
|
+
|
123
|
+
# region: Serialization methods
|
124
|
+
@property
|
125
|
+
def name(self) -> str:
|
126
|
+
"Helper function so questions and instructions can use the same access method"
|
127
|
+
return self.question_name
|
128
|
+
|
129
|
+
def __hash__(self) -> int:
|
130
|
+
"""Return a hash of the question.
|
131
|
+
|
132
|
+
>>> from edsl import QuestionFreeText as Q
|
133
|
+
>>> hash(Q.example())
|
134
|
+
1144312636257752766
|
135
|
+
"""
|
136
|
+
from edsl.utilities.utilities import dict_hash
|
137
|
+
|
138
|
+
return dict_hash(self._to_dict())
|
139
|
+
|
140
|
+
@property
|
141
|
+
def data(self) -> dict:
|
142
|
+
"""Return a dictionary of question attributes **except** for question_type.
|
143
|
+
|
144
|
+
>>> from edsl import QuestionFreeText as Q
|
145
|
+
>>> Q.example().data
|
146
|
+
{'question_name': 'how_are_you', 'question_text': 'How are you?'}
|
147
|
+
"""
|
148
|
+
exclude_list = [
|
149
|
+
"question_type",
|
150
|
+
"_include_comment",
|
151
|
+
"_fake_data_factory",
|
152
|
+
"_use_code",
|
153
|
+
"_model_instructions",
|
154
|
+
]
|
155
|
+
only_if_not_na_list = ["_answering_instructions", "_question_presentation"]
|
156
|
+
|
157
|
+
def ok(key, value):
|
158
|
+
if not key.startswith("_"):
|
159
|
+
return False
|
160
|
+
if key in exclude_list:
|
161
|
+
return False
|
162
|
+
if key in only_if_not_na_list and value is None:
|
163
|
+
return False
|
164
|
+
return True
|
165
|
+
|
166
|
+
candidate_data = {
|
167
|
+
k.replace("_", "", 1): v for k, v in self.__dict__.items() if ok(k, v)
|
168
|
+
}
|
169
|
+
|
170
|
+
if "func" in candidate_data:
|
171
|
+
func = candidate_data.pop("func")
|
172
|
+
import inspect
|
173
|
+
|
174
|
+
candidate_data["function_source_code"] = inspect.getsource(func)
|
175
|
+
|
176
|
+
return candidate_data
|
177
|
+
|
178
|
+
def _to_dict(self):
|
179
|
+
"""Convert the question to a dictionary that includes the question type (used in deserialization).
|
180
|
+
|
181
|
+
>>> from edsl import QuestionFreeText as Q; Q.example()._to_dict()
|
182
|
+
{'question_name': 'how_are_you', 'question_text': 'How are you?', 'question_type': 'free_text'}
|
183
|
+
"""
|
184
|
+
candidate_data = self.data.copy()
|
185
|
+
candidate_data["question_type"] = self.question_type
|
186
|
+
return {
|
187
|
+
key: value for key, value in candidate_data.items() if value is not None
|
188
|
+
}
|
189
|
+
|
190
|
+
@add_edsl_version
|
191
|
+
def to_dict(self) -> dict[str, Any]:
|
192
|
+
"""Convert the question to a dictionary that includes the question type (used in deserialization).
|
193
|
+
>>> from edsl import QuestionFreeText as Q; Q.example().to_dict()
|
194
|
+
{'question_name': 'how_are_you', 'question_text': 'How are you?', 'question_type': 'free_text', 'edsl_version': '...'}
|
195
|
+
"""
|
196
|
+
return self._to_dict()
|
197
|
+
|
198
|
+
@classmethod
|
199
|
+
@remove_edsl_version
|
200
|
+
def from_dict(cls, data: dict) -> Type[QuestionBase]:
|
201
|
+
"""Construct a question object from a dictionary created by that question's `to_dict` method."""
|
202
|
+
local_data = data.copy()
|
203
|
+
|
204
|
+
try:
|
205
|
+
question_type = local_data.pop("question_type")
|
206
|
+
if question_type == "linear_scale":
|
207
|
+
# This is a fix for issue https://github.com/expectedparrot/edsl/issues/165
|
208
|
+
options_labels = local_data.get("option_labels", None)
|
209
|
+
if options_labels:
|
210
|
+
options_labels = {
|
211
|
+
int(key): value for key, value in options_labels.items()
|
212
|
+
}
|
213
|
+
local_data["option_labels"] = options_labels
|
214
|
+
except:
|
215
|
+
raise QuestionSerializationError(
|
216
|
+
f"Data does not have a 'question_type' field (got {data})."
|
217
|
+
)
|
218
|
+
from edsl.questions.question_registry import get_question_class
|
219
|
+
|
220
|
+
try:
|
221
|
+
question_class = get_question_class(question_type)
|
222
|
+
except ValueError:
|
223
|
+
raise QuestionSerializationError(
|
224
|
+
f"No question registered with question_type {question_type}"
|
225
|
+
)
|
226
|
+
|
227
|
+
if "model_instructions" in local_data:
|
228
|
+
model_instructions = local_data.pop("model_instructions")
|
229
|
+
new_q = question_class(**local_data)
|
230
|
+
new_q.model_instructions = model_instructions
|
231
|
+
return new_q
|
232
|
+
|
233
|
+
return question_class(**local_data)
|
234
|
+
|
235
|
+
# endregion
|
236
|
+
|
237
|
+
# region: Running methods
|
238
|
+
@classmethod
|
239
|
+
def _get_test_model(self, canned_response: Optional[str] = None) -> "LanguageModel":
|
240
|
+
"""Get a test model for the question."""
|
241
|
+
from edsl.language_models import LanguageModel
|
242
|
+
|
243
|
+
return LanguageModel.example(canned_response=canned_response, test_model=True)
|
244
|
+
|
245
|
+
@classmethod
|
246
|
+
def run_example(
|
247
|
+
cls,
|
248
|
+
show_answer: bool = True,
|
249
|
+
model: Optional["LanguageModel"] = None,
|
250
|
+
cache=False,
|
251
|
+
disable_remote_cache: bool = False,
|
252
|
+
disable_remote_inference: bool = False,
|
253
|
+
**kwargs,
|
254
|
+
):
|
255
|
+
"""Run an example of the question.
|
256
|
+
>>> from edsl.language_models import LanguageModel
|
257
|
+
>>> from edsl import QuestionFreeText as Q
|
258
|
+
>>> m = Q._get_test_model(canned_response = "Yo, what's up?")
|
259
|
+
>>> m.execute_model_call("", "")
|
260
|
+
{'message': [{'text': "Yo, what's up?"}], 'usage': {'prompt_tokens': 1, 'completion_tokens': 1}}
|
261
|
+
>>> Q.run_example(show_answer = True, model = m, disable_remote_cache = True, disable_remote_inference = True)
|
262
|
+
┏━━━━━━━━━━━━━━━━┓
|
263
|
+
┃ answer ┃
|
264
|
+
┃ .how_are_you ┃
|
265
|
+
┡━━━━━━━━━━━━━━━━┩
|
266
|
+
│ Yo, what's up? │
|
267
|
+
└────────────────┘
|
268
|
+
"""
|
269
|
+
if model is None:
|
270
|
+
from edsl import Model
|
271
|
+
|
272
|
+
model = Model()
|
273
|
+
results = (
|
274
|
+
cls.example(**kwargs)
|
275
|
+
.by(model)
|
276
|
+
.run(
|
277
|
+
cache=cache,
|
278
|
+
disable_remote_cache=disable_remote_cache,
|
279
|
+
disable_remote_inference=disable_remote_inference,
|
280
|
+
)
|
281
|
+
)
|
282
|
+
if show_answer:
|
283
|
+
results.select("answer.*").print()
|
284
|
+
else:
|
285
|
+
return results
|
286
|
+
|
287
|
+
def __call__(
|
288
|
+
self,
|
289
|
+
just_answer=True,
|
290
|
+
model=None,
|
291
|
+
agent=None,
|
292
|
+
disable_remote_cache: bool = False,
|
293
|
+
disable_remote_inference: bool = False,
|
294
|
+
**kwargs,
|
295
|
+
):
|
296
|
+
"""Call the question.
|
297
|
+
|
298
|
+
|
299
|
+
>>> from edsl import QuestionFreeText as Q
|
300
|
+
>>> m = Q._get_test_model(canned_response = "Yo, what's up?")
|
301
|
+
>>> q = Q(question_name = "color", question_text = "What is your favorite color?")
|
302
|
+
>>> q(model = m, disable_remote_cache = True, disable_remote_inference = True)
|
303
|
+
"Yo, what's up?"
|
304
|
+
|
305
|
+
"""
|
306
|
+
survey = self.to_survey()
|
307
|
+
results = survey(
|
308
|
+
model=model,
|
309
|
+
agent=agent,
|
310
|
+
**kwargs,
|
311
|
+
cache=False,
|
312
|
+
disable_remote_cache=disable_remote_cache,
|
313
|
+
disable_remote_inference=disable_remote_inference,
|
314
|
+
)
|
315
|
+
if just_answer:
|
316
|
+
return results.select(f"answer.{self.question_name}").first()
|
317
|
+
else:
|
318
|
+
return results
|
319
|
+
|
320
|
+
def run(self, *args, **kwargs) -> "Results":
|
321
|
+
"""Turn a single question into a survey and runs it."""
|
322
|
+
from edsl.surveys.Survey import Survey
|
323
|
+
|
324
|
+
s = self.to_survey()
|
325
|
+
return s.run(*args, **kwargs)
|
326
|
+
|
327
|
+
async def run_async(
|
328
|
+
self,
|
329
|
+
just_answer: bool = True,
|
330
|
+
model: Optional["Model"] = None,
|
331
|
+
agent: Optional["Agent"] = None,
|
332
|
+
disable_remote_inference: bool = False,
|
333
|
+
**kwargs,
|
334
|
+
) -> Union[Any, "Results"]:
|
335
|
+
"""Call the question asynchronously.
|
336
|
+
|
337
|
+
>>> import asyncio
|
338
|
+
>>> from edsl import QuestionFreeText as Q
|
339
|
+
>>> m = Q._get_test_model(canned_response = "Blue")
|
340
|
+
>>> q = Q(question_name = "color", question_text = "What is your favorite color?")
|
341
|
+
>>> async def test_run_async(): result = await q.run_async(model=m, disable_remote_inference = True); print(result)
|
342
|
+
>>> asyncio.run(test_run_async())
|
343
|
+
Blue
|
344
|
+
"""
|
345
|
+
survey = self.to_survey()
|
346
|
+
results = await survey.run_async(
|
347
|
+
model=model,
|
348
|
+
agent=agent,
|
349
|
+
disable_remote_inference=disable_remote_inference,
|
350
|
+
**kwargs,
|
351
|
+
)
|
352
|
+
if just_answer:
|
353
|
+
return results.select(f"answer.{self.question_name}").first()
|
354
|
+
else:
|
355
|
+
return results
|
356
|
+
|
357
|
+
# endregion
|
358
|
+
|
359
|
+
# region: Magic methods
|
360
|
+
def _repr_html_(self):
|
361
|
+
from edsl.utilities.utilities import data_to_html
|
362
|
+
|
363
|
+
data = self.to_dict()
|
364
|
+
try:
|
365
|
+
_ = data.pop("edsl_version")
|
366
|
+
_ = data.pop("edsl_class_name")
|
367
|
+
except KeyError:
|
368
|
+
print("Serialized question lacks edsl version, but is should have it.")
|
369
|
+
|
370
|
+
return data_to_html(data)
|
371
|
+
|
372
|
+
def __getitem__(self, key: str) -> Any:
|
373
|
+
"""Get an attribute of the question so it can be treated like a dictionary.
|
374
|
+
|
375
|
+
>>> from edsl.questions import QuestionFreeText as Q
|
376
|
+
>>> Q.example()['question_text']
|
377
|
+
'How are you?'
|
378
|
+
"""
|
379
|
+
return getattr(self, key)
|
380
|
+
|
381
|
+
def __repr__(self) -> str:
|
382
|
+
"""Return a string representation of the question. Should be able to be used to reconstruct the question.
|
383
|
+
|
384
|
+
>>> from edsl import QuestionFreeText as Q
|
385
|
+
>>> repr(Q.example())
|
386
|
+
'Question(\\'free_text\\', question_name = \"""how_are_you\""", question_text = \"""How are you?\""")'
|
387
|
+
"""
|
388
|
+
items = [
|
389
|
+
f'{k} = """{v}"""' if isinstance(v, str) else f"{k} = {v}"
|
390
|
+
for k, v in self.data.items()
|
391
|
+
if k != "question_type"
|
392
|
+
]
|
393
|
+
question_type = self.to_dict().get("question_type", "None")
|
394
|
+
return f"Question('{question_type}', {', '.join(items)})"
|
395
|
+
|
396
|
+
def __eq__(self, other: Union[Any, Type[QuestionBase]]) -> bool:
|
397
|
+
"""Check if two questions are equal. Equality is defined as having the .to_dict().
|
398
|
+
|
399
|
+
>>> from edsl import QuestionFreeText as Q
|
400
|
+
>>> q1 = Q.example()
|
401
|
+
>>> q2 = Q.example()
|
402
|
+
>>> q1 == q2
|
403
|
+
True
|
404
|
+
>>> q1.question_text = "How are you John?"
|
405
|
+
>>> q1 == q2
|
406
|
+
False
|
407
|
+
|
408
|
+
"""
|
409
|
+
if not isinstance(other, QuestionBase):
|
410
|
+
return False
|
411
|
+
return self.to_dict() == other.to_dict()
|
412
|
+
|
413
|
+
def __sub__(self, other) -> BaseDiff:
|
414
|
+
"""Return the difference between two objects.
|
415
|
+
>>> from edsl import QuestionFreeText as Q
|
416
|
+
>>> q1 = Q.example()
|
417
|
+
>>> q2 = q1.copy()
|
418
|
+
>>> q2.question_text = "How are you John?"
|
419
|
+
>>> diff = q1 - q2
|
420
|
+
"""
|
421
|
+
|
422
|
+
return BaseDiff(other, self)
|
423
|
+
|
424
|
+
# TODO: Throws an error that should be addressed at QuestionFunctional
|
425
|
+
def __add__(self, other_question_or_diff):
|
426
|
+
"""
|
427
|
+
Compose two questions into a single question.
|
428
|
+
|
429
|
+
TODO: Probably getting deprecated.
|
430
|
+
|
431
|
+
"""
|
432
|
+
if isinstance(other_question_or_diff, BaseDiff) or isinstance(
|
433
|
+
other_question_or_diff, BaseDiffCollection
|
434
|
+
):
|
435
|
+
return other_question_or_diff.apply(self)
|
436
|
+
|
437
|
+
# from edsl.questions import compose_questions
|
438
|
+
# return compose_questions(self, other_question_or_diff)
|
439
|
+
|
440
|
+
# def _validate_response(self, response):
|
441
|
+
# """Validate the response from the LLM. Behavior depends on the question type."""
|
442
|
+
# if "answer" not in response:
|
443
|
+
# raise QuestionResponseValidationError(
|
444
|
+
# "Response from LLM does not have an answer"
|
445
|
+
# )
|
446
|
+
# return response
|
447
|
+
|
448
|
+
def _translate_answer_code_to_answer(
|
449
|
+
self, answer, scenario: Optional["Scenario"] = None
|
450
|
+
):
|
451
|
+
"""There is over-ridden by child classes that ask for codes."""
|
452
|
+
return answer
|
453
|
+
|
454
|
+
# endregion
|
455
|
+
|
456
|
+
# region: Forward methods
|
457
|
+
def add_question(self, other: QuestionBase) -> "Survey":
|
458
|
+
"""Add a question to this question by turning them into a survey with two questions.
|
459
|
+
|
460
|
+
>>> from edsl.questions import QuestionFreeText as Q
|
461
|
+
>>> from edsl.questions import QuestionMultipleChoice as QMC
|
462
|
+
>>> s = Q.example().add_question(QMC.example())
|
463
|
+
>>> len(s.questions)
|
464
|
+
2
|
465
|
+
"""
|
466
|
+
from edsl.surveys.Survey import Survey
|
467
|
+
|
468
|
+
s = Survey([self, other])
|
469
|
+
return s
|
470
|
+
|
471
|
+
def to_survey(self) -> "Survey":
|
472
|
+
"""Turn a single question into a survey.
|
473
|
+
>>> from edsl import QuestionFreeText as Q
|
474
|
+
>>> Q.example().to_survey().questions[0].question_name
|
475
|
+
'how_are_you'
|
476
|
+
"""
|
477
|
+
from edsl.surveys.Survey import Survey
|
478
|
+
|
479
|
+
s = Survey([self])
|
480
|
+
return s
|
481
|
+
|
482
|
+
def by(self, *args) -> "Jobs":
|
483
|
+
"""Turn a single question into a survey and then a Job."""
|
484
|
+
from edsl.surveys.Survey import Survey
|
485
|
+
|
486
|
+
s = Survey([self])
|
487
|
+
return s.by(*args)
|
488
|
+
|
489
|
+
# endregion
|
490
|
+
|
491
|
+
# region: Display methods
|
492
|
+
def print(self):
|
493
|
+
from rich import print_json
|
494
|
+
import json
|
495
|
+
|
496
|
+
print_json(json.dumps(self.to_dict()))
|
497
|
+
|
498
|
+
def human_readable(self) -> str:
|
499
|
+
"""Print the question in a human readable format.
|
500
|
+
|
501
|
+
>>> from edsl.questions import QuestionFreeText
|
502
|
+
>>> QuestionFreeText.example().human_readable()
|
503
|
+
'Question Type: free_text\\nQuestion: How are you?'
|
504
|
+
"""
|
505
|
+
lines = []
|
506
|
+
lines.append(f"Question Type: {self.question_type}")
|
507
|
+
lines.append(f"Question: {self.question_text}")
|
508
|
+
if hasattr(self, "question_options"):
|
509
|
+
lines.append("Please name the option you choose from the following.:")
|
510
|
+
for index, option in enumerate(self.question_options):
|
511
|
+
lines.append(f"{option}")
|
512
|
+
return "\n".join(lines)
|
513
|
+
|
514
|
+
def html(
|
515
|
+
self,
|
516
|
+
scenario: Optional[dict] = None,
|
517
|
+
agent: Optional[dict] = {},
|
518
|
+
answers: Optional[dict] = None,
|
519
|
+
include_question_name: bool = False,
|
520
|
+
height: Optional[int] = None,
|
521
|
+
width: Optional[int] = None,
|
522
|
+
iframe=False,
|
523
|
+
):
|
524
|
+
"""Return the question in HTML format."""
|
525
|
+
from jinja2 import Template
|
526
|
+
|
527
|
+
if scenario is None:
|
528
|
+
scenario = {}
|
529
|
+
|
530
|
+
prior_answers_dict = {}
|
531
|
+
|
532
|
+
if isinstance(answers, dict):
|
533
|
+
for key, value in answers.items():
|
534
|
+
if not key.endswith("_comment") and not key.endswith(
|
535
|
+
"_generated_tokens"
|
536
|
+
):
|
537
|
+
prior_answers_dict[key] = {"answer": value}
|
538
|
+
|
539
|
+
# breakpoint()
|
540
|
+
|
541
|
+
base_template = """
|
542
|
+
<div id="{{ question_name }}" class="survey_question" data-type="{{ question_type }}">
|
543
|
+
{% if include_question_name %}
|
544
|
+
<p>question_name: {{ question_name }}</p>
|
545
|
+
{% endif %}
|
546
|
+
<p class="question_text">{{ question_text }}</p>
|
547
|
+
{{ question_content }}
|
548
|
+
</div>
|
549
|
+
"""
|
550
|
+
if not hasattr(self, "question_type"):
|
551
|
+
self.question_type = "unknown"
|
552
|
+
|
553
|
+
if hasattr(self, "question_html_content"):
|
554
|
+
question_content = self.question_html_content
|
555
|
+
else:
|
556
|
+
question_content = Template("")
|
557
|
+
|
558
|
+
base_template = Template(base_template)
|
559
|
+
|
560
|
+
context = {
|
561
|
+
"scenario": scenario,
|
562
|
+
"agent": agent,
|
563
|
+
} | prior_answers_dict
|
564
|
+
|
565
|
+
# Render the question text
|
566
|
+
try:
|
567
|
+
question_text = Template(self.question_text).render(context)
|
568
|
+
except Exception as e:
|
569
|
+
print(
|
570
|
+
f"Error rendering question: question_text = {self.question_text}, error = {e}"
|
571
|
+
)
|
572
|
+
question_text = self.question_text
|
573
|
+
|
574
|
+
try:
|
575
|
+
question_content = Template(question_content).render(context)
|
576
|
+
except Exception as e:
|
577
|
+
print(
|
578
|
+
f"Error rendering question: question_content = {question_content}, error = {e}"
|
579
|
+
)
|
580
|
+
question_content = question_content
|
581
|
+
|
582
|
+
try:
|
583
|
+
params = {
|
584
|
+
"question_name": self.question_name,
|
585
|
+
"question_text": question_text,
|
586
|
+
"question_type": self.question_type,
|
587
|
+
"question_content": question_content,
|
588
|
+
"include_question_name": include_question_name,
|
589
|
+
}
|
590
|
+
except Exception as e:
|
591
|
+
raise ValueError(
|
592
|
+
f"Error rendering question: params = {params}, error = {e}"
|
593
|
+
)
|
594
|
+
rendered_html = base_template.render(**params)
|
595
|
+
|
596
|
+
if iframe:
|
597
|
+
import html
|
598
|
+
from IPython.display import display, HTML
|
599
|
+
|
600
|
+
height = height or 200
|
601
|
+
width = width or 600
|
602
|
+
escaped_output = html.escape(rendered_html)
|
603
|
+
# escaped_output = rendered_html
|
604
|
+
iframe = f""""
|
605
|
+
<iframe srcdoc="{ escaped_output }" style="width: {width}px; height: {height}px;"></iframe>
|
606
|
+
"""
|
607
|
+
display(HTML(iframe))
|
608
|
+
return None
|
609
|
+
|
610
|
+
return rendered_html
|
611
|
+
|
612
|
+
@classmethod
|
613
|
+
def example_model(cls):
|
614
|
+
from edsl import Model
|
615
|
+
|
616
|
+
q = cls.example()
|
617
|
+
m = Model("test", canned_response=cls._simulate_answer(q)["answer"])
|
618
|
+
|
619
|
+
return m
|
620
|
+
|
621
|
+
@classmethod
|
622
|
+
def example_results(cls):
|
623
|
+
m = cls.example_model()
|
624
|
+
q = cls.example()
|
625
|
+
return q.by(m).run(cache=False)
|
626
|
+
|
627
|
+
def rich_print(self):
|
628
|
+
"""Print the question in a rich format."""
|
629
|
+
from rich.table import Table
|
630
|
+
|
631
|
+
table = Table(show_header=True, header_style="bold magenta")
|
632
|
+
table.add_column("Question Name", style="dim")
|
633
|
+
table.add_column("Question Type")
|
634
|
+
table.add_column("Question Text")
|
635
|
+
table.add_column("Options")
|
636
|
+
|
637
|
+
question = self
|
638
|
+
if hasattr(question, "question_options"):
|
639
|
+
options = ", ".join([str(o) for o in question.question_options])
|
640
|
+
else:
|
641
|
+
options = "None"
|
642
|
+
table.add_row(
|
643
|
+
question.question_name,
|
644
|
+
question.question_type,
|
645
|
+
question.question_text,
|
646
|
+
options,
|
647
|
+
)
|
648
|
+
return table
|
649
|
+
|
650
|
+
# endregion
|
651
|
+
|
652
|
+
|
653
|
+
if __name__ == "__main__":
|
654
|
+
import doctest
|
655
|
+
|
656
|
+
doctest.testmod(optionflags=doctest.ELLIPSIS)
|