Skip to content

Conversation

@dm1tryG
Copy link
Contributor

@dm1tryG dm1tryG commented Mar 16, 2025

Description

New Text to Cypher Retriever

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin

Summary by CodeRabbit

  • New Features
    • Introduced a new "Cypher prompting" search option in the interface that expands and enhances search capabilities for graph-based queries.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 16, 2025

Walkthrough

This pull request integrates a new Cypher query search option into the application. The frontend SearchView component now offers a "Cypher prompting" choice. On the backend, a new CypherQueryRetriever class is introduced with asynchronous methods to generate and execute Cypher queries using an LLM client and a graph engine. In addition, the search types enumeration and the search method are updated to handle this new query type.

Changes

File(s) Change Summary
cognee-frontend/.../SearchView.tsx Added a new search option "CYPHER_QUERY" with label "Cypher prompting" to the searchOptions array in the SearchView component.
cognee/modules/retrieval/cypher_query_retriever.py Introduced a new class CypherQueryRetriever with async methods get_context and get_completion to generate and execute Cypher queries with error handling.
cognee/modules/search/methods/search.py,
cognee/modules/search/types/SearchType.py
Added a new enumeration value CYPHER_QUERY and updated the specific_search function to map this type to the get_completion method of the new retriever.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant SV as SearchView
    participant SM as Search Module
    participant CR as CypherQueryRetriever
    participant GE as Graph Engine

    U->>SV: Selects "Cypher prompting" option
    SV->>SM: Initiates specific_search(query, type: CYPHER_QUERY)
    SM->>CR: Calls get_completion(query)
    alt No context available
        CR->>CR: Invoke get_context(query)
        CR->>GE: Retrieve graph schema & execute Cypher query
    end
    CR-->>SM: Return query context/result
    SM-->>SV: Return search result
    SV-->>U: Display result
Loading

Possibly related issues

Possibly related PRs

Suggested labels

run-checks

Suggested reviewers

  • borisarzentar
  • lxobr

Poem

In the code fields I hop with glee,
New Cypher paths blossom for all to see.
A search so keen, a query so bright,
Carrots and code in delightful flight.
From bunny to bytes, we celebrate the night!
🐇✨

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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.

@gitguardian
Copy link

gitguardian bot commented Mar 18, 2025

️✅ There are no secrets present in this pull request anymore.

If these secrets were true positive and are still valid, we highly recommend you to revoke them.
While these secrets were previously flagged, we no longer have a reference to the
specific commits where they were detected. Once a secret has been leaked into a git
repository, you should consider it compromised, even if it was deleted immediately.
Find here more information about risks.


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@dm1tryG
Copy link
Contributor Author

dm1tryG commented Mar 18, 2025

@hajdul88 Hey, I see that you added #648

I added same logic here 🤔

Text to cypher as well. How can we merge it? Can you check text 2 cypher logic?

@dm1tryG dm1tryG marked this pull request as ready for review March 18, 2025 19:54
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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 24e0805 and 06ffa5c.

📒 Files selected for processing (4)
  • cognee-frontend/src/ui/Partials/SearchView/SearchView.tsx (1 hunks)
  • cognee/modules/retrieval/cypher_query_retriever.py (1 hunks)
  • cognee/modules/search/methods/search.py (2 hunks)
  • cognee/modules/search/types/SearchType.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
cognee/modules/retrieval/cypher_query_retriever.py

36-43: f-string without any placeholders

Remove extraneous f prefix

(F541)

🪛 GitHub Actions: lint | ruff lint
cognee/modules/retrieval/cypher_query_retriever.py

[error] 36-36: Ruff: F541 - f-string without any placeholders. Remove extraneous f prefix.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: windows-latest
  • GitHub Check: run_simple_example_test
🔇 Additional comments (7)
cognee/modules/search/types/SearchType.py (1)

12-12: Add new enum entry for CYPHER_QUERY

This addition nicely expands the search functionality.

cognee-frontend/src/ui/Partials/SearchView/SearchView.tsx (1)

39-41: New 'Cypher prompting' search option

Great job adding this to the dropdown list, ensuring consistency with the existing search types.

cognee/modules/search/methods/search.py (2)

15-15: Import for CypherQueryRetriever

Importing the new retriever aligns with the existing retrieval modules and is clearly placed.


69-69: Extended the search_tasks mapping

Properly incorporates SearchType.CYPHER_QUERY with the new retriever. This addition looks correct.

cognee/modules/retrieval/cypher_query_retriever.py (3)

1-16: Class definition and constructor

Creating a maximum attempt count and initializing the LLM client in the constructor is well-structured.


17-32: Gathering node and edge schemas

Fetching the graph schema before generating queries ensures a context-aware approach. Nicely done.


73-78: get_completion method

Delegating context retrieval to get_context if not already provided is straightforward and aligns well with the retriever pattern.

previous_attempt_context = None
for attempt in range(self.max_attempts):
llm_client = get_llm_client()
system_prompt = f"""
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Extraneous f-string prefix

No placeholders are used in this multiline string. Removing the f prefix resolves the lint error.

-            system_prompt = f"""
+            system_prompt = """
📝 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
system_prompt = f"""
system_prompt = """
🧰 Tools
🪛 Ruff (0.8.2)

36-43: f-string without any placeholders

Remove extraneous f prefix

(F541)

🪛 GitHub Actions: lint | ruff lint

[error] 36-36: Ruff: F541 - f-string without any placeholders. Remove extraneous f prefix.

Comment on lines +33 to +72
previous_attempt_context = None
for attempt in range(self.max_attempts):
llm_client = get_llm_client()
system_prompt = f"""
You are an advanced Cypher query generator for Neo4j. Your task:
- Based on the following graph schema (nodes and edges) and a natural language query, generate a valid Cypher query that retrieves the requested information.
- Provide only the Cypher query, no explanations or additional formatting.
- Take into account the previous failed attempts and adjust the query accordingly.

