edsl 0.1.27.dev2__py3-none-any.whl → 0.1.28__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 (88) hide show
  1. edsl/Base.py +99 -22
  2. edsl/BaseDiff.py +260 -0
  3. edsl/__init__.py +4 -0
  4. edsl/__version__.py +1 -1
  5. edsl/agents/Agent.py +26 -5
  6. edsl/agents/AgentList.py +62 -7
  7. edsl/agents/Invigilator.py +4 -9
  8. edsl/agents/InvigilatorBase.py +5 -5
  9. edsl/agents/descriptors.py +3 -1
  10. edsl/conjure/AgentConstructionMixin.py +152 -0
  11. edsl/conjure/Conjure.py +56 -0
  12. edsl/conjure/InputData.py +628 -0
  13. edsl/conjure/InputDataCSV.py +48 -0
  14. edsl/conjure/InputDataMixinQuestionStats.py +182 -0
  15. edsl/conjure/InputDataPyRead.py +91 -0
  16. edsl/conjure/InputDataSPSS.py +8 -0
  17. edsl/conjure/InputDataStata.py +8 -0
  18. edsl/conjure/QuestionOptionMixin.py +76 -0
  19. edsl/conjure/QuestionTypeMixin.py +23 -0
  20. edsl/conjure/RawQuestion.py +65 -0
  21. edsl/conjure/SurveyResponses.py +7 -0
  22. edsl/conjure/__init__.py +9 -4
  23. edsl/conjure/examples/placeholder.txt +0 -0
  24. edsl/conjure/naming_utilities.py +263 -0
  25. edsl/conjure/utilities.py +165 -28
  26. edsl/conversation/Conversation.py +238 -0
  27. edsl/conversation/car_buying.py +58 -0
  28. edsl/conversation/mug_negotiation.py +81 -0
  29. edsl/conversation/next_speaker_utilities.py +93 -0
  30. edsl/coop/coop.py +191 -12
  31. edsl/coop/utils.py +20 -2
  32. edsl/data/Cache.py +55 -17
  33. edsl/data/CacheHandler.py +10 -9
  34. edsl/inference_services/AnthropicService.py +1 -0
  35. edsl/inference_services/DeepInfraService.py +20 -13
  36. edsl/inference_services/GoogleService.py +7 -1
  37. edsl/inference_services/InferenceServicesCollection.py +33 -7
  38. edsl/inference_services/OpenAIService.py +17 -10
  39. edsl/inference_services/models_available_cache.py +69 -0
  40. edsl/inference_services/rate_limits_cache.py +25 -0
  41. edsl/inference_services/write_available.py +10 -0
  42. edsl/jobs/Jobs.py +240 -36
  43. edsl/jobs/buckets/BucketCollection.py +9 -3
  44. edsl/jobs/interviews/Interview.py +4 -1
  45. edsl/jobs/interviews/InterviewTaskBuildingMixin.py +24 -10
  46. edsl/jobs/interviews/retry_management.py +4 -4
  47. edsl/jobs/runners/JobsRunnerAsyncio.py +87 -45
  48. edsl/jobs/runners/JobsRunnerStatusData.py +3 -3
  49. edsl/jobs/tasks/QuestionTaskCreator.py +4 -2
  50. edsl/language_models/LanguageModel.py +37 -44
  51. edsl/language_models/ModelList.py +96 -0
  52. edsl/language_models/registry.py +14 -0
  53. edsl/language_models/repair.py +95 -24
  54. edsl/notebooks/Notebook.py +119 -31
  55. edsl/questions/QuestionBase.py +109 -12
  56. edsl/questions/descriptors.py +5 -2
  57. edsl/questions/question_registry.py +7 -0
  58. edsl/results/Result.py +20 -8
  59. edsl/results/Results.py +85 -11
  60. edsl/results/ResultsDBMixin.py +3 -6
  61. edsl/results/ResultsExportMixin.py +47 -16
  62. edsl/results/ResultsToolsMixin.py +5 -5
  63. edsl/scenarios/Scenario.py +59 -5
  64. edsl/scenarios/ScenarioList.py +97 -40
  65. edsl/study/ObjectEntry.py +97 -0
  66. edsl/study/ProofOfWork.py +110 -0
  67. edsl/study/SnapShot.py +77 -0
  68. edsl/study/Study.py +491 -0
  69. edsl/study/__init__.py +2 -0
  70. edsl/surveys/Survey.py +79 -31
  71. edsl/surveys/SurveyExportMixin.py +21 -3
  72. edsl/utilities/__init__.py +1 -0
  73. edsl/utilities/gcp_bucket/__init__.py +0 -0
  74. edsl/utilities/gcp_bucket/cloud_storage.py +96 -0
  75. edsl/utilities/gcp_bucket/simple_example.py +9 -0
  76. edsl/utilities/interface.py +24 -28
  77. edsl/utilities/repair_functions.py +28 -0
  78. edsl/utilities/utilities.py +57 -2
  79. {edsl-0.1.27.dev2.dist-info → edsl-0.1.28.dist-info}/METADATA +43 -17
  80. {edsl-0.1.27.dev2.dist-info → edsl-0.1.28.dist-info}/RECORD +83 -55
  81. edsl-0.1.28.dist-info/entry_points.txt +3 -0
  82. edsl/conjure/RawResponseColumn.py +0 -327
  83. edsl/conjure/SurveyBuilder.py +0 -308
  84. edsl/conjure/SurveyBuilderCSV.py +0 -78
  85. edsl/conjure/SurveyBuilderSPSS.py +0 -118
  86. edsl/data/RemoteDict.py +0 -103
  87. {edsl-0.1.27.dev2.dist-info → edsl-0.1.28.dist-info}/LICENSE +0 -0
  88. {edsl-0.1.27.dev2.dist-info → edsl-0.1.28.dist-info}/WHEEL +0 -0
