edsl 0.1.33.dev1__py3-none-any.whl → 0.1.33.dev2__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 (163) hide show
  1. edsl/TemplateLoader.py +24 -0
  2. edsl/__init__.py +8 -4
  3. edsl/agents/Agent.py +46 -14
  4. edsl/agents/AgentList.py +43 -0
  5. edsl/agents/Invigilator.py +125 -212
  6. edsl/agents/InvigilatorBase.py +140 -32
  7. edsl/agents/PromptConstructionMixin.py +43 -66
  8. edsl/agents/__init__.py +1 -0
  9. edsl/auto/AutoStudy.py +117 -0
  10. edsl/auto/StageBase.py +230 -0
  11. edsl/auto/StageGenerateSurvey.py +178 -0
  12. edsl/auto/StageLabelQuestions.py +125 -0
  13. edsl/auto/StagePersona.py +61 -0
  14. edsl/auto/StagePersonaDimensionValueRanges.py +88 -0
  15. edsl/auto/StagePersonaDimensionValues.py +74 -0
  16. edsl/auto/StagePersonaDimensions.py +69 -0
  17. edsl/auto/StageQuestions.py +73 -0
  18. edsl/auto/SurveyCreatorPipeline.py +21 -0
  19. edsl/auto/utilities.py +224 -0
  20. edsl/config.py +38 -39
  21. edsl/coop/PriceFetcher.py +58 -0
  22. edsl/coop/coop.py +39 -5
  23. edsl/data/Cache.py +35 -1
  24. edsl/data_transfer_models.py +120 -38
  25. edsl/enums.py +2 -0
  26. edsl/exceptions/language_models.py +25 -1
  27. edsl/exceptions/questions.py +62 -5
  28. edsl/exceptions/results.py +4 -0
  29. edsl/inference_services/AnthropicService.py +13 -11
  30. edsl/inference_services/AwsBedrock.py +19 -17
  31. edsl/inference_services/AzureAI.py +37 -20
  32. edsl/inference_services/GoogleService.py +16 -12
  33. edsl/inference_services/GroqService.py +2 -0
  34. edsl/inference_services/InferenceServiceABC.py +24 -0
  35. edsl/inference_services/MistralAIService.py +120 -0
  36. edsl/inference_services/OpenAIService.py +41 -50
  37. edsl/inference_services/TestService.py +71 -0
  38. edsl/inference_services/models_available_cache.py +0 -6
  39. edsl/inference_services/registry.py +4 -0
  40. edsl/jobs/Answers.py +10 -12
  41. edsl/jobs/FailedQuestion.py +78 -0
  42. edsl/jobs/Jobs.py +18 -13
  43. edsl/jobs/buckets/TokenBucket.py +39 -14
  44. edsl/jobs/interviews/Interview.py +297 -77
  45. edsl/jobs/interviews/InterviewExceptionEntry.py +83 -19
  46. edsl/jobs/interviews/interview_exception_tracking.py +0 -70
  47. edsl/jobs/interviews/retry_management.py +3 -1
  48. edsl/jobs/runners/JobsRunnerAsyncio.py +116 -70
  49. edsl/jobs/runners/JobsRunnerStatusMixin.py +1 -1
  50. edsl/jobs/tasks/QuestionTaskCreator.py +30 -23
  51. edsl/jobs/tasks/TaskHistory.py +131 -213
  52. edsl/language_models/LanguageModel.py +239 -129
  53. edsl/language_models/ModelList.py +2 -2
  54. edsl/language_models/RegisterLanguageModelsMeta.py +14 -29
  55. edsl/language_models/fake_openai_call.py +15 -0
  56. edsl/language_models/fake_openai_service.py +61 -0
  57. edsl/language_models/registry.py +15 -2
  58. edsl/language_models/repair.py +0 -19
  59. edsl/language_models/utilities.py +61 -0
  60. edsl/prompts/Prompt.py +52 -2
  61. edsl/questions/AnswerValidatorMixin.py +23 -26
  62. edsl/questions/QuestionBase.py +273 -242
  63. edsl/questions/QuestionBaseGenMixin.py +133 -0
  64. edsl/questions/QuestionBasePromptsMixin.py +266 -0
  65. edsl/questions/QuestionBudget.py +6 -0
  66. edsl/questions/QuestionCheckBox.py +227 -35
  67. edsl/questions/QuestionExtract.py +98 -27
  68. edsl/questions/QuestionFreeText.py +46 -29
  69. edsl/questions/QuestionFunctional.py +7 -0
  70. edsl/questions/QuestionList.py +141 -22
  71. edsl/questions/QuestionMultipleChoice.py +173 -64
  72. edsl/questions/QuestionNumerical.py +87 -46
  73. edsl/questions/QuestionRank.py +182 -24
  74. edsl/questions/RegisterQuestionsMeta.py +31 -12
  75. edsl/questions/ResponseValidatorABC.py +169 -0
  76. edsl/questions/__init__.py +3 -4
  77. edsl/questions/decorators.py +21 -0
  78. edsl/questions/derived/QuestionLikertFive.py +10 -5
  79. edsl/questions/derived/QuestionLinearScale.py +11 -1
  80. edsl/questions/derived/QuestionTopK.py +6 -0
  81. edsl/questions/derived/QuestionYesNo.py +16 -1
  82. edsl/questions/descriptors.py +43 -7
  83. edsl/questions/prompt_templates/question_budget.jinja +13 -0
  84. edsl/questions/prompt_templates/question_checkbox.jinja +32 -0
  85. edsl/questions/prompt_templates/question_extract.jinja +11 -0
  86. edsl/questions/prompt_templates/question_free_text.jinja +3 -0
  87. edsl/questions/prompt_templates/question_linear_scale.jinja +11 -0
  88. edsl/questions/prompt_templates/question_list.jinja +17 -0
  89. edsl/questions/prompt_templates/question_multiple_choice.jinja +33 -0
  90. edsl/questions/prompt_templates/question_numerical.jinja +37 -0
  91. edsl/questions/question_registry.py +6 -2
  92. edsl/questions/templates/__init__.py +0 -0
  93. edsl/questions/templates/checkbox/__init__.py +0 -0
  94. edsl/questions/templates/checkbox/answering_instructions.jinja +10 -0
  95. edsl/questions/templates/checkbox/question_presentation.jinja +22 -0
  96. edsl/questions/templates/extract/answering_instructions.jinja +7 -0
  97. edsl/questions/templates/extract/question_presentation.jinja +1 -0
  98. edsl/questions/templates/free_text/__init__.py +0 -0
  99. edsl/questions/templates/free_text/answering_instructions.jinja +0 -0
  100. edsl/questions/templates/free_text/question_presentation.jinja +1 -0
  101. edsl/questions/templates/likert_five/__init__.py +0 -0
  102. edsl/questions/templates/likert_five/answering_instructions.jinja +10 -0
  103. edsl/questions/templates/likert_five/question_presentation.jinja +12 -0
  104. edsl/questions/templates/linear_scale/__init__.py +0 -0
  105. edsl/questions/templates/linear_scale/answering_instructions.jinja +5 -0
  106. edsl/questions/templates/linear_scale/question_presentation.jinja +5 -0
  107. edsl/questions/templates/list/__init__.py +0 -0
  108. edsl/questions/templates/list/answering_instructions.jinja +4 -0
  109. edsl/questions/templates/list/question_presentation.jinja +5 -0
  110. edsl/questions/templates/multiple_choice/__init__.py +0 -0
  111. edsl/questions/templates/multiple_choice/answering_instructions.jinja +9 -0
  112. edsl/questions/templates/multiple_choice/html.jinja +0 -0
  113. edsl/questions/templates/multiple_choice/question_presentation.jinja +12 -0
  114. edsl/questions/templates/numerical/__init__.py +0 -0
  115. edsl/questions/templates/numerical/answering_instructions.jinja +8 -0
  116. edsl/questions/templates/numerical/question_presentation.jinja +7 -0
  117. edsl/questions/templates/rank/answering_instructions.jinja +11 -0
  118. edsl/questions/templates/rank/question_presentation.jinja +15 -0
  119. edsl/questions/templates/top_k/__init__.py +0 -0
  120. edsl/questions/templates/top_k/answering_instructions.jinja +8 -0
  121. edsl/questions/templates/top_k/question_presentation.jinja +22 -0
  122. edsl/questions/templates/yes_no/__init__.py +0 -0
  123. edsl/questions/templates/yes_no/answering_instructions.jinja +6 -0
  124. edsl/questions/templates/yes_no/question_presentation.jinja +12 -0
  125. edsl/results/Dataset.py +20 -0
  126. edsl/results/DatasetExportMixin.py +41 -47
  127. edsl/results/DatasetTree.py +145 -0
  128. edsl/results/Result.py +32 -5
  129. edsl/results/Results.py +131 -45
  130. edsl/results/ResultsDBMixin.py +3 -3
  131. edsl/results/Selector.py +118 -0
  132. edsl/results/tree_explore.py +115 -0
  133. edsl/scenarios/Scenario.py +10 -4
  134. edsl/scenarios/ScenarioList.py +348 -39
  135. edsl/scenarios/ScenarioListExportMixin.py +9 -0
  136. edsl/study/SnapShot.py +8 -1
  137. edsl/surveys/RuleCollection.py +2 -2
  138. edsl/surveys/Survey.py +634 -315
  139. edsl/surveys/SurveyExportMixin.py +71 -9
  140. edsl/surveys/SurveyFlowVisualizationMixin.py +2 -1
  141. edsl/surveys/SurveyQualtricsImport.py +75 -4
  142. edsl/surveys/instructions/ChangeInstruction.py +47 -0
  143. edsl/surveys/instructions/Instruction.py +34 -0
  144. edsl/surveys/instructions/InstructionCollection.py +77 -0
  145. edsl/surveys/instructions/__init__.py +0 -0
  146. edsl/templates/error_reporting/base.html +24 -0
  147. edsl/templates/error_reporting/exceptions_by_model.html +35 -0
  148. edsl/templates/error_reporting/exceptions_by_question_name.html +17 -0
  149. edsl/templates/error_reporting/exceptions_by_type.html +17 -0
  150. edsl/templates/error_reporting/interview_details.html +111 -0
  151. edsl/templates/error_reporting/interviews.html +10 -0
  152. edsl/templates/error_reporting/overview.html +5 -0
  153. edsl/templates/error_reporting/performance_plot.html +2 -0
  154. edsl/templates/error_reporting/report.css +74 -0
  155. edsl/templates/error_reporting/report.html +118 -0
  156. edsl/templates/error_reporting/report.js +25 -0
  157. {edsl-0.1.33.dev1.dist-info → edsl-0.1.33.dev2.dist-info}/METADATA +4 -2
  158. edsl-0.1.33.dev2.dist-info/RECORD +289 -0
  159. edsl/jobs/interviews/InterviewTaskBuildingMixin.py +0 -286
  160. edsl/utilities/gcp_bucket/simple_example.py +0 -9
  161. edsl-0.1.33.dev1.dist-info/RECORD +0 -209
  162. {edsl-0.1.33.dev1.dist-info → edsl-0.1.33.dev2.dist-info}/LICENSE +0 -0
  163. {edsl-0.1.33.dev1.dist-info → edsl-0.1.33.dev2.dist-info}/WHEEL +0 -0
