Skip to content

Conversation

@lxobr
Copy link
Collaborator

@lxobr lxobr commented Nov 5, 2024

  • Created a new example script based on the simple example in the README
  • Updated the simple example in README with additional instructions

Summary by CodeRabbit

  • New Features

    • Updated the README.md with clearer usage instructions and examples for the cognee library.
    • Introduced a new asynchronous example (simple_example.py) demonstrating the library's functionality for NLP tasks.
    • Enhanced documentation on creating memory stores and added an example of a naive LLM classifier.
  • Bug Fixes

    • Improved clarity and usability of the documentation for better developer understanding.

@lxobr lxobr self-assigned this Nov 5, 2024
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes include updates to the README.md file to clarify usage instructions for the cognee library, particularly regarding setup and configuration. An asynchronous example script, simple_example.py, has been added to demonstrate the library's capabilities in natural language processing tasks. This script illustrates the process of resetting data, adding text, and querying for insights. Overall, the documentation and examples have been enhanced for better clarity and usability.

Changes

File Change Summary
README.md Updated usage instructions, clarified setup process, added optional VECTOR_DB_PROVIDER config, and expanded memory store section. Enhanced example code structure with an async main function and updated search functionality.
examples/python/simple_example.py Introduced a new asynchronous example demonstrating cognee usage, including data resetting, adding text, and querying for insights.

Possibly related PRs

Suggested reviewers

  • dexters1
  • Vasilije1990

🐰 "In the garden of code, we hop and play,
With cognee's magic, we brighten the day.
From setup to insights, our paths intertwine,
In this world of knowledge, our efforts align!
So let's code together, with joy and with cheer,
For every new feature, a rabbit's leap near!" 🐇


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.

@Vasilije1990 Vasilije1990 merged commit 401befc into main Nov 5, 2024
25 of 27 checks passed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (6)
examples/python/simple_example.py (3)

5-9: Enhance prerequisites with error handling guidance.

The setup instructions are clear, but consider adding information about common errors and troubleshooting steps, such as what happens if the API key is invalid or if the .env file is not found.

 # Prerequisites:
 # 1. Copy `.env.template` and rename it to `.env`.
 # 2. Add your OpenAI API key to the `.env` file in the `LLM_API_KEY` field:
 #    LLM_API_KEY = "your_key_here"
-# 3. (Optional) To minimize setup effort, set `VECTOR_DB_PROVIDER="lancedb"` in `.env".
+# 3. (Optional) To minimize setup effort, set `VECTOR_DB_PROVIDER="lancedb"` in `.env`.
+# 
+# Common issues:
+# - If you get an authentication error, verify your OpenAI API key is correct
+# - If you get a configuration error, ensure the .env file exists in the root directory

38-39: Add proper shutdown handling for the async event loop.

Consider adding signal handlers to ensure clean shutdown of the async operations.

+import signal
+
 if __name__ == '__main__':
-    asyncio.run(main())
+    try:
+        loop = asyncio.get_event_loop()
+        signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
+        for s in signals:
+            loop.add_signal_handler(
+                s, lambda s=s: asyncio.create_task(loop.shutdown_asyncgens())
+            )
+        loop.run_until_complete(main())
+    except KeyboardInterrupt:
+        print("\nShutting down gracefully...")
+    finally:
+        loop.close()

1-1: Add comprehensive module documentation.

As this is an example file, it should include a detailed module docstring explaining its purpose, usage, and expected output.

+"""Example script demonstrating basic usage of the cognee library.
+
+This script shows how to:
+1. Set up and configure cognee
+2. Add text to the knowledge base
+3. Create a knowledge graph
+4. Query for insights
+
+Example usage:
+    $ python simple_example.py
+
+Expected output:
+    Adding text to cognee...
+    Text added successfully
+    Creating knowledge graph...
+    Knowledge graph created successfully
+    
+    Searching for insights...
+    Search Results:
+    --------------------------------------------------
+    1. [Search results will appear here]
+    --------------------------------------------------
+"""
+
 import cognee
README.md (3)

99-102: Add path information for .env.template.

The setup instructions should specify where to find the .env.template file. Consider adding the repository root path or a link to the template file in the repository.

-First, copy `.env.template` to `.env` and add your OpenAI API key to the LLM_API_KEY field. 
+First, copy the `.env.template` file from the repository root to `.env` and add your OpenAI API key to the LLM_API_KEY field. 

105-130: Consider enhancing the example with error handling and type hints.

The example effectively demonstrates the basic workflow. However, consider these improvements for production readiness:

  1. Add error handling for potential API failures
  2. Include type hints for better code clarity
  3. Show how to handle missing API key gracefully

Here's a suggested enhancement:

 import cognee
 import asyncio
 from cognee.api.v1.search import SearchType
+from typing import List, Optional
 
-async def main():
+async def main() -> None:
     await cognee.prune.prune_data()  # Reset cognee data
     await cognee.prune.prune_system(metadata=True)  # Reset cognee system state
 
     text = """
     Natural language processing (NLP) is an interdisciplinary
     subfield of computer science and information retrieval.
     """
 
-    await cognee.add(text)  # Add text to cognee
-    await cognee.cognify()  # Use LLMs and cognee to create knowledge graph
+    try:
+        await cognee.add(text)  # Add text to cognee
+        await cognee.cognify()  # Use LLMs and cognee to create knowledge graph
 
