Skip to content

Commit a390491

Browse files
Merge pull request #796 from expectedparrot/af-small-edits
Add randomize arg to example methods - setting us up for coop hash
2 parents 2513e13 + 66f1e2b commit a390491

22 files changed

+156
-148
lines changed

Diff for: edsl/__version__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "0.1.30.dev1"
1+
__version__ = "0.1.30.dev3"

Diff for: edsl/agents/Agent.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
import copy
55
import inspect
66
import types
7-
from typing import Any, Callable, Optional, Union, Dict, Sequence
7+
from typing import Callable, Optional, Union
8+
from uuid import uuid4
89
from edsl.Base import Base
910

1011
from edsl.exceptions.agents import (
@@ -688,13 +689,14 @@ def rich_print(self):
688689
return table
689690

690691
@classmethod
691-
def example(cls) -> Agent:
692-
"""Return an example agent.
692+
def example(cls, randomize: bool = False) -> Agent:
693+
"""
694+
Returns an example Agent instance.
693695
694-
>>> Agent.example()
695-
Agent(traits = {'age': 22, 'hair': 'brown', 'height': 5.5})
696+
:param randomize: If True, adds a random string to the value of an example key.
696697
"""
697-
return cls(traits={"age": 22, "hair": "brown", "height": 5.5})
698+
addition = "" if not randomize else str(uuid4())
699+
return cls(traits={"age": 22, "hair": f"brown{addition}", "height": 5.5})
698700

699701
def code(self) -> str:
700702
"""Return the code for the agent.

Diff for: edsl/agents/AgentList.py

+9-19
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,15 @@
1111
"""
1212

1313
from __future__ import annotations
14+
import csv
15+
import json
1416
from collections import UserList
15-
from typing import Optional, Union, Sequence, List, Any
17+
from typing import Any, List, Optional, Union
1618
from rich import print_json
1719
from rich.table import Table
18-
import json
19-
import csv
20-
21-
2220
from simpleeval import EvalWithCompoundTypes
23-
2421
from edsl.Base import Base
25-
26-
# from edsl.agents import Agent
27-
from edsl.utilities.decorators import (
28-
add_edsl_version,
29-
remove_edsl_version,
30-
)
22+
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
3123

3224

3325
class AgentList(UserList, Base):
@@ -239,17 +231,15 @@ def from_dict(cls, data: dict) -> "AgentList":
239231
return cls(agents)
240232

241233
@classmethod
242-
def example(cls) -> "AgentList":
243-
"""Return an example AgentList.
244-
245-
>>> al = AgentList.example()
246-
>>> len(al)
247-
2
234+
def example(cls, randomize: bool = False) -> AgentList:
235+
"""
236+
Returns an example AgentList instance.
248237
238+
:param randomize: If True, uses Agent's randomize method.
249239
"""
250240
from edsl.agents.Agent import Agent
251241

252-
return cls([Agent.example(), Agent.example()])
242+
return cls([Agent.example(randomize), Agent.example(randomize)])
253243

254244
@classmethod
255245
def from_list(self, trait_name: str, values: List[Any]):

Diff for: edsl/agents/Invigilator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def _format_raw_response(
9797
answer = question._translate_answer_code_to_answer(
9898
response["answer"], combined_dict
9999
)
100-
#breakpoint()
100+
# breakpoint()
101101
data = {
102102
"answer": answer,
103103
"comment": response.get(

Diff for: edsl/data/Cache.py

+13-14
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,10 @@
77
import os
88
import warnings
99
from typing import Optional, Union
10-
import time
11-
from edsl.config import CONFIG
12-
from edsl.data.CacheEntry import CacheEntry
13-
14-
# from edsl.data.SQLiteDict import SQLiteDict
1510
from edsl.Base import Base
11+
from edsl.data.CacheEntry import CacheEntry
1612
from edsl.utilities.utilities import dict_hash
17-
from edsl.utilities.decorators import (
18-
add_edsl_version,
19-
remove_edsl_version,
20-
)
13+
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
2114

2215

2316
class Cache(Base):
@@ -41,7 +34,7 @@ def __init__(
4134
data: Optional[Union["SQLiteDict", dict]] = None,
4235
immediate_write: bool = True,
4336
method=None,
44-
verbose = False
37+
verbose=False,
4538
):
4639
"""
4740
Create two dictionaries to store the cache data.
@@ -480,12 +473,18 @@ def view(self) -> None:
480473
webbrowser.open("file://" + filepath)
481474

482475
@classmethod
483-
def example(cls) -> Cache:
476+
def example(cls, randomize: bool = False) -> Cache:
484477
"""
485-
Return an example Cache.
486-
The example Cache has one entry.
478+
Returns an example Cache instance.
479+
480+
:param randomize: If True, uses CacheEntry's randomize method.
487481
"""
488-
return cls(data={CacheEntry.example().key: CacheEntry.example()})
482+
return cls(
483+
data={
484+
CacheEntry.example(randomize).key: CacheEntry.example(),
485+
CacheEntry.example(randomize).key: CacheEntry.example(),
486+
}
487+
)
489488

490489

491490
if __name__ == "__main__":

Diff for: edsl/data/CacheEntry.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,8 @@
22
import json
33
import datetime
44
import hashlib
5-
import random
65
from typing import Optional
7-
8-
9-
# TODO: Timestamp should probably be float?
6+
from uuid import uuid4
107

118

129
class CacheEntry:
@@ -151,10 +148,12 @@ def __repr__(self) -> str:
151148
@classmethod
152149
def example(cls, randomize: bool = False) -> CacheEntry:
153150
"""
154-
Returns a CacheEntry example.
151+
Returns an example CacheEntry instance.
152+
153+
:param randomize: If True, adds a random string to the system prompt.
155154
"""
156-
# if random, create a random number for 0-100
157-
addition = "" if not randomize else str(random.randint(0, 1000))
155+
# if random, create a uuid
156+
addition = "" if not randomize else str(uuid4())
158157
return CacheEntry(
159158
model="gpt-3.5-turbo",
160159
parameters={"temperature": 0.5},

Diff for: edsl/data_transfer_models.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def __init__(
1717
cached_response=None,
1818
raw_model_response=None,
1919
simple_model_raw_response=None,
20-
cache_used=None,
20+
cache_used=None,
2121
cache_key=None,
2222
):
2323
"""Initialize the AgentResponseDict object."""

Diff for: edsl/jobs/Jobs.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,9 @@ def __eq__(self, other: Jobs) -> bool:
687687
# Example methods
688688
#######################
689689
@classmethod
690-
def example(cls, throw_exception_probability=0) -> Jobs:
690+
def example(
691+
cls, throw_exception_probability: int = 0, randomize: bool = False
692+
) -> Jobs:
691693
"""Return an example Jobs instance.
692694
693695
:param throw_exception_probability: the probability that an exception will be thrown when answering a question. This is useful for testing error handling.
@@ -697,10 +699,13 @@ def example(cls, throw_exception_probability=0) -> Jobs:
697699
698700
"""
699701
import random
702+
from uuid import uuid4
700703
from edsl.questions import QuestionMultipleChoice
701704
from edsl.agents.Agent import Agent
702705
from edsl.scenarios.Scenario import Scenario
703706

707+
addition = "" if not randomize else str(uuid4())
708+
704709
# (status, question, period)
705710
agent_answers = {
706711
("Joyful", "how_feeling", "morning"): "OK",
@@ -743,7 +748,10 @@ def answer_question_directly(self, question, scenario):
743748
base_survey = Survey(questions=[q1, q2])
744749

745750
scenario_list = ScenarioList(
746-
[Scenario({"period": "morning"}), Scenario({"period": "afternoon"})]
751+
[
752+
Scenario({"period": f"morning{addition}"}),
753+
Scenario({"period": "afternoon"}),
754+
]
747755
)
748756
job = base_survey.by(scenario_list).by(joy_agent, sad_agent)
749757

Diff for: edsl/jobs/buckets/ModelBuckets.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __add__(self, other: "ModelBuckets"):
2424
requests_bucket=self.requests_bucket + other.requests_bucket,
2525
tokens_bucket=self.tokens_bucket + other.tokens_bucket,
2626
)
27-
27+
2828
def turbo_mode_on(self):
2929
"""Set the refill rate to infinity for both buckets."""
3030
self.requests_bucket.turbo_mode_on()

Diff for: edsl/jobs/buckets/TokenBucket.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,15 @@ def turbo_mode_on(self):
3131
pass
3232
else:
3333
self.turbo_mode = True
34-
self.capacity=float("inf")
35-
self.refill_rate=float("inf")
34+
self.capacity = float("inf")
35+
self.refill_rate = float("inf")
3636

3737
def turbo_mode_off(self):
3838
"""Restore the refill rate to its original value."""
3939
self.turbo_mode = False
4040
self.capacity = self._old_capacity
4141
self.refill_rate = self._old_refill_rate
42-
42+
4343
def __add__(self, other) -> "TokenBucket":
4444
"""Combine two token buckets.
4545

Diff for: edsl/jobs/interviews/Interview.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@ class Interview(InterviewStatusMixin, InterviewTaskBuildingMixin):
3030

3131
def __init__(
3232
self,
33-
agent: 'Agent',
34-
survey: 'Survey',
35-
scenario: 'Scenario',
36-
model: Type['LanguageModel'],
33+
agent: "Agent",
34+
survey: "Survey",
35+
scenario: "Scenario",
36+
model: Type["LanguageModel"],
3737
debug: Optional[bool] = False,
3838
iteration: int = 0,
3939
cache: "Cache" = None,
40-
sidecar_model: 'LanguageModel' = None,
40+
sidecar_model: "LanguageModel" = None,
4141
):
4242
"""Initialize the Interview instance.
4343

Diff for: edsl/jobs/runners/JobsRunnerAsyncio.py

+2
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ def _populate_total_interviews(self, n: int = 1) -> None:
8989

9090
async def run_async(self, cache=None) -> Results:
9191
from edsl.results.Results import Results
92+
9293
if cache is None:
9394
self.cache = Cache()
9495
else:
@@ -100,6 +101,7 @@ async def run_async(self, cache=None) -> Results:
100101

101102
def simple_run(self):
102103
from edsl.results.Results import Results
104+
103105
data = asyncio.run(self.run_async())
104106
return Results(survey=self.jobs.survey, data=data)
105107

Diff for: edsl/jobs/tasks/QuestionTaskCreator.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -144,26 +144,25 @@ async def _run_focal_task(self, debug: bool) -> Answers:
144144
self.task_status = TaskStatus.FAILED
145145
raise e
146146

147-
## This isn't working
148-
#breakpoint()
149-
if results.get('cache_used', False):
147+
## This isn't working
148+
# breakpoint()
149+
if results.get("cache_used", False):
150150
self.tokens_bucket.add_tokens(requested_tokens)
151151
self.requests_bucket.add_tokens(1)
152152
self.from_cache = True
153-
#print("Turning on turbo!")
153+
# print("Turning on turbo!")
154154
self.tokens_bucket.turbo_mode_on()
155155
self.requests_bucket.turbo_mode_on()
156156
else:
157-
#breakpoint()
158-
#print("Turning off turbo!")
157+
# breakpoint()
158+
# print("Turning off turbo!")
159159
self.tokens_bucket.turbo_mode_off()
160160
self.requests_bucket.turbo_mode_off()
161161

162162
_ = results.pop("cached_response", None)
163163

164164
tracker = self.cached_token_usage if self.from_cache else self.new_token_usage
165165

166-
167166
# TODO: This is hacky. The 'func' call should return an object that definitely has a 'usage' key.
168167
usage = results.get("usage", {"prompt_tokens": 0, "completion_tokens": 0})
169168
prompt_tokens = usage.get("prompt_tokens", 0)

Diff for: edsl/notebooks/Notebook.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
"""A Notebook is a utility class that allows you to easily share/pull ipynbs from Coop."""
22

3+
from __future__ import annotations
34
import json
45
from typing import Dict, List, Optional
5-
6-
6+
from uuid import uuid4
77
from edsl.Base import Base
8-
from edsl.utilities.decorators import (
9-
add_edsl_version,
10-
remove_edsl_version,
11-
)
8+
from edsl.utilities.decorators import add_edsl_version, remove_edsl_version
129

1310

1411
class Notebook(Base):
@@ -192,10 +189,13 @@ def rich_print(self) -> "Table":
192189
return table
193190

194191
@classmethod
195-
def example(cls) -> "Notebook":
192+
def example(cls, randomize: bool = False) -> Notebook:
196193
"""
197-
Return an example Notebook.
194+
Returns an example Notebook instance.
195+
196+
:param randomize: If True, adds a random string one of the cells' output.
198197
"""
198+
addition = "" if not randomize else str(uuid4())
199199
cells = [
200200
{
201201
"cell_type": "markdown",
@@ -210,7 +210,7 @@ def example(cls) -> "Notebook":
210210
{
211211
"name": "stdout",
212212
"output_type": "stream",
213-
"text": "Hello world!\n",
213+
"text": f"Hello world!\n{addition}",
214214
}
215215
],
216216
"source": 'print("Hello world!")',

Diff for: edsl/questions/QuestionFreeText.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22
import textwrap
33
from typing import Any, Optional
4+
from uuid import uuid4
45
from edsl.questions.QuestionBase import QuestionBase
56

67

@@ -65,9 +66,10 @@ def question_html_content(self) -> str:
6566
return question_html_content
6667

6768
@classmethod
68-
def example(cls) -> QuestionFreeText:
69+
def example(cls, randomize: bool = False) -> QuestionFreeText:
6970
"""Return an example instance of a free text question."""
70-
return cls(question_name="how_are_you", question_text="How are you?")
71+
addition = "" if not randomize else str(uuid4())
72+
return cls(question_name="how_are_you", question_text=f"How are you?{addition}")
7173

7274

7375
def main():

Diff for: edsl/results/Results.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -949,7 +949,7 @@ def create_evaluator(result):
949949
return Results(survey=self.survey, data=new_data, created_columns=None)
950950

951951
@classmethod
952-
def example(cls, debug: bool = False) -> Results:
952+
def example(cls, debug: bool = False, randomize: bool = False) -> Results:
953953
"""Return an example `Results` object.
954954
955955
Example usage:
@@ -962,7 +962,7 @@ def example(cls, debug: bool = False) -> Results:
962962
from edsl.data.Cache import Cache
963963

964964
c = Cache()
965-
job = Jobs.example()
965+
job = Jobs.example(randomize=randomize)
966966
results = job.run(cache=c, debug=debug)
967967
return results
968968

0 commit comments

Comments
 (0)