@@ -1,4 +1,16 @@
1
- """This module contains the LanguageModel class, which is an abstract base class for all language models."""
1
+ """This module contains the LanguageModel class, which is an abstract base class for all language models.
2
+
3
+ Terminology:
4
+
5
+ raw_response: The JSON response from the model. This has all the model meta-data about the call.
6
+
7
+ edsl_augmented_response: The JSON response from model, but augmented with EDSL-specific information,
8
+ such as the cache key, token usage, etc.
9
+
10
+ generated_tokens: The actual tokens generated by the model. This is the output that is used by the user.
11
+ edsl_answer_dict: The parsed JSON response from the model either {'answer': ...} or {'answer': ..., 'comment': ...}
12
+
13
+ """
2
14
 
3
15
  from __future__ import annotations
4
16
  import warnings
@@ -8,47 +20,103 @@ import json
8
20
  import time
9
21
  import os
10
22
  import hashlib
11
- from typing import Coroutine, Any, Callable, Type, List, get_type_hints
23
+ from typing import (
24
+ Coroutine,
25
+ Any,
26
+ Callable,
27
+ Type,
28
+ Union,
29
+ List,
30
+ get_type_hints,
31
+ TypedDict,
32
+ Optional,
33
+ )
12
34
  from abc import ABC, abstractmethod
