edsl 0.1.32__py3-none-any.whl → 0.1.33__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 +9 -3
- edsl/TemplateLoader.py +24 -0
- edsl/__init__.py +8 -3
- edsl/__version__.py +1 -1
- edsl/agents/Agent.py +40 -8
- edsl/agents/AgentList.py +43 -0
- edsl/agents/Invigilator.py +135 -219
- edsl/agents/InvigilatorBase.py +148 -59
- edsl/agents/{PromptConstructionMixin.py → PromptConstructor.py} +138 -89
- edsl/agents/__init__.py +1 -0
- edsl/auto/AutoStudy.py +117 -0
- edsl/auto/StageBase.py +230 -0
- edsl/auto/StageGenerateSurvey.py +178 -0
- edsl/auto/StageLabelQuestions.py +125 -0
- edsl/auto/StagePersona.py +61 -0
- edsl/auto/StagePersonaDimensionValueRanges.py +88 -0
- edsl/auto/StagePersonaDimensionValues.py +74 -0
- edsl/auto/StagePersonaDimensions.py +69 -0
- edsl/auto/StageQuestions.py +73 -0
- edsl/auto/SurveyCreatorPipeline.py +21 -0
- edsl/auto/utilities.py +224 -0
- edsl/config.py +47 -56
- edsl/coop/PriceFetcher.py +58 -0
- edsl/coop/coop.py +50 -7
- edsl/data/Cache.py +35 -1
- edsl/data_transfer_models.py +73 -38
- edsl/enums.py +4 -0
- edsl/exceptions/language_models.py +25 -1
- edsl/exceptions/questions.py +62 -5
- edsl/exceptions/results.py +4 -0
- edsl/inference_services/AnthropicService.py +13 -11
- edsl/inference_services/AwsBedrock.py +19 -17
- edsl/inference_services/AzureAI.py +37 -20
- edsl/inference_services/GoogleService.py +16 -12
- edsl/inference_services/GroqService.py +2 -0
- edsl/inference_services/InferenceServiceABC.py +58 -3
- edsl/inference_services/MistralAIService.py +120 -0
- edsl/inference_services/OpenAIService.py +48 -54
- edsl/inference_services/TestService.py +80 -0
- edsl/inference_services/TogetherAIService.py +170 -0
- edsl/inference_services/models_available_cache.py +0 -6
- edsl/inference_services/registry.py +6 -0
- edsl/jobs/Answers.py +10 -12
- edsl/jobs/FailedQuestion.py +78 -0
- edsl/jobs/Jobs.py +37 -22
- edsl/jobs/buckets/BucketCollection.py +24 -15
- edsl/jobs/buckets/TokenBucket.py +93 -14
- edsl/jobs/interviews/Interview.py +366 -78
- edsl/jobs/interviews/{interview_exception_tracking.py → InterviewExceptionCollection.py} +14 -68
- edsl/jobs/interviews/InterviewExceptionEntry.py +85 -19
- edsl/jobs/runners/JobsRunnerAsyncio.py +146 -175
- edsl/jobs/runners/JobsRunnerStatus.py +331 -0
- edsl/jobs/tasks/QuestionTaskCreator.py +30 -23
- edsl/jobs/tasks/TaskHistory.py +148 -213
- edsl/language_models/LanguageModel.py +261 -156
- edsl/language_models/ModelList.py +2 -2
- edsl/language_models/RegisterLanguageModelsMeta.py +14 -29
- edsl/language_models/fake_openai_call.py +15 -0
- edsl/language_models/fake_openai_service.py +61 -0
- edsl/language_models/registry.py +23 -6
- edsl/language_models/repair.py +0 -19
- edsl/language_models/utilities.py +61 -0
- edsl/notebooks/Notebook.py +20 -2
- edsl/prompts/Prompt.py +52 -2
- edsl/questions/AnswerValidatorMixin.py +23 -26
- edsl/questions/QuestionBase.py +330 -249
- edsl/questions/QuestionBaseGenMixin.py +133 -0
- edsl/questions/QuestionBasePromptsMixin.py +266 -0
- edsl/questions/QuestionBudget.py +99 -41
- edsl/questions/QuestionCheckBox.py +227 -35
- edsl/questions/QuestionExtract.py +98 -27
- edsl/questions/QuestionFreeText.py +52 -29
- edsl/questions/QuestionFunctional.py +7 -0
- edsl/questions/QuestionList.py +141 -22
- edsl/questions/QuestionMultipleChoice.py +159 -65
- edsl/questions/QuestionNumerical.py +88 -46
- edsl/questions/QuestionRank.py +182 -24
- edsl/questions/Quick.py +41 -0
- edsl/questions/RegisterQuestionsMeta.py +31 -12
- edsl/questions/ResponseValidatorABC.py +170 -0
- edsl/questions/__init__.py +3 -4
- edsl/questions/decorators.py +21 -0
- edsl/questions/derived/QuestionLikertFive.py +10 -5
- edsl/questions/derived/QuestionLinearScale.py +15 -2
- edsl/questions/derived/QuestionTopK.py +10 -1
- edsl/questions/derived/QuestionYesNo.py +24 -3
- edsl/questions/descriptors.py +43 -7
- edsl/questions/prompt_templates/question_budget.jinja +13 -0
- edsl/questions/prompt_templates/question_checkbox.jinja +32 -0
- edsl/questions/prompt_templates/question_extract.jinja +11 -0
- edsl/questions/prompt_templates/question_free_text.jinja +3 -0
- edsl/questions/prompt_templates/question_linear_scale.jinja +11 -0
- edsl/questions/prompt_templates/question_list.jinja +17 -0
- edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -0
- edsl/questions/prompt_templates/question_numerical.jinja +37 -0
- edsl/questions/question_registry.py +6 -2
- edsl/questions/templates/__init__.py +0 -0
- edsl/questions/templates/budget/__init__.py +0 -0
- edsl/questions/templates/budget/answering_instructions.jinja +7 -0
- edsl/questions/templates/budget/question_presentation.jinja +7 -0
- edsl/questions/templates/checkbox/__init__.py +0 -0
- edsl/questions/templates/checkbox/answering_instructions.jinja +10 -0
- edsl/questions/templates/checkbox/question_presentation.jinja +22 -0
- edsl/questions/templates/extract/__init__.py +0 -0
- edsl/questions/templates/extract/answering_instructions.jinja +7 -0
- edsl/questions/templates/extract/question_presentation.jinja +1 -0
- edsl/questions/templates/free_text/__init__.py +0 -0
- edsl/questions/templates/free_text/answering_instructions.jinja +0 -0
- edsl/questions/templates/free_text/question_presentation.jinja +1 -0
- edsl/questions/templates/likert_five/__init__.py +0 -0
- edsl/questions/templates/likert_five/answering_instructions.jinja +10 -0
- edsl/questions/templates/likert_five/question_presentation.jinja +12 -0
- edsl/questions/templates/linear_scale/__init__.py +0 -0
- edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -0
- edsl/questions/templates/linear_scale/question_presentation.jinja +5 -0
- edsl/questions/templates/list/__init__.py +0 -0
- edsl/questions/templates/list/answering_instructions.jinja +4 -0
- edsl/questions/templates/list/question_presentation.jinja +5 -0
- edsl/questions/templates/multiple_choice/__init__.py +0 -0
- edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -0
- edsl/questions/templates/multiple_choice/html.jinja +0 -0
- edsl/questions/templates/multiple_choice/question_presentation.jinja +12 -0
- edsl/questions/templates/numerical/__init__.py +0 -0
- edsl/questions/templates/numerical/answering_instructions.jinja +8 -0
- edsl/questions/templates/numerical/question_presentation.jinja +7 -0
- edsl/questions/templates/rank/__init__.py +0 -0
- edsl/questions/templates/rank/answering_instructions.jinja +11 -0
- edsl/questions/templates/rank/question_presentation.jinja +15 -0
- edsl/questions/templates/top_k/__init__.py +0 -0
- edsl/questions/templates/top_k/answering_instructions.jinja +8 -0
- edsl/questions/templates/top_k/question_presentation.jinja +22 -0
- edsl/questions/templates/yes_no/__init__.py +0 -0
- edsl/questions/templates/yes_no/answering_instructions.jinja +6 -0
- edsl/questions/templates/yes_no/question_presentation.jinja +12 -0
- edsl/results/Dataset.py +20 -0
- edsl/results/DatasetExportMixin.py +46 -48
- edsl/results/DatasetTree.py +145 -0
- edsl/results/Result.py +32 -5
- edsl/results/Results.py +135 -46
- edsl/results/ResultsDBMixin.py +3 -3
- edsl/results/Selector.py +118 -0
- edsl/results/tree_explore.py +115 -0
- edsl/scenarios/FileStore.py +71 -10
- edsl/scenarios/Scenario.py +96 -25
- edsl/scenarios/ScenarioImageMixin.py +2 -2
- edsl/scenarios/ScenarioList.py +361 -39
- edsl/scenarios/ScenarioListExportMixin.py +9 -0
- edsl/scenarios/ScenarioListPdfMixin.py +150 -4
- edsl/study/SnapShot.py +8 -1
- edsl/study/Study.py +32 -0
- edsl/surveys/Rule.py +10 -1
- edsl/surveys/RuleCollection.py +21 -5
- edsl/surveys/Survey.py +637 -311
- edsl/surveys/SurveyExportMixin.py +71 -9
- edsl/surveys/SurveyFlowVisualizationMixin.py +2 -1
- edsl/surveys/SurveyQualtricsImport.py +75 -4
- edsl/surveys/instructions/ChangeInstruction.py +47 -0
- edsl/surveys/instructions/Instruction.py +34 -0
- edsl/surveys/instructions/InstructionCollection.py +77 -0
- edsl/surveys/instructions/__init__.py +0 -0
- edsl/templates/error_reporting/base.html +24 -0
- edsl/templates/error_reporting/exceptions_by_model.html +35 -0
- edsl/templates/error_reporting/exceptions_by_question_name.html +17 -0
- edsl/templates/error_reporting/exceptions_by_type.html +17 -0
- edsl/templates/error_reporting/interview_details.html +116 -0
- edsl/templates/error_reporting/interviews.html +10 -0
- edsl/templates/error_reporting/overview.html +5 -0
- edsl/templates/error_reporting/performance_plot.html +2 -0
- edsl/templates/error_reporting/report.css +74 -0
- edsl/templates/error_reporting/report.html +118 -0
- edsl/templates/error_reporting/report.js +25 -0
- edsl/utilities/utilities.py +9 -1
- {edsl-0.1.32.dist-info → edsl-0.1.33.dist-info}/METADATA +5 -2
- edsl-0.1.33.dist-info/RECORD +295 -0
- edsl/jobs/interviews/InterviewTaskBuildingMixin.py +0 -286
- edsl/jobs/interviews/retry_management.py +0 -37
- edsl/jobs/runners/JobsRunnerStatusMixin.py +0 -333
- edsl/utilities/gcp_bucket/simple_example.py +0 -9
- edsl-0.1.32.dist-info/RECORD +0 -209
- {edsl-0.1.32.dist-info → edsl-0.1.33.dist-info}/LICENSE +0 -0
- {edsl-0.1.32.dist-info → edsl-0.1.33.dist-info}/WHEEL +0 -0
@@ -1,50 +1,76 @@
|
|
1
1
|
"""This module contains the Interview class, which is responsible for conducting an interview asynchronously."""
|
2
2
|
|
3
3
|
from __future__ import annotations
|
4
|
-
import traceback
|
5
4
|
import asyncio
|
6
|
-
import
|
7
|
-
|
5
|
+
from typing import Any, Type, List, Generator, Optional, Union
|
6
|
+
|
7
|
+
from tenacity import (
|
8
|
+
retry,
|
9
|
+
stop_after_attempt,
|
10
|
+
wait_exponential,
|
11
|
+
retry_if_exception_type,
|
12
|
+
RetryError,
|
13
|
+
)
|
8
14
|
|
9
|
-
from edsl
|
15
|
+
from edsl import CONFIG
|
10
16
|
from edsl.surveys.base import EndOfSurvey
|
17
|
+
from edsl.exceptions import QuestionAnswerValidationError
|
18
|
+
from edsl.exceptions import QuestionAnswerValidationError
|
19
|
+
from edsl.data_transfer_models import AgentResponseDict, EDSLResultObjectInput
|
20
|
+
|
11
21
|
from edsl.jobs.buckets.ModelBuckets import ModelBuckets
|
22
|
+
from edsl.jobs.Answers import Answers
|
23
|
+
from edsl.jobs.tasks.QuestionTaskCreator import QuestionTaskCreator
|
12
24
|
from edsl.jobs.tasks.TaskCreators import TaskCreators
|
13
|
-
|
14
25
|
from edsl.jobs.interviews.InterviewStatusLog import InterviewStatusLog
|
15
|
-
from edsl.jobs.interviews.
|
26
|
+
from edsl.jobs.interviews.InterviewExceptionCollection import (
|
16
27
|
InterviewExceptionCollection,
|
17
28
|
)
|
18
|
-
|
19
|
-
from edsl.jobs.interviews.retry_management import retry_strategy
|
20
|
-
from edsl.jobs.interviews.InterviewTaskBuildingMixin import InterviewTaskBuildingMixin
|
29
|
+
|
21
30
|
from edsl.jobs.interviews.InterviewStatusMixin import InterviewStatusMixin
|
22
31
|
|
23
|
-
import
|
32
|
+
from edsl.surveys.base import EndOfSurvey
|
33
|
+
from edsl.jobs.buckets.ModelBuckets import ModelBuckets
|
34
|
+
from edsl.jobs.interviews.InterviewExceptionEntry import InterviewExceptionEntry
|
35
|
+
from edsl.jobs.tasks.task_status_enum import TaskStatus
|
36
|
+
from edsl.jobs.tasks.QuestionTaskCreator import QuestionTaskCreator
|
37
|
+
|
38
|
+
|
39
|
+
from edsl import Agent, Survey, Scenario, Cache
|
40
|
+
from edsl.language_models import LanguageModel
|
41
|
+
from edsl.questions import QuestionBase
|
42
|
+
from edsl.agents.InvigilatorBase import InvigilatorBase
|
43
|
+
|
44
|
+
from edsl.exceptions.language_models import LanguageModelNoResponseError
|
24
45
|
|
25
46
|
|
26
|
-
|
27
|
-
return asyncio.run(coro)
|
47
|
+
from edsl import CONFIG
|
28
48
|
|
49
|
+
EDSL_BACKOFF_START_SEC = float(CONFIG.get("EDSL_BACKOFF_START_SEC"))
|
50
|
+
EDSL_BACKOFF_MAX_SEC = float(CONFIG.get("EDSL_BACKOFF_MAX_SEC"))
|
51
|
+
EDSL_MAX_ATTEMPTS = int(CONFIG.get("EDSL_MAX_ATTEMPTS"))
|
29
52
|
|
30
|
-
|
53
|
+
|
54
|
+
class Interview(InterviewStatusMixin):
|
31
55
|
"""
|
32
56
|
An 'interview' is one agent answering one survey, with one language model, for a given scenario.
|
33
57
|
|
34
58
|
The main method is `async_conduct_interview`, which conducts the interview asynchronously.
|
59
|
+
Most of the class is dedicated to creating the tasks for each question in the survey, and then running them.
|
35
60
|
"""
|
36
61
|
|
37
62
|
def __init__(
|
38
63
|
self,
|
39
|
-
agent:
|
40
|
-
survey:
|
41
|
-
scenario:
|
64
|
+
agent: Agent,
|
65
|
+
survey: Survey,
|
66
|
+
scenario: Scenario,
|
42
67
|
model: Type["LanguageModel"],
|
43
68
|
debug: Optional[bool] = False,
|
44
69
|
iteration: int = 0,
|
45
70
|
cache: Optional["Cache"] = None,
|
46
71
|
sidecar_model: Optional["LanguageModel"] = None,
|
47
|
-
skip_retry=False,
|
72
|
+
skip_retry: bool = False,
|
73
|
+
raise_validation_errors: bool = True,
|
48
74
|
):
|
49
75
|
"""Initialize the Interview instance.
|
50
76
|
|
@@ -84,11 +110,15 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
84
110
|
] = Answers() # will get filled in as interview progresses
|
85
111
|
self.sidecar_model = sidecar_model
|
86
112
|
|
113
|
+
# self.stop_on_exception = False
|
114
|
+
|
87
115
|
# Trackers
|
88
116
|
self.task_creators = TaskCreators() # tracks the task creators
|
89
117
|
self.exceptions = InterviewExceptionCollection()
|
118
|
+
|
90
119
|
self._task_status_log_dict = InterviewStatusLog()
|
91
120
|
self.skip_retry = skip_retry
|
121
|
+
self.raise_validation_errors = raise_validation_errors
|
92
122
|
|
93
123
|
# dictionary mapping question names to their index in the survey.
|
94
124
|
self.to_index = {
|
@@ -96,6 +126,9 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
96
126
|
for index, question_name in enumerate(self.survey.question_names)
|
97
127
|
}
|
98
128
|
|
129
|
+
self.failed_questions = []
|
130
|
+
|
131
|
+
# region: Serialization
|
99
132
|
def _to_dict(self, include_exceptions=False) -> dict[str, Any]:
|
100
133
|
"""Return a dictionary representation of the Interview instance.
|
101
134
|
This is just for hashing purposes.
|
@@ -120,13 +153,301 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
120
153
|
|
121
154
|
return dict_hash(self._to_dict())
|
122
155
|
|
123
|
-
|
156
|
+
# endregion
|
157
|
+
|
158
|
+
# region: Creating tasks
|
159
|
+
@property
|
160
|
+
def dag(self) -> "DAG":
|
161
|
+
"""Return the directed acyclic graph for the survey.
|
162
|
+
|
163
|
+
The DAG, or directed acyclic graph, is a dictionary that maps question names to their dependencies.
|
164
|
+
It is used to determine the order in which questions should be answered.
|
165
|
+
This reflects both agent 'memory' considerations and 'skip' logic.
|
166
|
+
The 'textify' parameter is set to True, so that the question names are returned as strings rather than integer indices.
|
167
|
+
|
168
|
+
>>> i = Interview.example()
|
169
|
+
>>> i.dag == {'q2': {'q0'}, 'q1': {'q0'}}
|
170
|
+
True
|
171
|
+
"""
|
172
|
+
return self.survey.dag(textify=True)
|
173
|
+
|
174
|
+
def _build_question_tasks(
|
175
|
+
self,
|
176
|
+
model_buckets: ModelBuckets,
|
177
|
+
) -> list[asyncio.Task]:
|
178
|
+
"""Create a task for each question, with dependencies on the questions that must be answered before this one can be answered.
|
179
|
+
|
180
|
+
:param debug: whether to use debug mode, in which case `InvigilatorDebug` is used.
|
181
|
+
:param model_buckets: the model buckets used to track and control usage rates.
|
182
|
+
"""
|
183
|
+
tasks = []
|
184
|
+
for question in self.survey.questions:
|
185
|
+
tasks_that_must_be_completed_before = list(
|
186
|
+
self._get_tasks_that_must_be_completed_before(
|
187
|
+
tasks=tasks, question=question
|
188
|
+
)
|
189
|
+
)
|
190
|
+
question_task = self._create_question_task(
|
191
|
+
question=question,
|
192
|
+
tasks_that_must_be_completed_before=tasks_that_must_be_completed_before,
|
193
|
+
model_buckets=model_buckets,
|
194
|
+
iteration=self.iteration,
|
195
|
+
)
|
196
|
+
tasks.append(question_task)
|
197
|
+
return tuple(tasks)
|
198
|
+
|
199
|
+
def _get_tasks_that_must_be_completed_before(
|
200
|
+
self, *, tasks: list[asyncio.Task], question: "QuestionBase"
|
201
|
+
) -> Generator[asyncio.Task, None, None]:
|
202
|
+
"""Return the tasks that must be completed before the given question can be answered.
|
203
|
+
|
204
|
+
:param tasks: a list of tasks that have been created so far.
|
205
|
+
:param question: the question for which we are determining dependencies.
|
206
|
+
|
207
|
+
If a question has no dependencies, this will be an empty list, [].
|
208
|
+
"""
|
209
|
+
parents_of_focal_question = self.dag.get(question.question_name, [])
|
210
|
+
for parent_question_name in parents_of_focal_question:
|
211
|
+
yield tasks[self.to_index[parent_question_name]]
|
212
|
+
|
213
|
+
def _create_question_task(
|
214
|
+
self,
|
215
|
+
*,
|
216
|
+
question: QuestionBase,
|
217
|
+
tasks_that_must_be_completed_before: list[asyncio.Task],
|
218
|
+
model_buckets: ModelBuckets,
|
219
|
+
iteration: int = 0,
|
220
|
+
) -> asyncio.Task:
|
221
|
+
"""Create a task that depends on the passed-in dependencies that are awaited before the task is run.
|
222
|
+
|
223
|
+
:param question: the question to be answered. This is the question we are creating a task for.
|
224
|
+
:param tasks_that_must_be_completed_before: the tasks that must be completed before the focal task is run.
|
225
|
+
:param model_buckets: the model buckets used to track and control usage rates.
|
226
|
+
:param debug: whether to use debug mode, in which case `InvigilatorDebug` is used.
|
227
|
+
:param iteration: the iteration number for the interview.
|
228
|
+
|
229
|
+
The task is created by a `QuestionTaskCreator`, which is responsible for creating the task and managing its dependencies.
|
230
|
+
It is passed a reference to the function that will be called to answer the question.
|
231
|
+
It is passed a list "tasks_that_must_be_completed_before" that are awaited before the task is run.
|
232
|
+
These are added as a dependency to the focal task.
|
233
|
+
"""
|
234
|
+
task_creator = QuestionTaskCreator(
|
235
|
+
question=question,
|
236
|
+
answer_question_func=self._answer_question_and_record_task,
|
237
|
+
token_estimator=self._get_estimated_request_tokens,
|
238
|
+
model_buckets=model_buckets,
|
239
|
+
iteration=iteration,
|
240
|
+
)
|
241
|
+
for task in tasks_that_must_be_completed_before:
|
242
|
+
task_creator.add_dependency(task)
|
243
|
+
|
244
|
+
self.task_creators.update(
|
245
|
+
{question.question_name: task_creator}
|
246
|
+
) # track this task creator
|
247
|
+
return task_creator.generate_task()
|
248
|
+
|
249
|
+
def _get_estimated_request_tokens(self, question) -> float:
|
250
|
+
"""Estimate the number of tokens that will be required to run the focal task."""
|
251
|
+
invigilator = self._get_invigilator(question=question)
|
252
|
+
# TODO: There should be a way to get a more accurate estimate.
|
253
|
+
combined_text = ""
|
254
|
+
for prompt in invigilator.get_prompts().values():
|
255
|
+
if hasattr(prompt, "text"):
|
256
|
+
combined_text += prompt.text
|
257
|
+
elif isinstance(prompt, str):
|
258
|
+
combined_text += prompt
|
259
|
+
else:
|
260
|
+
raise ValueError(f"Prompt is of type {type(prompt)}")
|
261
|
+
return len(combined_text) / 4.0
|
262
|
+
|
263
|
+
async def _answer_question_and_record_task(
|
124
264
|
self,
|
125
265
|
*,
|
126
|
-
|
127
|
-
|
266
|
+
question: "QuestionBase",
|
267
|
+
task=None,
|
268
|
+
) -> "AgentResponseDict":
|
269
|
+
"""Answer a question and records the task."""
|
270
|
+
|
271
|
+
had_language_model_no_response_error = False
|
272
|
+
|
273
|
+
@retry(
|
274
|
+
stop=stop_after_attempt(EDSL_MAX_ATTEMPTS),
|
275
|
+
wait=wait_exponential(
|
276
|
+
multiplier=EDSL_BACKOFF_START_SEC, max=EDSL_BACKOFF_MAX_SEC
|
277
|
+
),
|
278
|
+
retry=retry_if_exception_type(LanguageModelNoResponseError),
|
279
|
+
reraise=True,
|
280
|
+
)
|
281
|
+
async def attempt_answer():
|
282
|
+
nonlocal had_language_model_no_response_error
|
283
|
+
|
284
|
+
invigilator = self._get_invigilator(question)
|
285
|
+
|
286
|
+
if self._skip_this_question(question):
|
287
|
+
return invigilator.get_failed_task_result(
|
288
|
+
failure_reason="Question skipped."
|
289
|
+
)
|
290
|
+
|
291
|
+
try:
|
292
|
+
response: EDSLResultObjectInput = (
|
293
|
+
await invigilator.async_answer_question()
|
294
|
+
)
|
295
|
+
if response.validated:
|
296
|
+
self.answers.add_answer(response=response, question=question)
|
297
|
+
self._cancel_skipped_questions(question)
|
298
|
+
else:
|
299
|
+
if (
|
300
|
+
hasattr(response, "exception_occurred")
|
301
|
+
and response.exception_occurred
|
302
|
+
):
|
303
|
+
raise response.exception_occurred
|
304
|
+
|
305
|
+
except QuestionAnswerValidationError as e:
|
306
|
+
self._handle_exception(e, invigilator, task)
|
307
|
+
return invigilator.get_failed_task_result(
|
308
|
+
failure_reason="Question answer validation failed."
|
309
|
+
)
|
310
|
+
|
311
|
+
except asyncio.TimeoutError as e:
|
312
|
+
self._handle_exception(e, invigilator, task)
|
313
|
+
had_language_model_no_response_error = True
|
314
|
+
raise LanguageModelNoResponseError(
|
315
|
+
f"Language model timed out for question '{question.question_name}.'"
|
316
|
+
)
|
317
|
+
|
318
|
+
except Exception as e:
|
319
|
+
self._handle_exception(e, invigilator, task)
|
320
|
+
|
321
|
+
if "response" not in locals():
|
322
|
+
had_language_model_no_response_error = True
|
323
|
+
raise LanguageModelNoResponseError(
|
324
|
+
f"Language model did not return a response for question '{question.question_name}.'"
|
325
|
+
)
|
326
|
+
|
327
|
+
# if it gets here, it means the no response error was fixed
|
328
|
+
if (
|
329
|
+
question.question_name in self.exceptions
|
330
|
+
and had_language_model_no_response_error
|
331
|
+
):
|
332
|
+
self.exceptions.record_fixed_question(question.question_name)
|
333
|
+
|
334
|
+
return response
|
335
|
+
|
336
|
+
try:
|
337
|
+
return await attempt_answer()
|
338
|
+
except RetryError as retry_error:
|
339
|
+
# All retries have failed for LanguageModelNoResponseError
|
340
|
+
original_error = retry_error.last_attempt.exception()
|
341
|
+
self._handle_exception(
|
342
|
+
original_error, self._get_invigilator(question), task
|
343
|
+
)
|
344
|
+
raise original_error # Re-raise the original error after handling
|
345
|
+
|
346
|
+
def _get_invigilator(self, question: QuestionBase) -> InvigilatorBase:
|
347
|
+
"""Return an invigilator for the given question.
|
348
|
+
|
349
|
+
:param question: the question to be answered
|
350
|
+
:param debug: whether to use debug mode, in which case `InvigilatorDebug` is used.
|
351
|
+
"""
|
352
|
+
invigilator = self.agent.create_invigilator(
|
353
|
+
question=question,
|
354
|
+
scenario=self.scenario,
|
355
|
+
model=self.model,
|
356
|
+
debug=False,
|
357
|
+
survey=self.survey,
|
358
|
+
memory_plan=self.survey.memory_plan,
|
359
|
+
current_answers=self.answers,
|
360
|
+
iteration=self.iteration,
|
361
|
+
cache=self.cache,
|
362
|
+
sidecar_model=self.sidecar_model,
|
363
|
+
raise_validation_errors=self.raise_validation_errors,
|
364
|
+
)
|
365
|
+
"""Return an invigilator for the given question."""
|
366
|
+
return invigilator
|
367
|
+
|
368
|
+
def _skip_this_question(self, current_question: "QuestionBase") -> bool:
|
369
|
+
"""Determine if the current question should be skipped.
|
370
|
+
|
371
|
+
:param current_question: the question to be answered.
|
372
|
+
"""
|
373
|
+
current_question_index = self.to_index[current_question.question_name]
|
374
|
+
|
375
|
+
answers = self.answers | self.scenario | self.agent["traits"]
|
376
|
+
skip = self.survey.rule_collection.skip_question_before_running(
|
377
|
+
current_question_index, answers
|
378
|
+
)
|
379
|
+
return skip
|
380
|
+
|
381
|
+
def _handle_exception(
|
382
|
+
self, e: Exception, invigilator: "InvigilatorBase", task=None
|
383
|
+
):
|
384
|
+
import copy
|
385
|
+
|
386
|
+
# breakpoint()
|
387
|
+
|
388
|
+
answers = copy.copy(self.answers)
|
389
|
+
exception_entry = InterviewExceptionEntry(
|
390
|
+
exception=e,
|
391
|
+
invigilator=invigilator,
|
392
|
+
answers=answers,
|
393
|
+
)
|
394
|
+
if task:
|
395
|
+
task.task_status = TaskStatus.FAILED
|
396
|
+
self.exceptions.add(invigilator.question.question_name, exception_entry)
|
397
|
+
|
398
|
+
if self.raise_validation_errors:
|
399
|
+
if isinstance(e, QuestionAnswerValidationError):
|
400
|
+
raise e
|
401
|
+
|
402
|
+
if hasattr(self, "stop_on_exception"):
|
403
|
+
stop_on_exception = self.stop_on_exception
|
404
|
+
else:
|
405
|
+
stop_on_exception = False
|
406
|
+
|
407
|
+
if stop_on_exception:
|
408
|
+
raise e
|
409
|
+
|
410
|
+
def _cancel_skipped_questions(self, current_question: QuestionBase) -> None:
|
411
|
+
"""Cancel the tasks for questions that are skipped.
|
412
|
+
|
413
|
+
:param current_question: the question that was just answered.
|
414
|
+
|
415
|
+
It first determines the next question, given the current question and the current answers.
|
416
|
+
If the next question is the end of the survey, it cancels all remaining tasks.
|
417
|
+
If the next question is after the current question, it cancels all tasks between the current question and the next question.
|
418
|
+
"""
|
419
|
+
current_question_index: int = self.to_index[current_question.question_name]
|
420
|
+
|
421
|
+
next_question: Union[
|
422
|
+
int, EndOfSurvey
|
423
|
+
] = self.survey.rule_collection.next_question(
|
424
|
+
q_now=current_question_index,
|
425
|
+
answers=self.answers | self.scenario | self.agent["traits"],
|
426
|
+
)
|
427
|
+
|
428
|
+
next_question_index = next_question.next_q
|
429
|
+
|
430
|
+
def cancel_between(start, end):
|
431
|
+
"""Cancel the tasks between the start and end indices."""
|
432
|
+
for i in range(start, end):
|
433
|
+
self.tasks[i].cancel()
|
434
|
+
|
435
|
+
if next_question_index == EndOfSurvey:
|
436
|
+
cancel_between(current_question_index + 1, len(self.survey.questions))
|
437
|
+
return
|
438
|
+
|
439
|
+
if next_question_index > (current_question_index + 1):
|
440
|
+
cancel_between(current_question_index + 1, next_question_index)
|
441
|
+
|
442
|
+
# endregion
|
443
|
+
|
444
|
+
# region: Conducting the interview
|
445
|
+
async def async_conduct_interview(
|
446
|
+
self,
|
447
|
+
model_buckets: Optional[ModelBuckets] = None,
|
128
448
|
stop_on_exception: bool = False,
|
129
449
|
sidecar_model: Optional["LanguageModel"] = None,
|
450
|
+
raise_validation_errors: bool = True,
|
130
451
|
) -> tuple["Answers", List[dict[str, Any]]]:
|
131
452
|
"""
|
132
453
|
Conduct an Interview asynchronously.
|
@@ -146,19 +467,6 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
146
467
|
|
147
468
|
>>> i = Interview.example(throw_exception = True)
|
148
469
|
>>> result, _ = asyncio.run(i.async_conduct_interview())
|
149
|
-
Attempt 1 failed with exception:This is a test error now waiting 1.00 seconds before retrying.Parameters: start=1.0, max=60.0, max_attempts=5.
|
150
|
-
<BLANKLINE>
|
151
|
-
<BLANKLINE>
|
152
|
-
Attempt 2 failed with exception:This is a test error now waiting 2.00 seconds before retrying.Parameters: start=1.0, max=60.0, max_attempts=5.
|
153
|
-
<BLANKLINE>
|
154
|
-
<BLANKLINE>
|
155
|
-
Attempt 3 failed with exception:This is a test error now waiting 4.00 seconds before retrying.Parameters: start=1.0, max=60.0, max_attempts=5.
|
156
|
-
<BLANKLINE>
|
157
|
-
<BLANKLINE>
|
158
|
-
Attempt 4 failed with exception:This is a test error now waiting 8.00 seconds before retrying.Parameters: start=1.0, max=60.0, max_attempts=5.
|
159
|
-
<BLANKLINE>
|
160
|
-
<BLANKLINE>
|
161
|
-
|
162
470
|
>>> i.exceptions
|
163
471
|
{'q0': ...
|
164
472
|
>>> i = Interview.example()
|
@@ -168,26 +476,30 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
168
476
|
asyncio.exceptions.CancelledError
|
169
477
|
"""
|
170
478
|
self.sidecar_model = sidecar_model
|
479
|
+
self.stop_on_exception = stop_on_exception
|
171
480
|
|
172
481
|
# if no model bucket is passed, create an 'infinity' bucket with no rate limits
|
173
482
|
if model_buckets is None or hasattr(self.agent, "answer_question_directly"):
|
174
483
|
model_buckets = ModelBuckets.infinity_bucket()
|
175
484
|
|
176
|
-
## build the tasks using the InterviewTaskBuildingMixin
|
177
485
|
## This is the key part---it creates a task for each question,
|
178
486
|
## with dependencies on the questions that must be answered before this one can be answered.
|
179
|
-
self.tasks = self._build_question_tasks(
|
180
|
-
debug=debug, model_buckets=model_buckets
|
181
|
-
)
|
487
|
+
self.tasks = self._build_question_tasks(model_buckets=model_buckets)
|
182
488
|
|
183
489
|
## 'Invigilators' are used to administer the survey
|
184
|
-
self.invigilators =
|
185
|
-
|
186
|
-
|
490
|
+
self.invigilators = [
|
491
|
+
self._get_invigilator(question) for question in self.survey.questions
|
492
|
+
]
|
493
|
+
await asyncio.gather(
|
494
|
+
*self.tasks, return_exceptions=not stop_on_exception
|
495
|
+
) # not stop_on_exception)
|
187
496
|
self.answers.replace_missing_answers_with_none(self.survey)
|
188
497
|
valid_results = list(self._extract_valid_results())
|
189
498
|
return self.answers, valid_results
|
190
499
|
|
500
|
+
# endregion
|
501
|
+
|
502
|
+
# region: Extracting results and recording errors
|
191
503
|
def _extract_valid_results(self) -> Generator["Answers", None, None]:
|
192
504
|
"""Extract the valid results from the list of results.
|
193
505
|
|
@@ -200,8 +512,6 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
200
512
|
>>> results = list(i._extract_valid_results())
|
201
513
|
>>> len(results) == len(i.survey)
|
202
514
|
True
|
203
|
-
>>> type(results[0])
|
204
|
-
<class 'edsl.data_transfer_models.AgentResponseDict'>
|
205
515
|
"""
|
206
516
|
assert len(self.tasks) == len(self.invigilators)
|
207
517
|
|
@@ -212,46 +522,24 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
212
522
|
try:
|
213
523
|
result = task.result()
|
214
524
|
except asyncio.CancelledError as e: # task was cancelled
|
215
|
-
result = invigilator.get_failed_task_result(
|
525
|
+
result = invigilator.get_failed_task_result(
|
526
|
+
failure_reason="Task was cancelled."
|
527
|
+
)
|
216
528
|
except Exception as e: # any other kind of exception in the task
|
217
|
-
result = invigilator.get_failed_task_result(
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
|
222
|
-
|
223
|
-
|
224
|
-
|
225
|
-
|
226
|
-
>>> i = Interview.example()
|
227
|
-
>>> result, _ = asyncio.run(i.async_conduct_interview())
|
228
|
-
>>> i.exceptions
|
229
|
-
{}
|
230
|
-
>>> i._record_exception(i.tasks[0], Exception("An exception occurred."))
|
231
|
-
>>> i.exceptions
|
232
|
-
{'q0': ...
|
233
|
-
"""
|
234
|
-
exception_entry = InterviewExceptionEntry(exception)
|
235
|
-
self.exceptions.add(task.get_name(), exception_entry)
|
529
|
+
result = invigilator.get_failed_task_result(
|
530
|
+
failure_reason=f"Task failed with exception: {str(e)}."
|
531
|
+
)
|
532
|
+
exception_entry = InterviewExceptionEntry(
|
533
|
+
exception=e,
|
534
|
+
invigilator=invigilator,
|
535
|
+
)
|
536
|
+
self.exceptions.add(task.get_name(), exception_entry)
|
236
537
|
|
237
|
-
|
238
|
-
def dag(self) -> "DAG":
|
239
|
-
"""Return the directed acyclic graph for the survey.
|
240
|
-
|
241
|
-
The DAG, or directed acyclic graph, is a dictionary that maps question names to their dependencies.
|
242
|
-
It is used to determine the order in which questions should be answered.
|
243
|
-
This reflects both agent 'memory' considerations and 'skip' logic.
|
244
|
-
The 'textify' parameter is set to True, so that the question names are returned as strings rather than integer indices.
|
538
|
+
yield result
|
245
539
|
|
246
|
-
|
247
|
-
>>> i.dag == {'q2': {'q0'}, 'q1': {'q0'}}
|
248
|
-
True
|
249
|
-
"""
|
250
|
-
return self.survey.dag(textify=True)
|
540
|
+
# endregion
|
251
541
|
|
252
|
-
|
253
|
-
# Dunder methods
|
254
|
-
#######################
|
542
|
+
# region: Magic methods
|
255
543
|
def __repr__(self) -> str:
|
256
544
|
"""Return a string representation of the Interview instance."""
|
257
545
|
return f"Interview(agent = {repr(self.agent)}, survey = {repr(self.survey)}, scenario = {repr(self.scenario)}, model = {repr(self.model)})"
|
@@ -1,74 +1,26 @@
|
|
1
|
-
import traceback
|
2
|
-
import datetime
|
3
|
-
import time
|
4
1
|
from collections import UserDict
|
5
2
|
|
6
3
|
from edsl.jobs.interviews.InterviewExceptionEntry import InterviewExceptionEntry
|
7
4
|
|
8
|
-
# #traceback=traceback.format_exc(),
|
9
|
-
# #traceback = frame_summary_to_dict(traceback.extract_tb(e.__traceback__))
|
10
|
-
# #traceback = [frame_summary_to_dict(f) for f in traceback.extract_tb(e.__traceback__)]
|
11
5
|
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
# >>> entry = InterviewExceptionEntry.example()
|
16
|
-
# >>> entry.to_dict()['exception']
|
17
|
-
# "ValueError('An error occurred.')"
|
18
|
-
# """
|
19
|
-
|
20
|
-
# def __init__(self, exception: Exception):
|
21
|
-
# self.time = datetime.datetime.now().isoformat()
|
22
|
-
# self.exception = exception
|
23
|
-
|
24
|
-
# def __getitem__(self, key):
|
25
|
-
# # Support dict-like access obj['a']
|
26
|
-
# return str(getattr(self, key))
|
27
|
-
|
28
|
-
# @classmethod
|
29
|
-
# def example(cls):
|
30
|
-
# try:
|
31
|
-
# raise ValueError("An error occurred.")
|
32
|
-
# except Exception as e:
|
33
|
-
# entry = InterviewExceptionEntry(e)
|
34
|
-
# return entry
|
35
|
-
|
36
|
-
# @property
|
37
|
-
# def traceback(self):
|
38
|
-
# """Return the exception as HTML."""
|
39
|
-
# e = self.exception
|
40
|
-
# tb_str = ''.join(traceback.format_exception(type(e), e, e.__traceback__))
|
41
|
-
# return tb_str
|
42
|
-
|
43
|
-
|
44
|
-
# @property
|
45
|
-
# def html(self):
|
46
|
-
# from rich.console import Console
|
47
|
-
# from rich.table import Table
|
48
|
-
# from rich.traceback import Traceback
|
49
|
-
|
50
|
-
# from io import StringIO
|
51
|
-
# html_output = StringIO()
|
52
|
-
|
53
|
-
# console = Console(file=html_output, record=True)
|
54
|
-
# tb = Traceback(show_locals=True)
|
55
|
-
# console.print(tb)
|
6
|
+
class InterviewExceptionCollection(UserDict):
|
7
|
+
"""A collection of exceptions that occurred during the interview."""
|
56
8
|
|
57
|
-
|
58
|
-
|
59
|
-
|
9
|
+
def __init__(self):
|
10
|
+
super().__init__()
|
11
|
+
self.fixed = set()
|
60
12
|
|
61
|
-
|
62
|
-
|
63
|
-
|
64
|
-
# 'exception': repr(self.exception),
|
65
|
-
# 'time': self.time,
|
66
|
-
# 'traceback': self.traceback
|
67
|
-
# }
|
13
|
+
def unfixed_exceptions(self) -> list:
|
14
|
+
"""Return a list of unfixed exceptions."""
|
15
|
+
return {k: v for k, v in self.data.items() if k not in self.fixed}
|
68
16
|
|
17
|
+
def num_unfixed(self) -> list:
|
18
|
+
"""Return a list of unfixed questions."""
|
19
|
+
return len([k for k in self.data.keys() if k not in self.fixed])
|
69
20
|
|
70
|
-
|
71
|
-
|
21
|
+
def record_fixed_question(self, question_name: str) -> None:
|
22
|
+
"""Record that a question has been fixed."""
|
23
|
+
self.fixed.add(question_name)
|
72
24
|
|
73
25
|
def add(self, question_name: str, entry: InterviewExceptionEntry) -> None:
|
74
26
|
"""Add an exception entry to the collection."""
|
@@ -80,12 +32,6 @@ class InterviewExceptionCollection(UserDict):
|
|
80
32
|
def to_dict(self, include_traceback=True) -> dict:
|
81
33
|
"""Return the collection of exceptions as a dictionary."""
|
82
34
|
newdata = {k: [e.to_dict() for e in v] for k, v in self.data.items()}
|
83
|
-
# if not include_traceback:
|
84
|
-
# for question in newdata:
|
85
|
-
# for exception in newdata[question]:
|
86
|
-
# exception[
|
87
|
-
# "traceback"
|
88
|
-
# ] = "Traceback removed. Set include_traceback=True to include."
|
89
35
|
return newdata
|
90
36
|
|
91
37
|
def _repr_html_(self) -> str:
|