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.
Files changed (212) hide show
  1. edsl/Base.py +116 -197
  2. edsl/__init__.py +7 -15
  3. edsl/__version__.py +1 -1
  4. edsl/agents/Agent.py +147 -351
  5. edsl/agents/AgentList.py +73 -211
  6. edsl/agents/Invigilator.py +50 -101
  7. edsl/agents/InvigilatorBase.py +70 -62
  8. edsl/agents/PromptConstructor.py +225 -143
  9. edsl/agents/__init__.py +1 -0
  10. edsl/agents/prompt_helpers.py +3 -3
  11. edsl/auto/AutoStudy.py +5 -18
  12. edsl/auto/StageBase.py +40 -53
  13. edsl/auto/StageQuestions.py +1 -2
  14. edsl/auto/utilities.py +6 -0
  15. edsl/config.py +2 -22
  16. edsl/conversation/car_buying.py +1 -2
  17. edsl/coop/PriceFetcher.py +1 -1
  18. edsl/coop/coop.py +47 -125
  19. edsl/coop/utils.py +14 -14
  20. edsl/data/Cache.py +27 -45
  21. edsl/data/CacheEntry.py +15 -12
  22. edsl/data/CacheHandler.py +12 -31
  23. edsl/data/RemoteCacheSync.py +46 -154
  24. edsl/data/__init__.py +3 -4
  25. edsl/data_transfer_models.py +1 -2
  26. edsl/enums.py +0 -27
  27. edsl/exceptions/__init__.py +50 -50
  28. edsl/exceptions/agents.py +0 -12
  29. edsl/exceptions/questions.py +6 -24
  30. edsl/exceptions/scenarios.py +0 -7
  31. edsl/inference_services/AnthropicService.py +19 -38
  32. edsl/inference_services/AwsBedrock.py +2 -0
  33. edsl/inference_services/AzureAI.py +2 -0
  34. edsl/inference_services/GoogleService.py +12 -7
  35. edsl/inference_services/InferenceServiceABC.py +85 -18
  36. edsl/inference_services/InferenceServicesCollection.py +79 -120
  37. edsl/inference_services/MistralAIService.py +3 -0
  38. edsl/inference_services/OpenAIService.py +35 -47
  39. edsl/inference_services/PerplexityService.py +3 -0
  40. edsl/inference_services/TestService.py +10 -11
  41. edsl/inference_services/TogetherAIService.py +3 -5
  42. edsl/jobs/Answers.py +14 -1
  43. edsl/jobs/Jobs.py +431 -356
  44. edsl/jobs/JobsChecks.py +10 -35
  45. edsl/jobs/JobsPrompts.py +4 -6
  46. edsl/jobs/JobsRemoteInferenceHandler.py +133 -205
  47. edsl/jobs/buckets/BucketCollection.py +3 -44
  48. edsl/jobs/buckets/TokenBucket.py +21 -53
  49. edsl/jobs/interviews/Interview.py +408 -143
  50. edsl/jobs/runners/JobsRunnerAsyncio.py +403 -88
  51. edsl/jobs/runners/JobsRunnerStatus.py +165 -133
  52. edsl/jobs/tasks/QuestionTaskCreator.py +19 -21
  53. edsl/jobs/tasks/TaskHistory.py +18 -38
  54. edsl/jobs/tasks/task_status_enum.py +2 -0
  55. edsl/language_models/KeyLookup.py +30 -0
  56. edsl/language_models/LanguageModel.py +236 -194
  57. edsl/language_models/ModelList.py +19 -28
  58. edsl/language_models/__init__.py +2 -1
  59. edsl/language_models/registry.py +190 -0
  60. edsl/language_models/repair.py +2 -2
  61. edsl/language_models/unused/ReplicateBase.py +83 -0
  62. edsl/language_models/utilities.py +4 -5
  63. edsl/notebooks/Notebook.py +14 -19
  64. edsl/prompts/Prompt.py +39 -29
  65. edsl/questions/{answer_validator_mixin.py → AnswerValidatorMixin.py} +2 -47
  66. edsl/questions/QuestionBase.py +214 -68
  67. edsl/questions/{question_base_gen_mixin.py → QuestionBaseGenMixin.py} +50 -57
  68. edsl/questions/QuestionBasePromptsMixin.py +3 -7
  69. edsl/questions/QuestionBudget.py +1 -1
  70. edsl/questions/QuestionCheckBox.py +3 -3
  71. edsl/questions/QuestionExtract.py +7 -5
  72. edsl/questions/QuestionFreeText.py +3 -2
  73. edsl/questions/QuestionList.py +18 -10
  74. edsl/questions/QuestionMultipleChoice.py +23 -67
  75. edsl/questions/QuestionNumerical.py +4 -2
  76. edsl/questions/QuestionRank.py +17 -7
  77. edsl/questions/{response_validator_abc.py → ResponseValidatorABC.py} +26 -40
  78. edsl/questions/SimpleAskMixin.py +3 -4
  79. edsl/questions/__init__.py +1 -2
  80. edsl/questions/derived/QuestionLinearScale.py +3 -6
  81. edsl/questions/derived/QuestionTopK.py +1 -1
  82. edsl/questions/descriptors.py +3 -17
  83. edsl/questions/question_registry.py +1 -1
  84. edsl/results/CSSParameterizer.py +1 -1
  85. edsl/results/Dataset.py +7 -170
  86. edsl/results/DatasetExportMixin.py +305 -168
  87. edsl/results/DatasetTree.py +8 -28
  88. edsl/results/Result.py +206 -298
  89. edsl/results/Results.py +131 -149
  90. edsl/results/ResultsDBMixin.py +238 -0
  91. edsl/results/ResultsExportMixin.py +0 -2
  92. edsl/results/{results_selector.py → Selector.py} +13 -23
  93. edsl/results/TableDisplay.py +171 -98
  94. edsl/results/__init__.py +1 -1
  95. edsl/scenarios/FileStore.py +239 -150
  96. edsl/scenarios/Scenario.py +193 -90
  97. edsl/scenarios/ScenarioHtmlMixin.py +3 -4
  98. edsl/scenarios/{scenario_join.py → ScenarioJoin.py} +6 -10
  99. edsl/scenarios/ScenarioList.py +244 -415
  100. edsl/scenarios/ScenarioListExportMixin.py +7 -0
  101. edsl/scenarios/ScenarioListPdfMixin.py +37 -15
  102. edsl/scenarios/__init__.py +2 -1
  103. edsl/study/ObjectEntry.py +1 -1
  104. edsl/study/SnapShot.py +1 -1
  105. edsl/study/Study.py +12 -5
  106. edsl/surveys/Rule.py +4 -5
  107. edsl/surveys/RuleCollection.py +27 -25
  108. edsl/surveys/Survey.py +791 -270
  109. edsl/surveys/SurveyCSS.py +8 -20
  110. edsl/surveys/{SurveyFlowVisualization.py → SurveyFlowVisualizationMixin.py} +9 -11
  111. edsl/surveys/__init__.py +2 -4
  112. edsl/surveys/descriptors.py +2 -6
  113. edsl/surveys/instructions/ChangeInstruction.py +2 -1
  114. edsl/surveys/instructions/Instruction.py +13 -4
  115. edsl/surveys/instructions/InstructionCollection.py +6 -11
  116. edsl/templates/error_reporting/interview_details.html +1 -1
  117. edsl/templates/error_reporting/report.html +1 -1
  118. edsl/tools/plotting.py +1 -1
  119. edsl/utilities/utilities.py +23 -35
  120. {edsl-0.1.39.dist-info → edsl-0.1.39.dev1.dist-info}/METADATA +10 -12
  121. edsl-0.1.39.dev1.dist-info/RECORD +277 -0
  122. {edsl-0.1.39.dist-info → edsl-0.1.39.dev1.dist-info}/WHEEL +1 -1
  123. edsl/agents/QuestionInstructionPromptBuilder.py +0 -128
  124. edsl/agents/QuestionTemplateReplacementsBuilder.py +0 -137
  125. edsl/agents/question_option_processor.py +0 -172
  126. edsl/coop/CoopFunctionsMixin.py +0 -15
  127. edsl/coop/ExpectedParrotKeyHandler.py +0 -125
  128. edsl/exceptions/inference_services.py +0 -5
  129. edsl/inference_services/AvailableModelCacheHandler.py +0 -184
  130. edsl/inference_services/AvailableModelFetcher.py +0 -215
  131. edsl/inference_services/ServiceAvailability.py +0 -135
  132. edsl/inference_services/data_structures.py +0 -134
  133. edsl/jobs/AnswerQuestionFunctionConstructor.py +0 -223
  134. edsl/jobs/FetchInvigilator.py +0 -47
  135. edsl/jobs/InterviewTaskManager.py +0 -98
  136. edsl/jobs/InterviewsConstructor.py +0 -50
  137. edsl/jobs/JobsComponentConstructor.py +0 -189
  138. edsl/jobs/JobsRemoteInferenceLogger.py +0 -239
  139. edsl/jobs/RequestTokenEstimator.py +0 -30
  140. edsl/jobs/async_interview_runner.py +0 -138
  141. edsl/jobs/buckets/TokenBucketAPI.py +0 -211
  142. edsl/jobs/buckets/TokenBucketClient.py +0 -191
  143. edsl/jobs/check_survey_scenario_compatibility.py +0 -85
  144. edsl/jobs/data_structures.py +0 -120
  145. edsl/jobs/decorators.py +0 -35
  146. edsl/jobs/jobs_status_enums.py +0 -9
  147. edsl/jobs/loggers/HTMLTableJobLogger.py +0 -304
  148. edsl/jobs/results_exceptions_handler.py +0 -98
  149. edsl/language_models/ComputeCost.py +0 -63
  150. edsl/language_models/PriceManager.py +0 -127
  151. edsl/language_models/RawResponseHandler.py +0 -106
  152. edsl/language_models/ServiceDataSources.py +0 -0
  153. edsl/language_models/key_management/KeyLookup.py +0 -63
  154. edsl/language_models/key_management/KeyLookupBuilder.py +0 -273
  155. edsl/language_models/key_management/KeyLookupCollection.py +0 -38
  156. edsl/language_models/key_management/__init__.py +0 -0
  157. edsl/language_models/key_management/models.py +0 -131
  158. edsl/language_models/model.py +0 -256
  159. edsl/notebooks/NotebookToLaTeX.py +0 -142
  160. edsl/questions/ExceptionExplainer.py +0 -77
  161. edsl/questions/HTMLQuestion.py +0 -103
  162. edsl/questions/QuestionMatrix.py +0 -265
  163. edsl/questions/data_structures.py +0 -20
  164. edsl/questions/loop_processor.py +0 -149
  165. edsl/questions/response_validator_factory.py +0 -34
  166. edsl/questions/templates/matrix/__init__.py +0 -1
  167. edsl/questions/templates/matrix/answering_instructions.jinja +0 -5
  168. edsl/questions/templates/matrix/question_presentation.jinja +0 -20
  169. edsl/results/MarkdownToDocx.py +0 -122
  170. edsl/results/MarkdownToPDF.py +0 -111
  171. edsl/results/TextEditor.py +0 -50
  172. edsl/results/file_exports.py +0 -252
  173. edsl/results/smart_objects.py +0 -96
  174. edsl/results/table_data_class.py +0 -12
  175. edsl/results/table_renderers.py +0 -118
  176. edsl/scenarios/ConstructDownloadLink.py +0 -109
  177. edsl/scenarios/DocumentChunker.py +0 -102
  178. edsl/scenarios/DocxScenario.py +0 -16
  179. edsl/scenarios/PdfExtractor.py +0 -40
  180. edsl/scenarios/directory_scanner.py +0 -96
  181. edsl/scenarios/file_methods.py +0 -85
  182. edsl/scenarios/handlers/__init__.py +0 -13
  183. edsl/scenarios/handlers/csv.py +0 -49
  184. edsl/scenarios/handlers/docx.py +0 -76
  185. edsl/scenarios/handlers/html.py +0 -37
  186. edsl/scenarios/handlers/json.py +0 -111
  187. edsl/scenarios/handlers/latex.py +0 -5
  188. edsl/scenarios/handlers/md.py +0 -51
  189. edsl/scenarios/handlers/pdf.py +0 -68
  190. edsl/scenarios/handlers/png.py +0 -39
  191. edsl/scenarios/handlers/pptx.py +0 -105
  192. edsl/scenarios/handlers/py.py +0 -294
  193. edsl/scenarios/handlers/sql.py +0 -313
  194. edsl/scenarios/handlers/sqlite.py +0 -149
  195. edsl/scenarios/handlers/txt.py +0 -33
  196. edsl/scenarios/scenario_selector.py +0 -156
  197. edsl/surveys/ConstructDAG.py +0 -92
  198. edsl/surveys/EditSurvey.py +0 -221
  199. edsl/surveys/InstructionHandler.py +0 -100
  200. edsl/surveys/MemoryManagement.py +0 -72
  201. edsl/surveys/RuleManager.py +0 -172
  202. edsl/surveys/Simulator.py +0 -75
  203. edsl/surveys/SurveyToApp.py +0 -141
  204. edsl/utilities/PrettyList.py +0 -56
  205. edsl/utilities/is_notebook.py +0 -18
  206. edsl/utilities/is_valid_variable_name.py +0 -11
  207. edsl/utilities/remove_edsl_version.py +0 -24
  208. edsl-0.1.39.dist-info/RECORD +0 -358
  209. /edsl/questions/{register_questions_meta.py → RegisterQuestionsMeta.py} +0 -0
  210. /edsl/results/{results_fetch_mixin.py → ResultsFetchMixin.py} +0 -0
  211. /edsl/results/{results_tools_mixin.py → ResultsToolsMixin.py} +0 -0
  212. {edsl-0.1.39.dist-info → edsl-0.1.39.dev1.dist-info}/LICENSE +0 -0
