Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task-Centric Memory #5227

Open
wants to merge 134 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 112 commits
Commits
Show all changes
134 commits
Select commit Hold shift + click to select a range
442a9d8
initial checkin
rickyloynd-microsoft Nov 29, 2024
f8584cd
support for extensive evaluations
rickyloynd-microsoft Dec 2, 2024
607e7ff
Enhance retrieval with task generalization and insight validation
rickyloynd-microsoft Dec 4, 2024
b045636
Support TRAPI client.
rickyloynd-microsoft Dec 9, 2024
63b28d7
Restoring earlier results, and general cleanup.
rickyloynd-microsoft Dec 24, 2024
b921d83
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Dec 24, 2024
9dfb074
Modify imports after merge from main.
rickyloynd-microsoft Dec 24, 2024
93a5ca4
Log model and token counts.
rickyloynd-microsoft Dec 26, 2024
2cb9344
Only instantiate the client once.
rickyloynd-microsoft Dec 26, 2024
878f458
Fix bug that was duplicating insights across trials.
rickyloynd-microsoft Dec 26, 2024
21562f1
Add the Grader class.
rickyloynd-microsoft Dec 27, 2024
3a40b30
Adjustments for comparison tests.
rickyloynd-microsoft Dec 28, 2024
8622c5e
Test generalization over multiple tasks.
rickyloynd-microsoft Dec 30, 2024
20b26c1
Add teachability and a test for it.
rickyloynd-microsoft Dec 31, 2024
9d47227
Learning from demonstration, in-progress.
rickyloynd-microsoft Jan 1, 2025
52d4e00
In memory retrieval, validate insights separately rather than together.
rickyloynd-microsoft Jan 1, 2025
6b15777
Finish learning from demonstration.
rickyloynd-microsoft Jan 2, 2025
a18674c
Added RecordableChatCompletionClient as a guardrail during refactoring.
rickyloynd-microsoft Jan 3, 2025
52e213e
Ran 3 evals with session recording and replay.
rickyloynd-microsoft Jan 5, 2025
a440b0a
Add results to recorded sessions, including session length.
rickyloynd-microsoft Jan 5, 2025
cab51f1
Use yaml file for eval settings.
rickyloynd-microsoft Jan 7, 2025
d91e58c
Simplify paths and other settings.
rickyloynd-microsoft Jan 7, 2025
f1d7a2f
Renamed the memory classes.
rickyloynd-microsoft Jan 7, 2025
17d4c42
Apprentice.
rickyloynd-microsoft Jan 8, 2025
19654e8
Moved test into the evaluator, and removed eval.py's other util funct…
rickyloynd-microsoft Jan 8, 2025
7aa20c1
renaming
rickyloynd-microsoft Jan 8, 2025
83a7ddc
Rerouted calls to AgenticMemoryController through FastLearner.
rickyloynd-microsoft Jan 9, 2025
3047c1c
Replace task_assignment_callback with AgentWrapper.
rickyloynd-microsoft Jan 9, 2025
1f20b79
Segregate files into subfolders, eval framework vs. implementation, etc.
rickyloynd-microsoft Jan 10, 2025
de4c12b
Rename FastLearner subclass to Apprentice, and import it only as spec…
rickyloynd-microsoft Jan 10, 2025
a9d6108
Refactoring, preparatory to removing eval_framework from the branch a…
rickyloynd-microsoft Jan 11, 2025
d67e2cc
Remove the outdated final_format_instructions parameter.
rickyloynd-microsoft Jan 11, 2025
6470fd8
Move tasks into yaml files.
rickyloynd-microsoft Jan 12, 2025
b025199
Move client support to a subdir.
rickyloynd-microsoft Jan 12, 2025
4f9267c
Move evaluations to a separate dir.
rickyloynd-microsoft Jan 12, 2025
db34844
single line
rickyloynd-microsoft Jan 14, 2025
c780852
Add baseline evaluation for the no-memory case.
rickyloynd-microsoft Jan 16, 2025
fa688f7
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Jan 17, 2025
43bda2f
Support o1 models
rickyloynd-microsoft Jan 18, 2025
be081b3
simplification of client creation code
rickyloynd-microsoft Jan 18, 2025
29d1494
simplify folder structure
rickyloynd-microsoft Jan 18, 2025
8e9a550
Move task data strings out of the eval functions.
rickyloynd-microsoft Jan 20, 2025
b3fe084
simplify page_log
rickyloynd-microsoft Jan 21, 2025
077615f
simplify page_log
rickyloynd-microsoft Jan 21, 2025
8847168
simplify page_log
rickyloynd-microsoft Jan 21, 2025
4091ab3
conventional logging terminology
rickyloynd-microsoft Jan 22, 2025
3865cff
control logger enabling
rickyloynd-microsoft Jan 22, 2025
6c73674
add logging to string map
rickyloynd-microsoft Jan 22, 2025
db5e07b
simplify logging
rickyloynd-microsoft Jan 22, 2025
07cb3f0
simplify logging
rickyloynd-microsoft Jan 22, 2025
e88bd69
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Jan 22, 2025
9b3f77d
merge from main
rickyloynd-microsoft Jan 23, 2025
a0dee67
Changes made by poe check.
rickyloynd-microsoft Jan 23, 2025
7e359e9
docstrings etc.
rickyloynd-microsoft Jan 23, 2025
9466ea8
docstrings etc.
rickyloynd-microsoft Jan 24, 2025
4ec9bff
docstrings etc.
rickyloynd-microsoft Jan 24, 2025
76c16f9
docstrings etc.
rickyloynd-microsoft Jan 24, 2025
a8cd0d7
docstrings etc.
rickyloynd-microsoft Jan 24, 2025
ed7fae1
docstrings etc.
rickyloynd-microsoft Jan 25, 2025
93de858
docstrings etc.
rickyloynd-microsoft Jan 25, 2025
1a309f9
docstrings etc.
rickyloynd-microsoft Jan 25, 2025
8993aa1
docstrings etc.
rickyloynd-microsoft Jan 25, 2025
fa60d5a
Simplify naming
rickyloynd-microsoft Jan 25, 2025
882d578
Simplify tests
rickyloynd-microsoft Jan 26, 2025
00cbb8c
standardize logging levels
rickyloynd-microsoft Jan 27, 2025
88294d2
Remove Evaluator class
rickyloynd-microsoft Jan 27, 2025
7d0ed63
sample code
rickyloynd-microsoft Jan 27, 2025
5b3876f
readme
rickyloynd-microsoft Jan 28, 2025
21220d4
readme fixes
rickyloynd-microsoft Jan 28, 2025
232ed0f
samples readme
rickyloynd-microsoft Jan 28, 2025
87ee27b
readme files
rickyloynd-microsoft Jan 28, 2025
b21d140
readme files
rickyloynd-microsoft Jan 28, 2025
1e88eb6
remove ame
rickyloynd-microsoft Jan 28, 2025
a3addc1
readme
rickyloynd-microsoft Jan 28, 2025
c6ffa43
comment out api_key lines
rickyloynd-microsoft Jan 28, 2025
8f66612
Optional disabling of prefix caching (to decorrelate repeated runs)
rickyloynd-microsoft Jan 28, 2025
491964f
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Jan 28, 2025
2ed08ae
Remove unnecessary instantiation of Grader
rickyloynd-microsoft Jan 29, 2025
f879487
Updated image using git-lfs
rickyloynd-microsoft Jan 30, 2025
60f8ad3
Merge branch 'agentic_memory' of github.com:microsoft/autogen into ag…
rickyloynd-microsoft Jan 30, 2025
ed0a4a6
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Jan 30, 2025
f0eceef
installation fixes
rickyloynd-microsoft Jan 30, 2025
70db202
Refactor to remove AgentWrapper, and use AssistantAgent as a TaskRunn…
rickyloynd-microsoft Jan 31, 2025
5e4ad48
uv fixes
rickyloynd-microsoft Jan 31, 2025
b6c59ae
uv fixes
rickyloynd-microsoft Jan 31, 2025
bef7e5d
uv fixes
rickyloynd-microsoft Feb 1, 2025
1fb5ee4
uv fixes
rickyloynd-microsoft Feb 1, 2025
1d7f4eb
uv fixes
rickyloynd-microsoft Feb 1, 2025
516e689
uv fixes
rickyloynd-microsoft Feb 1, 2025
ffe719a
uv fixes
rickyloynd-microsoft Feb 1, 2025
ba14e78
uv fixes
rickyloynd-microsoft Feb 3, 2025
2eb817e
uv fixes
rickyloynd-microsoft Feb 3, 2025
95b1276
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 3, 2025
6633169
uv fixes
rickyloynd-microsoft Feb 4, 2025
880df13
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 4, 2025
b4ea0ce
uv fixes
rickyloynd-microsoft Feb 5, 2025
53da266
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 5, 2025
6a04851
Add line to autogenstudio section of uv.lock
rickyloynd-microsoft Feb 5, 2025
ad514eb
poe check fixes
rickyloynd-microsoft Feb 5, 2025
18ae4dc
uv
rickyloynd-microsoft Feb 5, 2025
7be995d
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 5, 2025
0e01720
hash output for detecting log changes
rickyloynd-microsoft Feb 6, 2025
0416e8d
Merge branch 'main' of github.com:microsoft/autogen
rickyloynd-microsoft Feb 6, 2025
0298591
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 6, 2025
0bc0500
Make logger and config args optional
rickyloynd-microsoft Feb 7, 2025
66029cf
terminology: settings -> configs
rickyloynd-microsoft Feb 7, 2025
d9ad986
Merge branch 'main' of github.com:microsoft/autogen
rickyloynd-microsoft Feb 7, 2025
2b2cbdb
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 7, 2025
566709b
Simplify the API in preparation for Webby
rickyloynd-microsoft Feb 11, 2025
2ef5e4a
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 11, 2025
9e7d245
uv.lock
rickyloynd-microsoft Feb 11, 2025
1ce4cd9
Restore version for autogenstudio
rickyloynd-microsoft Feb 11, 2025
494d81e
Add a retrieval sample, which accesses the memory controller directly…
rickyloynd-microsoft Feb 12, 2025
54b0faa
Change of terminology: Agentic Memory -> Task-Centric Memory
rickyloynd-microsoft Feb 12, 2025
0b9f042
Move support files into utils subdir.
rickyloynd-microsoft Feb 12, 2025
a720863
Update readme files per reviewer feedback.
rickyloynd-microsoft Feb 14, 2025
b0e72a7
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 14, 2025
dba5b55
Get API Reference documentation to build correctly.
rickyloynd-microsoft Feb 15, 2025
01d8b9d
Add code example provided by @ekzhu
rickyloynd-microsoft Feb 15, 2025
193466b
Added installation instructions and a code snippet to the docstring.
rickyloynd-microsoft Feb 15, 2025
39d460a
Code format fix in the docstring
rickyloynd-microsoft Feb 15, 2025
8f9d066
Use TypedDicts in the nested-config pattern to minimize code changes …
rickyloynd-microsoft Feb 17, 2025
94eab06
Merge branch 'refs/heads/main' into agentic_memory
rickyloynd-microsoft Feb 17, 2025
f892c18
Add clarifying diagrams.
rickyloynd-microsoft Feb 18, 2025
a15bfd1
fix image sizes
rickyloynd-microsoft Feb 18, 2025
3ea8011
Merge branch 'main' into agentic_memory
rickyloynd-microsoft Feb 19, 2025
58ecd7e
Add file docstrings to sample code.
rickyloynd-microsoft Feb 20, 2025
00e27e1
Merge branch 'agentic_memory' of github.com:microsoft/autogen into ag…
rickyloynd-microsoft Feb 20, 2025
4466eee
uv sync --all-extras
rickyloynd-microsoft Feb 20, 2025
64dc3c0
restore previous uv.lock
rickyloynd-microsoft Feb 20, 2025
e15d0eb
changes for webby
rickyloynd-microsoft Feb 21, 2025
af362f6
experimental
rickyloynd-microsoft Feb 21, 2025
4d6c9f4
docs
rickyloynd-microsoft Feb 23, 2025
261fe6f
Add Teachability(Memory)
rickyloynd-microsoft Feb 26, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion python/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ cython_debug/
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.idea/