Return only a valid, optimized Cypher query.
"""

cypher_query = await llm_client.acreate_structured_output(
text_input=f"""
User query:
{query}

Node schema (labels and properties):
{node_schemas}

Edge schema (relationship properties):
{edge_schemas}

Previous attempts:
{previous_attempt_context}
""",
system_prompt=system_prompt,
response_model=str,
)
try:
context = await graph_engine.query(cypher_query)
if context:
return context
else:
previous_attempt_context += f"Query: {cypher_query} -> Result: None\n"
continue
except Exception as e:
previous_attempt_context += f"Query: {cypher_query} -> Executed with error: {e}\n"
return None

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Multiple attempts loop

previous_attempt_context is initialized to None, but string concatenation on the first attempt can cause an error. Please initialize it as an empty string or handle it conditionally.

-        previous_attempt_context = None
+        previous_attempt_context = ""
📝 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
previous_attempt_context = None
for attempt in range(self.max_attempts):
llm_client = get_llm_client()
system_prompt = f"""
You are an advanced Cypher query generator for Neo4j. Your task:
- Based on the following graph schema (nodes and edges) and a natural language query, generate a valid Cypher query that retrieves the requested information.
- Provide only the Cypher query, no explanations or additional formatting.
- Take into account the previous failed attempts and adjust the query accordingly.
Return only a valid, optimized Cypher query.
"""
cypher_query = await llm_client.acreate_structured_output(
text_input=f"""
User query:
{query}
Node schema (labels and properties):
{node_schemas}
Edge schema (relationship properties):
{edge_schemas}
Previous attempts:
{previous_attempt_context}
""",
system_prompt=system_prompt,
response_model=str,
)
try:
context = await graph_engine.query(cypher_query)
if context:
return context
else:
previous_attempt_context += f"Query: {cypher_query} -> Result: None\n"
continue
except Exception as e:
previous_attempt_context += f"Query: {cypher_query} -> Executed with error: {e}\n"
return None
previous_attempt_context = ""
for attempt in range(self.max_attempts):
llm_client = get_llm_client()
system_prompt = f"""
You are an advanced Cypher query generator for Neo4j. Your task:
- Based on the following graph schema (nodes and edges) and a natural language query, generate a valid Cypher query that retrieves the requested information.
- Provide only the Cypher query, no explanations or additional formatting.
- Take into account the previous failed attempts and adjust the query accordingly.
Return only a valid, optimized Cypher query.
"""
cypher_query = await llm_client.acreate_structured_output(
text_input=f"""
User query:
{query}
Node schema (labels and properties):
{node_schemas}
Edge schema (relationship properties):
{edge_schemas}
Previous attempts:
{previous_attempt_context}
""",
system_prompt=system_prompt,
response_model=str,
)
try:
context = await graph_engine.query(cypher_query)
if context:
return context
else:
previous_attempt_context += f"Query: {cypher_query} -> Result: None\n"
continue
except Exception as e:
previous_attempt_context += f"Query: {cypher_query} -> Executed with error: {e}\n"
return None
🧰 Tools
🪛 Ruff (0.8.2)

36-43: f-string without any placeholders

Remove extraneous f prefix

(F541)

🪛 GitHub Actions: lint | ruff lint

[error] 36-36: Ruff: F541 - f-string without any placeholders. Remove extraneous f prefix.

@dm1tryG dm1tryG changed the title Text2cypher feat: Text to Cypher Retriever Mar 18, 2025
@hajdul88
Copy link
Collaborator

@hajdul88 Hey, I see that you added #648

I added same logic here 🤔

Text to cypher as well. How can we merge it? Can you check text 2 cypher logic?

I will talk to @borisarzentar about this. I think it's slightly different. In my PR, it's about exposing the cypher search parameter of the DB adapter, so the query is ultimately just a cypher query, not a natural language query.

Text to cypher means the user is forming a natural language query and you have to create a corresponding cypher right?

@borisarzentar
Copy link
Contributor

borisarzentar commented Mar 21, 2025

@hajdul88 Hey, I see that you added #648
I added same logic here 🤔
Text to cypher as well. How can we merge it? Can you check text 2 cypher logic?

I will talk to @borisarzentar about this. I think it's slightly different. In my PR, it's about exposing the cypher search parameter of the DB adapter, so the query is ultimately just a cypher query, not a natural language query.

Text to cypher means the user is forming a natural language query and you have to create a corresponding cypher right?

@hajdul88 @dm1tryG Yes, this one is different from the one we implemented last week. I would name it differently, so we know that it is a natural language search. Cypher is the implementation detail, right? Users don't care what happens behind the scene, they just send the natural language query and get results.

@dm1tryG
Copy link
Contributor Author

dm1tryG commented Mar 24, 2025

@borisarzentar @hajdul88 I will rename the retriever, maybe good idea to inherit from new cypher retriever from #648 will check

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