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

feat: Add GraphDBBlock to LongtermAgentMemory and add GraphDBMemory #851

Open
wants to merge 20 commits into
base: master
Choose a base branch
from

Conversation

mrsbeep
Copy link
Contributor

@mrsbeep mrsbeep commented Aug 21, 2024

Description

This pull request introduces a new feature to the LongtermAgentMemory by integrating a GraphDBBlock and adding a new GraphDBMemory. The changes aim to leverage knowledge graphs within AgentMemory, enhancing the capability to store and retrieve structured information through graph databases.

Motivation and Context

close #846

Types of changes

What types of changes does your code introduce? Put an x in all the boxes that apply:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds core functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation (update in the documentation)
  • Example (update in the folder of example)

Implemented Tasks

  • Implemented GraphDBBlock in LongtermAgentMemory.
  • Added GraphDBMemory to handle graph-based data.
  • Created tests for the new GraphDBMemory functionality.
  • Updated documentation to reflect the new feature.

Checklist

Go over all the following points, and put an x in all the boxes that apply.
If you are unsure about any of these, don't hesitate to ask. We are here to help!

  • I have read the CONTRIBUTION guide. (required)
  • My change requires a change to the documentation.
  • I have updated the tests accordingly. (required for a bug fix or a new feature)
  • I have updated the documentation accordingly.

Copy link

coderabbitai bot commented Aug 21, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mrsbeep mrsbeep self-assigned this Aug 21, 2024
@mrsbeep mrsbeep linked an issue Aug 21, 2024 that may be closed by this pull request
2 tasks
Copy link
Member

@lightaime lightaime left a comment

Choose a reason for hiding this comment

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

Thanks @mrsbeep for the PR. There may be still something to be redeign for this PR.

An example on how to use Neo4jGraph for GraphRAG here:

https://colab.research.google.com/drive/1meBf9w8KzZvQdQU2I1bCyOg9ehoGDK1u#scrollTo=l4VANToobUzu

A couple things to be discussed:

  • What is the default structure of the LongtermAgentMemory? Should we always have both VectorDBBlock and GraphDBBlock or allow different combinations?
  • Should we allow user to load a pre-built knowledge graph?
  • Should we allow agent to automatically convert chat messages into knowledge graphs?
  • How to score, retrieve and decide whether to use the retrieved results?
  • How to combine to retrieved KGs with vector_db_retrieve and chat_history?

"""

def __init__(self, storage: Optional[BaseGraphStorage] = None) -> None:
self.storage = storage or self.default_graph_storage()
Copy link
Member

Choose a reason for hiding this comment

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

Should we use Neo4jGraph as the default storage?

class Neo4jGraph(BaseGraphStorage):

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm currently using BaseGraphStorage as storage in GraphDBBlock. I will make it so that Neo4jGraph can use it too.

self,
context_creator: BaseContextCreator,
storage: Optional[BaseGraphStorage] = None,
query: str = "",
Copy link
Member

Choose a reason for hiding this comment

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

Should we use self._current_topic similar to VectorDBMemory for the query?

Copy link
Member

Choose a reason for hiding this comment

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

here haven't been update

Comment on lines 51 to 58
results = self.storage.query(query, params)
score = 1.0
return [
ContextRecord(
memory_record=MemoryRecord.from_dict(result), score=score
)
for result in results
]
Copy link
Member

Choose a reason for hiding this comment

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

Does this run?

graph database.
"""
results = self.storage.query(query, params)
score = 1.0
Copy link
Member

Choose a reason for hiding this comment

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

score should not be 1.0 for all ContextRecord

@mrsbeep
Copy link
Contributor Author

mrsbeep commented Aug 22, 2024

Thanks @mrsbeep for the PR. There may be still something to be redeign for this PR.

An example on how to use Neo4jGraph for GraphRAG here:

https://colab.research.google.com/drive/1meBf9w8KzZvQdQU2I1bCyOg9ehoGDK1u#scrollTo=l4VANToobUzu

A couple things to be discussed:

  • What is the default structure of the LongtermAgentMemory? Should we always have both VectorDBBlock and GraphDBBlock or allow different combinations?
  • Should we allow user to load a pre-built knowledge graph?
  • Should we allow agent to automatically convert chat messages into knowledge graphs?
  • How to score, retrieve and decide whether to use the retrieved results?
  • How to combine to retrieved KGs with vector_db_retrieve and chat_history?

What is the default structure of the LongtermAgentMemory? Should we always have both VectorDBBlock and GraphDBBlock or allow different combinations?
LongtermAgentMemory contains chat_history_block, vector_db_block, graph_db_block. You don't always need to have both VectorDBBlock and GraphDBBlock. You can include them as needed.

Should we allow user to load a pre-built knowledge graph?
The current design allows this.

Should we allow agent to automatically convert chat messages into knowledge graphs?
It would be nice if this feature existed. Let me create some conversion functions today.