@@ -1,131 +0,0 @@
1
- from dataclasses import dataclass, asdict
2
- from typing import Optional
3
-
4
-
5
- @dataclass
6
- class APIKeyEntry:
7
- """A class representing an API key entry.
8
-
9
- >>> entry = APIKeyEntry.example()
10
- >>> entry.service
11
- 'openai'
12
- >>> entry.name
13
- 'OPENAI_API_KEY'
14
- >>> entry.value
15
- 'sk-abcd1234'
16
- >>> entry.source
17
- 'env'
18
- """
19
-
20
- service: str
21
- name: str
22
- value: str
23
- source: Optional[str] = None
24
-
25
- @classmethod
26
- def example(cls):
27
- return APIKeyEntry(
28
- service="openai", name="OPENAI_API_KEY", value="sk-abcd1234", source="env"
29
- )
30
-
31
-
32
- @dataclass
33
- class LimitEntry:
34
- """A class representing rate limit entries for a service.
35
-
36
- >>> limit = LimitEntry.example()
37
- >>> limit.service
38
- 'openai'
39
- >>> limit.rpm
40
- 60
41
- >>> limit.tpm
42
- 100000
43
- >>> limit.source
44
- 'config'
45
- """
46
-
47
- service: str
48
- rpm: int
49
- tpm: int
50
- source: Optional[str] = None
51
-
52
- @classmethod
53
- def example(cls):
54
- return LimitEntry(service="openai", rpm=60, tpm=100000, source="config")
55
-
56
-
57
- @dataclass
58
- class APIIDEntry:
59
- """A class representing an API ID entry.
60
-
61
- >>> id_entry = APIIDEntry.example()
62
- >>> id_entry.service
63
- 'bedrock'
64
- >>> id_entry.name
65
- 'AWS_ACCESS_KEY_ID'
66
- >>> id_entry.value
67
- 'AKIA1234'
68
- >>> id_entry.source
69
- 'env'
70
- """
71
-
72
- service: str
73
- name: str
74
- value: str
75
- source: Optional[str] = None
76
-
77
- @classmethod
78
- def example(cls):
79
- return APIIDEntry(
80
- service="bedrock", name="AWS_ACCESS_KEY_ID", value="AKIA1234", source="env"
81
- )
82
-
83
-
84
- @dataclass
85
- class LanguageModelInput:
86
- """A class representing input configuration for a language model service.
87
-
88
- >>> lm_input = LanguageModelInput.example()
89
- >>> lm_input.api_token
90
- 'sk-abcd123'
91
- >>> lm_input.rpm
92
- 60
93
- >>> lm_input.tpm
94
- 100000
95
- >>> lm_input.api_id
96
-
97
-
98
- Test dictionary conversion:
99
- >>> d = lm_input.to_dict()
100
- >>> isinstance(d, dict)
101
- True
102
- >>> LanguageModelInput.from_dict(d).api_token == lm_input.api_token
103
- True
104
- """
105
-
106
- api_token: str
107
- rpm: int
108
- tpm: int
109
- api_id: Optional[str] = None
110
- token_source: Optional[str] = None
111
- limit_source: Optional[str] = None
112
- id_source: Optional[str] = None
113
-
114
- def to_dict(self):
115
- return asdict(self)
116
-
117
- @classmethod
118
- def from_dict(cls, d):
119
- return cls(**d)
120
-
121
- @classmethod
122
- def example(cls):
123
- return LanguageModelInput(
124
- api_token="sk-abcd123", tpm=100000, rpm=60, api_id=None
125
- )
126
-
127
-
128
- if __name__ == "__main__":
129
- import doctest
130
-
131
- doctest.testmod()
@@ -1,256 +0,0 @@
1
- import textwrap
2
- from random import random
3
- from typing import Optional, TYPE_CHECKING, List
4
-
5
- from edsl.utilities.PrettyList import PrettyList
6
- from edsl.config import CONFIG
7
-
8
- from edsl.inference_services.InferenceServicesCollection import (
9
- InferenceServicesCollection,
10
- )
11
- from edsl.inference_services.data_structures import AvailableModels
12
- from edsl.inference_services.InferenceServiceABC import InferenceServiceABC
13
- from edsl.enums import InferenceServiceLiteral
14
-
15
- if TYPE_CHECKING:
16
- from edsl.results.Dataset import Dataset
17
-
18
-
19
- def get_model_class(model_name, registry: Optional[InferenceServicesCollection] = None):
20
- from edsl.inference_services.registry import default
21
-
22
- registry = registry or default
23
- factory = registry.create_model_factory(model_name)
24
- return factory
25
-
26
-
27
- class Meta(type):
28
- def __repr__(cls):
29
- return textwrap.dedent(
30
- f"""\
31
- Available models: {cls.available()}
32
-
33
- To create an instance, you can do:
34
- >>> m = Model('gpt-4-1106-preview', temperature=0.5, ...)
35
-
36
- To get the default model, you can leave out the model name.
37
- To see the available models, you can do:
38
- >>> Model.available()
39
- """
40
- )
41
-
42
-
43
- class Model(metaclass=Meta):
44
- default_model = CONFIG.get("EDSL_DEFAULT_MODEL")
45
- _registry: InferenceServicesCollection = None # Class-level registry storage
46
-
47
- @classmethod
48
- def get_registry(cls) -> InferenceServicesCollection:
49
- """Get the current registry or initialize with default if None"""
50
- if cls._registry is None:
51
- from edsl.inference_services.registry import default
52
-
53
- cls._registry = default
54
- return cls._registry
55
-
56
- @classmethod
57
- def set_registry(cls, registry: InferenceServicesCollection) -> None:
58
- """Set a new registry"""
59
- cls._registry = registry
60
-
61
- def __new__(
62
- cls,
63
- model_name: Optional[str] = None,
64
- service_name: Optional[InferenceServiceLiteral] = None,
65
- registry: Optional[InferenceServicesCollection] = None,
66
- *args,
67
- **kwargs,
68
- ):
69
- "Instantiate a new language model."
70
- # Map index to the respective subclass
71
- if model_name is None:
72
- model_name = (
73
- cls.default_model
74
- ) # when model_name is None, use the default model, set in the config file
75
-
76
- if registry is not None:
77
- cls.set_registry(registry)
78
-
79
- if isinstance(model_name, int): # can refer to a model by index
80
- model_name = cls.available(name_only=True)[model_name]
81
-
82
- factory = cls.get_registry().create_model_factory(
83
- model_name, service_name=service_name
84
- )
85
- return factory(*args, **kwargs)
86
-
87
- @classmethod
88
- def add_model(cls, service_name, model_name) -> None:
89
- cls.get_registry().add_model(service_name, model_name)
90
-
91
- @classmethod
92
- def service_classes(cls) -> List["InferenceServiceABC"]:
93
- """Returns a list of service classes.
94
-
95
- >>> Model.service_classes()
96
- [...]
97
- """
98
- return [r for r in cls.services(name_only=True)]
99
-
100
- @classmethod
101
- def services(cls, name_only: bool = False) -> List[str]:
102
- """Returns a list of services, annotated with whether the user has local keys for them."""
103
- services_with_local_keys = set(cls.key_info().select("service").to_list())
104
- f = lambda service_name: (
105
- "yes" if service_name in services_with_local_keys else " "
106
- )
107
- if name_only:
108
- return PrettyList(
109
- [r._inference_service_ for r in cls.get_registry().services],
110
- columns=["Service Name"],
111
- )
112
- else:
113
- return PrettyList(
114
- [
115
- (r._inference_service_, f(r._inference_service_))
116
- for r in cls.get_registry().services
117
- ],
118
- columns=["Service Name", "Local key?"],
119
- )
120
-
121
- @classmethod
122
- def services_with_local_keys(cls) -> set:
123
- """Returns a list of services for which the user has local keys."""
124
- return set(cls.key_info().select("service").to_list())
125
-
126
- @classmethod
127
- def key_info(cls, obscure_api_key: bool = True) -> "Dataset":
128
- """Returns a dataset of local key information."""
129
- from edsl.language_models.key_management.KeyLookupCollection import (
130
- KeyLookupCollection,
131
- )
132
- from edsl.scenarios import Scenario, ScenarioList
133
-
134
- klc = KeyLookupCollection()
135
- klc.add_key_lookup(fetch_order=None)
136
- sl = ScenarioList()
137
- for service, entry in list(klc.data.values())[0].items():
138
- sl.append(Scenario({"service": service} | entry.to_dict()))
139
- if obscure_api_key:
140
- for service in sl:
141
- service["api_token"] = (
142
- service["api_token"][:4] + "..." + service["api_token"][-4:]
143
- )
144
- return sl.to_dataset()
145
-
146
- @classmethod
147
- def search_models(cls, search_term: str):
148
- return cls.available(search_term=search_term)
149
-
150
- @classmethod
151
- def all_known_models(cls) -> "AvailableModels":
152
- return cls.get_registry().available()
153
-
154
- @classmethod
155
- def available_with_local_keys(cls):
156
- services_with_local_keys = set(cls.key_info().select("service").to_list())
157
- return [
158
- m
159
- for m in cls.get_registry().available()
160
- if m.service_name in services_with_local_keys
161
- ]
162
-
163
- @classmethod
164
- def available(
165
- cls,
166
- search_term: str = None,
167
- name_only: bool = False,
168
- service: Optional[str] = None,
169
- ):
170
- # if search_term is None and service is None:
171
- # print("Getting available models...")
172
- # print("You have local keys for the following services:")
173
- # print(cls.services_with_local_keys())
174
- # print("\n")
175
- # print("To see models by service, use the 'service' parameter.")
176
- # print("E.g., Model.available(service='openai')")
177
- # return None
178
-
179
- if service is not None:
180
- if service not in cls.services(name_only=True):
181
- raise ValueError(
182
- f"Service {service} not found in available services.",
183
- f"Available services are: {cls.services()}",
184
- )
185
-
186
- full_list = cls.get_registry().available(service=service)
187
-
188
- if search_term is None:
189
- if name_only:
190
- return PrettyList(
191
- [m.model_name for m in full_list],
192
- columns=["Model Name"],
193
- )
194
- else:
195
- return PrettyList(
196
- [[m.model_name, m.service_name] for m in full_list],
197
- columns=["Model Name", "Service Name"],
198
- )
199
- else:
200
- filtered_results = [
201
- m
202
- for m in full_list
203
- if search_term in m.model_name or search_term in m.service_name
204
- ]
205
- if name_only:
206
- return PrettyList(
207
- [m.model_name for m in filtered_results],
208
- columns=["Model Name"],
209
- )
210
- else:
211
- return PrettyList(
212
- [[m.model_name, m.service_name] for m in full_list],
213
- columns=["Model Name", "Service Name"],
214
- )
215
-
216
- @classmethod
217
- def check_models(cls, verbose=False):
218
- print("Checking all available models...\n")
219
- for model in cls.available(name_only=True):
220
- print(f"Now checking: {model}")
221
- try:
222
- m = cls(model)
223
- except Exception as e:
224
- print(f"Error creating instance of {model}: {e}")
225
- continue
226
- try:
227
- results = m.hello(verbose)
228
- if verbose:
229
- print(f"Results from model call: {results}")
230
- except Exception as e:
231
- print(f"Error calling 'hello' on {model}: {e}")
232
- continue
233
- print("OK!")
234
- print("\n")
235
-
236
- @classmethod
237
- def example(cls, randomize: bool = False) -> "Model":
238
- """
239
- Returns an example Model instance.
240
-
241
- :param randomize: If True, the temperature is set to a random decimal between 0 and 1.
242
- """
243
- temperature = 0.5 if not randomize else round(random(), 2)
244
- model_name = cls.default_model
245
- return cls(model_name, temperature=temperature)
246
-
247
-
248
- if __name__ == "__main__":
249
- import doctest
250
-
251
- doctest.testmod(optionflags=doctest.ELLIPSIS)
252
-
253
- available = Model.available()
254
- m = Model("gpt-4-1106-preview")
255
- results = m.execute_model_call("Hello world")
256
- print(results)
@@ -1,142 +0,0 @@
1
- from typing import Optional, Dict
2
- import os
3
- import nbformat
4
- from nbconvert.exporters import LatexExporter
5
- from nbconvert.writers import FilesWriter
6
-
7
-
8
- class NotebookToLaTeX:
9
- """
10
- A class for converting Jupyter notebooks to LaTeX with proper directory structure.
11
- """
12
-
13
- def __init__(self, notebook):
14
- """
15
- Initialize with a Notebook instance.
16
-
17
- :param notebook: An instance of the Notebook class
18
- """
19
- self.notebook = notebook
20
- self.latex_exporter = LatexExporter()
21
- self._configure_exporter()
22
-
23
- def _configure_exporter(self):
24
- """Configure the LaTeX exporter with default settings."""
25
- self.latex_exporter.exclude_input_prompt = True
26
- self.latex_exporter.exclude_output_prompt = True
27
- self.latex_exporter.template_name = "classic"
28
-
29
- def _create_makefile(self, filename: str, output_dir: str):
30
- """Create a Makefile for the LaTeX project."""
31
- makefile_content = f"""# Makefile for {filename}
32
- all: pdf
33
-
34
- pdf: {filename}.pdf
35
-
36
- {filename}.pdf: {filename}.tex
37
- \tpdflatex {filename}.tex
38
- \tpdflatex {filename}.tex # Run twice for references
39
- \tbibtex {filename} # Run bibtex if needed
40
- \tpdflatex {filename}.tex # Run one more time for bibtex
41
-
42
- clean:
43
- \trm -f *.aux *.log *.out *.toc *.pdf *.bbl *.blg
44
- """
45
- makefile_path = os.path.join(output_dir, "Makefile")
46
- with open(makefile_path, "w") as f:
47
- f.write(makefile_content)
48
-
49
- def _create_readme(self, filename: str, output_dir: str):
50
- """Create a README file with usage instructions."""
51
- readme_content = f"""# {filename}
52
-
53
- This folder contains the LaTeX version of your Jupyter notebook.
54
-
55
- Files:
56
- - {filename}.tex: Main LaTeX file
57
- - Makefile: Build automation
58
-
59
- To compile the PDF:
60
- 1. Make sure you have a LaTeX distribution installed (e.g., TexLive)
61
- 2. Run `make` in this directory
62
- 3. The output will be {filename}.pdf
63
-
64
- To clean up build files:
65
- - Run `make clean`
66
- """
67
- readme_path = os.path.join(output_dir, "README.md")
68
- with open(readme_path, "w") as f:
69
- f.write(readme_content)
70
-
71
- def convert(self, filename: str, output_dir: Optional[str] = None):
72
- """
73
- Convert the notebook to LaTeX and create a project directory.
74
-
75
- :param filename: Name for the output files (without extension)
76
- :param output_dir: Optional directory path. If None, uses filename as directory
77
- """
78
- # Use filename as directory if no output_dir specified
79
- output_dir = output_dir or filename
80
-
81
- # Create output directory
82
- os.makedirs(output_dir, exist_ok=True)
83
-
84
- # Convert notebook to nbformat
85
- notebook_node = nbformat.from_dict(self.notebook.data)
86
-
87
- # Convert to LaTeX
88
- body, resources = self.latex_exporter.from_notebook_node(notebook_node)
89
-
90
- # Write the main tex file
91
- output_file_path = os.path.join(output_dir, f"{filename}.tex")
92
- with open(output_file_path, "w", encoding="utf-8") as f:
93
- f.write(body)
94
-
95
- # Write additional resources (images, etc.)
96
- if resources.get("outputs"):
97
- for fname, data in resources["outputs"].items():
98
- resource_path = os.path.join(output_dir, fname)
99
- with open(resource_path, "wb") as f:
100
- f.write(data)
101
-
102
- # Create supporting files
103
- self._create_makefile(filename, output_dir)
104
- self._create_readme(filename, output_dir)
105
-
106
- def set_template(self, template_name: str):
107
- """
108
- Set the LaTeX template to use.
109
-
110
- :param template_name: Name of the template (e.g., 'classic', 'article')
111
- """
112
- self.latex_exporter.template_name = template_name
113
-
114
- def set_template_options(self, options: Dict):
115
- """
116
- Set additional template options.
117
-
118
- :param options: Dictionary of template options
119
- """
120
- for key, value in options.items():
121
- setattr(self.latex_exporter, key, value)
122
-
123
-
124
- # Example usage:
125
- if __name__ == "__main__":
126
- from edsl import Notebook
127
-
128
- # Create or load a notebook
129
- notebook = Notebook.example()
130
-
131
- # Create converter and convert
132
- converter = NotebookToLaTeX(notebook)
133
- converter.convert("example_output")
134
-
135
- # Example with custom template options
136
- converter.set_template_options(
137
- {
138
- "exclude_input": True, # Hide input cells
139
- "exclude_output": False, # Show output cells
140
- }
141
- )
142
- converter.convert("example_output_custom")
@@ -1,77 +0,0 @@
1
- from pydantic import ValidationError
2
- from typing import Union
3
-
4
-
5
- class ExceptionExplainer:
6
- """
7
- A class that converts validation errors into human-readable explanations,
8
- specifically for Language Model responses.
9
- """
10
-
11
- def __init__(self, error: Union[ValidationError, Exception], model_response: str):
12
- """
13
- Initialize the explainer with the error and model response.
14
-
15
- Args:
16
- error: The validation error that occurred
17
- model_response: The raw response from the Language Model
18
- """
19
- self.error = error
20
- self.model_response = model_response
21
-
22
- def explain(self) -> str:
23
- """
24
- Generate a human-readable explanation of why the model's response failed validation.
25
-
26
- Returns:
27
- A user-friendly explanation of why the model's response was invalid
28
- """
29
- self.error = self.error.pydantic_error
30
- return self._explain_validation_error()
31
-
32
- # Fallback for unknown errors
33
- return self._create_generic_explanation()
34
-
35
- def _explain_validation_error(self) -> str:
36
- """Handle Pydantic ValidationError specifically."""
37
- error_dict = self.error.errors()
38
- explanations = []
39
-
40
- context = f'The AI model returned "{self.model_response}", but this was invalid for the question you asked and the constraints you provided.\n'
41
- explanations.append(context)
42
- explanations.append("Reason(s) invalidated:")
43
- for e in error_dict:
44
- msg = e.get("msg", "Unknown error")
45
- explanations.append(f"- {msg}")
46
-
47
- main_message = "\n".join(explanations)
48
- return f"{main_message}\n\n{self._get_suggestion()}"
49
-
50
- def _create_generic_explanation(self) -> str:
51
- """Create a generic explanation for non-ValidationError exceptions."""
52
- return (
53
- f'The AI model returned "{self.model_response}", but this response was invalid. '
54
- f"Error: {str(self.error)}"
55
- )
56
-
57
- def _get_suggestion(self) -> str:
58
- """Get a suggestion for handling the error."""
59
- return (
60
- "EDSL Advice:\n"
61
- "- Look at the Model comments - often the model will provide a hint about what went wrong.\n"
62
- "- If the model's response doesn't make sense, try rephrasing your question.\n"
63
- "- Try using 'use_code' parameter of a MultipleChoice.\n"
64
- "- A QuestionFreeText will almost always validate.\n"
65
- "- Try setting the 'permissive' = True parameter in the Question constructor."
66
- )
67
-
68
-
69
- # Example usage:
70
- if __name__ == "__main__":
71
- try:
72
- # Your validation code here
73
- raise ValidationError.parse_obj({"answer": "120"})
74
- except ValidationError as e:
75
- explainer = ExceptionExplainer(e, "120")
76
- explanation = explainer.explain()
77
- print(explanation)