Skip to content

Commit 0bc0500

Browse files
Make logger and config args optional
1 parent 0298591 commit 0bc0500

10 files changed

+140
-55
lines changed

python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

+33-8
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,13 @@ class AgenticMemoryBank:
2424
Stores task-completion insights in a vector DB for later retrieval.
2525
2626
Args:
27-
- settings: Settings for the memory bank.
2827
- reset: True to clear the DB before starting.
29-
- logger: The PageLogger object to use for logging.
28+
- config: An optional dict that can be used to override the following values:
29+
- path: The path to the directory where the memory bank files are stored.
30+
- relevance_conversion_threshold: The threshold used to normalize relevance.
31+
- n_results: The maximum number of most relevant results to return for any given topic.
32+
- distance_threshold: The maximum topic-insight distance for an insight to be retrieved.
33+
- logger: An optional logger. If None, no logging will be performed.
3034
3135
Methods:
3236
- reset: Forces immediate deletion of all contents, in memory and on disk.
@@ -37,15 +41,36 @@ class AgenticMemoryBank:
3741
- get_relevant_insights: Returns any insights from the memory bank that appear sufficiently relevant to the given task topics.
3842
"""
3943

40-
def __init__(self, settings: Dict[str, Any], reset: bool, logger: PageLogger) -> None:
41-
self.settings = settings
44+
def __init__(
45+
self,
46+
reset: bool,
47+
config: Dict[str, Any] | None = None,
48+
logger: PageLogger | None = None,
49+
) -> None:
50+
if logger is None:
51+
logger = PageLogger() # Nothing will be logged by this object.
4252
self.logger = logger
4353
self.logger.enter_function()
4454

45-
memory_dir_path = os.path.expanduser(self.settings["path"])
46-
self.relevance_conversion_threshold = self.settings["relevance_conversion_threshold"]
47-
self.n_results = self.settings["n_results"]
48-
self.distance_threshold = self.settings["distance_threshold"]
55+
# Assign default values that can be overridden by config.
56+
memory_dir_path = os.path.expanduser("~/agentic_memory/temp")
57+
self.relevance_conversion_threshold = 1.7
58+
self.n_results = 25
59+
self.distance_threshold = 100
60+
61+
if config is not None:
62+
# Apply any overrides from the config.
63+
for key in config:
64+
if key == "path":
65+
memory_dir_path = os.path.expanduser(config[key])
66+
elif key == "relevance_conversion_threshold":
67+
self.relevance_conversion_threshold = config[key]
68+
elif key == "n_results":
69+
self.n_results = config[key]
70+
elif key == "distance_threshold":
71+
self.distance_threshold = config[key]
72+
else:
73+
self.logger.error('Unexpected item in config: ["{}"] = {}'.format(key, config[key]))
4974

5075
path_to_db_dir = os.path.join(memory_dir_path, "string_map")
5176
self.path_to_dict = os.path.join(memory_dir_path, "uid_insight_dict.pkl")

python/packages/autogen-ext/src/autogen_ext/agentic_memory/_prompter.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class Prompter:
2121
2222
Args:
2323
client: The client to call the model.
24-
logger: The logger to log the model calls.
24+
logger: An optional logger. If None, no logging will be performed.
2525
2626
Methods:
2727
call_model: Calls the model client with the given input and returns the response.
@@ -33,9 +33,12 @@ class Prompter:
3333
extract_advice: Returns advice from the given text, or None if not found.
3434
"""
3535

36-
def __init__(self, client: ChatCompletionClient, logger: PageLogger):
37-
self.client = client
36+
def __init__(self, client: ChatCompletionClient, logger: PageLogger | None = None) -> None:
37+
if logger is None:
38+
logger = PageLogger() # Nothing will be logged by this object.
3839
self.logger = logger
40+
41+
self.client = client
3942
self.default_system_message_content = "You are a helpful assistant."
4043
self.time_spent_in_model_calls = 0.0
4144
self.num_model_calls = 0