@@ -27,13 +27,13 @@ class InvigilatorBase(ABC):
27
27
  This returns an empty prompt because there is no memory the agent needs to have at q0.
28
28
 
29
29
  >>> InvigilatorBase.example().create_memory_prompt("q0")
30
- Prompt(text='')
30
+ Prompt(text=\"""\""")
31
31
 
32
32
  >>> i = InvigilatorBase.example()
33
33
  >>> i.current_answers = {"q0": "Prior answer"}
34
34
  >>> i.memory_plan.add_single_memory("q1", "q0")
35
35
  >>> i.create_memory_prompt("q1")
36
- Prompt(text='
36
+ Prompt(text=\"""
37
37
  Before the question you are now answering, you already answered the following question(s):
38
38
  ...
39
39
  """
@@ -67,7 +67,7 @@ class InvigilatorBase(ABC):
67
67
  """Return a string representation of the Invigilator.
68
68
 
69
69
  >>> InvigilatorBase.example().__repr__()
70
- "InvigilatorExample(...)"
70
+ 'InvigilatorExample(...)'
71
71
 
72
72
  """
73
73
  return f"{self.__class__.__name__}(agent={repr(self.agent)}, question={repr(self.question)}, scneario={repr(self.scenario)}, model={repr(self.model)}, memory_plan={repr(self.memory_plan)}, current_answers={repr(self.current_answers)}, iteration{repr(self.iteration)}, additional_prompt_data={repr(self.additional_prompt_data)}, cache={repr(self.cache)}, sidecarmodel={repr(self.sidecar_model)})"
@@ -89,7 +89,7 @@ class InvigilatorBase(ABC):
89
89
  """Return the prompt used.
90
90
 
91
91
  >>> InvigilatorBase.example().get_prompts()
92
- {'user_prompt': Prompt(text='NA'), 'system_prompt': Prompt(text='NA')}
92
+ {'user_prompt': Prompt(text=\"""NA\"""), 'system_prompt': Prompt(text=\"""NA\""")}
93
93
  """
94
94
  return {
95
95
  "user_prompt": Prompt("NA"),
@@ -133,7 +133,7 @@ class InvigilatorBase(ABC):
133
133
  """Return an example invigilator.
134
134
 
135
135
  >>> InvigilatorBase.example()
136
- InvigilatorExample(agent=Agent(traits = {'age': 22, 'hair': 'brown', 'height': 5.5}), question=Question('multiple_choice', question_name = 'how_feeling', question_text = 'How are you?', question_options = ['Good', 'Great', 'OK', 'Bad']), scneario=Scenario({'persona': 'A reseacher studying whether LLMs can be used to generate surveys.'}), model=Model(model_name = 'test', temperature = 0.5), memory_plan={}, current_answers=None, iteration1, additional_prompt_data=None, cache=None, sidecarmodel=None)
136
+ InvigilatorExample(...)
137
137
 
138
138
  """
139
139
  from edsl.agents.Agent import Agent
@@ -40,7 +40,9 @@ class TraitsDescriptor:
40
40
 
41
41
  if not is_valid_variable_name(key):
42
42
  raise AgentTraitKeyError(
43
- "Trait keys must be valid Python identifiers (must be alphanumeric, cannot start with a number and must use underscores instead of spaces)."
43
+ f"""Trait keys must be valid Python identifiers (must be alphanumeric, cannot start with a number and must use underscores instead of spaces).
44
+ You passed: {key}
45
+ """
44
46
  )
45
47
 
46
48
  instance.__dict__[self.name] = traits_dict
@@ -0,0 +1,152 @@
1
+ import random
2
+ from typing import Generator, List, Optional, Union, Callable
3
+ from edsl.agents.Agent import Agent
4
+ from edsl.agents.AgentList import AgentList
5
+ from edsl.questions import QuestionBase
6
+ from edsl.results.Results import Results
7
+
8
+
9
+ class AgentConstructionMixin:
10
+ def agent(self, index) -> Agent:
11
+ """Return an agent constructed from the data.
12
+
13
+ :param index: The index of the agent to construct.
14
+
15
+ >>> from edsl.conjure.InputData import InputDataABC
16
+ >>> id = InputDataABC.example()
17
+ >>> id.agent(0)
18
+ Agent(traits = {'morning': '1', 'feeling': '3'}, codebook = {'morning': 'how are you doing this morning?', 'feeling': 'how are you feeling?'})
19
+
20
+
21
+ """
22
+ responses = [responses[index] for responses in self.raw_data]
23
+ traits = {qn: r for qn, r in zip(self.question_names, responses)}
24
+
25
+ a = Agent(traits=traits, codebook=self.names_to_texts)
26
+
27
+ def construct_answer_dict_function(traits: dict) -> Callable:
28
+ def func(self, question: "QuestionBase", scenario=None):
29
+ return traits.get(question.question_name, None)
30
+
31
+ return func
32
+
33
+ a.add_direct_question_answering_method(construct_answer_dict_function(traits))
34
+ return a
35
+
36
+ def _agents(self, indices) -> Generator[Agent, None, None]:
37
+ """Return a generator of agents, one for each index."""
38
+ for idx in indices:
39
+ yield self.agent(idx)
40
+
41
+ def to_agent_list(
42
+ self,
43
+ indices: Optional[List] = None,
44
+ sample_size: int = None,
45
+ seed: str = "edsl",
46
+ remove_direct_question_answering_method: bool = True,
47
+ ) -> AgentList:
48
+ """Return an AgentList from the data.
49
+
50
+ :param indices: The indices of the agents to include.
51
+ :param sample_size: The number of agents to sample.
52
+ :param seed: The seed for the random number generator.
53
+
54
+ >>> from edsl.conjure.InputData import InputDataABC
55
+ >>> id = InputDataABC.example()
56
+ >>> al = id.to_agent_list()
57
+ >>> len(al) == id.num_observations
58
+ True
59
+ >>> al = id.to_agent_list(indices = [0, 1, 2])
60
+ Traceback (most recent call last):
61
+ ...
62
+ ValueError: Index 2 is greater than the number of agents 2.
63
+ """
64
+ if indices and (sample_size or seed != "edsl"):
65
+ raise ValueError(
66
+ "You cannot pass both indices and sample_size/seed, as these are mutually exclusive."
67
+ )
68
+
69
+ if indices:
70
+ if len(indices) == 0:
71
+ raise ValueError("Indices must be a non-empty list.")
72
+ if max(indices) >= self.num_observations:
73
+ raise ValueError(
74
+ f"Index {max(indices)} is greater than the number of agents {self.num_observations}."
75
+ )
76
+ if min(indices) < 0:
77
+ raise ValueError(f"Index {min(indices)} is less than 0.")
78
+
79
+ if indices is None:
80
+ if sample_size is None:
81
+ indices = range(self.num_observations)
82
+ else:
83
+ if sample_size > self.num_observations:
84
+ raise ValueError(
85
+ f"Sample size {sample_size} is greater than the number of agents {self.num_observations}."
86
+ )
87
+ random.seed(seed)
88
+ indices = random.sample(range(self.num_observations), sample_size)
89
+
90
+ agents = list(self._agents(indices))
91
+ if remove_direct_question_answering_method:
92
+ for a in agents:
93
+ a.remove_direct_question_answering_method()
94
+ return AgentList(agents)
95
+
96
+ def to_results(
97
+ self,
98
+ indices: Optional[List] = None,
99
+ sample_size: int = None,
100
+ seed: str = "edsl",
101
+ dryrun=False,
102
+ ) -> Union[Results, None]:
103
+ """Return the results of the survey.
104
+
105
+ :param indices: The indices of the agents to include.
106
+ :param sample_size: The number of agents to sample.
107
+ :param seed: The seed for the random number generator.
108
+ :param dryrun: If True, the survey will not be run, but the time to run it will be printed.
109
+
110
+ >>> from edsl.conjure.InputData import InputDataABC
111
+ >>> id = InputDataABC.example()
112
+ >>> r = id.to_results()
113
+ >>> len(r) == id.num_observations
114
+ True
115
+ """
116
+ agent_list = self.to_agent_list(
117
+ indices=indices,
118
+ sample_size=sample_size,
119
+ seed=seed,
120
+ remove_direct_question_answering_method=False,
121
+ )
122
+ DRYRUN_SAMPLE = 30
123
+ survey = self.to_survey()
124
+ if dryrun:
125
+ import time
126
+
127
+ start = time.time()
128
+ _ = survey.by(agent_list.sample(DRYRUN_SAMPLE)).run()
129
+ end = time.time()
130
+ print(f"Time to run {DRYRUN_SAMPLE} agents (s): {round(end - start, 2)}")
131
+ time_per_agent = (end - start) / DRYRUN_SAMPLE
132
+ full_sample_time = time_per_agent * len(agent_list)
133
+ if full_sample_time < 60:
134
+ print(
135
+ f"Full sample will take about {round(full_sample_time, 2)} seconds."
136
+ )
137
+ if full_sample_time > 60 and full_sample_time < 3600:
138
+ print(
139
+ f"Full sample will take about {round(full_sample_time / 60, 2)} minutes."
140
+ )
141
+ if full_sample_time > 3600:
142
+ print(
143
+ f"Full sample will take about {round(full_sample_time / 3600, 2)} hours."
144
+ )
145
+ return None
146
+ return survey.by(agent_list).run()
147
+
148
+
149
+ if __name__ == "__main__":
150
+ import doctest
151
+
152
+ doctest.testmod(optionflags=doctest.ELLIPSIS)
@@ -0,0 +1,56 @@
1
+ from typing import List, Optional, Dict, Callable
2
+
3
+
4
+ class Conjure:
5
+ def __new__(cls, datafile_name: str, *args, **kwargs):
6
+ if datafile_name.endswith(".csv"):
7
+ from edsl.conjure.InputDataCSV import InputDataCSV
8
+
9
+ return InputDataCSV(datafile_name, *args, **kwargs)
10
+ elif datafile_name.endswith(".sav"):
11
+ from edsl.conjure.InputDataSPSS import InputDataSPSS
12
+
13
+ return InputDataSPSS(datafile_name, *args, **kwargs)
14
+ elif datafile_name.endswith(".dta"):
15
+ from edsl.conjure.InputDataStata import InputDataStata
16
+
17
+ return InputDataStata(datafile_name, *args, **kwargs)
18
+ else:
19
+ raise ValueError("Unsupported file type")
20
+
21
+ def __init__(
22
+ self,
23
+ datafile_name: str,
24
+ config: Optional[dict] = None,
25
+ naming_function: Optional[Callable] = None,
26
+ raw_data: Optional[List] = None,
27
+ question_names: Optional[List[str]] = None,
28
+ question_texts: Optional[List[str]] = None,
29
+ answer_codebook: Optional[Dict] = None,
30
+ question_types: Optional[List[str]] = None,
31
+ question_options: Optional[List] = None,
32
+ order_options=False,
33
+ question_name_repair_func: Callable = None,
34
+ ):
35
+ # The __init__ method in Conjure won't be called because __new__ returns a different class instance.
36
+ pass
37
+
38
+
39
+ if __name__ == "__main__":
40
+ pass
41
+ # import glob
42
+
43
+ # for file in glob.glob("examples/*"):
44
+ # if file.endswith(".txt"):
45
+ # continue
46
+ # print("\n\n")
47
+ # print("Now processing:", file)
48
+ # conjure_instance = Conjure(file)
49
+ # print(conjure_instance)
50
+ # conjure_instance.to_results(dryrun=True)
51
+ # print("\n\n")
52
+
53
+ # # c = Conjure("mayors.sav")
54
+ # # al = c.to_agent_list()
55
+ # # s = c.to_survey()
56
+ # # r = c.results()