edsl 0.1.31.dev4__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 +136 -221
- edsl/agents/InvigilatorBase.py +148 -59
- edsl/agents/{PromptConstructionMixin.py → PromptConstructor.py} +154 -85
- 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 +48 -47
- edsl/conjure/Conjure.py +6 -0
- edsl/coop/PriceFetcher.py +58 -0
- edsl/coop/coop.py +50 -7
- edsl/data/Cache.py +35 -1
- edsl/data/CacheHandler.py +3 -4
- edsl/data_transfer_models.py +73 -38
- edsl/enums.py +8 -0
- edsl/exceptions/general.py +10 -8
- 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 +112 -0
- edsl/inference_services/AzureAI.py +214 -0
- edsl/inference_services/DeepInfraService.py +4 -3
- edsl/inference_services/GoogleService.py +16 -12
- edsl/inference_services/GroqService.py +5 -4
- edsl/inference_services/InferenceServiceABC.py +58 -3
- edsl/inference_services/InferenceServicesCollection.py +13 -8
- edsl/inference_services/MistralAIService.py +120 -0
- edsl/inference_services/OllamaService.py +18 -0
- edsl/inference_services/OpenAIService.py +55 -56
- edsl/inference_services/TestService.py +80 -0
- edsl/inference_services/TogetherAIService.py +170 -0
- edsl/inference_services/models_available_cache.py +25 -0
- edsl/inference_services/registry.py +19 -1
- edsl/jobs/Answers.py +10 -12
- edsl/jobs/FailedQuestion.py +78 -0
- edsl/jobs/Jobs.py +137 -41
- edsl/jobs/buckets/BucketCollection.py +24 -15
- edsl/jobs/buckets/TokenBucket.py +105 -18
- edsl/jobs/interviews/Interview.py +393 -83
- edsl/jobs/interviews/{interview_exception_tracking.py → InterviewExceptionCollection.py} +22 -18
- edsl/jobs/interviews/InterviewExceptionEntry.py +167 -0
- edsl/jobs/runners/JobsRunnerAsyncio.py +152 -160
- edsl/jobs/runners/JobsRunnerStatus.py +331 -0
- edsl/jobs/tasks/QuestionTaskCreator.py +30 -23
- edsl/jobs/tasks/TaskCreators.py +1 -1
- edsl/jobs/tasks/TaskHistory.py +205 -126
- edsl/language_models/LanguageModel.py +297 -177
- 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 +25 -8
- 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 -42
- edsl/questions/QuestionCheckBox.py +227 -36
- edsl/questions/QuestionExtract.py +98 -28
- edsl/questions/QuestionFreeText.py +47 -31
- edsl/questions/QuestionFunctional.py +7 -0
- edsl/questions/QuestionList.py +141 -23
- edsl/questions/QuestionMultipleChoice.py +159 -66
- edsl/questions/QuestionNumerical.py +88 -47
- edsl/questions/QuestionRank.py +182 -25
- 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 +58 -30
- 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 +109 -24
- edsl/scenarios/ScenarioImageMixin.py +2 -2
- edsl/scenarios/ScenarioList.py +546 -21
- edsl/scenarios/ScenarioListExportMixin.py +24 -4
- edsl/scenarios/ScenarioListPdfMixin.py +153 -4
- edsl/study/SnapShot.py +8 -1
- edsl/study/Study.py +32 -0
- edsl/surveys/Rule.py +15 -3
- edsl/surveys/RuleCollection.py +21 -5
- edsl/surveys/Survey.py +707 -298
- edsl/surveys/SurveyExportMixin.py +71 -9
- edsl/surveys/SurveyFlowVisualizationMixin.py +2 -1
- edsl/surveys/SurveyQualtricsImport.py +284 -0
- 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 +40 -1
- {edsl-0.1.31.dev4.dist-info → edsl-0.1.33.dist-info}/METADATA +8 -2
- edsl-0.1.33.dist-info/RECORD +295 -0
- edsl/jobs/interviews/InterviewTaskBuildingMixin.py +0 -271
- edsl/jobs/interviews/retry_management.py +0 -37
- edsl/jobs/runners/JobsRunnerStatusMixin.py +0 -303
- edsl/utilities/gcp_bucket/simple_example.py +0 -9
- edsl-0.1.31.dev4.dist-info/RECORD +0 -204
- {edsl-0.1.31.dev4.dist-info → edsl-0.1.33.dist-info}/LICENSE +0 -0
- {edsl-0.1.31.dev4.dist-info → edsl-0.1.33.dist-info}/WHEEL +0 -0
@@ -1,49 +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
|
-
InterviewExceptionEntry,
|
18
28
|
)
|
19
|
-
|
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,
|
72
|
+
skip_retry: bool = False,
|
73
|
+
raise_validation_errors: bool = True,
|
47
74
|
):
|
48
75
|
"""Initialize the Interview instance.
|
49
76
|
|
@@ -83,10 +110,15 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
83
110
|
] = Answers() # will get filled in as interview progresses
|
84
111
|
self.sidecar_model = sidecar_model
|
85
112
|
|
113
|
+
# self.stop_on_exception = False
|
114
|
+
|
86
115
|
# Trackers
|
87
116
|
self.task_creators = TaskCreators() # tracks the task creators
|
88
117
|
self.exceptions = InterviewExceptionCollection()
|
118
|
+
|
89
119
|
self._task_status_log_dict = InterviewStatusLog()
|
120
|
+
self.skip_retry = skip_retry
|
121
|
+
self.raise_validation_errors = raise_validation_errors
|
90
122
|
|
91
123
|
# dictionary mapping question names to their index in the survey.
|
92
124
|
self.to_index = {
|
@@ -94,13 +126,328 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
94
126
|
for index, question_name in enumerate(self.survey.question_names)
|
95
127
|
}
|
96
128
|
|
97
|
-
|
129
|
+
self.failed_questions = []
|
130
|
+
|
131
|
+
# region: Serialization
|
132
|
+
def _to_dict(self, include_exceptions=False) -> dict[str, Any]:
|
133
|
+
"""Return a dictionary representation of the Interview instance.
|
134
|
+
This is just for hashing purposes.
|
135
|
+
|
136
|
+
>>> i = Interview.example()
|
137
|
+
>>> hash(i)
|
138
|
+
1646262796627658719
|
139
|
+
"""
|
140
|
+
d = {
|
141
|
+
"agent": self.agent._to_dict(),
|
142
|
+
"survey": self.survey._to_dict(),
|
143
|
+
"scenario": self.scenario._to_dict(),
|
144
|
+
"model": self.model._to_dict(),
|
145
|
+
"iteration": self.iteration,
|
146
|
+
"exceptions": {},
|
147
|
+
}
|
148
|
+
if include_exceptions:
|
149
|
+
d["exceptions"] = self.exceptions.to_dict()
|
150
|
+
|
151
|
+
def __hash__(self) -> int:
|
152
|
+
from edsl.utilities.utilities import dict_hash
|
153
|
+
|
154
|
+
return dict_hash(self._to_dict())
|
155
|
+
|
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(
|
98
214
|
self,
|
99
215
|
*,
|
100
|
-
|
101
|
-
|
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(
|
264
|
+
self,
|
265
|
+
*,
|
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,
|
102
448
|
stop_on_exception: bool = False,
|
103
449
|
sidecar_model: Optional["LanguageModel"] = None,
|
450
|
+
raise_validation_errors: bool = True,
|
104
451
|
) -> tuple["Answers", List[dict[str, Any]]]:
|
105
452
|
"""
|
106
453
|
Conduct an Interview asynchronously.
|
@@ -120,22 +467,8 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
120
467
|
|
121
468
|
>>> i = Interview.example(throw_exception = True)
|
122
469
|
>>> result, _ = asyncio.run(i.async_conduct_interview())
|
123
|
-
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.
|
124
|
-
<BLANKLINE>
|
125
|
-
<BLANKLINE>
|
126
|
-
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.
|
127
|
-
<BLANKLINE>
|
128
|
-
<BLANKLINE>
|
129
|
-
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.
|
130
|
-
<BLANKLINE>
|
131
|
-
<BLANKLINE>
|
132
|
-
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.
|
133
|
-
<BLANKLINE>
|
134
|
-
<BLANKLINE>
|
135
|
-
|
136
470
|
>>> i.exceptions
|
137
|
-
{'q0':
|
138
|
-
|
471
|
+
{'q0': ...
|
139
472
|
>>> i = Interview.example()
|
140
473
|
>>> result, _ = asyncio.run(i.async_conduct_interview(stop_on_exception = True))
|
141
474
|
Traceback (most recent call last):
|
@@ -143,26 +476,30 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
143
476
|
asyncio.exceptions.CancelledError
|
144
477
|
"""
|
145
478
|
self.sidecar_model = sidecar_model
|
479
|
+
self.stop_on_exception = stop_on_exception
|
146
480
|
|
147
481
|
# if no model bucket is passed, create an 'infinity' bucket with no rate limits
|
148
482
|
if model_buckets is None or hasattr(self.agent, "answer_question_directly"):
|
149
483
|
model_buckets = ModelBuckets.infinity_bucket()
|
150
484
|
|
151
|
-
## build the tasks using the InterviewTaskBuildingMixin
|
152
485
|
## This is the key part---it creates a task for each question,
|
153
486
|
## with dependencies on the questions that must be answered before this one can be answered.
|
154
|
-
self.tasks = self._build_question_tasks(
|
155
|
-
debug=debug, model_buckets=model_buckets
|
156
|
-
)
|
487
|
+
self.tasks = self._build_question_tasks(model_buckets=model_buckets)
|
157
488
|
|
158
489
|
## 'Invigilators' are used to administer the survey
|
159
|
-
self.invigilators =
|
160
|
-
|
161
|
-
|
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)
|
162
496
|
self.answers.replace_missing_answers_with_none(self.survey)
|
163
497
|
valid_results = list(self._extract_valid_results())
|
164
498
|
return self.answers, valid_results
|
165
499
|
|
500
|
+
# endregion
|
501
|
+
|
502
|
+
# region: Extracting results and recording errors
|
166
503
|
def _extract_valid_results(self) -> Generator["Answers", None, None]:
|
167
504
|
"""Extract the valid results from the list of results.
|
168
505
|
|
@@ -175,8 +512,6 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
175
512
|
>>> results = list(i._extract_valid_results())
|
176
513
|
>>> len(results) == len(i.survey)
|
177
514
|
True
|
178
|
-
>>> type(results[0])
|
179
|
-
<class 'edsl.data_transfer_models.AgentResponseDict'>
|
180
515
|
"""
|
181
516
|
assert len(self.tasks) == len(self.invigilators)
|
182
517
|
|
@@ -187,50 +522,24 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
187
522
|
try:
|
188
523
|
result = task.result()
|
189
524
|
except asyncio.CancelledError as e: # task was cancelled
|
190
|
-
result = invigilator.get_failed_task_result(
|
525
|
+
result = invigilator.get_failed_task_result(
|
526
|
+
failure_reason="Task was cancelled."
|
527
|
+
)
|
191
528
|
except Exception as e: # any other kind of exception in the task
|
192
|
-
result = invigilator.get_failed_task_result(
|
193
|
-
|
194
|
-
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
|
199
|
-
|
200
|
-
|
201
|
-
>>> i = Interview.example()
|
202
|
-
>>> result, _ = asyncio.run(i.async_conduct_interview())
|
203
|
-
>>> i.exceptions
|
204
|
-
{}
|
205
|
-
>>> i._record_exception(i.tasks[0], Exception("An exception occurred."))
|
206
|
-
>>> i.exceptions
|
207
|
-
{'q0': [{'exception': "Exception('An exception occurred.')", 'time': ..., 'traceback': 'NoneType: None\\n'}]}
|
208
|
-
"""
|
209
|
-
exception_entry = InterviewExceptionEntry(
|
210
|
-
exception=repr(exception),
|
211
|
-
time=time.time(),
|
212
|
-
traceback=traceback.format_exc(),
|
213
|
-
)
|
214
|
-
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)
|
215
537
|
|
216
|
-
|
217
|
-
def dag(self) -> "DAG":
|
218
|
-
"""Return the directed acyclic graph for the survey.
|
219
|
-
|
220
|
-
The DAG, or directed acyclic graph, is a dictionary that maps question names to their dependencies.
|
221
|
-
It is used to determine the order in which questions should be answered.
|
222
|
-
This reflects both agent 'memory' considerations and 'skip' logic.
|
223
|
-
The 'textify' parameter is set to True, so that the question names are returned as strings rather than integer indices.
|
538
|
+
yield result
|
224
539
|
|
225
|
-
|
226
|
-
>>> i.dag == {'q2': {'q0'}, 'q1': {'q0'}}
|
227
|
-
True
|
228
|
-
"""
|
229
|
-
return self.survey.dag(textify=True)
|
540
|
+
# endregion
|
230
541
|
|
231
|
-
|
232
|
-
# Dunder methods
|
233
|
-
#######################
|
542
|
+
# region: Magic methods
|
234
543
|
def __repr__(self) -> str:
|
235
544
|
"""Return a string representation of the Interview instance."""
|
236
545
|
return f"Interview(agent = {repr(self.agent)}, survey = {repr(self.survey)}, scenario = {repr(self.scenario)}, model = {repr(self.model)})"
|
@@ -251,6 +560,7 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
|
|
251
560
|
model=self.model,
|
252
561
|
iteration=iteration,
|
253
562
|
cache=cache,
|
563
|
+
skip_retry=self.skip_retry,
|
254
564
|
)
|
255
565
|
|
256
566
|
@classmethod
|
@@ -1,22 +1,26 @@
|
|
1
|
-
from rich.console import Console
|
2
|
-
from rich.table import Table
|
3
1
|
from collections import UserDict
|
4
2
|
|
3
|
+
from edsl.jobs.interviews.InterviewExceptionEntry import InterviewExceptionEntry
|
5
4
|
|
6
|
-
class InterviewExceptionEntry(UserDict):
|
7
|
-
"""Class to record an exception that occurred during the interview."""
|
8
5
|
|
9
|
-
|
10
|
-
|
11
|
-
super().__init__(data)
|
6
|
+
class InterviewExceptionCollection(UserDict):
|
7
|
+
"""A collection of exceptions that occurred during the interview."""
|
12
8
|
|
13
|
-
def
|
14
|
-
|
15
|
-
|
9
|
+
def __init__(self):
|
10
|
+
super().__init__()
|
11
|
+
self.fixed = set()
|
16
12
|
|
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}
|
17
16
|
|
18
|
-
|
19
|
-
|
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])
|
20
|
+
|
21
|
+
def record_fixed_question(self, question_name: str) -> None:
|
22
|
+
"""Record that a question has been fixed."""
|
23
|
+
self.fixed.add(question_name)
|
20
24
|
|
21
25
|
def add(self, question_name: str, entry: InterviewExceptionEntry) -> None:
|
22
26
|
"""Add an exception entry to the collection."""
|
@@ -28,12 +32,6 @@ class InterviewExceptionCollection(UserDict):
|
|
28
32
|
def to_dict(self, include_traceback=True) -> dict:
|
29
33
|
"""Return the collection of exceptions as a dictionary."""
|
30
34
|
newdata = {k: [e.to_dict() for e in v] for k, v in self.data.items()}
|
31
|
-
# if not include_traceback:
|
32
|
-
# for question in newdata:
|
33
|
-
# for exception in newdata[question]:
|
34
|
-
# exception[
|
35
|
-
# "traceback"
|
36
|
-
# ] = "Traceback removed. Set include_traceback=True to include."
|
37
35
|
return newdata
|
38
36
|
|
39
37
|
def _repr_html_(self) -> str:
|
@@ -84,3 +82,9 @@ class InterviewExceptionCollection(UserDict):
|
|
84
82
|
)
|
85
83
|
|
86
84
|
console.print(table)
|
85
|
+
|
86
|
+
|
87
|
+
if __name__ == "__main__":
|
88
|
+
import doctest
|
89
|
+
|
90
|
+
doctest.testmod(optionflags=doctest.ELLIPSIS)
|