python/packages/autogen-ext/src/autogen_ext/agentic_memory/_string_similarity_map.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class StringSimilarityMap:
2222
Args:
2323
- reset: True to clear the DB immediately after creation.
2424
- path_to_db_dir: Path to the directory where the DB is stored.
25-
- logger: The PageLogger object to use for logging.
25+
- logger: An optional logger. If None, no logging will be performed.
2626
2727
Methods:
2828
- add_input_output_pair: Adds one input-output string pair to the DB.
@@ -31,7 +31,9 @@ class StringSimilarityMap:
3131
- save_string_pairs: Saves the string-pair dict to disk.
3232
"""
3333

34-
def __init__(self, reset: bool, path_to_db_dir: str, logger: PageLogger) -> None:
34+
def __init__(self, reset: bool, path_to_db_dir: str, logger: PageLogger | None = None) -> None:
35+
if logger is None:
36+
logger = PageLogger() # Nothing will be logged by this object.
3537
self.logger = logger
3638
self.path_to_db_dir = path_to_db_dir
3739

python/packages/autogen-ext/src/autogen_ext/agentic_memory/agentic_memory_controller.py

+35-17
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,14 @@ class AgenticMemoryController:
1515
Manages memory-based learning, testing, and the flow of information to and from the memory bank.
1616
1717
Args:
18-
settings: Settings for the memory controller.
1918
reset: True to clear the memory bank before starting.
2019
client: The client to call the model.
2120
task_assignment_callback: The callback to assign a task to the agent.
22-
logger: The logger to log the model calls.
21+
- config: An optional dict that can be used to override the following values:
22+
- max_train_trials: The maximum number of trials to attempt when training on a task.
23+
- max_test_trials: The maximum number of trials to attempt when testing on a task.
24+
- AgenticMemoryBank: A config dict passed to AgenticMemoryBank.
25+
logger: An optional logger. If None, a default logger will be created.
2326
2427
Methods:
2528
reset_memory: Resets the memory bank.
@@ -34,19 +37,38 @@ class AgenticMemoryController:
3437

3538
def __init__(
3639
self,
37-
settings: Dict[str, Any],
3840
reset: bool,
3941
client: ChatCompletionClient,
4042
task_assignment_callback: Callable[[str], Awaitable[Tuple[str, str]]],
41-
logger: PageLogger,
43+
config: Dict[str, Any] | None = None,
44+
logger: PageLogger | None = None,
4245
) -> None:
46+
if logger is None:
47+
logger = PageLogger({"level": "INFO"})
4348
self.logger = logger
4449
self.logger.enter_function()
45-
self.settings = settings
50+
51+
# Assign default values that can be overridden by config.
52+
self.max_train_trials = 10
53+
self.max_test_trials = 3
54+
agentic_memory_bank_config = None
55+
56+
if config is not None:
57+
# Apply any overrides from the config.
58+
for key in config:
59+
if key == "max_train_trials":
60+
self.max_train_trials = config[key]
61+
elif key == "max_test_trials":
62+
self.max_test_trials = config[key]
63+
elif key == "AgenticMemoryBank":
64+
agentic_memory_bank_config = config[key]
65+
else:
66+
self.logger.error('Unexpected item in config: ["{}"] = {}'.format(key, config[key]))
67+
4668
self.client = client
4769
self.task_assignment_callback = task_assignment_callback
4870
self.prompter = Prompter(client, logger)
49-
self.memory_bank = AgenticMemoryBank(self.settings["AgenticMemoryBank"], reset=reset, logger=logger)
71+
self.memory_bank = AgenticMemoryBank(reset=reset, config=agentic_memory_bank_config, logger=logger)
5072
self.grader = Grader(client, logger)
5173
self.logger.leave_function()
5274

@@ -62,9 +84,7 @@ async def train_on_task(self, task: str, expected_answer: str) -> None:
6284
"""
6385
self.logger.enter_function()
6486
self.logger.info("Iterate on the task, possibly discovering a useful new insight.\n")
65-
_, insight = await self._iterate_on_task(
66-
task, expected_answer, self.settings["max_train_trials"], self.settings["max_test_trials"]
67-
)
87+
_, insight = await self._iterate_on_task(task, expected_answer)
6888
if insight is None:
6989
self.logger.info("No useful insight was discovered.\n")
7090
else:
@@ -219,7 +239,7 @@ def _format_memory_section(self, memories: List[str]) -> str:
219239
return memory_section
220240