13
35
 
36
+ from json_repair import repair_json
14
37
 
15
- class IntendedModelCallOutcome:
16
- "This is a tuple-like class that holds the response, cache_used, and cache_key."
17
-
18
- def __init__(self, response: dict, cache_used: bool, cache_key: str):
19
- self.response = response
20
- self.cache_used = cache_used
21
- self.cache_key = cache_key
22
-
23
- def __iter__(self):
24
- """Iterate over the class attributes.
25
-
26
- >>> a, b, c = IntendedModelCallOutcome({'answer': "yes"}, True, 'x1289')
27
- >>> a
28
- {'answer': 'yes'}
29
- """
30
- yield self.response
31
- yield self.cache_used
32
- yield self.cache_key
33
-
34
- def __len__(self):
35
- return 3
36
-
37
- def __repr__(self):
38
- return f"IntendedModelCallOutcome(response = {self.response}, cache_used = {self.cache_used}, cache_key = '{self.cache_key}')"
38
+ from edsl.data_transfer_models import (
39
+ ModelResponse,
40
+ ModelInputs,
41
+ EDSLOutput,
42
+ AgentResponseDict,
43
+ )
39
44
 
40
45
 
41
46
  from edsl.config import CONFIG
42
-
43
47
  from edsl.utilities.decorators import sync_wrapper, jupyter_nb_handler
44
48
  from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
45
-
46
49
  from edsl.language_models.repair import repair
47
50
  from edsl.enums import InferenceServiceType
48
51
  from edsl.Base import RichPrintingMixin, PersistenceMixin
49
52
  from edsl.enums import service_to_api_keyname
50
53
  from edsl.exceptions import MissingAPIKeyError
51
54
  from edsl.language_models.RegisterLanguageModelsMeta import RegisterLanguageModelsMeta
