edsl 0.1.45__py3-none-any.whl → 0.1.47__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 (44) hide show
  1. edsl/Base.py +87 -16
  2. edsl/__version__.py +1 -1
  3. edsl/agents/PromptConstructor.py +26 -79
  4. edsl/agents/QuestionInstructionPromptBuilder.py +70 -32
  5. edsl/agents/QuestionTemplateReplacementsBuilder.py +12 -2
  6. edsl/coop/coop.py +289 -147
  7. edsl/data/Cache.py +2 -0
  8. edsl/data/CacheEntry.py +10 -2
  9. edsl/data/RemoteCacheSync.py +10 -9
  10. edsl/inference_services/AvailableModelFetcher.py +1 -1
  11. edsl/inference_services/PerplexityService.py +9 -5
  12. edsl/jobs/AnswerQuestionFunctionConstructor.py +12 -1
  13. edsl/jobs/Jobs.py +35 -17
  14. edsl/jobs/JobsComponentConstructor.py +2 -1
  15. edsl/jobs/JobsPrompts.py +49 -26
  16. edsl/jobs/JobsRemoteInferenceHandler.py +4 -5
  17. edsl/jobs/data_structures.py +3 -0
  18. edsl/jobs/interviews/Interview.py +6 -3
  19. edsl/language_models/LanguageModel.py +7 -1
  20. edsl/questions/QuestionBase.py +5 -0
  21. edsl/questions/question_base_gen_mixin.py +2 -0
  22. edsl/questions/question_registry.py +6 -7
  23. edsl/results/DatasetExportMixin.py +124 -6
  24. edsl/results/Results.py +59 -0
  25. edsl/scenarios/FileStore.py +112 -7
  26. edsl/scenarios/ScenarioList.py +283 -21
  27. edsl/study/Study.py +2 -2
  28. edsl/surveys/Survey.py +15 -20
  29. {edsl-0.1.45.dist-info → edsl-0.1.47.dist-info}/METADATA +4 -3
  30. {edsl-0.1.45.dist-info → edsl-0.1.47.dist-info}/RECORD +32 -44
  31. edsl/auto/AutoStudy.py +0 -130
  32. edsl/auto/StageBase.py +0 -243
  33. edsl/auto/StageGenerateSurvey.py +0 -178
  34. edsl/auto/StageLabelQuestions.py +0 -125
  35. edsl/auto/StagePersona.py +0 -61
  36. edsl/auto/StagePersonaDimensionValueRanges.py +0 -88
  37. edsl/auto/StagePersonaDimensionValues.py +0 -74
  38. edsl/auto/StagePersonaDimensions.py +0 -69
  39. edsl/auto/StageQuestions.py +0 -74
  40. edsl/auto/SurveyCreatorPipeline.py +0 -21
  41. edsl/auto/utilities.py +0 -218
  42. edsl/base/Base.py +0 -279
  43. {edsl-0.1.45.dist-info → edsl-0.1.47.dist-info}/LICENSE +0 -0
  44. {edsl-0.1.45.dist-info → edsl-0.1.47.dist-info}/WHEEL +0 -0