221241
async def _test_for_failure(
222-
self, task: str, task_plus_insights: str, expected_answer: str, num_trials: int
242+
self, task: str, task_plus_insights: str, expected_answer: str
223243
) -> Tuple[bool, str, str]:
224244
"""
225245
Attempts to solve the given task multiple times to find a failure case to learn from.
@@ -231,7 +251,7 @@ async def _test_for_failure(
231251
failure_found = False
232252
response, work_history = "", ""
233253

234-
for trial in range(num_trials):
254+
for trial in range(self.max_test_trials):
235255
self.logger.info("\n----- TRIAL {} -----\n".format(trial + 1))
236256

237257
# Attempt to solve the task.
@@ -252,9 +272,7 @@ async def _test_for_failure(
252272
self.logger.leave_function()
253273
return failure_found, response, work_history
254274

255-
async def _iterate_on_task(
256-
self, task: str, expected_answer: str, max_train_trials: int, max_test_trials: int
257-
) -> Tuple[str, None | str]:
275+
async def _iterate_on_task(self, task: str, expected_answer: str) -> Tuple[str, None | str]:
258276
"""
259277
Repeatedly assigns a task to the agent, and tries to learn from failures by creating useful insights as memories.
260278
"""
@@ -270,7 +288,7 @@ async def _iterate_on_task(
270288
successful_insight = None
271289

272290
# Loop until success (or timeout) while learning from failures.
273-
for trial in range(1, max_train_trials + 1):
291+
for trial in range(1, self.max_train_trials + 1):
274292
self.logger.info("\n----- TRAIN TRIAL {} -----\n".format(trial))
275293
task_plus_insights = task
276294

@@ -284,7 +302,7 @@ async def _iterate_on_task(
284302

285303
# Can we find a failure case to learn from?
286304
failure_found, response, work_history = await self._test_for_failure(
287-
task, task_plus_insights, expected_answer, max_test_trials
305+
task, task_plus_insights, expected_answer
288306
)
289307
if not failure_found:
290308
# No. Time to exit the loop.
@@ -299,7 +317,7 @@ async def _iterate_on_task(
299317
break
300318

301319
# Will we try again?
302-
if trial == max_train_trials:
320+
if trial == self.max_train_trials:
303321
# No. We're out of training trials.
304322
self.logger.info("\nNo more trials will be attempted.\n")
305323
break

python/packages/autogen-ext/src/autogen_ext/agentic_memory/apprentice.py

+32-7
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,12 @@ class Apprentice:
2626
and call the Agentic Memory Controller using this class as an example.
2727
2828
Args:
29-
settings: The settings for the apprentice.
3029
client: The client to call the model.
31-
logger: The logger to log the model calls.
30+
- config: An optional dict that can be used to override the following values:
31+
- name_of_agent_or_team: The name of the target agent or team for assigning tasks to.
32+
- disable_prefix_caching: True to disable prefix caching by prepending random ints to the first message.
33+
- AgenticMemoryController: A config dict passed to AgenticMemoryController.
34+
logger: An optional logger. If None, a default logger will be created.
3235
3336
Methods:
3437
reset_memory: Resets the memory bank.
@@ -38,22 +41,44 @@ class Apprentice:
3841
train_on_task: Repeatedly assigns a task to the completion agent, and tries to learn from failures by creating useful insights as memories.
3942
"""
4043

41-
def __init__(self, settings: Dict[str, Any], client: ChatCompletionClient, logger: PageLogger) -> None:
42-
self.client = client
44+
def __init__(
45+
self,
46+
client: ChatCompletionClient,
47+
config: Dict[str, Any] | None = None,
48+
logger: PageLogger | None = None,
49+
) -> None:
50+
if logger is None:
51+
logger = PageLogger({"level": "INFO"})
4352
self.logger = logger
44-
self.name_of_agent_or_team = settings["name_of_agent_or_team"]
45-
self.disable_prefix_caching = settings["disable_prefix_caching"]
4653

54+
# Assign default values that can be overridden by config.
55+
self.name_of_agent_or_team = "SimpleAgent"
56+
self.disable_prefix_caching = False
57+
agentic_memory_controller_config = None
58+
59+
if config is not None:
60+
# Apply any overrides from the config.
61+
for key in config:
62+
if key == "name_of_agent_or_team":
63+
self.name_of_agent_or_team = config[key]
64+
elif key == "disable_prefix_caching":
65+
self.disable_prefix_caching = config[key]
66+
elif key == "AgenticMemoryController":
67+
agentic_memory_controller_config = config[key]
68+
else:
69+
self.logger.error('Unexpected item in config: ["{}"] = {}'.format(key, config[key]))
70+
71+
self.client = client
4772
if self.disable_prefix_caching:
4873
self.rand = random.Random()
4974
self.rand.seed(int(time.time() * 1000))
5075