55
+ from edsl.exceptions.language_models import LanguageModelBadResponseError
56
+
57
+ TIMEOUT = float(CONFIG.get("EDSL_API_TIMEOUT"))
58
+
59
+
60
+ def convert_answer(response_part):
61
+ import json
62
+
63
+ response_part = response_part.strip()
64
+
65
+ if response_part == "None":
66
+ return None
67
+
68
+ repaired = repair_json(response_part)
69
+ if repaired == '""':
70
+ # it was a literal string
71
+ return response_part
72
+
73
+ try:
74
+ return json.loads(repaired)
75
+ except json.JSONDecodeError as j:
76
+ # last resort
77
+ return response_part
78
+
79
+
80
+ def extract_item_from_raw_response(data, key_sequence):
81
+ if isinstance(data, str):
82
+ try:
83
+ data = json.loads(data)
84
+ except json.JSONDecodeError as e:
85
+ return data
86
+ current_data = data
87
+ for i, key in enumerate(key_sequence):
88
+ try:
89
+ if isinstance(current_data, (list, tuple)):
90
+ if not isinstance(key, int):
91
+ raise TypeError(
92
+ f"Expected integer index for sequence at position {i}, got {type(key).__name__}"
93
+ )
94
+ if key < 0 or key >= len(current_data):
95
+ raise IndexError(
96
+ f"Index {key} out of range for sequence of length {len(current_data)} at position {i}"
97
+ )
98
+ elif isinstance(current_data, dict):
99
+ if key not in current_data:
100
+ raise KeyError(
101
+ f"Key '{key}' not found in dictionary at position {i}"
102
+ )
103
+ else:
104
+ raise TypeError(
105
+ f"Cannot index into {type(current_data).__name__} at position {i}. Full response is: {data} of type {type(data)}. Key sequence is: {key_sequence}"
106
+ )
107
+
108
+ current_data = current_data[key]
109
+ except Exception as e:
110
+ path = " -> ".join(map(str, key_sequence[: i + 1]))
111
+ if "error" in data:
112
+ msg = data["error"]
113
+ else:
114
+ msg = f"Error accessing path: {path}. {str(e)}. Full response is: '{data}'"
115
+ raise LanguageModelBadResponseError(message=msg, response_json=data)
116
+ if isinstance(current_data, str):
117
+ return current_data.strip()
118
+ else:
119
+ return current_data
52
120
 
53
121
 
54
122
  def handle_key_error(func):
