edsl 0.1.39__py3-none-any.whl → 0.1.39.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 +116 -197
- edsl/__init__.py +7 -15
- edsl/__version__.py +1 -1
- edsl/agents/Agent.py +147 -351
- edsl/agents/AgentList.py +73 -211
- edsl/agents/Invigilator.py +50 -101
- edsl/agents/InvigilatorBase.py +70 -62
- edsl/agents/PromptConstructor.py +225 -143
- edsl/agents/__init__.py +1 -0
- edsl/agents/prompt_helpers.py +3 -3
- edsl/auto/AutoStudy.py +5 -18
- edsl/auto/StageBase.py +40 -53
- edsl/auto/StageQuestions.py +1 -2
- edsl/auto/utilities.py +6 -0
- edsl/config.py +2 -22
- edsl/conversation/car_buying.py +1 -2
- edsl/coop/PriceFetcher.py +1 -1
- edsl/coop/coop.py +47 -125
- edsl/coop/utils.py +14 -14
- edsl/data/Cache.py +27 -45
- edsl/data/CacheEntry.py +15 -12
- edsl/data/CacheHandler.py +12 -31
- edsl/data/RemoteCacheSync.py +46 -154
- edsl/data/__init__.py +3 -4
- edsl/data_transfer_models.py +1 -2
- edsl/enums.py +0 -27
- edsl/exceptions/__init__.py +50 -50
- edsl/exceptions/agents.py +0 -12
- edsl/exceptions/questions.py +6 -24
- edsl/exceptions/scenarios.py +0 -7
- edsl/inference_services/AnthropicService.py +19 -38
- edsl/inference_services/AwsBedrock.py +2 -0
- edsl/inference_services/AzureAI.py +2 -0
- edsl/inference_services/GoogleService.py +12 -7
- edsl/inference_services/InferenceServiceABC.py +85 -18
- edsl/inference_services/InferenceServicesCollection.py +79 -120
- edsl/inference_services/MistralAIService.py +3 -0
- edsl/inference_services/OpenAIService.py +35 -47
- edsl/inference_services/PerplexityService.py +3 -0
- edsl/inference_services/TestService.py +10 -11
- edsl/inference_services/TogetherAIService.py +3 -5
- edsl/jobs/Answers.py +14 -1
- edsl/jobs/Jobs.py +431 -356
- edsl/jobs/JobsChecks.py +10 -35
- edsl/jobs/JobsPrompts.py +4 -6
- edsl/jobs/JobsRemoteInferenceHandler.py +133 -205
- edsl/jobs/buckets/BucketCollection.py +3 -44
- edsl/jobs/buckets/TokenBucket.py +21 -53
- edsl/jobs/interviews/Interview.py +408 -143
- edsl/jobs/runners/JobsRunnerAsyncio.py +403 -88
- edsl/jobs/runners/JobsRunnerStatus.py +165 -133
- edsl/jobs/tasks/QuestionTaskCreator.py +19 -21
- edsl/jobs/tasks/TaskHistory.py +18 -38
- edsl/jobs/tasks/task_status_enum.py +2 -0
- edsl/language_models/KeyLookup.py +30 -0
- edsl/language_models/LanguageModel.py +236 -194
- edsl/language_models/ModelList.py +19 -28
- edsl/language_models/__init__.py +2 -1
- edsl/language_models/registry.py +190 -0
- edsl/language_models/repair.py +2 -2
- edsl/language_models/unused/ReplicateBase.py +83 -0
- edsl/language_models/utilities.py +4 -5
- edsl/notebooks/Notebook.py +14 -19
- edsl/prompts/Prompt.py +39 -29
- edsl/questions/{answer_validator_mixin.py → AnswerValidatorMixin.py} +2 -47
- edsl/questions/QuestionBase.py +214 -68
- edsl/questions/{question_base_gen_mixin.py → QuestionBaseGenMixin.py} +50 -57
- edsl/questions/QuestionBasePromptsMixin.py +3 -7
- edsl/questions/QuestionBudget.py +1 -1
- edsl/questions/QuestionCheckBox.py +3 -3
- edsl/questions/QuestionExtract.py +7 -5
- edsl/questions/QuestionFreeText.py +3 -2
- edsl/questions/QuestionList.py +18 -10
- edsl/questions/QuestionMultipleChoice.py +23 -67
- edsl/questions/QuestionNumerical.py +4 -2
- edsl/questions/QuestionRank.py +17 -7
- edsl/questions/{response_validator_abc.py → ResponseValidatorABC.py} +26 -40
- edsl/questions/SimpleAskMixin.py +3 -4
- edsl/questions/__init__.py +1 -2
- edsl/questions/derived/QuestionLinearScale.py +3 -6
- edsl/questions/derived/QuestionTopK.py +1 -1
- edsl/questions/descriptors.py +3 -17
- edsl/questions/question_registry.py +1 -1
- edsl/results/CSSParameterizer.py +1 -1
- edsl/results/Dataset.py +7 -170
- edsl/results/DatasetExportMixin.py +305 -168
- edsl/results/DatasetTree.py +8 -28
- edsl/results/Result.py +206 -298
- edsl/results/Results.py +131 -149
- edsl/results/ResultsDBMixin.py +238 -0
- edsl/results/ResultsExportMixin.py +0 -2
- edsl/results/{results_selector.py → Selector.py} +13 -23
- edsl/results/TableDisplay.py +171 -98
- edsl/results/__init__.py +1 -1
- edsl/scenarios/FileStore.py +239 -150
- edsl/scenarios/Scenario.py +193 -90
- edsl/scenarios/ScenarioHtmlMixin.py +3 -4
- edsl/scenarios/{scenario_join.py → ScenarioJoin.py} +6 -10
- edsl/scenarios/ScenarioList.py +244 -415
- edsl/scenarios/ScenarioListExportMixin.py +7 -0
- edsl/scenarios/ScenarioListPdfMixin.py +37 -15
- edsl/scenarios/__init__.py +2 -1
- edsl/study/ObjectEntry.py +1 -1
- edsl/study/SnapShot.py +1 -1
- edsl/study/Study.py +12 -5
- edsl/surveys/Rule.py +4 -5
- edsl/surveys/RuleCollection.py +27 -25
- edsl/surveys/Survey.py +791 -270
- edsl/surveys/SurveyCSS.py +8 -20
- edsl/surveys/{SurveyFlowVisualization.py → SurveyFlowVisualizationMixin.py} +9 -11
- edsl/surveys/__init__.py +2 -4
- edsl/surveys/descriptors.py +2 -6
- edsl/surveys/instructions/ChangeInstruction.py +2 -1
- edsl/surveys/instructions/Instruction.py +13 -4
- edsl/surveys/instructions/InstructionCollection.py +6 -11
- edsl/templates/error_reporting/interview_details.html +1 -1
- edsl/templates/error_reporting/report.html +1 -1
- edsl/tools/plotting.py +1 -1
- edsl/utilities/utilities.py +23 -35
- {edsl-0.1.39.dist-info → edsl-0.1.39.dev1.dist-info}/METADATA +10 -12
- edsl-0.1.39.dev1.dist-info/RECORD +277 -0
- {edsl-0.1.39.dist-info → edsl-0.1.39.dev1.dist-info}/WHEEL +1 -1
- edsl/agents/QuestionInstructionPromptBuilder.py +0 -128
- edsl/agents/QuestionTemplateReplacementsBuilder.py +0 -137
- edsl/agents/question_option_processor.py +0 -172
- edsl/coop/CoopFunctionsMixin.py +0 -15
- edsl/coop/ExpectedParrotKeyHandler.py +0 -125
- edsl/exceptions/inference_services.py +0 -5
- edsl/inference_services/AvailableModelCacheHandler.py +0 -184
- edsl/inference_services/AvailableModelFetcher.py +0 -215
- edsl/inference_services/ServiceAvailability.py +0 -135
- edsl/inference_services/data_structures.py +0 -134
- edsl/jobs/AnswerQuestionFunctionConstructor.py +0 -223
- edsl/jobs/FetchInvigilator.py +0 -47
- edsl/jobs/InterviewTaskManager.py +0 -98
- edsl/jobs/InterviewsConstructor.py +0 -50
- edsl/jobs/JobsComponentConstructor.py +0 -189
- edsl/jobs/JobsRemoteInferenceLogger.py +0 -239
- edsl/jobs/RequestTokenEstimator.py +0 -30
- edsl/jobs/async_interview_runner.py +0 -138
- edsl/jobs/buckets/TokenBucketAPI.py +0 -211
- edsl/jobs/buckets/TokenBucketClient.py +0 -191
- edsl/jobs/check_survey_scenario_compatibility.py +0 -85
- edsl/jobs/data_structures.py +0 -120
- edsl/jobs/decorators.py +0 -35
- edsl/jobs/jobs_status_enums.py +0 -9
- edsl/jobs/loggers/HTMLTableJobLogger.py +0 -304
- edsl/jobs/results_exceptions_handler.py +0 -98
- edsl/language_models/ComputeCost.py +0 -63
- edsl/language_models/PriceManager.py +0 -127
- edsl/language_models/RawResponseHandler.py +0 -106
- edsl/language_models/ServiceDataSources.py +0 -0
- edsl/language_models/key_management/KeyLookup.py +0 -63
- edsl/language_models/key_management/KeyLookupBuilder.py +0 -273
- edsl/language_models/key_management/KeyLookupCollection.py +0 -38
- edsl/language_models/key_management/__init__.py +0 -0
- edsl/language_models/key_management/models.py +0 -131
- edsl/language_models/model.py +0 -256
- edsl/notebooks/NotebookToLaTeX.py +0 -142
- edsl/questions/ExceptionExplainer.py +0 -77
- edsl/questions/HTMLQuestion.py +0 -103
- edsl/questions/QuestionMatrix.py +0 -265
- edsl/questions/data_structures.py +0 -20
- edsl/questions/loop_processor.py +0 -149
- edsl/questions/response_validator_factory.py +0 -34
- edsl/questions/templates/matrix/__init__.py +0 -1
- edsl/questions/templates/matrix/answering_instructions.jinja +0 -5
- edsl/questions/templates/matrix/question_presentation.jinja +0 -20
- edsl/results/MarkdownToDocx.py +0 -122
- edsl/results/MarkdownToPDF.py +0 -111
- edsl/results/TextEditor.py +0 -50
- edsl/results/file_exports.py +0 -252
- edsl/results/smart_objects.py +0 -96
- edsl/results/table_data_class.py +0 -12
- edsl/results/table_renderers.py +0 -118
- edsl/scenarios/ConstructDownloadLink.py +0 -109
- edsl/scenarios/DocumentChunker.py +0 -102
- edsl/scenarios/DocxScenario.py +0 -16
- edsl/scenarios/PdfExtractor.py +0 -40
- edsl/scenarios/directory_scanner.py +0 -96
- edsl/scenarios/file_methods.py +0 -85
- edsl/scenarios/handlers/__init__.py +0 -13
- edsl/scenarios/handlers/csv.py +0 -49
- edsl/scenarios/handlers/docx.py +0 -76
- edsl/scenarios/handlers/html.py +0 -37
- edsl/scenarios/handlers/json.py +0 -111
- edsl/scenarios/handlers/latex.py +0 -5
- edsl/scenarios/handlers/md.py +0 -51
- edsl/scenarios/handlers/pdf.py +0 -68
- edsl/scenarios/handlers/png.py +0 -39
- edsl/scenarios/handlers/pptx.py +0 -105
- edsl/scenarios/handlers/py.py +0 -294
- edsl/scenarios/handlers/sql.py +0 -313
- edsl/scenarios/handlers/sqlite.py +0 -149
- edsl/scenarios/handlers/txt.py +0 -33
- edsl/scenarios/scenario_selector.py +0 -156
- edsl/surveys/ConstructDAG.py +0 -92
- edsl/surveys/EditSurvey.py +0 -221
- edsl/surveys/InstructionHandler.py +0 -100
- edsl/surveys/MemoryManagement.py +0 -72
- edsl/surveys/RuleManager.py +0 -172
- edsl/surveys/Simulator.py +0 -75
- edsl/surveys/SurveyToApp.py +0 -141
- edsl/utilities/PrettyList.py +0 -56
- edsl/utilities/is_notebook.py +0 -18
- edsl/utilities/is_valid_variable_name.py +0 -11
- edsl/utilities/remove_edsl_version.py +0 -24
- edsl-0.1.39.dist-info/RECORD +0 -358
- /edsl/questions/{register_questions_meta.py → RegisterQuestionsMeta.py} +0 -0
- /edsl/results/{results_fetch_mixin.py → ResultsFetchMixin.py} +0 -0
- /edsl/results/{results_tools_mixin.py → ResultsToolsMixin.py} +0 -0
- {edsl-0.1.39.dist-info → edsl-0.1.39.dev1.dist-info}/LICENSE +0 -0
@@ -3,17 +3,31 @@ import time
|
|
3
3
|
import asyncio
|
4
4
|
import threading
|
5
5
|
import warnings
|
6
|
-
from typing import
|
6
|
+
from typing import Coroutine, List, AsyncGenerator, Optional, Union, Generator, Type
|
7
|
+
from uuid import UUID
|
8
|
+
from collections import UserList
|
7
9
|
|
8
10
|
from edsl.results.Results import Results
|
9
|
-
from edsl.jobs.
|
11
|
+
from edsl.jobs.interviews.Interview import Interview
|
12
|
+
from edsl.jobs.runners.JobsRunnerStatus import JobsRunnerStatus, JobsRunnerStatusBase
|
13
|
+
|
10
14
|
from edsl.jobs.tasks.TaskHistory import TaskHistory
|
15
|
+
from edsl.jobs.buckets.BucketCollection import BucketCollection
|
11
16
|
from edsl.utilities.decorators import jupyter_nb_handler
|
12
|
-
from edsl.
|
13
|
-
from edsl.
|
17
|
+
from edsl.data.Cache import Cache
|
18
|
+
from edsl.results.Result import Result
|
19
|
+
from edsl.results.Results import Results
|
20
|
+
from edsl.language_models.LanguageModel import LanguageModel
|
21
|
+
from edsl.data.Cache import Cache
|
22
|
+
|
14
23
|
|
15
|
-
|
16
|
-
|
24
|
+
class StatusTracker(UserList):
|
25
|
+
def __init__(self, total_tasks: int):
|
26
|
+
self.total_tasks = total_tasks
|
27
|
+
super().__init__()
|
28
|
+
|
29
|
+
def current_status(self):
|
30
|
+
return print(f"Completed: {len(self.data)} of {self.total_tasks}", end="\r")
|
17
31
|
|
18
32
|
|
19
33
|
class JobsRunnerAsyncio:
|
@@ -23,129 +37,430 @@ class JobsRunnerAsyncio:
|
|
23
37
|
The Jobs object is a collection of interviews that are to be run.
|
24
38
|
"""
|
25
39
|
|
26
|
-
|
40
|
+
MAX_CONCURRENT_DEFAULT = 500
|
41
|
+
|
42
|
+
def __init__(self, jobs: "Jobs"):
|
27
43
|
self.jobs = jobs
|
28
|
-
self.
|
44
|
+
self.interviews: List["Interview"] = jobs.interviews()
|
45
|
+
self.bucket_collection: "BucketCollection" = jobs.bucket_collection
|
46
|
+
self.total_interviews: List["Interview"] = []
|
47
|
+
self._initialized = threading.Event()
|
29
48
|
|
30
|
-
|
31
|
-
return len(self.jobs)
|
49
|
+
from edsl.config import CONFIG
|
32
50
|
|
33
|
-
|
34
|
-
"
|
51
|
+
self.MAX_CONCURRENT = int(CONFIG.get("EDSL_MAX_CONCURRENT_TASKS"))
|
52
|
+
# print(f"MAX_CONCURRENT: {self.MAX_CONCURRENT}")
|
35
53
|
|
36
|
-
|
37
|
-
|
38
|
-
|
54
|
+
# async def run_async_generator(
|
55
|
+
# self,
|
56
|
+
# cache: Cache,
|
57
|
+
# n: int = 1,
|
58
|
+
# stop_on_exception: bool = False,
|
59
|
+
# sidecar_model: Optional[LanguageModel] = None,
|
60
|
+
# total_interviews: Optional[List["Interview"]] = None,
|
61
|
+
# raise_validation_errors: bool = False,
|
62
|
+
# ) -> AsyncGenerator["Result", None]:
|
63
|
+
# """Creates the tasks, runs them asynchronously, and returns the results as a Results object.
|
39
64
|
|
40
|
-
|
41
|
-
result_generator = AsyncInterviewRunner(self.jobs, run_config)
|
65
|
+
# Completed tasks are yielded as they are completed.
|
42
66
|
|
43
|
-
|
44
|
-
|
45
|
-
|
67
|
+
# :param n: how many times to run each interview
|
68
|
+
# :param stop_on_exception: Whether to stop the interview if an exception is raised
|
69
|
+
# :param sidecar_model: a language model to use in addition to the interview's model
|
70
|
+
# :param total_interviews: A list of interviews to run can be provided instead.
|
71
|
+
# :param raise_validation_errors: Whether to raise validation errors
|
72
|
+
# """
|
73
|
+
# tasks = []
|
74
|
+
# if total_interviews: # was already passed in total interviews
|
75
|
+
# self.total_interviews = total_interviews
|
76
|
+
# else:
|
77
|
+
# self.total_interviews = list(
|
78
|
+
# self._populate_total_interviews(n=n)
|
79
|
+
# ) # Populate self.total_interviews before creating tasks
|
80
|
+
# self._initialized.set() # Signal that we're ready
|
81
|
+
|
82
|
+
# for interview in self.total_interviews:
|
83
|
+
# interviewing_task = self._build_interview_task(
|
84
|
+
# interview=interview,
|
85
|
+
# stop_on_exception=stop_on_exception,
|
86
|
+
# sidecar_model=sidecar_model,
|
87
|
+
# raise_validation_errors=raise_validation_errors,
|
88
|
+
# )
|
89
|
+
# tasks.append(asyncio.create_task(interviewing_task))
|
90
|
+
|
91
|
+
# for task in asyncio.as_completed(tasks):
|
92
|
+
# result = await task
|
93
|
+
# self.jobs_runner_status.add_completed_interview(result)
|
94
|
+
# yield result
|
95
|
+
|
96
|
+
async def run_async_generator(
|
97
|
+
self,
|
98
|
+
cache: Cache,
|
99
|
+
n: int = 1,
|
100
|
+
stop_on_exception: bool = False,
|
101
|
+
sidecar_model: Optional[LanguageModel] = None,
|
102
|
+
total_interviews: Optional[List["Interview"]] = None,
|
103
|
+
raise_validation_errors: bool = False,
|
104
|
+
) -> AsyncGenerator["Result", None]:
|
105
|
+
"""Creates and processes tasks asynchronously, yielding results as they complete.
|
106
|
+
|
107
|
+
Tasks are created and processed in a streaming fashion rather than building the full list upfront.
|
108
|
+
Results are yielded as soon as they are available.
|
109
|
+
|
110
|
+
:param n: how many times to run each interview
|
111
|
+
:param stop_on_exception: Whether to stop the interview if an exception is raised
|
112
|
+
:param sidecar_model: a language model to use in addition to the interview's model
|
113
|
+
:param total_interviews: A list of interviews to run can be provided instead.
|
114
|
+
:param raise_validation_errors: Whether to raise validation errors
|
115
|
+
"""
|
116
|
+
# Initialize interviews iterator
|
117
|
+
if total_interviews:
|
118
|
+
interviews_iter = iter(total_interviews)
|
119
|
+
self.total_interviews = total_interviews
|
120
|
+
else:
|
121
|
+
interviews_iter = self._populate_total_interviews(n=n)
|
122
|
+
self.total_interviews = list(interviews_iter)
|
123
|
+
interviews_iter = iter(self.total_interviews) # Create fresh iterator
|
124
|
+
|
125
|
+
self._initialized.set() # Signal that we're ready
|
126
|
+
|
127
|
+
# Keep track of active tasks
|
128
|
+
active_tasks = set()
|
129
|
+
|
130
|
+
try:
|
131
|
+
while True:
|
132
|
+
# Add new tasks if we're below max_concurrent and there are more interviews
|
133
|
+
while len(active_tasks) < self.MAX_CONCURRENT:
|
134
|
+
try:
|
135
|
+
interview = next(interviews_iter)
|
136
|
+
task = asyncio.create_task(
|
137
|
+
self._build_interview_task(
|
138
|
+
interview=interview,
|
139
|
+
stop_on_exception=stop_on_exception,
|
140
|
+
sidecar_model=sidecar_model,
|
141
|
+
raise_validation_errors=raise_validation_errors,
|
142
|
+
)
|
143
|
+
)
|
144
|
+
active_tasks.add(task)
|
145
|
+
# Add callback to remove task from set when done
|
146
|
+
task.add_done_callback(active_tasks.discard)
|
147
|
+
except StopIteration:
|
148
|
+
break
|
149
|
+
|
150
|
+
if not active_tasks:
|
151
|
+
break
|
152
|
+
|
153
|
+
# Wait for next completed task
|
154
|
+
done, _ = await asyncio.wait(
|
155
|
+
active_tasks, return_when=asyncio.FIRST_COMPLETED
|
156
|
+
)
|
46
157
|
|
47
|
-
|
158
|
+
# Process completed tasks
|
159
|
+
for task in done:
|
160
|
+
try:
|
161
|
+
result = await task
|
162
|
+
self.jobs_runner_status.add_completed_interview(result)
|
163
|
+
yield result
|
164
|
+
except Exception as e:
|
165
|
+
if stop_on_exception:
|
166
|
+
# Cancel remaining tasks
|
167
|
+
for t in active_tasks:
|
168
|
+
if not t.done():
|
169
|
+
t.cancel()
|
170
|
+
raise
|
171
|
+
else:
|
172
|
+
# Log error and continue
|
173
|
+
# logger.error(f"Task failed with error: {e}")
|
174
|
+
continue
|
175
|
+
finally:
|
176
|
+
# Ensure we cancel any remaining tasks if we exit early
|
177
|
+
for task in active_tasks:
|
178
|
+
if not task.done():
|
179
|
+
task.cancel()
|
180
|
+
|
181
|
+
def _populate_total_interviews(
|
182
|
+
self, n: int = 1
|
183
|
+
) -> Generator["Interview", None, None]:
|
184
|
+
"""Populates self.total_interviews with n copies of each interview.
|
185
|
+
|
186
|
+
:param n: how many times to run each interview.
|
187
|
+
"""
|
188
|
+
for interview in self.interviews:
|
189
|
+
for iteration in range(n):
|
190
|
+
if iteration > 0:
|
191
|
+
yield interview.duplicate(iteration=iteration, cache=self.cache)
|
192
|
+
else:
|
193
|
+
interview.cache = self.cache
|
194
|
+
yield interview
|
195
|
+
|
196
|
+
async def run_async(self, cache: Optional[Cache] = None, n: int = 1) -> Results:
|
197
|
+
"""Used for some other modules that have a non-standard way of running interviews."""
|
198
|
+
self.jobs_runner_status = JobsRunnerStatus(self, n=n)
|
199
|
+
self.cache = Cache() if cache is None else cache
|
200
|
+
data = []
|
201
|
+
async for result in self.run_async_generator(cache=self.cache, n=n):
|
202
|
+
data.append(result)
|
203
|
+
return Results(survey=self.jobs.survey, data=data)
|
48
204
|
|
49
205
|
def simple_run(self):
|
50
206
|
data = asyncio.run(self.run_async())
|
51
207
|
return Results(survey=self.jobs.survey, data=data)
|
52
208
|
|
209
|
+
async def _build_interview_task(
|
210
|
+
self,
|
211
|
+
*,
|
212
|
+
interview: Interview,
|
213
|
+
stop_on_exception: bool = False,
|
214
|
+
sidecar_model: Optional["LanguageModel"] = None,
|
215
|
+
raise_validation_errors: bool = False,
|
216
|
+
) -> "Result":
|
217
|
+
"""Conducts an interview and returns the result.
|
218
|
+
|
219
|
+
:param interview: the interview to conduct
|
220
|
+
:param stop_on_exception: stops the interview if an exception is raised
|
221
|
+
:param sidecar_model: a language model to use in addition to the interview's model
|
222
|
+
"""
|
223
|
+
# the model buckets are used to track usage rates
|
224
|
+
model_buckets = self.bucket_collection[interview.model]
|
225
|
+
|
226
|
+
# get the results of the interview
|
227
|
+
answer, valid_results = await interview.async_conduct_interview(
|
228
|
+
model_buckets=model_buckets,
|
229
|
+
stop_on_exception=stop_on_exception,
|
230
|
+
sidecar_model=sidecar_model,
|
231
|
+
raise_validation_errors=raise_validation_errors,
|
232
|
+
)
|
233
|
+
|
234
|
+
question_results = {}
|
235
|
+
for result in valid_results:
|
236
|
+
question_results[result.question_name] = result
|
237
|
+
|
238
|
+
answer_key_names = list(question_results.keys())
|
239
|
+
|
240
|
+
generated_tokens_dict = {
|
241
|
+
k + "_generated_tokens": question_results[k].generated_tokens
|
242
|
+
for k in answer_key_names
|
243
|
+
}
|
244
|
+
comments_dict = {
|
245
|
+
k + "_comment": question_results[k].comment for k in answer_key_names
|
246
|
+
}
|
247
|
+
|
248
|
+
# we should have a valid result for each question
|
249
|
+
answer_dict = {k: answer[k] for k in answer_key_names}
|
250
|
+
assert len(valid_results) == len(answer_key_names)
|
251
|
+
|
252
|
+
# TODO: move this down into Interview
|
253
|
+
question_name_to_prompts = dict({})
|
254
|
+
for result in valid_results:
|
255
|
+
question_name = result.question_name
|
256
|
+
question_name_to_prompts[question_name] = {
|
257
|
+
"user_prompt": result.prompts["user_prompt"],
|
258
|
+
"system_prompt": result.prompts["system_prompt"],
|
259
|
+
}
|
260
|
+
|
261
|
+
prompt_dictionary = {}
|
262
|
+
for answer_key_name in answer_key_names:
|
263
|
+
prompt_dictionary[
|
264
|
+
answer_key_name + "_user_prompt"
|
265
|
+
] = question_name_to_prompts[answer_key_name]["user_prompt"]
|
266
|
+
prompt_dictionary[
|
267
|
+
answer_key_name + "_system_prompt"
|
268
|
+
] = question_name_to_prompts[answer_key_name]["system_prompt"]
|
269
|
+
|
270
|
+
raw_model_results_dictionary = {}
|
271
|
+
cache_used_dictionary = {}
|
272
|
+
for result in valid_results:
|
273
|
+
question_name = result.question_name
|
274
|
+
raw_model_results_dictionary[
|
275
|
+
question_name + "_raw_model_response"
|
276
|
+
] = result.raw_model_response
|
277
|
+
raw_model_results_dictionary[question_name + "_cost"] = result.cost
|
278
|
+
one_use_buys = (
|
279
|
+
"NA"
|
280
|
+
if isinstance(result.cost, str)
|
281
|
+
or result.cost == 0
|
282
|
+
or result.cost is None
|
283
|
+
else 1.0 / result.cost
|
284
|
+
)
|
285
|
+
raw_model_results_dictionary[question_name + "_one_usd_buys"] = one_use_buys
|
286
|
+
cache_used_dictionary[question_name] = result.cache_used
|
287
|
+
|
288
|
+
result = Result(
|
289
|
+
agent=interview.agent,
|
290
|
+
scenario=interview.scenario,
|
291
|
+
model=interview.model,
|
292
|
+
iteration=interview.iteration,
|
293
|
+
answer=answer_dict,
|
294
|
+
prompt=prompt_dictionary,
|
295
|
+
raw_model_response=raw_model_results_dictionary,
|
296
|
+
survey=interview.survey,
|
297
|
+
generated_tokens=generated_tokens_dict,
|
298
|
+
comments_dict=comments_dict,
|
299
|
+
cache_used_dict=cache_used_dictionary,
|
300
|
+
)
|
301
|
+
result.interview_hash = hash(interview)
|
302
|
+
|
303
|
+
return result
|
304
|
+
|
305
|
+
@property
|
306
|
+
def elapsed_time(self):
|
307
|
+
return time.monotonic() - self.start_time
|
308
|
+
|
309
|
+
def process_results(
|
310
|
+
self, raw_results: Results, cache: Cache, print_exceptions: bool
|
311
|
+
):
|
312
|
+
interview_lookup = {
|
313
|
+
hash(interview): index
|
314
|
+
for index, interview in enumerate(self.total_interviews)
|
315
|
+
}
|
316
|
+
interview_hashes = list(interview_lookup.keys())
|
317
|
+
|
318
|
+
task_history = TaskHistory(self.total_interviews, include_traceback=False)
|
319
|
+
|
320
|
+
results = Results(
|
321
|
+
survey=self.jobs.survey,
|
322
|
+
data=sorted(
|
323
|
+
raw_results, key=lambda x: interview_hashes.index(x.interview_hash)
|
324
|
+
),
|
325
|
+
task_history=task_history,
|
326
|
+
cache=cache,
|
327
|
+
)
|
328
|
+
results.bucket_collection = self.bucket_collection
|
329
|
+
|
330
|
+
if results.has_unfixed_exceptions and print_exceptions:
|
331
|
+
from edsl.scenarios.FileStore import HTMLFileStore
|
332
|
+
from edsl.config import CONFIG
|
333
|
+
from edsl.coop.coop import Coop
|
334
|
+
|
335
|
+
msg = f"Exceptions were raised in {len(results.task_history.indices)} out of {len(self.total_interviews)} interviews.\n"
|
336
|
+
|
337
|
+
if len(results.task_history.indices) > 5:
|
338
|
+
msg += f"Exceptions were raised in the following interviews: {results.task_history.indices}.\n"
|
339
|
+
|
340
|
+
import sys
|
341
|
+
|
342
|
+
print(msg, file=sys.stderr)
|
343
|
+
from edsl.config import CONFIG
|
344
|
+
|
345
|
+
if CONFIG.get("EDSL_OPEN_EXCEPTION_REPORT_URL") == "True":
|
346
|
+
open_in_browser = True
|
347
|
+
elif CONFIG.get("EDSL_OPEN_EXCEPTION_REPORT_URL") == "False":
|
348
|
+
open_in_browser = False
|
349
|
+
else:
|
350
|
+
raise Exception(
|
351
|
+
"EDSL_OPEN_EXCEPTION_REPORT_URL", "must be either True or False"
|
352
|
+
)
|
353
|
+
|
354
|
+
# print("open_in_browser", open_in_browser)
|
355
|
+
|
356
|
+
filepath = results.task_history.html(
|
357
|
+
cta="Open report to see details.",
|
358
|
+
open_in_browser=open_in_browser,
|
359
|
+
return_link=True,
|
360
|
+
)
|
361
|
+
|
362
|
+
try:
|
363
|
+
coop = Coop()
|
364
|
+
user_edsl_settings = coop.edsl_settings
|
365
|
+
remote_logging = user_edsl_settings["remote_logging"]
|
366
|
+
except Exception as e:
|
367
|
+
print(e)
|
368
|
+
remote_logging = False
|
369
|
+
|
370
|
+
if remote_logging:
|
371
|
+
filestore = HTMLFileStore(filepath)
|
372
|
+
coop_details = filestore.push(description="Error report")
|
373
|
+
print(coop_details)
|
374
|
+
|
375
|
+
print("Also see: https://docs.expectedparrot.com/en/latest/exceptions.html")
|
376
|
+
|
377
|
+
return results
|
378
|
+
|
53
379
|
@jupyter_nb_handler
|
54
|
-
async def run(
|
380
|
+
async def run(
|
381
|
+
self,
|
382
|
+
cache: Union[Cache, False, None],
|
383
|
+
n: int = 1,
|
384
|
+
stop_on_exception: bool = False,
|
385
|
+
progress_bar: bool = False,
|
386
|
+
sidecar_model: Optional[LanguageModel] = None,
|
387
|
+
jobs_runner_status: Optional[Type[JobsRunnerStatusBase]] = None,
|
388
|
+
job_uuid: Optional[UUID] = None,
|
389
|
+
print_exceptions: bool = True,
|
390
|
+
raise_validation_errors: bool = False,
|
391
|
+
) -> "Coroutine":
|
55
392
|
"""Runs a collection of interviews, handling both async and sync contexts."""
|
56
393
|
|
57
|
-
|
58
|
-
|
394
|
+
self.results = []
|
59
395
|
self.start_time = time.monotonic()
|
60
396
|
self.completed = False
|
397
|
+
self.cache = cache
|
398
|
+
self.sidecar_model = sidecar_model
|
61
399
|
|
62
400
|
from edsl.coop import Coop
|
63
401
|
|
64
402
|
coop = Coop()
|
65
403
|
endpoint_url = coop.get_progress_bar_url()
|
66
404
|
|
67
|
-
|
68
|
-
|
69
|
-
|
70
|
-
|
71
|
-
|
72
|
-
|
73
|
-
|
74
|
-
|
75
|
-
else:
|
76
|
-
return JobsRunnerStatus(
|
77
|
-
self,
|
78
|
-
n=parameters.n,
|
79
|
-
endpoint_url=endpoint_url,
|
80
|
-
job_uuid=parameters.job_uuid,
|
81
|
-
)
|
82
|
-
|
83
|
-
run_config.environment.jobs_runner_status = set_up_jobs_runner_status(
|
84
|
-
self.environment.jobs_runner_status
|
85
|
-
)
|
405
|
+
if jobs_runner_status is not None:
|
406
|
+
self.jobs_runner_status = jobs_runner_status(
|
407
|
+
self, n=n, endpoint_url=endpoint_url, job_uuid=job_uuid
|
408
|
+
)
|
409
|
+
else:
|
410
|
+
self.jobs_runner_status = JobsRunnerStatus(
|
411
|
+
self, n=n, endpoint_url=endpoint_url, job_uuid=job_uuid
|
412
|
+
)
|
86
413
|
|
87
|
-
|
88
|
-
"""Conducted the interviews and append to the results list."""
|
89
|
-
result_generator = AsyncInterviewRunner(self.jobs, run_config)
|
90
|
-
async for result, interview in result_generator.run():
|
91
|
-
results.append(result)
|
92
|
-
results.task_history.add_interview(interview)
|
414
|
+
stop_event = threading.Event()
|
93
415
|
|
416
|
+
async def process_results(cache):
|
417
|
+
"""Processes results from interviews."""
|
418
|
+
async for result in self.run_async_generator(
|
419
|
+
n=n,
|
420
|
+
stop_on_exception=stop_on_exception,
|
421
|
+
cache=cache,
|
422
|
+
sidecar_model=sidecar_model,
|
423
|
+
raise_validation_errors=raise_validation_errors,
|
424
|
+
):
|
425
|
+
self.results.append(result)
|
94
426
|
self.completed = True
|
95
427
|
|
96
|
-
def run_progress_bar(stop_event
|
428
|
+
def run_progress_bar(stop_event):
|
97
429
|
"""Runs the progress bar in a separate thread."""
|
98
|
-
jobs_runner_status.update_progress(stop_event)
|
99
|
-
|
100
|
-
def set_up_progress_bar(progress_bar: bool, jobs_runner_status):
|
101
|
-
progress_thread = None
|
102
|
-
if progress_bar and jobs_runner_status.has_ep_api_key():
|
103
|
-
jobs_runner_status.setup()
|
104
|
-
progress_thread = threading.Thread(
|
105
|
-
target=run_progress_bar, args=(stop_event, jobs_runner_status)
|
106
|
-
)
|
107
|
-
progress_thread.start()
|
108
|
-
elif progress_bar:
|
109
|
-
warnings.warn(
|
110
|
-
"You need an Expected Parrot API key to view job progress bars."
|
111
|
-
)
|
112
|
-
return progress_thread
|
430
|
+
self.jobs_runner_status.update_progress(stop_event)
|
113
431
|
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
122
|
-
|
123
|
-
|
432
|
+
if progress_bar and self.jobs_runner_status.has_ep_api_key():
|
433
|
+
self.jobs_runner_status.setup()
|
434
|
+
progress_thread = threading.Thread(
|
435
|
+
target=run_progress_bar, args=(stop_event,)
|
436
|
+
)
|
437
|
+
progress_thread.start()
|
438
|
+
elif progress_bar:
|
439
|
+
warnings.warn(
|
440
|
+
"You need an Expected Parrot API key to view job progress bars."
|
441
|
+
)
|
124
442
|
|
125
443
|
exception_to_raise = None
|
126
444
|
try:
|
127
|
-
|
445
|
+
with cache as c:
|
446
|
+
await process_results(cache=c)
|
128
447
|
except KeyboardInterrupt:
|
129
448
|
print("Keyboard interrupt received. Stopping gracefully...")
|
130
449
|
stop_event.set()
|
131
450
|
except Exception as e:
|
132
|
-
if
|
451
|
+
if stop_on_exception:
|
133
452
|
exception_to_raise = e
|
134
453
|
stop_event.set()
|
135
454
|
finally:
|
136
455
|
stop_event.set()
|
137
|
-
if
|
138
|
-
|
456
|
+
if progress_bar and self.jobs_runner_status.has_ep_api_key():
|
457
|
+
# self.jobs_runner_status.stop_event.set()
|
458
|
+
if progress_thread:
|
459
|
+
progress_thread.join()
|
139
460
|
|
140
461
|
if exception_to_raise:
|
141
462
|
raise exception_to_raise
|
142
463
|
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
from edsl.jobs.results_exceptions_handler import ResultsExceptionsHandler
|
147
|
-
|
148
|
-
results_exceptions_handler = ResultsExceptionsHandler(results, parameters)
|
149
|
-
|
150
|
-
results_exceptions_handler.handle_exceptions()
|
151
|
-
return results
|
464
|
+
return self.process_results(
|
465
|
+
raw_results=self.results, cache=cache, print_exceptions=print_exceptions
|
466
|
+
)
|