.ruff_cache/

Expand Down
3 changes: 3 additions & 0 deletions python/packages/autogen-ext/imgs/agentic_memory.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 3 additions & 1 deletion python/packages/autogen-ext/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ jupyter-executor = [
"nbclient>=0.10.2",
]

agentic-memory = ["chromadb>=0.6.3"]

semantic-kernel-core = [
"semantic-kernel>=1.17.1",
]
Expand Down Expand Up @@ -140,7 +142,7 @@ dev = [
[tool.ruff]
extend = "../../pyproject.toml"
include = ["src/**", "tests/*.py"]
exclude = ["src/autogen_ext/agents/web_surfer/*.js", "src/autogen_ext/runtimes/grpc/protos", "tests/protos"]
exclude = ["src/autogen_ext/agents/web_surfer/*.js", "src/autogen_ext/runtimes/grpc/protos", "tests/protos", "README.md"]

[tool.pyright]
extends = "../../pyproject.toml"
Expand Down
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This README is really useful but a bit too verbose. Can we please make this more concise?

Also move installation instructions and a minimal example to the top.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Agentic Memory

This AutoGen extension provides an implementation of agentic memory, which we define as a
broad ability for AI agents to accomplish tasks more effectively by learning quickly and continually (over the long term).
This is distinct from what RAG or long context windows can provide.
While still under active research and development, this implementation of agentic memory
can be attached to virtually any unmodified AI agent, and is designed to enable agents that:

* Remember guidance, corrections, and demonstrations provided by users.
* Succeed more frequently on tasks after finding successful solutions to similar tasks.
* Learn and adapt quickly to changing circumstances to enable workflows that are dynamic and self-healing.

The implementation is also intended to:

* Be general purpose, unconstrained by types and schemas required by standard databases.
* Augment rather than interfere with an agent’s special capabilities, such as powerful reasoning, long-horizon autonomy, and tool handling.
* Operate in both foreground and background modes, so that an agent can discuss tasks with a user (in the foreground)
then work productively on those tasks (in the background) while the user does other things.
* Allow for fine-grained transparency and auditing of individual memories by human users or other agents.
* Allow agents to be personalized (to a single user) as well as specialized (to a subject, domain or project).
The benefits of personalization scale linearly with the number of users, but the benefits of domain specialization
can scale quadratically with the number of users working in that domain, as insights gained from interactions with one user
can benefit other users in similar situations.
* Support multiple memory banks dynamically attached to an agent at runtime.
* Enable enforcement of security boundaries at the level of individual memory banks.
* Allow users to download and port memory banks between agents and systems.

![agentic_memory.png](../../../imgs/agentic_memory.png)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Figure font size is too large. Would be good to reduce and make consistent.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed


The block diagram above outlines the key components of our baseline agentic memory architecture,
which augments an agent or team with agentic memory mechanisms.

The **Agentic Memory Controller** implements the fast-learning methods described below,
and manages communication with an **Agentic Memory Bank** containing a vector DB and associated structures.

The **Apprentice** is a minimal reference implementation that wraps the combination of agentic memory plus some agent or team.
Certain applications will use the Apprentice,
while others will directly instantiate and call the Agentic Memory Controller.

We’ve successfully tested agentic memory with a simple AssistantAgent and MagenticOneGroupChat.

## Memory Creation and Storage

Each stored memory (called a _memo_) is an insight (in text form) crafted to help the agent accomplish future tasks that are similar
to some task encountered in the past. If the user provides advice for solving a given task,
the advice is extracted and stored as an insight. If the user demonstrates how to perform a task,
the task and demonstration are stored together as an insight that could be applied to similar but different tasks.
If the agent is given a task (free of side-effects) and some means of determining success or failure,
the memory controller repeats the following learning loop in the background some number of times:

1. Test the agent on the task a few times to check for a failure.
2. If a failure is found, analyze the agent’s response in order to:
1. Diagnose the failure of reasoning or missing information,
2. Phrase a general piece of advice, such as what a teacher might give to a student,
3. Temporarily append this advice to the task description,
4. Return to step 1.
5. If some piece of advice succeeds in helping the agent solve the task a number of times, add the advice as an insight to memory.
3. For each insight to be stored in memory, an LLM is prompted to generate a set of free-form, multi-word topics related to the insight. Each topic is embedded to a fixed-length vector and stored in a vector DB mapping it to the topic’s related insight.

## Memory Retrieval and Usage

When the agent is given a task, the following steps are performed by the memory controller:
1. The task is rephrased into a generalized form.
2. A set of free-form, multi-word query topics are generated from the generalized task.
3. A potentially large number of previously stored topics, those most similar to each query topic, are retrieved from the vector DB along with the insights they map to.
4. These candidate memos are filtered by the aggregate similarity of their stored topics to the query topics.
5. In the final filtering stage, an LLM is prompted to return only those insights that seem potentially useful in solving the task at hand.

Retrieved insights that pass the filtering steps are listed under a heading like
“Important insights that may help solve tasks like this”, then appended to the task description before it is passed to the agent as usual.

## Setup and Usage

Install AutoGen and its extension package as follows:

`pip install "autogen-ext[agentic-memory]"`

We provide [sample code](../../../../../samples/agentic_memory) to illustrate the following forms of memory-based fast learning:
* Agent learning from user advice and corrections
* Agent learning from user demonstrations
* Agent learning from its own experience
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from .agentic_memory_controller import AgenticMemoryController
from .apprentice import Apprentice
from .grader import Grader
from .page_logger import PageLogger

Check warning on line 4 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/__init__.py

View check run for this annotation

Codecov / codecov/patch

python/packages/autogen-ext/src/autogen_ext/agentic_memory/__init__.py#L1-L4

Added lines #L1 - L4 were not covered by tests

__all__ = ["Apprentice", "PageLogger", "Grader", "AgenticMemoryController"]

Check warning on line 6 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/__init__.py

View check run for this annotation

Codecov / codecov/patch

python/packages/autogen-ext/src/autogen_ext/agentic_memory/__init__.py#L6

Added line #L6 was not covered by tests
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import os
import pickle
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple

Check warning on line 4 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L1 - L4 were not covered by tests

from ._string_similarity_map import StringSimilarityMap
from .page_logger import PageLogger

Check warning on line 7 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L6 - L7 were not covered by tests


@dataclass
class Memo:

Check warning on line 11 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L10 - L11 were not covered by tests
"""
Represents an atomic unit of memory that can be stored in a memory bank and later retrieved.
"""

task: str | None # The task description, if any.
insight: str # A hint, solution, plan, or any other text that may help solve a similar task.

Check warning on line 17 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L16 - L17 were not covered by tests


class AgenticMemoryBank:

Check warning on line 20 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L20 was not covered by tests
"""
Stores task-completion insights as memories in a vector DB for later retrieval.

Args:
- reset: True to clear the DB before starting.
- config: An optional dict that can be used to override the following values:
- path: The path to the directory where the memory bank files are stored.
- relevance_conversion_threshold: The threshold used to normalize relevance.
- n_results: The maximum number of most relevant results to return for any given topic.
- distance_threshold: The maximum string-pair distance for a memo to be retrieved.
- logger: An optional logger. If None, no logging will be performed.

Methods:
- reset: Forces immediate deletion of all contents, in memory and on disk.
- save_memos: Saves the current memo structures (possibly empty) to disk.
- contains_memos: Returns True if the memory bank contains any memos.
- add_memo: Adds a memo to the memory bank, given topics related to the insight, and optionally the task.
- add_task_with_solution: Adds a task-insight pair to the memory bank, to be retrieved together later.
- get_relevant_memos: Returns any memos from the memory bank that appear sufficiently relevant to the input topics.
"""

def __init__(

Check warning on line 42 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L42 was not covered by tests
self,
reset: bool,
config: Dict[str, Any] | None = None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to the commont on agentic memory controller, is there a reason to have a dictionary as part of the argument list? Can we add the keys of the dictionary directly as arguments?

I understand it may be "easier" for the developer of this module to use a config dictionary. But from user experience point of view, as well as for consistency with the rest of the library, it is better to keep the argument list flat rather than introducing additional dictionary, especially the dictionary is quite small.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed per our discussion, using TypedDict in the nested-config pattern to minimize code changes by encapsulating the settings that change frequently, as when loading many settings from a single YAML file.

logger: PageLogger | None = None,
) -> None:
if logger is None:
logger = PageLogger() # Nothing will be logged by this object.
self.logger = logger
self.logger.enter_function()

Check warning on line 51 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L48 - L51 were not covered by tests

# Assign default values that can be overridden by config.
memory_dir_path = os.path.expanduser("~/agentic_memory/temp")
self.relevance_conversion_threshold = 1.7
self.n_results = 25
self.distance_threshold = 100

Check warning on line 57 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L54 - L57 were not covered by tests

if config is not None:

Check warning on line 59 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L59 was not covered by tests
# Apply any overrides from the config.
for key in config:
if key == "path":
memory_dir_path = os.path.expanduser(config[key])
elif key == "relevance_conversion_threshold":
self.relevance_conversion_threshold = config[key]
elif key == "n_results":
self.n_results = config[key]
elif key == "distance_threshold":
self.distance_threshold = config[key]

Check warning on line 69 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L61 - L69 were not covered by tests
else:
self.logger.error('Unexpected item in config: ["{}"] = {}'.format(key, config[key]))

Check warning on line 71 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L71 was not covered by tests

path_to_db_dir = os.path.join(memory_dir_path, "string_map")
self.path_to_dict = os.path.join(memory_dir_path, "uid_memo_dict.pkl")

Check warning on line 74 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L73 - L74 were not covered by tests

self.string_map = StringSimilarityMap(reset=reset, path_to_db_dir=path_to_db_dir, logger=self.logger)

Check warning on line 76 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L76 was not covered by tests

# Load or create the associated memo dict on disk.
self.uid_memo_dict: Dict[str, Memo] = {}
self.last_memo_id = 0
if (not reset) and os.path.exists(self.path_to_dict):
self.logger.info("\nLOADING MEMOS FROM DISK {}".format(self.path_to_dict))
self.logger.info(" Location = {}".format(self.path_to_dict))
with open(self.path_to_dict, "rb") as f:
self.uid_memo_dict = pickle.load(f)
self.last_memo_id = len(self.uid_memo_dict)
self.logger.info("\n{} MEMOS LOADED".format(len(self.uid_memo_dict)))

Check warning on line 87 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L79 - L87 were not covered by tests

# Clear the DB if requested.
if reset:
self._reset_memos()

Check warning on line 91 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L90 - L91 were not covered by tests

self.logger.leave_function()

Check warning on line 93 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L93 was not covered by tests

def reset(self) -> None:

Check warning on line 95 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L95 was not covered by tests
"""
Forces immediate deletion of all contents, in memory and on disk.
"""
self.string_map.reset_db()
self._reset_memos()

Check warning on line 100 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L99 - L100 were not covered by tests

def _reset_memos(self) -> None:

Check warning on line 102 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L102 was not covered by tests
"""
Forces immediate deletion of the memos, in memory and on disk.
"""
self.uid_memo_dict = {}
self.save_memos()

Check warning on line 107 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L106 - L107 were not covered by tests

def save_memos(self) -> None:

Check warning on line 109 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L109 was not covered by tests
"""
Saves the current memo structures (possibly empty) to disk.
"""
self.string_map.save_string_pairs()
with open(self.path_to_dict, "wb") as file:
pickle.dump(self.uid_memo_dict, file)

Check warning on line 115 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L113 - L115 were not covered by tests

def contains_memos(self) -> bool:

Check warning on line 117 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L117 was not covered by tests
"""
Returns True if the memory bank contains any memo.
"""
return len(self.uid_memo_dict) > 0

Check warning on line 121 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L121 was not covered by tests

def _map_topics_to_memo(self, topics: List[str], memo_id: str, memo: Memo) -> None:

Check warning on line 123 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L123 was not covered by tests
"""
Adds a mapping in the vec DB from each topic to the memo.
"""
self.logger.enter_function()
self.logger.info("\nINSIGHT\n{}".format(memo.insight))
for topic in topics:
self.logger.info("\n TOPIC = {}".format(topic))
self.string_map.add_input_output_pair(topic, memo_id)
self.uid_memo_dict[memo_id] = memo
self.logger.leave_function()

Check warning on line 133 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L127 - L133 were not covered by tests

def add_memo(self, insight_str: str, topics: List[str], task_str: Optional[str] = None) -> None:

Check warning on line 135 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L135 was not covered by tests
"""
Adds an insight to the memory bank, given topics related to the insight, and optionally the task.
"""
self.logger.enter_function()
self.last_memo_id += 1
id_str = str(self.last_memo_id)
insight = Memo(insight=insight_str, task=task_str)
self._map_topics_to_memo(topics, id_str, insight)
self.logger.leave_function()

Check warning on line 144 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L139 - L144 were not covered by tests

def add_task_with_solution(self, task: str, solution: str, topics: List[str]) -> None:

Check warning on line 146 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L146 was not covered by tests
"""
Adds a task-solution pair to the memory bank, to be retrieved together later as a combined insight.
This is useful when the insight is a demonstration of how to solve a given type of task.
"""
self.logger.enter_function()
self.last_memo_id += 1
id_str = str(self.last_memo_id)

Check warning on line 153 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L151 - L153 were not covered by tests
# Prepend the insight to the task description for context.
insight_str = "Example task:\n\n{}\n\nExample solution:\n\n{}".format(task, solution)
memo = Memo(insight=insight_str, task=task)
self._map_topics_to_memo(topics, id_str, memo)
self.logger.leave_function()

Check warning on line 158 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L155 - L158 were not covered by tests

def get_relevant_memos(self, topics: List[str]) -> List[Memo]:

Check warning on line 160 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L160 was not covered by tests
"""
Returns any memos from the memory bank that appear sufficiently relevant to the input topics.
"""
self.logger.enter_function()

Check warning on line 164 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L164 was not covered by tests

# Retrieve all topic matches, and gather them into a single list.
matches: List[Tuple[str, str, float]] = [] # Each match is a tuple: (topic, memo_id, distance)
for topic in topics:
matches.extend(self.string_map.get_related_string_pairs(topic, self.n_results, self.distance_threshold))

Check warning on line 169 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L167 - L169 were not covered by tests

# Build a dict of memo-relevance pairs from the matches.
memo_relevance_dict: Dict[str, float] = {}
for match in matches:
relevance = self.relevance_conversion_threshold - match[2]
memo_id = match[1]
if memo_id in memo_relevance_dict:
memo_relevance_dict[memo_id] += relevance

Check warning on line 177 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L172 - L177 were not covered by tests
else:
memo_relevance_dict[memo_id] = relevance

Check warning on line 179 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L179 was not covered by tests

# Log the details of all the retrieved memos.
self.logger.info("\n{} POTENTIALLY RELEVANT MEMOS".format(len(memo_relevance_dict)))
for memo_id, relevance in memo_relevance_dict.items():
memo = self.uid_memo_dict[memo_id]
details = ""
if memo.task is not None:
details += "\n TASK: {}\n".format(memo.task)
details += "\n INSIGHT: {}\n\n RELEVANCE: {:.3f}\n".format(memo.insight, relevance)
self.logger.info(details)

Check warning on line 189 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L182 - L189 were not covered by tests

# Compose the list of sufficiently relevant memos to return.
memo_list: List[Memo] = []
for memo_id in memo_relevance_dict:
if memo_relevance_dict[memo_id] >= 0:
memo_list.append(self.uid_memo_dict[memo_id])

Check warning on line 195 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L192 - L195 were not covered by tests

self.logger.leave_function()
return memo_list

Check warning on line 198 in python/packages/autogen-ext/src/autogen_ext/agentic_memory/_agentic_memory_bank.py

View check run for this annotation

Codecov / codecov/patch

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

Added lines #L197 - L198 were not covered by tests
Loading
Loading