How to score, retrieve and decide whether to use the retrieved results?
Scoring: The scoring mechanism is already partially implemented in the ChatHistoryBlock where historical messages are scored based on their proximity to recent messages and a keep_rate. A similar approach could be used for the vector and graph database retrievals by scoring based on similarity or relevance.
Retrieval: Each block implements its own retrieval method. For VectorDBBlock, retrieval is based on vector similarity, while GraphDBBlock might use structured queries.
Decision to Use Retrieved Results: The decision to use retrieved results can be based on the scores assigned during retrieval. Implementing threshold-based filtering or a ranking system to prioritize high-scoring results can ensure that only the most relevant information is included in the context provided to the agent.

How to Combine Retrieved Knowledge Graphs with VectorDBRetrieve and Chat History?
Combining these elements involves merging the retrieved results from each block into a cohesive context. The retrieve method in LongtermAgentMemory currently combines these by appending vector_db_retrieve and graph_db_retrieve results between the first and subsequent chat history records.
This combination could be optimized by:
Prioritizing certain types of information based on relevance or score.
Ensuring consistency and coherence in the context by resolving any potential conflicts or redundancies.
Implementing a context creation logic that respects the token limits and maintains the logical flow of conversation, potentially using the BaseContextCreator as a guide for structuring the final output.

@mrsbeep mrsbeep added New Feature Memory P1 Task with middle level priority labels Aug 22, 2024
@mrsbeep mrsbeep requested a review from lightaime August 28, 2024 19:58
Copy link
Member

@Wendong-Fan Wendong-Fan left a comment

Choose a reason for hiding this comment

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

Thanks @mrsbeep 's great contribution! Left some comments below~

Comment on lines 52 to 75
def default_graph_storage(
self,
url: Optional[str] = None,
username: Optional[str] = None,
password: Optional[str] = None,
database: Optional[str] = "neo4j",
) -> BaseGraphStorage:
# Try to get details from environment variables first
url = os.getenv('NEO4J_URI', url)
username = os.getenv('NEO4J_USERNAME', username)
password = os.getenv('NEO4J_PASSWORD', password)
database = os.getenv('NEO4J_DATABASE', database)

# Log an error if any of the necessary values are missing
if not url or not username or not password:
logger.error(
"Neo4j connection detailed are missing."
"Ensure environment variables or parameters are set for"
"NEO4J_URI, NEO4J_USERNAME, and NEO4J_PASSWORD."
)
raise ValueError("Missing Neo4j connection details.")

# Create and return an instance of Neo4jGraph
return Neo4jGraph(url, username, password, database or "neo4j")
Copy link
Member

Choose a reason for hiding this comment

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

we can just pass config information to Neo4jGraph directly since the environment variable fetching and checking would be done from class Neo4jGraph's side

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It has already been corrected.

Comment on lines 145 to 152
def _calculate_scores(self, query: str, results: List[Any]) -> List[float]:
query_graph = self._build_graph(query)
scores = []
for result in results:
result_graph = self._build_graph(result)
score = self._graph_similarity(query_graph, result_graph)
scores.append(score)
return scores
Copy link
Member

Choose a reason for hiding this comment

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

for the score I think using an embedding-based vector would be more effective for calculating the score, as it aligns better with matching the user's query. A semantic-based score would be more suitable in this case. WDYT?

Comment on lines 117 to 120
else:
subj = content.get('subject')
obj = content.get('object')
rel = content.get('relation')
Copy link
Member

Choose a reason for hiding this comment

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

record.message.content should be str, for what case it will go to this part?

"""
self.storage.add_triplet(subj, obj, rel)

def delete_triplet(self, subj: str, obj: str, rel: str) -> None:
Copy link
Member

Choose a reason for hiding this comment

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

I think the delete_triplet shouldn't be put into here, it will be managed from graph db's side, but we can add delete_records method

Comment on lines 119 to 120
query (str, optional):
The query to retrieve data from the graph database.
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
query (str, optional):
The query to retrieve data from the graph database.
query (str, optional): The query to retrieve data from the graph
database.

Comment on lines 587 to 588
def clear(self) -> None:
pass
Copy link
Member

@Wendong-Fan Wendong-Fan Aug 30, 2024

Choose a reason for hiding this comment

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

we can also add code to realize this method if it's required by the memory module

Comment on lines 136 to 144
def write_triplet(self, subj: str, obj: str, rel: str) -> None:
r"""Writes a triplet to the graph database.

Args:
subj (str): The subject of the triplet.
obj (str): The object of the triplet.
rel (str): The relationship between subject and object.
"""
self._graphdb_block.write_triplet(subj, obj, rel)
Copy link
Member

Choose a reason for hiding this comment

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

I think here should be write_records using self._graphdb_block.write_record()

self,
context_creator: BaseContextCreator,
storage: Optional[BaseGraphStorage] = None,
query: str = "",
Copy link
Member

Choose a reason for hiding this comment

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

here haven't been update

Comment on lines 91 to 92
results = self.storage.query(query, params)
scores = self._calculate_scores(query, results)
Copy link
Member

Choose a reason for hiding this comment

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

here the query is some query language like Cypher, calculate the score between the query and the matched result from graph database seems doesn't make sense

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Memory New Feature P1 Task with middle level priority
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature Request] Add GraphDBBlock to LongtermAgentMemory and add GraphDBMemory
3 participants