| 1 | from graphrag_sdk.steps.Step import Step |
| 2 | from graphrag_sdk.ontology import Ontology |
| 3 | from graphrag_sdk.models import ( |
| 4 | GenerativeModelChatSession, |
| 5 | ) |
| 6 | from graphrag_sdk.fixtures.prompts import ( |
| 7 | CYPHER_GEN_SYSTEM, |
| 8 | CYPHER_GEN_PROMPT, |
| 9 | CYPHER_GEN_PROMPT_WITH_ERROR, |
| 10 | ) |
| 11 | import logging |
| 12 | from graphrag_sdk.helpers import ( |
| 13 | extract_cypher, |
| 14 | validate_cypher, |
| 15 | stringify_falkordb_response, |
| 16 | ) |
| 17 | from falkordb import Graph |
| 18 | |
| 19 | logger = logging.getLogger(__name__) |
| 20 | logger.setLevel(logging.DEBUG) |
| 21 | |
| 22 | |
| 23 | class GraphQueryGenerationStep(Step): |
| 24 | """ |
| 25 | Graph Query Step |
| 26 | """ |
| 27 | |
| 28 | def __init__( |
| 29 | self, |
| 30 | graph: Graph, |
| 31 | ontology: Ontology, |
| 32 | chat_session: GenerativeModelChatSession, |
| 33 | config: dict = None, |
| 34 | ) -> None: |
| 35 | self.ontology = ontology |
| 36 | self.config = config or {} |
| 37 | self.graph = graph |
| 38 | self.chat_session = chat_session |
| 39 | |
| 40 | def run(self, question: str, retries: int = 5): |
| 41 | error = False |
| 42 | |
| 43 | cypher = "" |
| 44 | while error is not None and retries > 0: |
| 45 | try: |
| 46 | cypher_prompt = ( |
| 47 | CYPHER_GEN_PROMPT.format(question=question) |
| 48 | if error is False |
| 49 | else CYPHER_GEN_PROMPT_WITH_ERROR.format( |
| 50 | question=question, error=error |
| 51 | ) |
| 52 | ) |
| 53 | logger.debug(f"Cypher Prompt: {cypher_prompt}") |
| 54 | cypher_statement_response = self.chat_session.send_message( |
| 55 | cypher_prompt, |
| 56 | ) |
| 57 | logger.debug(f"Cypher Statement Response: {cypher_statement_response}") |
| 58 | cypher = extract_cypher(cypher_statement_response.text) |
| 59 | logger.debug(f"Cypher: {cypher}") |
| 60 | |
| 61 | if not cypher or len(cypher) == 0: |
| 62 | return (None, None) |
| 63 | |
| 64 | validation_errors = validate_cypher(cypher, self.ontology) |
| 65 | # print(f"Is valid: {is_valid}") |
| 66 | if validation_errors is not None: |
| 67 | raise Exception("\n".join(validation_errors)) |
| 68 | |
| 69 | if cypher is not None: |
| 70 | result_set = self.graph.query(cypher).result_set |
| 71 | context = stringify_falkordb_response(result_set) |
| 72 | logger.debug(f"Context: {context}") |
| 73 | logger.debug(f"Context size: {len(result_set)}") |
| 74 | logger.debug(f"Context characters: {len(str(context))}") |
| 75 | |
| 76 | return (context, cypher) |
| 77 | except Exception as e: |
| 78 | logger.debug(f"Error: {e}") |
| 79 | error = e |
| 80 | retries -= 1 |
| 81 | |
| 82 | raise Exception("Failed to generate Cypher query: " + str(error)) |