@@ -92,7 +160,9 @@ class LanguageModel(
92
160
  """
93
161
 
94
162
  _model_ = None
95
-
163
+ key_sequence = (
164
+ None # This should be something like ["choices", 0, "message", "content"]
165
+ )
96
166
  __rate_limits = None
97
167
  __default_rate_limits = {
98
168
  "rpm": 10_000,
@@ -100,7 +170,7 @@ class LanguageModel(
100
170
  } # TODO: Use the OpenAI Teir 1 rate limits
101
171
  _safety_factor = 0.8
102
172
 
103
- def __init__(self, **kwargs):
173
+ def __init__(self, tpm=None, rpm=None, **kwargs):
104
174
  """Initialize the LanguageModel."""
105
175
  self.model = getattr(self, "_model_", None)
106
176
  default_parameters = getattr(self, "_parameters_", None)
@@ -108,6 +178,12 @@ class LanguageModel(
108
178
  self.parameters = parameters
109
179
  self.remote = False
110
180
 
181
+ if rpm is not None:
182
+ self._rpm = rpm
183
+
184
+ if tpm is not None:
185
+ self._tpm = tpm
186
+
111
187
  for key, value in parameters.items():
112
188
  setattr(self, key, value)
113
189
 
@@ -133,7 +209,6 @@ class LanguageModel(
133
209
  def api_token(self) -> str:
134
210
  if not hasattr(self, "_api_token"):
135
211
  key_name = service_to_api_keyname.get(self._inference_service_, "NOT FOUND")
136
-
137
212
  if self._inference_service_ == "bedrock":
138
213
  self._api_token = [os.getenv(key_name[0]), os.getenv(key_name[1])]
139
214
  # Check if any of the tokens are None
@@ -142,13 +217,13 @@ class LanguageModel(
142
217
  self._api_token = os.getenv(key_name)
143
218
  missing_token = self._api_token is None
144
219
  if missing_token and self._inference_service_ != "test" and not self.remote:
145
- print("rainsing error")
220
+ print("raising error")
146
221
  raise MissingAPIKeyError(
147
222
  f"""The key for service: `{self._inference_service_}` is not set.
148
223
  Need a key with name {key_name} in your .env file."""
149
224
  )
150
225
 
151
- return self._api_token
226
+ return self._api_token
152
227
 
153
228
  def __getitem__(self, key):
154
229
  return getattr(self, key)
@@ -209,7 +284,7 @@ class LanguageModel(
209
284
  >>> m = LanguageModel.example()
210
285
  >>> m.set_rate_limits(rpm=100, tpm=1000)
211
286
  >>> m.RPM
212
- 80.0
287
+ 100
213
288
  """
214
289
  self._set_rate_limits(rpm=rpm, tpm=tpm)
215
290
 
@@ -230,8 +305,32 @@ class LanguageModel(
230
305
  @property
231
306
  def RPM(self):
232
307
  """Model's requests-per-minute limit."""
233
- self._set_rate_limits()
234
- return self._safety_factor * self.__rate_limits["rpm"]
308
+ # self._set_rate_limits()
309
+ # return self._safety_factor * self.__rate_limits["rpm"]
310
+ return self.rpm
311
+
312
+ @property
313
+ def TPM(self):
314
+ """Model's tokens-per-minute limit."""
315
+ # self._set_rate_limits()
316
+ # return self._safety_factor * self.__rate_limits["tpm"]
317
+ return self.tpm
318
+
319
+ @property
320
+ def rpm(self):
321
+ return self._rpm
322
+
323
+ @rpm.setter
324
+ def rpm(self, value):
325
+ self._rpm = value
326
+
327
+ @property
328
+ def tpm(self):
329
+ return self._tpm
330
+
331
+ @tpm.setter
332
+ def tpm(self, value):
333
+ self._tpm = value
235
334
 
236
335
  @property
237
336
  def TPM(self):
@@ -270,11 +369,10 @@ class LanguageModel(
270
369
  >>> m = LanguageModel.example(test_model = True)
271
370
  >>> async def test(): return await m.async_execute_model_call("Hello, model!", "You are a helpful agent.")
272
371
  >>> asyncio.run(test())
273
- {'message': '{"answer": "Hello world"}'}
372
+ {'message': [{'text': 'Hello world'}], ...}
274
373
 
275
374
  >>> m.execute_model_call("Hello, model!", "You are a helpful agent.")
276
- {'message': '{"answer": "Hello world"}'}
277
-
375
+ {'message': [{'text': 'Hello world'}], ...}
278
376
  """
279
377
  pass
280
378
 
@@ -307,68 +405,40 @@ class LanguageModel(
307
405
 
308
406
  return main()
309
407
 
310
- @abstractmethod
311
- def parse_response(raw_response: dict[str, Any]) -> str:
312
- """Parse the response and returns the response text.
313
-
314
- >>> m = LanguageModel.example(test_model = True)
315
- >>> m
316
- Model(model_name = 'test', temperature = 0.5)
317
-
318
- What is returned by the API is model-specific and often includes meta-data that we do not need.
319
- For example, here is the results from a call to GPT-4:
320
- To actually track the response, we need to grab
321
- data["choices[0]"]["message"]["content"].
322
- """
323
- raise NotImplementedError
324
-
325
- async def _async_prepare_response(
326
- self, model_call_outcome: IntendedModelCallOutcome, cache: "Cache"
327
- ) -> dict:
328
- """Prepare the response for return."""
329
-
330
- model_response = {
331
- "cache_used": model_call_outcome.cache_used,
332
- "cache_key": model_call_outcome.cache_key,
333
- "usage": model_call_outcome.response.get("usage", {}),
334
- "raw_model_response": model_call_outcome.response,
335
- }
408
+ @classmethod
409
+ def get_generated_token_string(cls, raw_response: dict[str, Any]) -> str:
410
+ """Return the generated token string from the raw response."""
411
+ return extract_item_from_raw_response(raw_response, cls.key_sequence)
336
412
 
337
- answer_portion = self.parse_response(model_call_outcome.response)
338
- try:
339
- answer_dict = json.loads(answer_portion)
340
- except json.JSONDecodeError as e:
341
- # TODO: Turn into logs to generate issues
342
- answer_dict, success = await repair(
343
- bad_json=answer_portion, error_message=str(e), cache=cache
413
+ @classmethod
414
+ def get_usage_dict(cls, raw_response: dict[str, Any]) -> dict[str, Any]:
415
+ """Return the usage dictionary from the raw response."""
416
+ if not hasattr(cls, "usage_sequence"):
417
+ raise NotImplementedError(
418
+ "This inference service does not have a usage_sequence."
344
419
  )
345
- if not success:
346
- raise Exception(
347
- f"""Even the repair failed. The error was: {e}. The response was: {answer_portion}."""
348
- )
349
-
350
- return {**model_response, **answer_dict}
420
+ return extract_item_from_raw_response(raw_response, cls.usage_sequence)
351
421
 
352
- async def async_get_raw_response(
353
- self,
354
- user_prompt: str,
355
- system_prompt: str,
356
- cache: "Cache",
357
- iteration: int = 0,
358
- encoded_image=None,
359
- ) -> IntendedModelCallOutcome:
360
- import warnings
361
-
362
- warnings.warn(
363
- "This method is deprecated. Use async_get_intended_model_call_outcome."
364
- )
365
- return await self._async_get_intended_model_call_outcome(
366
- user_prompt=user_prompt,
367
- system_prompt=system_prompt,
368
- cache=cache,
369
- iteration=iteration,
370
- encoded_image=encoded_image,
371
- )
422
+ @classmethod
423
+ def parse_response(cls, raw_response: dict[str, Any]) -> EDSLOutput:
424
+ """Parses the API response and returns the response text."""
425
+ generated_token_string = cls.get_generated_token_string(raw_response)
426
+ last_newline = generated_token_string.rfind("\n")
427
+
428
+ if last_newline == -1:
429
+ # There is no comment
430
+ edsl_dict = {
431
+ "answer": convert_answer(generated_token_string),
432
+ "generated_tokens": generated_token_string,
433
+ "comment": None,
434
+ }
435
+ else:
436
+ edsl_dict = {
437
+ "answer": convert_answer(generated_token_string[:last_newline]),
438
+ "comment": generated_token_string[last_newline + 1 :].strip(),
439
+ "generated_tokens": generated_token_string,
440
+ }
441
+ return EDSLOutput(**edsl_dict)
372
442
 
373
443
  async def _async_get_intended_model_call_outcome(
374
444
  self,
@@ -377,7 +447,7 @@ class LanguageModel(
377
447
  cache: "Cache",
378
448
  iteration: int = 0,
379
449
  encoded_image=None,
380
- ) -> IntendedModelCallOutcome:
450
+ ) -> ModelResponse:
381
451
  """Handle caching of responses.
382
452
 
383
453
  :param user_prompt: The user's prompt.
@@ -396,8 +466,7 @@ class LanguageModel(
396
466
  >>> from edsl import Cache
397
467
  >>> m = LanguageModel.example(test_model = True)
398
468
  >>> m._get_intended_model_call_outcome(user_prompt = "Hello", system_prompt = "hello", cache = Cache())
399
- IntendedModelCallOutcome(response = {'message': '{"answer": "Hello world"}'}, cache_used = False, cache_key = '24ff6ac2bc2f1729f817f261e0792577')
400
- """
469
+ ModelResponse(...)"""
401
470
 
402
471
  if encoded_image:
403
472
  # the image has is appended to the user_prompt for hash-lookup purposes
@@ -425,21 +494,28 @@ class LanguageModel(
425
494
  "system_prompt": system_prompt,
426
495
  **({"encoded_image": encoded_image} if encoded_image else {}),
427
496
  }
428
- response = await f(**params)
497
+ # response = await f(**params)
498
+ response = await asyncio.wait_for(f(**params), timeout=TIMEOUT)
429
499
  new_cache_key = cache.store(
430
500
  **cache_call_params, response=response
431
501
  ) # store the response in the cache
432
502
  assert new_cache_key == cache_key # should be the same
433
503
 
434
- return IntendedModelCallOutcome(
435
- response=response, cache_used=cache_used, cache_key=cache_key
504
+ cost = self.cost(response)
505
+
506
+ return ModelResponse(
507
+ response=response,
508
+ cache_used=cache_used,
509
+ cache_key=cache_key,
510
+ cached_response=cached_response,
511
+ cost=cost,
436
512
  )
437
513
 
438
514
  _get_intended_model_call_outcome = sync_wrapper(
439
515
  _async_get_intended_model_call_outcome
440
516
  )
441
517
 
442
- get_raw_response = sync_wrapper(async_get_raw_response)
518
+ # get_raw_response = sync_wrapper(async_get_raw_response)
443
519
 
444
520
  def simple_ask(
445
521
  self,
@@ -478,14 +554,66 @@ class LanguageModel(
478
554
  "cache": cache,
479
555
  **({"encoded_image": encoded_image} if encoded_image else {}),
480
556
  }
481
- model_call_outcome = await self._async_get_intended_model_call_outcome(**params)
482
- return await self._async_prepare_response(model_call_outcome, cache=cache)
557
+ model_inputs = ModelInputs(user_prompt=user_prompt, system_prompt=system_prompt)
558
+ model_outputs = await self._async_get_intended_model_call_outcome(**params)
559
+ edsl_dict = self.parse_response(model_outputs.response)
560
+ agent_response_dict = AgentResponseDict(
561
+ model_inputs=model_inputs,
562
+ model_outputs=model_outputs,
563
+ edsl_dict=edsl_dict,
564
+ )
565
+ return agent_response_dict
566
+
567
+ # return await self._async_prepare_response(model_call_outcome, cache=cache)
483
568
 
484
569
  get_response = sync_wrapper(async_get_response)
485
570
 
486
- def cost(self, raw_response: dict[str, Any]) -> float:
571
+ def cost(self, raw_response: dict[str, Any]) -> Union[float, str]:
487
572
  """Return the dollar cost of a raw response."""
488
- raise NotImplementedError
573
+
574
+ usage = self.get_usage_dict(raw_response)
575
+ from edsl.coop import Coop
576
+
577
+ c = Coop()
578
+ price_lookup = c.fetch_prices()
579
+ key = (self._inference_service_, self.model)
580
+ if key not in price_lookup:
581
+ return f"Could not find price for model {self.model} in the price lookup."
582
+
583
+ relevant_prices = price_lookup[key]
584
+ try:
585
+ input_tokens = int(usage[self.input_token_name])
586
+ output_tokens = int(usage[self.output_token_name])
587
+ except Exception as e:
588
+ return f"Could not fetch tokens from model response: {e}"
589
+
590
+ try:
591
+ inverse_output_price = relevant_prices["output"]["one_usd_buys"]
592
+ inverse_input_price = relevant_prices["input"]["one_usd_buys"]
593
+ except Exception as e:
594
+ if "output" not in relevant_prices:
595
+ return f"Could not fetch prices from {relevant_prices} - {e}; Missing 'output' key."
596
+ if "input" not in relevant_prices:
597
+ return f"Could not fetch prices from {relevant_prices} - {e}; Missing 'input' key."
598
+ return f"Could not fetch prices from {relevant_prices} - {e}"
599
+
600
+ if inverse_input_price == "infinity":
601
+ input_cost = 0
602
+ else:
603
+ try:
604
+ input_cost = input_tokens / float(inverse_input_price)
605
+ except Exception as e:
606
+ return f"Could not compute input price - {e}."
607
+
608
+ if inverse_output_price == "infinity":
609
+ output_cost = 0
610
+ else:
611
+ try:
612
+ output_cost = output_tokens / float(inverse_output_price)
613
+ except Exception as e:
614
+ return f"Could not compute output price - {e}"
615
+
616
+ return input_cost + output_cost
489
617
 
490
618
  #######################
491
619
  # SERIALIZATION METHODS
@@ -499,7 +627,7 @@ class LanguageModel(
499
627
 
500
628
  >>> m = LanguageModel.example()
501
629
  >>> m.to_dict()
502
- {'model': 'gpt-4-1106-preview', 'parameters': {'temperature': 0.5, 'max_tokens': 1000, 'top_p': 1, 'frequency_penalty': 0, 'presence_penalty': 0, 'logprobs': False, 'top_logprobs': 3}, 'edsl_version': '...', 'edsl_class_name': 'LanguageModel'}
630
+ {'model': '...', 'parameters': {'temperature': ..., 'max_tokens': ..., 'top_p': ..., 'frequency_penalty': ..., 'presence_penalty': ..., 'logprobs': False, 'top_logprobs': ...}, 'edsl_version': '...', 'edsl_class_name': 'LanguageModel'}
503
631
  """
504
632
  return self._to_dict()
505
633
 
@@ -575,26 +703,8 @@ class LanguageModel(
575
703
  """
576
704
  from edsl import Model
577
705
 
578
- class TestLanguageModelGood(LanguageModel):
579
- use_cache = False
580
- _model_ = "test"
581
- _parameters_ = {"temperature": 0.5}
582
- _inference_service_ = InferenceServiceType.TEST.value
583
-
584
- async def async_execute_model_call(
585
- self, user_prompt: str, system_prompt: str
586
- ) -> dict[str, Any]:
587
- await asyncio.sleep(0.1)
588
- # return {"message": """{"answer": "Hello, world"}"""}
589
- if throw_exception:
590
- raise Exception("This is a test error")
591
- return {"message": f'{{"answer": "{canned_response}"}}'}
592
-
593
- def parse_response(self, raw_response: dict[str, Any]) -> str:
594
- return raw_response["message"]
595
-
596
706
  if test_model:
597
- m = TestLanguageModelGood()
707
+ m = Model("test", canned_response=canned_response)
598
708
  return m
599
709
  else:
600
710
  return Model(skip_api_key_check=True)
@@ -40,8 +40,8 @@ class ModelList(Base, UserList):
40
40
  def __hash__(self):
41
41
  """Return a hash of the ModelList. This is used for comparison of ModelLists.
42
42
 
43
- >>> hash(ModelList.example())
44
- 1423518243781418961
43
+ >>> isinstance(hash(Model()), int)
44
+ True
45
45
 
46
46
  """
47
47
  from edsl.utilities.utilities import dict_hash
@@ -47,13 +47,6 @@ class RegisterLanguageModelsMeta(ABCMeta):
47
47
  must_be_async=True,
48
48
  )
49
49
  # LanguageModel children have to implement the parse_response method
50
- RegisterLanguageModelsMeta.verify_method(
51
- candidate_class=cls,
52
- method_name="parse_response",
53
- expected_return_type=str,
54
- required_parameters=[("raw_response", dict[str, Any])],
55
- must_be_async=False,
56
- )
57
50
  RegisterLanguageModelsMeta._registry[model_name] = cls
58
51
 
59
52
  @classmethod
@@ -98,7 +91,7 @@ class RegisterLanguageModelsMeta(ABCMeta):
98
91
 
99
92
  required_parameters = required_parameters or []
100
93
  method = getattr(candidate_class, method_name)
101
- signature = inspect.signature(method)
94
+ # signature = inspect.signature(method)
102
95
 
103
96
  RegisterLanguageModelsMeta._check_return_type(method, expected_return_type)
104
97
 
@@ -106,11 +99,11 @@ class RegisterLanguageModelsMeta(ABCMeta):
106
99
  RegisterLanguageModelsMeta._check_is_coroutine(method)
107
100
 
108
101
  # Check the parameters
109
- params = signature.parameters
110
- for param_name, param_type in required_parameters:
111
- RegisterLanguageModelsMeta._verify_parameter(
112
- params, param_name, param_type, method_name
113
- )
102
+ # params = signature.parameters
103
+ # for param_name, param_type in required_parameters:
104
+ # RegisterLanguageModelsMeta._verify_parameter(
105
+ # params, param_name, param_type, method_name
106
+ # )
114
107
 
115
108
  @staticmethod
116
109
  def _check_method_defined(cls, method_name):
@@ -167,23 +160,15 @@ class RegisterLanguageModelsMeta(ABCMeta):
167
160
  Check if the return type of a method is as expected.
168
161
 
169
162
  Example:
170
- >>> class M:
171
- ... async def f(self) -> str: pass
172
- >>> RegisterLanguageModelsMeta._check_return_type(M.f, str)
173
- >>> class N:
174
- ... async def f(self) -> int: pass
175
- >>> RegisterLanguageModelsMeta._check_return_type(N.f, str)
176
- Traceback (most recent call last):
177
- ...
178
- TypeError: Return type of f must be <class 'str'>. Got <class 'int'>.
179
163
  """
180
- if inspect.isroutine(method):
181
- # return_type = inspect.signature(method).return_annotation
182
- return_type = get_type_hints(method)["return"]
183
- if return_type != expected_return_type:
184
- raise TypeError(
185
- f"Return type of {method.__name__} must be {expected_return_type}. Got {return_type}."
186
- )
164
+ pass
165
+ # if inspect.isroutine(method):
166
+ # # return_type = inspect.signature(method).return_annotation
167
+ # return_type = get_type_hints(method)["return"]
168
+ # if return_type != expected_return_type:
169
+ # raise TypeError(
170
+ # f"Return type of {method.__name__} must be {expected_return_type}. Got {return_type}."
171
+ # )
187
172
 
188
173
  @classmethod
189
174
  def model_names_to_classes(cls):
@@ -0,0 +1,15 @@
1
+ from openai import AsyncOpenAI
2
+ import asyncio
3
+
4
+ client = AsyncOpenAI(base_url="http://127.0.0.1:8000/v1", api_key="fake_key")
5
+
6
+
7
+ async def main():
8
+ response = await client.chat.completions.create(
9
+ model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Question XX42"}]
10
+ )
11
+ print(response)
12
+
13
+
14
+ if __name__ == "__main__":
15
+ asyncio.run(main())
@@ -0,0 +1,61 @@
1
+ import threading
2
+ import asyncio
3
+ from fastapi import FastAPI, Request
4
+ from fastapi.responses import JSONResponse
5
+ import uvicorn
6
+ import json
7
+ from typing import Any
8
+
9
+ app = FastAPI()
10
+
11
+
12
+ async def generate_response(question_number: int) -> dict:
13
+ # Simulate some asynchronous work
14
+ await asyncio.sleep(1)
15
+ return {
16
+ "id": "chatcmpl-123",
17
+ "object": "chat.completion",
18
+ "created": 1677652288,
19
+ "model": "gpt-3.5-turbo-0613",
20
+ "choices": [
21
+ {
22
+ "index": 0,
23
+ "message": {
24
+ "role": "assistant",
25
+ "content": json.dumps(
26
+ {"answer": f"SPAM for question {question_number}!"}
27
+ ),
28
+ },
29
+ "finish_reason": "stop",
30
+ }
31
+ ],
32
+ "usage": {"prompt_tokens": 9, "completion_tokens": 12, "total_tokens": 21},
33
+ }
34
+
35
+
36
+ @app.post("/v1/chat/completions")
37
+ async def chat_completions(request: Request):
38
+ body = await request.json()
39
+ user_prompt = body["messages"][-1]["content"]
40
+ question_number = int(user_prompt.split("XX")[1])
41
+
42
+ response = await generate_response(question_number)
43
+ return JSONResponse(content=response)
44
+
45
+
46
+ def run_server():
47
+ uvicorn.run(app, host="127.0.0.1", port=8000)
48
+
49
+
50
+ if __name__ == "__main__":
51
+ # Start the server in a separate thread
52
+ server_thread = threading.Thread(target=run_server)
53
+ server_thread.start()
54
+
55
+ # Your main code here
56
+ # ...
57
+
58
+ # To use this with the OpenAI SDK:
59
+ # from openai import AsyncOpenAI
60
+ # client = AsyncOpenAI(base_url="http://127.0.0.1:8000/v1", api_key="fake_key")
61
+ # response = await client.chat.completions.create(model="gpt-3.5-turbo", messages=[...])