5176
# Create the AgenticMemoryController, which creates the AgenticMemoryBank.
5277
self.memory_controller = AgenticMemoryController(
53-
settings=settings["AgenticMemoryController"],
5478
reset=True,
5579
client=self.client,
5680
task_assignment_callback=self.assign_task_to_agent_or_team,
81+
config=agentic_memory_controller_config,
5782
logger=self.logger,
5883
)
5984

python/packages/autogen-ext/src/autogen_ext/agentic_memory/grader.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,19 @@ class Grader:
2525
2626
Args:
2727
client: The client to call the model.
28-
logger: The logger to log the model calls.
28+
logger: An optional logger. If None, no logging will be performed.
2929
3030
Methods:
3131
test_apprentice: Tests the apprentice on the given task.
3232
call_model: Calls the model with the given input and returns the response.
3333
is_response_correct: Determines whether the response is equivalent to the task's correct answer.
3434
"""
3535

36-
def __init__(self, client: ChatCompletionClient, logger: PageLogger):
37-
self.client = client
36+
def __init__(self, client: ChatCompletionClient, logger: PageLogger | None = None) -> None:
37+
if logger is None:
38+
logger = PageLogger() # Nothing will be logged by this object.
3839
self.logger = logger
40+
self.client = client
3941

4042
# Check whether to report results to the client.
4143
self.report_results = hasattr(self.client, "report_result")
@@ -51,9 +53,8 @@ async def test_apprentice(
5153
num_trials: int,
5254
use_memory: bool,
5355
client: ChatCompletionClient,
54-
logger: PageLogger,
5556
) -> Tuple[int, int]:
56-
logger.enter_function()
57+
self.logger.enter_function()
5758

5859
self.logger.info("Testing the apprentice on the given task.\n")
5960

@@ -74,7 +75,7 @@ async def test_apprentice(
7475
self.logger.info("Answer is INCORRECT.\n")
7576

7677
self.logger.info("\nSuccess rate: {}%\n".format(round((num_successes / num_trials) * 100)))
77-
logger.leave_function()
78+
self.logger.leave_function()
7879
return num_successes, num_trials
7980

8081
async def call_model(

python/packages/autogen-ext/src/autogen_ext/agentic_memory/page_logger.py

+20-5
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,9 @@ class PageLogger:
7171
Logs text and images to a set of HTML pages, one per function/method, linked to each other in a call tree.
7272
7373
Args:
74-
settings: A dictionary containing the following keys:
74+
- config: An optional dict that can be used to override the following values:
7575
- level: The logging level, one of DEBUG, INFO, WARNING, ERROR, CRITICAL, or NONE.
76-
- path: The path to the directory where the log files will be saved.
76+
- path: The path to the directory where the log files will be written.
7777
7878
Methods:
7979
debug: Adds DEBUG text to the current page if debugging level <= DEBUG.
@@ -91,7 +91,7 @@ class PageLogger:
9191
leave_function: Finishes the page corresponding to the current function call.
9292
"""
9393

94-
def __init__(self, settings: Dict[str, Any]) -> None:
94+
def __init__(self, config: Dict[str, Any] | None = None) -> None:
9595
self.levels = {
9696
"DEBUG": 10,
9797
"INFO": 20,
@@ -100,10 +100,25 @@ def __init__(self, settings: Dict[str, Any]) -> None:
100100
"CRITICAL": 50,
101101
"NONE": 100,
102102
}
103-
self.level = self.levels[settings["level"]]
103+
104+
# Assign default values that can be overridden by config.
105+
self.level = self.levels["NONE"] # Default to no logging at all.
106+
self.log_dir = os.path.expanduser("~/pagelogs/temp")
107+
108+
if config is not None:
109+
# Apply any overrides from the config.
110+
for key in config:
111+
if key == "level":
112+
self.level = self.levels[config[key]]
113+
elif key == "path":
114+
self.log_dir = os.path.expanduser(config[key])
115+
else:
116+
raise ValueError(f"Unknown key in PageLogger config: {key}")
117+
118+
# If the log level is set to NONE or higher, don't log anything.
104119
if self.level >= self.levels["NONE"]:
105120
return
106-
self.log_dir = os.path.expanduser(settings["path"])
121+
107122
self.page_stack = PageStack()
108123
self.pages: List[Page] = []
109124
self.last_page_id = 0

0 commit comments

Comments
 (0)