edsl/auto/AutoStudy.py DELETED
@@ -1,130 +0,0 @@
1
- from typing import Optional, TYPE_CHECKING
2
-
3
- from edsl import Model
4
- from edsl.auto.StageQuestions import StageQuestions
5
- from edsl.auto.StagePersona import StagePersona
6
- from edsl.auto.StagePersonaDimensions import StagePersonaDimensions
7
- from edsl.auto.StagePersonaDimensionValues import StagePersonaDimensionValues
8
- from edsl.auto.StagePersonaDimensionValueRanges import (
9
- StagePersonaDimensionValueRanges,
10
- )
11
- from edsl.auto.StageLabelQuestions import StageLabelQuestions
12
- from edsl.auto.StageGenerateSurvey import StageGenerateSurvey
13
-
14
- from edsl.auto.utilities import agent_generator, create_agents, gen_pipeline
15
-
16
- if TYPE_CHECKING:
17
- from edsl.surveys.Survey import Survey
18
- from edsl.agents.AgentList import AgentList
19
-
20
-
21
- class AutoStudy:
22
- def __init__(
23
- self,
24
- overall_question: str,
25
- population: str,
26
- model: Optional["Model"] = None,
27
- survey: Optional["Survey"] = None,
28
- agent_list: Optional["AgentList"] = None,
29
- default_num_agents: int = 11,
30
- ):
31
- """AutoStudy class for generating surveys and agents."""
32
-
33
- self.overall_question = overall_question
34
- self.population = population
35
- self._survey = survey
36
- self._agent_list = agent_list
37
- self._agent_list_generator = None
38
- self._persona_mapping = None
39
- self._results = None
40
- self.default_num_agents = default_num_agents
41
- self.model = model or Model()
42
-
43
- def to_dict(self):
44
- return {
45
- "overall_question": self.overall_question,
46
- "population": self.population,
47
- "survey": self.survey.to_dict(),
48
- "persona_mapping": self.persona_mapping.to_dict(),
49
- "results": self.results.to_dict(),
50
- }
51
-
52
- @property
53
- def survey(self):
54
- if self._survey is None:
55
- self._survey = self._create_survey()
56
- return self._survey
57
-
58
- @property
59
- def persona_mapping(self):
60
- if self._persona_mapping is None:
61
- self._persona_mapping = self._create_persona_mapping()
62
- return self._persona_mapping
63
-
64
- @property
65
- def agent_list_generator(self):
66
- if self._agent_list_generator is None:
67
- self._agent_list_generator = self._create_agent_list_generator()
68
- return self._agent_list_generator
69
-
70
- @property
71
- def results(self):
72
- if self._results is None:
73
- self._results = self._create_results()
74
- return self._results
75
-
76
- def _create_survey(self):
77
- survey_pipline_stages = [
78
- StageQuestions,
79
- StageLabelQuestions,
80
- StageGenerateSurvey,
81
- ]
82
- survey_pipeline = gen_pipeline(survey_pipline_stages)
83
- return survey_pipeline.process(
84
- data=survey_pipeline.input(
85
- overall_question=self.overall_question, population=self.population
86
- )
87
- ).survey
88
-
89
- def _create_persona_mapping(self):
90
- persona_pipeline_stages = [
91
- StageQuestions,
92
- StagePersona,
93
- StagePersonaDimensions,
94
- StagePersonaDimensionValues,
95
- StagePersonaDimensionValueRanges,
96
- ]
97
-
98
- persona_pipeline = gen_pipeline(persona_pipeline_stages)
99
- sample_agent_results = persona_pipeline.process(
100
- persona_pipeline.input(
101
- overall_question=overall_question, population=self.population
102
- )
103
- )
104
- return sample_agent_results
105
-
106
- def _create_agent_list_generator(self):
107
- return agent_generator(
108
- persona=self.persona_mapping.persona,
109
- dimension_dict=self.persona_mapping.mapping,
110
- )
111
-
112
- def agent_list(self, num_agents):
113
- return create_agents(
114
- agent_generator=self.agent_list_generator,
115
- survey=self.survey,
116
- num_agents=num_agents,
117
- )
118
-
119
- def _create_results(self, num_agents=None):
120
- if num_agents is None:
121
- num_agents = self.default_num_agents
122
- agent_list = self.agent_list(num_agents)
123
- return self.survey.by(agent_list).by(self.model).run()
124
-
125
-
126
- if __name__ == "__main__":
127
- overall_question = "I have an open source Python library for working with LLMs. What are some ways we can market this to others?"
128
- auto_study = AutoStudy(overall_question, population="US Adults")
129
-
130
- results = auto_study.results
edsl/auto/StageBase.py DELETED
@@ -1,243 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- import json
3
- from typing import Dict, List, Any, TypeVar, Generator, Dict, Callable
4
- from dataclasses import dataclass, field, KW_ONLY, fields, asdict
5
- import textwrap
6
-
7
-
8
- class ExceptionPipesDoNotFit(Exception):
9
- pass
10
-
11
-
12
- class StageProcessingClosure:
13
- def __init__(self, stage_func: Callable, reduction_func=lambda x: x):
14
- self.data = []
15
- self.stage_func = stage_func
16
- # reduction function is applied to self.data when complete
17
- # it might just return the list, or it might do something more complicated such as
18
- # reduce the list to a dictionary
19
- self.reduction_func = reduction_func
20
-
21
- def func(self, obj: "FlowDataBase") -> None:
22
- "Function to apply to each stage"
23
- self.data.append(self.stage_func(obj))
24
-
25
- def __call__(self):
26
- return self.reduction_func(self.data)
27
-
28
-
29
- @dataclass
30
- class FlowDataBase:
31
- """Base class for dataclasses that are passed between stages."""
32
-
33
- _: KW_ONLY
34
- # previous_stage: Dict = field(default_factory=dict)
35
- previous_stage: Any = None
36
- sent_to_stage_name: str = field(default_factory=str)
37
- came_from_stage_name: str = field(default_factory=str)
38
-
39
- def to_dict(self):
40
- return asdict(self)
41
-
42
- @classmethod
43
- def from_dict(cls, data: dict):
44
- return cls(**data)
45
-
46
- def __getitem__(self, key):
47
- """Allows dictionary-style getting."""
48
- return getattr(self, key)
49
-
50
- def __setitem__(self, key, value):
51
- """Allows dictionary-style setting."""
52
- return setattr(self, key, value)
53
-
54
- def current_values(self):
55
- """Returns a dictionary of the current values of the dataclass"""
56
- to_exclude = ["sent_to_stage_name", "came_from_stage_name", "previous_stage"]
57
- d = asdict(self)
58
- [d.pop(key) for key in to_exclude]
59
- return d
60
-
61
- def stage_input_output(self):
62
- return {
63
- "came_from": self.came_from_stage_name,
64
- "sent_to": self.sent_to_stage_name,
65
- }
66
-
67
- def _align_values_with_padding(
68
- self, stages
69
- ) -> Generator[Dict[str, str], None, None]:
70
- "Pads out the the names of the stages so they are aligned when printing"
71
-
72
- def longest_value(stage):
73
- return max([len(v) for v in stage.values()])
74
-
75
- max_length = max([longest_value(stage) for stage in stages])
76
- for stage in stages:
77
- new_stage = {k: v.ljust(max_length) for k, v in stage.items()}
78
- yield new_stage
79
-
80
- def _reduce(self, stage_processor: StageProcessingClosure) -> Dict[str, dict]:
81
- """Applies some function defined in stage_processor to each stage in the chain, working from back to front
82
-
83
- The stage_processor will record the results of the function applied to each stage in
84
- an instance of the StageProcessingClosure class.
85
- The results can be accessed by calling the StageProcessingClosure instance.
86
- This somewhat convoluted approach is necessary because the stages are connected in a chain and
87
- we want a way to access the results of the function applied to each stage in the chain without
88
- writing the while-loop over and over again.
89
- """
90
- stage_processor.func(self)
91
- current_pipe = self
92
- while True:
93
- if current_pipe.previous_stage is None:
94
- break
95
- else:
96
- current_pipe = current_pipe.previous_stage
97
- stage_processor.func(
98
- current_pipe
99
- ) # the result is getting stored in stage_processor.data
100
-
101
- def combined_results(self) -> Dict[str, dict]:
102
- stage_processor = StageProcessingClosure(
103
- stage_func=lambda obj: obj.current_values(),
104
- reduction_func=lambda x: {k: v for d in x for k, v in d.items()},
105
- )
106
- self._reduce(stage_processor)
107
- return stage_processor()
108
-
109
- def flow_history(self):
110
- stage_processor = StageProcessingClosure(
111
- stage_func=lambda obj: obj.stage_input_output()
112
- )
113
- self._reduce(stage_processor)
114
- return stage_processor()
115
-
116
- def visualize_flow(self) -> str:
117
- """Visualize the flow of data through the chain"""
118
- stages = self.flow_history()
119
- new_stages = list(self._align_values_with_padding(stages))
120
- new_stages.reverse()
121
- return tuple(new_stages)
122
-
123
-
124
- class StageBase(ABC):
125
- input: FlowDataBase = NotImplemented
126
- output: FlowDataBase = NotImplemented
127
-
128
- def __init__(self, **kwargs):
129
- for key, value in kwargs.items():
130
- setattr(self, key, value)
131
-
132
- if hasattr(self, "next_stage"):
133
- self._validate_connection(self.next_stage)
134
- else:
135
- self.next_stage = None
136
-
137
- @classmethod
138
- def function_parameters(self):
139
- return fields(self.input)
140
-
141
- @classmethod
142
- def func(cls, **kwargs):
143
- "This provides a shortcut for running a stage by passing keyword arguments to the input function."
144
- input_data = cls.input(**kwargs)
145
- return cls().process(input_data)
146
-
147
- @abstractmethod
148
- def handle_data(self, data):
149
- "This implements how the stage actually handles the passed in data"
150
- raise NotImplementedError
151
-
152
- def _validate_connection(self, stage):
153
- "Checks that the outputs of the first stage match the inputs of the second stage"
154
- if not self.output == stage.input:
155
- raise ExceptionPipesDoNotFit(
156
- textwrap.dedent(
157
- f"""\
158
- Stage \"{self.__class__.__name__}\" cannot be connected to stage \"{stage.__class__.__name__}\".
159
- The outputs of the first stage {self.output} do not match the inputs of the second stage, {stage.input}."""
160
- )
161
- )
162
-
163
- def __init_subclass__(cls, **kwargs):
164
- "Checks that the subclass has the required class variables of input & output"
165
- super().__init_subclass__(**kwargs)
166
- if cls.input is NotImplemented:
167
- raise NotImplementedError(
168
- f"Class {cls.__name__} lacks required class variable 'inputs'"
169
- )
170
- if cls.output is NotImplemented:
171
- raise NotImplementedError(
172
- f"Class {cls.__name__} lacks required class variable 'outputs'"
173
- )
174
-
175
- def process(self, data):
176
- print(f"Running stage: {self.__class__.__name__}")
177
- data.sent_to_stage_name = self.__class__.__name__
178
- processed_data = self.handle_data(data)
179
- processed_data.came_from_stage_name = self.__class__.__name__
180
- processed_data.previous_stage = data
181
- if self.next_stage:
182
- return self.next_stage.process(processed_data)
183
- else:
184
- return processed_data
185
-
186
-
187
- if __name__ == "__main__":
188
- pass
189
- # try:
190
-
191
- # class StageMissing(StageBase):
192
- # def handle_data(self, data):
193
- # return data
194
-
195
- # except NotImplementedError as e:
196
- # print(e)
197
- # else:
198
- # raise Exception("Should have raised NotImplementedError")
199
-
200
- # try:
201
-
202
- # class StageMissingInput(StageBase):
203
- # output = FlowDataBase
204
-
205
- # except NotImplementedError as e:
206
- # print(e)
207
-
208
- # else:
209
- # raise Exception("Should have raised NotImplementedError")
210
-
211
- # @dataclass
212
- # class MockInputOutput(FlowDataBase):
213
- # text: str
214
-
215
- # class StageTest(StageBase):
216
- # input = MockInputOutput
217
- # output = MockInputOutput
218
-
219
- # def handle_data(self, data):
220
- # return self.output(text=data["text"] + "processed")
221
-
222
- # result = StageTest().process(MockInputOutput(text="Hello world!"))
223
- # print(result.text)
224
-
225
- # pipeline = StageTest(next_stage=StageTest(next_stage=StageTest()))
226
- # result = pipeline.process(MockInputOutput(text="Hello world!"))
227
- # print(result.text)
228
-
229
- # class BadMockInput(FlowDataBase):
230
- # text: str
231
- # other: str
232
-
233
- # class StageBad(StageBase):
234
- # input = BadMockInput
235
- # output = BadMockInput
236
-
237
- # def handle_data(self, data):
238
- # return self.output(text=data["text"] + "processed")
239
-
240
- # try:
241
- # pipeline = StageTest(next_stage=StageBad(next_stage=StageTest()))
242
- # except ExceptionPipesDoNotFit as e:
243
- # print(e)
@@ -1,178 +0,0 @@
1
- from textwrap import dedent
2
- from dataclasses import dataclass
3
- from collections import defaultdict
4
-
5
- from typing import List, Dict
6
-
7
- from edsl.auto.StageBase import StageBase
8
- from edsl.auto.utilities import gen_pipeline
9
- from edsl.auto.StageBase import FlowDataBase
10
-
11
- from edsl.auto.StageQuestions import StageQuestions
12
- from edsl.auto.StageLabelQuestions import StageLabelQuestions
13
-
14
- from edsl.questions import QuestionList
15
- from edsl.scenarios import Scenario
16
- from edsl import Model
17
- from edsl.surveys import Survey
18
- from edsl.questions import QuestionBase
19
-
20
- from edsl.utilities.utilities import is_valid_variable_name
21
- from edsl import Model
22
- from edsl.questions import QuestionExtract
23
-
24
-
25
- m = Model()
26
-
27
-
28
- def chunker(seq, size):
29
- return (seq[pos : pos + size] for pos in range(0, len(seq), size))
30
-
31
-
32
- def get_short_options(question_options, num_chars=20):
33
- """Gets short names for the options of a question
34
- >>> get_short_options(["No, I don't own a scooter", "Yes, I own a scooter"])
35
- {'No, I don\'t own a scooter': 'no_scooter', 'Yes, I own a scooter': 'yes_scooter'}
36
- """
37
- q = QuestionList(
38
- question_text=dedent(
39
- f"""\
40
- We need short (less than {num_chars} characters) names for the options of a question, with no spaces.
41
- E.g., if the options were "No, I don't own a scooter" and "Yes, I own a scooter",
42
- you could use "no_scooter" and "yes_scooter".
43
- They should be all lower case. Use snake case.
44
- The short names have to be unique.
45
- The options are: {question_options}
46
- The names are {question_options} of them."""
47
- ),
48
- # answer_template={k: None for k in question_options},
49
- question_name="short_options",
50
- )
51
- results = q.by(m).run()
52
- return results.select("short_options").first()
53
-
54
-
55
- def get_short_names_chunk(questions, num_chars=20):
56
- q = QuestionList(
57
- question_text=dedent(
58
- f"""\
59
- We need short (less than {num_chars} characters) names for the questions, with no spaces.
60
- E.g., if the question was: "What is your first name?", you could use "first_name".
61
- The short names have to be unique and not starting with numbers. They should be all lower case.
62
- The questions are: {questions}
63
- """
64
- ),
65
- question_name="short_names",
66
- )
67
- results = q.by(m).run()
68
- short_names = results.select("short_names").first()
69
- return {k: v for k, v in zip(questions, short_names)}
70
-
71
-
72
- def get_short_names(questions, max_size=10, num_chars=20):
73
- "Gets short names for questions"
74
- if len(questions) <= max_size:
75
- short_names_dict = get_short_names_chunk(questions, num_chars)
76
- else:
77
- short_names_dict = {}
78
- for chunk in chunker(questions, max_size):
79
- results = get_short_names_chunk(chunk, num_chars)
80
- short_names_dict.update(results)
81
- return short_names_dict
82
-
83
-
84
- class StageGenerateSurvey(StageBase):
85
- input = StageLabelQuestions.output
86
-
87
- @dataclass
88
- class Output(FlowDataBase):
89
- survey: Survey
90
-
91
- output = Output
92
-
93
- def handle_data(self, data):
94
- """This tage uses the question types to generate a survey
95
- It constucts the edsl-specific dictionary needed to create a question
96
- """
97
- # survey = Survey(name = {data.overall_question, population = data.population, description)
98
- survey = Survey()
99
-
100
- short_names = get_short_names(data.questions)
101
-
102
- question_count = -1
103
- for question, question_type, options, option_labels in zip(
104
- data.questions, data.types, data.options, data.option_labels
105
- ):
106
- question_count += 1
107
- short_names_dict = {}
108
- if question in short_names:
109
- short_names_dict[question] = short_names[question]
110
- data = {
111
- "question_text": question,
112
- "question_type": question_type,
113
- "question_name": short_names.get(question, f"q{question_count}"),
114
- }
115
- if options is not None:
116
- data["question_options"] = options
117
- # make sure it's not a linear scale question, in which case we don't want to add short names
118
-
119
- if option_labels is not None:
120
- data["option_labels"] = dict(zip(options, option_labels))
121
- # print(data["option_labels"])
122
- # breakpoint()
123
-
124
- if question_type == "linear_scale":
125
- option_keys = option_labels
126
- else:
127
- option_keys = options
128
-
129
- if options is not None:
130
- short_options = get_short_options(option_keys)
131
- short_names_dict.update(
132
- {k: v for k, v in zip(option_keys, short_options)}
133
- )
134
-
135
- if question_type not in ["numerical", "free_text"]:
136
- data["short_names_dict"] = short_names_dict
137
- _ = data.pop("short_names_dict", None)
138
- q = QuestionBase.from_dict(data)
139
- survey.add_question(q)
140
-
141
- survey.print()
142
- return self.output(survey=survey)
143
-
144
-
145
- if __name__ == "__main__":
146
- # pipeline = gen_pipeline([StageQuestions, StageLabelQuestions, StageGenerateSurvey])
147
-
148
- # results = pipeline.process(
149
- # pipeline.input(
150
- # overall_question="What are some factors that could determine whether someone likes ice cream?",
151
- # population="consumers",
152
- # )
153
- # )
154
- # # print(results)
155
- # short_options = get_short_options(
156
- # ["No, I don't own a scooter", "Yes, I own a scooter"]
157
- # )
158
- # print(short_options)
159
-
160
- sample_questions = [
161
- "What are the primary goals for your company in sponsoring a research center like the MIT IDE?",
162
- "How does your company measure the ROI on sponsorships like this?",
163
- "What specific aspects of the MIT IDEs work align with your companys strategic interests?",
164
- "Can you describe the decision-making process your company uses to select research initiatives for sponsorship?",
165
- "What are the most important factors your company considers when deciding to sponsor a research center?",
166
- "How important is the visibility and recognition your company receives from sponsoring a research center like the MIT IDE?",
167
- "What kind of collaborative opportunities with the MIT IDE are you looking for?",
168
- "What are your companys expectations regarding intellectual property and the commercialization of research outcomes?",
169
- "How does your company evaluate the success of the research projects it sponsors?",
170
- "Would your company be interested in engaging with students or faculty at the MIT IDE for recruitment or professional development opportunities?",
171
- "How does your company plan to leverage the research and insights gained from the MIT IDE?",
172
- "What challenges has your company faced in previous sponsorships that you would want to avoid in the future?",
173
- "Is there any additional support or involvement your company would like to have in the MIT IDE beyond financial sponsorship?",
174
- "How do you see your companys role in shaping the research agenda at the MIT IDE?",
175
- "What can the MIT IDE do to make its sponsorship opportunities more attractive to your company?",
176
- ]
177
-
178
- short_names = get_short_names(sample_questions)
@@ -1,125 +0,0 @@
1
- from textwrap import dedent
2
- from dataclasses import dataclass
3
- from collections import defaultdict
4
-
5
- from typing import List, Dict, Union
6
-
7
- from edsl.auto.StageBase import StageBase
8
- from edsl.auto.StageBase import FlowDataBase
9
-
10
- from edsl.auto.StageQuestions import StageQuestions
11
-
12
- from edsl.questions import QuestionMultipleChoice, QuestionList
13
- from edsl.scenarios import Scenario
14
- from edsl import Model
15
- from edsl.auto.utilities import gen_pipeline
16
-
17
-
18
- question_purpose = {
19
- "multiple_choice": "When options are known and limited",
20
- "free_text": "When we are asking an open-ended question",
21
- "checkbox": "When multiple options can be selected e.g., have you heard of the following products:",
22
- "numerical": "When the answer is a single numerical value e.g., a float",
23
- "linear_scale": "When options are text like multiple choice, but can be ordered e.g., daily, weekly, monthly, etc.",
24
- "yes_no": "When the question can be fully answered with either a yes or a no",
25
- }
26
-
27
-
28
- class StageLabelQuestions(StageBase):
29
- input = StageQuestions.output
30
-
31
- @dataclass
32
- class Output(FlowDataBase):
33
- questions: List[str]
34
- types: List[str]
35
- options: Dict[str, List[str]]
36
- option_labels: Dict[str, Union[List[str], None]]
37
-
38
- output = Output
39
-
40
- def handle_data(self, data):
41
- """
42
- Labels each edsl question type. This is then used later to instantiate the questions
43
- """
44
- m = Model()
45
- label_questions_scenarios = [
46
- Scenario({"question": q, "question_purpose": question_purpose})
47
- for q in data.questions
48
- ]
49
- q_type = QuestionMultipleChoice(
50
- question_text=dedent(
51
- """\
52
- Consider this question: "{{ question }}"
53
- The question options and purpose are: {{ question_purpose }}
54
- Please avoid free text questions much as possible.
55
- If it could be a multiple choice, use that type.
56
- What type of question should this be to make for an informative survey?"""
57
- ),
58
- question_options=list(question_purpose.keys()),
59
- question_name="question_type",
60
- )
61
- ## If it is a linear scale, multiple choice or checkbox question, we need to know the options
62
- option_questions = [
63
- "multiple_choice",
64
- "linear_scale",
65
- "checkbox",
66
- ]
67
- q_options_mc = QuestionList(
68
- question_text=dedent(
69
- """\
70
- Consider this question: "{{ question }}"
71
- What options should this question have?"""
72
- ),
73
- question_name="mc_options",
74
- )
75
- survey = q_type.add_question(q_options_mc).add_stop_rule(
76
- "question_type", f"question_type not in {option_questions}"
77
- )
78
- type_results = survey.by(label_questions_scenarios).by(m).run()
79
- type_results.select("question", "question_type", "mc_options").print()
80
-
81
- # breakpoint()
82
-
83
- question_types = type_results.select("question_type").to_list()
84
- options = type_results.select("mc_options").to_list()
85
- # question_types, options = type_results.select(
86
- # "question_type", "mc_options"
87
- # ).to_list()
88
-
89
- type_results.select("question", "question_type", "mc_options").print()
90
-
91
- # if the question is a yes/no question, we need to set the options to be yes/no
92
- types_to_questions = defaultdict(list)
93
- for question_type, question in zip(question_types, data.questions):
94
- types_to_questions[question_type].append(question)
95
-
96
- questions_to_options = dict(zip(data.questions, options))
97
- question_to_option_labels = dict(
98
- zip(data.questions, len(data.questions) * [None])
99
- )
100
- for question in types_to_questions.get("yes_no", []):
101
- questions_to_options[question] = ["Yes", "No"]
102
-
103
- for question in types_to_questions.get("linear_scale", []):
104
- options = questions_to_options[question]
105
- questions_to_options[question] = list(range(len(options)))
106
- question_to_option_labels[question] = options
107
-
108
- return self.output(
109
- questions=data.questions,
110
- types=question_types,
111
- options=list(questions_to_options.values()),
112
- option_labels=list(question_to_option_labels.values()),
113
- )
114
-
115
-
116
- if __name__ == "__main__":
117
- pipeline = gen_pipeline([StageQuestions, StageLabelQuestions])
118
-
119
- results = pipeline.process(
120
- pipeline.input(
121
- overall_question="What are some factors that could determine whether someone likes ice cream?"
122
- )
123
- )
124
-
125
- print(results.options)