-    search_results = await cognee.search(  # Search cognee for insights
-        SearchType.INSIGHTS,
-        {'query': 'Tell me about NLP'}
-    )
+        search_results: List[str] = await cognee.search(  # Search cognee for insights
+            SearchType.INSIGHTS,
+            {'query': 'Tell me about NLP'}
+        )
 
-    for result_text in search_results:  # Display results
-        print(result_text)
+        for result_text in search_results:  # Display results
+            print(result_text)
+    except Exception as e:
+        print(f"An error occurred: {e}")
+        raise

132-132: Fix typo in path.

There's a typo in the word "python" in the example path.

-A version of this example is here: `examples/pyton/simple_example.py`
+A version of this example is here: `examples/python/simple_example.py`
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cc77d84 and 6c395d7.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • examples/python/simple_example.py (1 hunks)
🔇 Additional comments (1)
README.md (1)

103-104: LGTM!

Clear and concise introduction to the example.

Comment on lines +11 to +14
async def main():
# Create a clean slate for cognee -- reset data and system state
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and type hints to the main function.

The reset operations could fail and should be wrapped in try-except blocks. Additionally, adding type hints would improve code clarity.

-async def main():
+async def main() -> None:
     # Create a clean slate for cognee -- reset data and system state
-    await cognee.prune.prune_data()
-    await cognee.prune.prune_system(metadata=True)
+    try:
+        await cognee.prune.prune_data()
+        await cognee.prune.prune_system(metadata=True)
+    except Exception as e:
+        print(f"Failed to reset cognee state: {e}")
+        raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async def main():
# Create a clean slate for cognee -- reset data and system state
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
async def main() -> None:
# Create a clean slate for cognee -- reset data and system state
try:
await cognee.prune.prune_data()
await cognee.prune.prune_system(metadata=True)
except Exception as e:
print(f"Failed to reset cognee state: {e}")
raise

Comment on lines +28 to +36
# Query cognee for insights on the added text
search_results = await cognee.search(
SearchType.INSIGHTS,
{'query': 'Tell me about NLP'}
)

# Display search results
for result_text in search_results:
print(result_text)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance search functionality with error handling and improved results display.

The search operation needs error handling, and the results display could be more user-friendly with proper formatting.

     # Query cognee for insights on the added text
-    search_results = await cognee.search(
-        SearchType.INSIGHTS,
-        {'query': 'Tell me about NLP'}
-    )
+    try:
+        print("\nSearching for insights...")
+        search_results = await cognee.search(
+            SearchType.INSIGHTS,
+            {'query': 'Tell me about NLP'}
+        )
 
-    # Display search results
-    for result_text in search_results:
-        print(result_text)
+        # Display search results
+        if not search_results:
+            print("No results found")
+        else:
+            print("\nSearch Results:")
+            print("-" * 50)
+            for i, result_text in enumerate(search_results, 1):
+                print(f"\n{i}. {result_text}")
+            print("-" * 50)
+    except Exception as e:
+        print(f"Search failed: {e}")
+        raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Query cognee for insights on the added text
search_results = await cognee.search(
SearchType.INSIGHTS,
{'query': 'Tell me about NLP'}
)
# Display search results
for result_text in search_results:
print(result_text)
# Query cognee for insights on the added text
try:
print("\nSearching for insights...")
search_results = await cognee.search(
SearchType.INSIGHTS,
{'query': 'Tell me about NLP'}
)
# Display search results
if not search_results:
print("No results found")
else:
print("\nSearch Results:")
print("-" * 50)
for i, result_text in enumerate(search_results, 1):
print(f"\n{i}. {result_text}")
print("-" * 50)
except Exception as e:
print(f"Search failed: {e}")
raise

Comment on lines +16 to +26
# cognee knowledge graph will be created based on this text
text = """
Natural language processing (NLP) is an interdisciplinary
subfield of computer science and information retrieval.
"""

# Add the text, and make it available for cognify
await cognee.add(text)

# Use LLMs and cognee to create knowledge graph
await cognee.cognify()
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and progress feedback for text processing.

The text processing operations should include error handling and provide feedback about the processing status to improve user experience.

     # cognee knowledge graph will be created based on this text
     text = """
     Natural language processing (NLP) is an interdisciplinary
     subfield of computer science and information retrieval.
     """

     # Add the text, and make it available for cognify
-    await cognee.add(text)
+    try:
+        print("Adding text to cognee...")
+        await cognee.add(text)
+        print("Text added successfully")
 
-    # Use LLMs and cognee to create knowledge graph
-    await cognee.cognify()
+        print("Creating knowledge graph...")
+        await cognee.cognify()
+        print("Knowledge graph created successfully")
+    except Exception as e:
+        print(f"Failed to process text: {e}")
+        raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# cognee knowledge graph will be created based on this text
text = """
Natural language processing (NLP) is an interdisciplinary
subfield of computer science and information retrieval.
"""
# Add the text, and make it available for cognify
await cognee.add(text)
# Use LLMs and cognee to create knowledge graph
await cognee.cognify()
# cognee knowledge graph will be created based on this text
text = """
Natural language processing (NLP) is an interdisciplinary
subfield of computer science and information retrieval.
"""
# Add the text, and make it available for cognify
try:
print("Adding text to cognee...")
await cognee.add(text)
print("Text added successfully")
print("Creating knowledge graph...")
await cognee.cognify()
print("Knowledge graph created successfully")
except Exception as e:
print(f"Failed to process text: {e}")
raise

@soobrosa soobrosa deleted the simple-python-example branch May 28, 2025 12:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants