diff options
Diffstat (limited to 'R2R/r2r/prompts')
-rwxr-xr-x | R2R/r2r/prompts/__init__.py | 3 | ||||
-rwxr-xr-x | R2R/r2r/prompts/local/__init__.py | 0 | ||||
-rwxr-xr-x | R2R/r2r/prompts/local/defaults.jsonl | 12 | ||||
-rwxr-xr-x | R2R/r2r/prompts/local/r2r_prompt_provider.py | 69 |
4 files changed, 84 insertions, 0 deletions
diff --git a/R2R/r2r/prompts/__init__.py b/R2R/r2r/prompts/__init__.py new file mode 100755 index 00000000..88ed0658 --- /dev/null +++ b/R2R/r2r/prompts/__init__.py @@ -0,0 +1,3 @@ +from .local.r2r_prompt_provider import R2RPromptProvider + +__all__ = ["R2RPromptProvider"] diff --git a/R2R/r2r/prompts/local/__init__.py b/R2R/r2r/prompts/local/__init__.py new file mode 100755 index 00000000..e69de29b --- /dev/null +++ b/R2R/r2r/prompts/local/__init__.py diff --git a/R2R/r2r/prompts/local/defaults.jsonl b/R2R/r2r/prompts/local/defaults.jsonl new file mode 100755 index 00000000..042136f6 --- /dev/null +++ b/R2R/r2r/prompts/local/defaults.jsonl @@ -0,0 +1,12 @@ +{"name": "default_system", "template": "You are a helpful assistant.", "input_types": {}} +{"name": "default_rag", "template": "## Task:\n\nAnswer the query given immediately below given the context which follows later. Use line item references to like [1], [2], ... refer to specifically numbered items in the provided context. Pay close attention to the title of each given source to ensure it is consistent with the query.\n\n### Query:\n{query}\n\n### Context:\n{context}\n\n### Query:\n{query}\n\nREMINDER - Use line item references to like [1], [2], ... refer to specifically numbered items in the provided context.\n## Response:\n", "input_types": {"query": "str", "context": "str"}} +{"name": "hyde", "template": "### Instruction:\n\nGiven the query that follows write a double newline separated list of {num_outputs} single paragraph distinct attempted answers to the given query. \nDO NOT generate any single answer which is likely to require information from multiple distinct documents, \nEACH single answer will be used to carry out a cosine similarity semantic search over distinct indexed documents, such as varied medical documents. \nFOR EXAMPLE if asked `how do the key themes of Great Gatsby compare with 1984`, the two attempted answers would be \n`The key themes of Great Gatsby are ... ANSWER_CONTINUED` and `The key themes of 1984 are ... ANSWER_CONTINUED`, where `ANSWER_CONTINUED` IS TO BE COMPLETED BY YOU in your response. \nHere is the original user query to be transformed into answers:\n\n### Query:\n{message}\n\n### Response:\n", "input_types": {"num_outputs": "int", "message": "str"}} +{"name": "rag_fusion_prompt", "template": "### Instruction:\n\nGiven the following query that follows to write a double newline separated list of up to {num_outputs} queries meant to help answer the original query. \nDO NOT generate any single query which is likely to require information from multiple distinct documents, \nEACH single query will be used to carry out a cosine similarity semantic search over distinct indexed documents, such as varied medical documents. \nFOR EXAMPLE if asked `how do the key themes of Great Gatsby compare with 1984`, the two queries would be \n`What are the key themes of Great Gatsby?` and `What are the key themes of 1984?`.\nHere is the original user query to be transformed into answers:\n\n### Query:\n{message}\n\n### Response:\n", "input_types": {"num_outputs": "int", "message": "str"}} +{"name": "rag_answer_eval", "template": "### Instruction:\n\nYou are given a `query`, related `context` and an associated `answer`. Your task is to sequentially score each sentence in the given answer as either 1 or 0, based on whether or not the given sentence is relevant to the given query and supported in full by the given context.\n### Example:\n#### Input:\n\nQuery:\nWhy does Alice prefer spending her mornings in the garden?\n\nContext:\nAlice loves to read books in her garden. She has a large collection of mystery novels. Every morning, she spends an hour reading while drinking her favorite tea. Her garden is filled with various flowers, and she especially loves the roses. On weekends, Alice's friend, Bob, often joins her for tea and they discuss the books they've read.\n\nAnswer:\nAlice enjoys her mornings in the garden because she loves to read there. She often listens to music while reading.\n####### Response:\n\n([1,0], '1/2')### Input:\nQuery:\n{query}\n\nContext:\n{context}\n\nAnswer:\n{answer}\n\nResponse:\n\n", "input_types": {"query": "str", "context": "str", "answer": "str"}} +{"name": "rag_context_eval", "template": "### Instruction:\n\nYou are given a `query` and an associated `context`. Your task is to sequentially score each sentence in the context as either 1 or 0, based on the relevancy to the given query. For instance, if the query is \"What is the capital of France?\" then the sentence \"The capital of France is Paris\" would receive a +1 value, whereas \"The french enjoy wine\" would receive a 0. Return your response as a tuple containing a list of 1s and 0s, where each value corresponds to the respective sentence in the context, and then the rational fraction of 1's to the total number of sentences (e.g. '1/4'). NOTE - do not include ANY extra text other than the requested tuple.\n\nQuery:\n{query}\n\nContext:\n{context}\n\n###Response\n\n", "input_types": {"query": "str", "context": "str"}} +{"name": "few_shot_ner_kg_extraction", "template": "### Instruction\nYou will shortly be asked to perform Named Entity Recognition (NER) and knowledge graph triplet extraction on the text that follows. NER involves identifying named entities in a text, and knowledge graph triplet extraction involves identifying relationships between these entities and other attributes in the text.\n\nA knowledge graph triplet contains the three following pieces of information:\n- `subject`: The main entity.\n- `predicate`: The relationship type.\n- `object`: The related entity.\n\nThey are represented below as `[subject]:<predicate>:[object]`.\n\n#### Process \n**Identify Named Entities**: Extract entities based on the given entity types, ensuring they appear in the order they are mentioned in the text.\n**Establish Triplets**: Form triplets using the provided predicates, again in the order they appear in the text.\n\nYour final response should follow this format:\n\n**Output:**\n```json\n{{\n \"entities_and_triples\": [\n \"[1], entity_type:entity_name\",\n \"[1] predicate [2]\",\n \"[1] predicate [3]\",\n \"[2], entity_type:entity_name\",\n ...\n ]\n}}\n```\n\n### Example:\n\n**Entity Types:**\nORGANIZATION\nCOMPANY\nCITY\nSTATE\nCOUNTRY\nOTHER\nPERSON\nYEAR\nMONTH\nDAY\nOTHER\nQUANTITY\nEVENT\n\n**Predicates:**\nFOUNDED_BY\nHEADQUARTERED_IN\nOPERATES_IN\nOWNED_BY\nACQUIRED_BY\nHAS_EMPLOYEE_COUNT\nGENERATED_REVENUE\nLISTED_ON\nINCORPORATED\nHAS_DIVISION\nALIAS\nANNOUNCED\nHAS_QUANTITY\nAS_OF\n\n**Input:**\nWalmart Inc. (formerly Wal-Mart Stores, Inc.) is an American multinational retail corporation that operates a chain of hypermarkets (also called supercenters), discount department stores, and grocery stores in the United States, headquartered in Bentonville, Arkansas.[10] The company was founded by brothers Sam and James \"Bud\" Walton in nearby Rogers, Arkansas in 1962 and incorporated under Delaware General Corporation Law on October 31, 1969. It also owns and operates Sam's Club retail warehouses.[11][12]\n\nAs of October 31, 2022, Walmart has 10,586 stores and clubs in 24 countries, operating under 46 different names.[2][3][4] The company operates under the name Walmart in the United States and Canada, as Walmart de M\u00e9xico y Centroam\u00e9rica in Mexico and Central America, and as Flipkart Wholesale in India.\n\n**Output:**\n```json\n{{\n \"entities_and_triples\": [\n \"[1], company:Walmart Inc.\",\n \"[2], company:Wal-Mart Stores, Inc.\",\n \"[1] ALIAS [2]\",\n \"[3], location:country:United States\",\n \"[1] OPERATES_IN [3]\",\n \"[4], location:city:Bentonville\",\n \"[1] HEADQUARTERED_IN [4]\",\n \"[5], location:state:Arkansas\",\n \"[1] HEADQUARTERED_IN [5]\",\n \"[6], person:Sam Walton\",\n \"[1] FOUNDED_BY [6]\",\n \"[7], person:James Walton\",\n \"[8], person:Bud Walton\",\n \"[7] ALIAS [8]\",\n \"[1] FOUNDED_BY [7]\",\n \"[9], location:city:Rogers\",\n \"[10], date:year:1962\",\n \"[11], event:incorporated under Delaware General Corporation Law\",\n \"[1] INCORPORATED [11]\",\n \"[12], date:day:October 31\",\n \"[1] INCORPORATED [12]\",\n \"[13], date:year:1969\",\n \"[1] INCORPORATED [13]\",\n \"[14], company:Sam's Club\",\n \"[1] INCORPORATED [14]\",\n \"[15], date:day:October 31, 2022\",\n \"[16], quantity:10,586 stores and clubs\",\n \"[16] AS_OF [15]\",\n \"[1] HAS_QUANTITY [16]\",\n \"[17], quantity:24 countries\",\n \"[18], quantity:46 different names\",\n \"[1] HAS_QUANTITY [18]\",\n \"[18], organization:company:Walmart de M\u00e9xico y Centroam\u00e9rica\",\n \"[1] ALIAS [18]\",\n \"[19], location:country:Mexico\",\n \"[1] OPERATES_IN [19]\",\n \"[20], location:region:Central America\",\n \"[1] OPERATES_IN [20]\",\n \"[21], organization:company:Flipkart Wholesale\",\n \"[1] ALIAS [21]\",\n \"[22], location:country:India\",\n \"[1] OPERATES_IN [22]\"\n ]\n}}\n```\n\n### Task:\nYour task is to perform Named Entity Recognition (NER) and knowledge graph triplet extraction on the text that follows below.\n\n**Input:**\n{input}\n\n**Output:**\n","input_types": {"input" : "str"}} +{"name": "few_shot_ner_kg_extraction_with_spec", "template": "### Instruction\nYou will shortly be asked to perform Named Entity Recognition (NER) and knowledge graph triplet extraction on the text that follows. NER involves identifying named entities in a text, and knowledge graph triplet extraction involves identifying relationships between these entities and other attributes in the text.\n\nA knowledge graph triplet contains the three following pieces of information:\n- `subject`: The main entity.\n- `predicate`: The relationship type.\n- `object`: The related entity.\n\nThey are represented below as `[subject]:<predicate>:[object]`.\n\n#### Process \n**Identify Named Entities**: Extract entities based on the given entity types, ensuring they appear in the order they are mentioned in the text.\n**Establish Triplets**: Form triplets using the provided predicates, again in the order they appear in the text.\n\nYour final response should follow this format:\n\n**Output:**\n```json\n{{\n \"entities_and_triples\": [\n \"[1], ENTITY_TYPE:ENTITY_NAME\",\n \"[1] PREDICATE [2]\",\n \"[1] PREDICATE [3]\",\n \"[2], ENTITY_TYPE:ENTITY_NAME\",\n ...\n ]\n}}\n```\n\n### Example:\n\n**Entity Types:**\nORGANIZATION\nCOMPANY\nCITY, STATE, COUNTRY, OTHER\nPERSON\nYEAR, MONTH, DAY, OTHER\nQUANTITY\nEVENT\n\n**Predicates:**\nFOUNDED_BY\nHEADQUARTERED_IN\nOPERATES_IN\nOWNED_BY\nACQUIRED_BY\nHAS_EMPLOYEE_COUNT\nGENERATED_REVENUE\nLISTED_ON\nINCORPORATED\nHAS_DIVISION\nALIAS\nANNOUNCED\nHAS_QUANTITY\nAS_OF\n\n**Input:**\nWalmart Inc. (formerly Wal-Mart Stores, Inc.) is an American multinational retail corporation that operates a chain of hypermarkets (also called supercenters), discount department stores, and grocery stores in the United States, headquartered in Bentonville, Arkansas.[10] The company was founded by brothers Sam and James \"Bud\" Walton in nearby Rogers, Arkansas in 1962 and incorporated under Delaware General Corporation Law on October 31, 1969. It also owns and operates Sam's Club retail warehouses.[11][12]\n\nAs of October 31, 2022, Walmart has 10,586 stores and clubs in 24 countries, operating under 46 different names.[2][3][4] The company operates under the name Walmart in the United States and Canada, as Walmart de M\u00e9xico y Centroam\u00e9rica in Mexico and Central America, and as Flipkart Wholesale in India.\n\n**Output:**\n```json\n{{\n \"entities_and_triples\": [\n \"[1], ORGANIZATION:COMPANY:Walmart Inc.\",\n \"[2], ORGANIZATION:COMPANY:Wal-Mart Stores, Inc.\",\n \"[1] ALIAS [2]\",\n \"[3], LOCATION:COUNTRY:United States\",\n \"[1] OPERATES_IN [3]\",\n \"[4], LOCATION:CITY:Bentonville\",\n \"[1] HEADQUARTERED_IN [4]\",\n \"[5], LOCATION:STATE:Arkansas\",\n \"[1] HEADQUARTERED_IN [5]\",\n \"[6], PERSON:Sam Walton\",\n \"[1] FOUNDED_BY [6]\",\n \"[7], PERSON:James Walton\",\n \"[8], PERSON:Bud Walton\",\n \"[7] ALIAS [8]\",\n \"[1] FOUNDED_BY [7]\",\n \"[9], LOCATION:CITY:Rogers\",\n \"[10], DATE:YEAR:1962\",\n \"[11], EVENT:Incorporated under Delaware General Corporation Law\",\n \"[1] INCORPORATED [11]\",\n \"[12], DATE:DAY:October 31\",\n \"[1] INCORPORATED [12]\",\n \"[13], DATE:YEAR:1969\",\n \"[1] INCORPORATED [13]\",\n \"[14], ORGANIZATION:COMPANY:Sam's Club\",\n \"[1] INCORPORATED [14]\",\n \"[15], DATE:DAY:October 31, 2022\",\n \"[16], QUANTITY:10,586 stores and clubs\",\n \"[16] AS_OF [15]\",\n \"[1] HAS_QUANTITY [16]\",\n \"[17], QUANTITY:24 countries\",\n \"[18], QUANTITY:46 different names\",\n \"[1] HAS_QUANTITY [18]\",\n \"[18], ORGANIZATION:COMPANY:Walmart de M\u00e9xico y Centroam\u00e9rica\",\n \"[1] ALIAS [18]\",\n \"[19], LOCATION:COUNTRY:Mexico\",\n \"[1] OPERATES_IN [19]\",\n \"[20], LOCATION:REGION:Central America\",\n \"[1] OPERATES_IN [20]\",\n \"[21], ORGANIZATION:COMPANY:Flipkart Wholesale\",\n \"[1] ALIAS [21]\",\n \"[22], LOCATION:COUNTRY:India\",\n \"[1] OPERATES_IN [22]\"\n ]\n}}\n```\n\n### Task:\nYour task is to perform Named Entity Recognition (NER) and knowledge graph triplet extraction on the text that follows below. Use the provided entities and predicates as shown\n\n**Entity Types:**\n{entity_types}\n\n**Predicates:**\n{relations}\n\n**Input:**\n{input}\n\n**Output:**\n", "input_types": {"entity_types": "str", "relations": "str", "input" : "str"}} +{"name": "zero_shot_ner_kg_extraction", "template": "Perform Named Entity Recognition (NER) and extract knowledge graph triplets from the text. NER identifies named entities of given entity types, and triple extraction identifies relationships between entities using specified predicates.\n\n**Entity Types**:\n\n[\"PERSON\", \"ORGANIZATION\", \"LOCATION\", \"DATE\", \"TIME\", \"MONEY\", \"PERCENTAGE\", \"PRODUCT\", \"EVENT\", \"LANGUAGE\", \"NATIONALITY\", \"RELIGION\", \"TITLE\", \"PROFESSION\", \"ANIMAL\", \"PLANT\", \"DISEASE\", \"MEDICATION\", \"CHEMICAL\", \"MATERIAL\", \"COLOR\", \"SHAPE\", \"MEASUREMENT\", \"WEATHER\", \"NATURAL_DISASTER\", \"AWARD\", \"LAW\", \"CRIME\", \"TECHNOLOGY\", \"SOFTWARE\", \"HARDWARE\", \"VEHICLE\", \"FOOD\", \"DRINK\", \"SPORT\", \"MUSIC_GENRE\", \"INSTRUMENT\", \"ARTWORK\", \"BOOK\", \"MOVIE\", \"TV_SHOW\", \"ACADEMIC_SUBJECT\", \"SCIENTIFIC_THEORY\", \"POLITICAL_PARTY\", \"CURRENCY\", \"STOCK_SYMBOL\", \"FILE_TYPE\", \"PROGRAMMING_LANGUAGE\", \"MEDICAL_PROCEDURE\", \"CELESTIAL_BODY\"]\n\n**Predicates**\n[\"IS_EMPLOYED_BY\", \"LIVES_IN\", \"BORN_IN\", \"DIED_IN\", \"FOUNDED\", \"INVENTED\", \"WROTE\", \"DIRECTED\", \"STARRED_IN\", \"MARRIED_TO\", \"PARENT_OF\", \"CHILD_OF\", \"SIBLING_OF\", \"MEMBER_OF\", \"OWNER_OF\", \"CEO_OF\", \"STUDIED_AT\", \"GRADUATED_FROM\", \"TEACHES_AT\", \"SPEAKS\", \"CAPITAL_OF\", \"LOCATED_IN\", \"PART_OF\", \"CONTAINS\", \"PRODUCES\", \"CONSUMES\", \"EXPORTS\", \"IMPORTS\", \"ALLIES_WITH\", \"CONFLICTS_WITH\", \"PREDECESSOR_OF\", \"SUCCESSOR_OF\", \"DISCOVERED\", \"DEVELOPED\", \"FUNDED_BY\", \"INVESTED_IN\", \"COLLABORATES_WITH\", \"COMPETES_WITH\", \"ACQUIRED\", \"MERGED_WITH\", \"SPECIALIZES_IN\", \"PERFORMS\", \"AFFECTS\", \"CAUSES\", \"PREVENTS\", \"TREATS\", \"SYMPTOMS_OF\", \"BELONGS_TO\", \"DERIVED_FROM\", \"MEASURED_IN\"]\n\n**Text**{input}", "input_types": {"input" : "str"}} +{"name": "zero_shot_ner_kg_extraction_with_spec", "template": "Perform Named Entity Recognition (NER) and extract knowledge graph triplets from the text. NER identifies named entities of given entity types, and triple extraction identifies relationships between entities using specified predicates.\n\n**Entity Types**\n{entity_types}\n\n**Predicates**\n{relations}\n\n**Text**{input}", "input_types": {"entity_types": "str", "relations": "str", "input" : "str"}} +{"name": "kg_agent", "template": "**System Message:**\n\nYou are an AI assistant capable of generating Cypher queries to interact with a Neo4j knowledge graph. The knowledge graph contains information about organizations, people, locations, and their relationships, such as founders of companies, locations of companies, and products associated with companies.\n\n**Instructions:**\n\nWhen a user asks a question, you will generate a Cypher query to retrieve the relevant information from the Neo4j knowledge graph. Later, you will be given a schema which specifies the available relationships to help you construct the query. First, review the examples provided to understand the expected format of the queries.\n\n### Example(s) - User Questions and Cypher Queries for an Academic Knowledge Graph\n\n**User Question:**\n\"List all courses available in the computer science department.\"\n\n**Generated Cypher Query:**\n```cypher\nMATCH (c:COURSE)-[:OFFERED_BY]->(d:DEPARTMENT)\nWHERE d.name CONTAINS 'Computer Science'\nRETURN c.id AS Course, d.name AS Department\nORDER BY c.id;\n```\n\n**User Question:**\n\"Retrieve all courses taught by professors who have published research on natural language processing.\"\n\n**Generated Cypher Query:**\n```cypher\nMATCH (pr:PERSON)-[:PUBLISHED]->(p:PAPER)\nMATCH (p)-[:TOPIC]->(t:TOPIC)\nWHERE t.name CONTAINS 'Natural Language Processing'\nMATCH (c:COURSE)-[:TAUGHT_BY]->(pr)\nRETURN DISTINCT c.id AS Course, pr.name AS Professor, t.name AS Topic\nORDER BY c.id;\n```\n\n\n### Example(s) - User Questions and Cypher Queries for an Historical Events and Figures\n\n**User Question:**\n\"List all battles that occurred in the 19th century and the generals who participated in them.\"\n\n**Generated Cypher Query:**\n```cypher\nMATCH (b:EVENT)-[:HAPPENED_AT]->(d:DATE)\nWHERE d.year >= 1800 AND d.year < 1900 AND b.type CONTAINS 'Battle'\nMATCH (g:PERSON)-[:PARTICIPATED_IN]->(b)\nRETURN b.name AS Battle, d.year AS Year, g.name AS General\nORDER BY d.year, b.name, g.name;\n```\n\n**User Question:**\n\"Find all treaties signed in Paris and the countries involved.\"\n\n\n**Generated Cypher Query:**\n```cypher\nMATCH (t:EVENT)-[:HAPPENED_AT]->(l:LOCATION)\nWHERE l.name CONTAINS 'Paris' AND t.type CONTAINS 'Treaty'\nMATCH (c:ORGANIZATION)-[:SIGNED]->(t)\nRETURN t.name AS Treaty, l.name AS Location, c.name AS Country\nORDER BY t.name, c.name;\n```\n\n\nNow, you will be provided with a schema for the entities and relationships in the Neo4j knowledge graph. Use this schema to construct Cypher queries based on user questions.\n\n- **Entities:**\n - `ORGANIZATION` (e.g.: `COMPANY`, `SCHOOL`, `NON-PROFIT`, `OTHER`)\n - `COMPANY`\n - `LOCATION` (e.g.: `CITY`, `STATE`, `COUNTRY`, `OTHER`)\n - `DATE` (e.g.: `YEAR`, `MONTH`, `DAY`, `BATCH`, `OTHER`)\n - `QUANTITY`\n - `EVENT` (e.g.: `INCORPORATION`, `FUNDING_ROUND`, `ACQUISITION`, `LAUNCH`, `OTHER`)\n\n- **Relationships:**\n - `FOUNDED_BY`\n - `HEADQUARTERED_IN`\n - `OPERATES_IN`\n - `RAISED`\n - `ACQUIRED_BY`\n - `HAS_EMPLOYEE_COUNT`\n - `GENERATED_REVENUE`\n - `LISTED_ON`\n - `INCORPORATED`\n - `HAS_DIVISION`\n - `ANNOUNCED`\n - `HAS_QUANTITY`\n\nUse the referenced examples and schema to help you construct an appropriate Cypher query based on the following question:\n\n**User Question:**\n{input}\n\n**Generated Cypher Query:**\n", "input_types": {"input" : "str"}} +{"name": "kg_agent_with_spec", "template": "**System Message:**\n\nYou are an AI assistant capable of generating Cypher queries to interact with a Neo4j knowledge graph. The knowledge graph contains information about organizations, people, locations, and their relationships, such as founders of companies, locations of companies, and products associated with companies.\n\n**Instructions:**\n\nWhen a user asks a question, you will generate a Cypher query to retrieve the relevant information from the Neo4j knowledge graph. Later, you will be given a schema which specifies the available relationships to help you construct the query. First, review the examples provided to understand the expected format of the queries.\n\n### Example(s) - User Questions and Cypher Queries for an Academic Knowledge Graph\n\n**User Question:**\n\"List all courses available in the computer science department.\"\n\n**Generated Cypher Query:**\n```cypher\nMATCH (c:COURSE)-[:OFFERED_BY]->(d:DEPARTMENT)\nWHERE d.name CONTAINS 'Computer Science'\nRETURN c.id AS Course, d.name AS Department\nORDER BY c.id;\n```\n\n**User Question:**\n\"Retrieve all courses taught by professors who have published research on natural language processing.\"\n\n**Generated Cypher Query:**\n```cypher\nMATCH (pr:PERSON)-[:PUBLISHED]->(p:PAPER)\nMATCH (p)-[:TOPIC]->(t:TOPIC)\nWHERE t.name CONTAINS 'Natural Language Processing'\nMATCH (c:COURSE)-[:TAUGHT_BY]->(pr)\nRETURN DISTINCT c.id AS Course, pr.name AS Professor, t.name AS Topic\nORDER BY c.id;\n```\n\n\n### Example(s) - User Questions and Cypher Queries for an Historical Events and Figures\n\n**User Question:**\n\"List all battles that occurred in the 19th century and the generals who participated in them.\"\n\n**Generated Cypher Query:**\n```cypher\nMATCH (b:EVENT)-[:HAPPENED_AT]->(d:DATE)\nWHERE d.year >= 1800 AND d.year < 1900 AND b.type CONTAINS 'Battle'\nMATCH (g:PERSON)-[:PARTICIPATED_IN]->(b)\nRETURN b.name AS Battle, d.year AS Year, g.name AS General\nORDER BY d.year, b.name, g.name;\n```\n\n**User Question:**\n\"Find all treaties signed in Paris and the countries involved.\"\n\n\n**Generated Cypher Query:**\n```cypher\nMATCH (t:EVENT)-[:HAPPENED_AT]->(l:LOCATION)\nWHERE l.name CONTAINS 'Paris' AND t.type CONTAINS 'Treaty'\nMATCH (c:ORGANIZATION)-[:SIGNED]->(t)\nRETURN t.name AS Treaty, l.name AS Location, c.name AS Country\nORDER BY t.name, c.name;\n```\n\n\nNow, you will be provided with a schema for the entities and relationships in the Neo4j knowledge graph. Use this schema to construct Cypher queries based on user questions.\n\n- **Entities:**\n{entity_types}\n\n- **Relationships:**\n{relations}\n\nUse the referenced examples and schema to help you construct an appropriate Cypher query based on the following question:\n\n**User Question:**\n{input}\n\n**Generated Cypher Query:**\n", "input_types": {"entity_types": "str", "relations": "str", "input" : "str"}}
\ No newline at end of file diff --git a/R2R/r2r/prompts/local/r2r_prompt_provider.py b/R2R/r2r/prompts/local/r2r_prompt_provider.py new file mode 100755 index 00000000..830c4203 --- /dev/null +++ b/R2R/r2r/prompts/local/r2r_prompt_provider.py @@ -0,0 +1,69 @@ +import json +import logging +import os +from typing import Any, Optional + +from r2r.base import Prompt, PromptProvider + +logger = logging.getLogger(__name__) + + +class R2RPromptProvider(PromptProvider): + def __init__(self, file_path: Optional[str] = None): + self.prompts: dict[str, Prompt] = {} + self._load_prompts_from_jsonl(file_path=file_path) + + def _load_prompts_from_jsonl(self, file_path: Optional[str] = None): + if not file_path: + file_path = os.path.join( + os.path.dirname(__file__), "defaults.jsonl" + ) + try: + with open(file_path, "r") as file: + for line in file: + if line.strip(): + data = json.loads(line) + self.add_prompt( + data["name"], + data["template"], + data.get("input_types", {}), + ) + except json.JSONDecodeError as e: + error_msg = f"Error loading prompts from JSONL file: {e}" + logger.error(error_msg) + raise ValueError(error_msg) + + def add_prompt( + self, name: str, template: str, input_types: dict[str, str] + ) -> None: + if name in self.prompts: + raise ValueError(f"Prompt '{name}' already exists.") + self.prompts[name] = Prompt( + name=name, template=template, input_types=input_types + ) + + def get_prompt( + self, prompt_name: str, inputs: Optional[dict[str, Any]] = None + ) -> str: + if prompt_name not in self.prompts: + raise ValueError(f"Prompt '{prompt_name}' not found.") + prompt = self.prompts[prompt_name] + if inputs is None: + return prompt.template + return prompt.format_prompt(inputs) + + def update_prompt( + self, + name: str, + template: Optional[str] = None, + input_types: Optional[dict[str, str]] = None, + ) -> None: + if name not in self.prompts: + raise ValueError(f"Prompt '{name}' not found.") + if template: + self.prompts[name].template = template + if input_types: + self.prompts[name].input_types = input_types + + def get_all_prompts(self) -> dict[str, Prompt]: + return self.prompts |