Skip to content

Instantly share code, notes, and snippets.

@MuddyBootsCode
Created October 26, 2023 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MuddyBootsCode/c746e172d71b9a0f9a954cc116d81859 to your computer and use it in GitHub Desktop.
Save MuddyBootsCode/c746e172d71b9a0f9a954cc116d81859 to your computer and use it in GitHub Desktop.
GraphAI
from langchain.chat_models import ChatOpenAI, ChatOllama
from langchain.chains import GraphCypherQAChain
from langchain.graphs import Neo4jGraph
from langchain.prompts.prompt import PromptTemplate
import os
os.environ["OPENAI_API_KEY"] = ""
graph = Neo4jGraph(
url="bolt://localhost:7687", username="neo4j", password="newpassword"
)
CYPHER_GENERATION_TEMPLATE = """Task:Generate Cypher statement to query a graph database.
Instructions:
Use only the provided relationship types and properties in the schema.
Do not use any other relationship types or properties that are not provided.
Schema:
{schema}
Note: Do not include any explanations or apologies in your responses.
Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.
Do not include any text except the generated Cypher statement.
Examples: Here are a few examples of generated Cypher statements for particular questions:
# What are the different tool categories?
MATCH (:Tool)-[:HAS_CATEGORY]->(c:Category)
RETURN DISTINCT c.name
# Who are people that Tina knows?
MATCH (p:Person)-[:KNOWS]->(n:Person)
RETURN n.name
# Who are people that Tina knows that don't know each other?
MATCH (p:Person)-[:KNOWS]->(person1:Person)
MATCH (p)-[:KNOWS]->(person2:Person)
WHERE person1 < person2 AND NOT (person1)-[:KNOWS]->(person2) AND NOT (person2)-[:KNOWS]->(person1)
RETURN person1.name, person2.name
The question is:
{question}"""
graph.refresh_schema()
CYPHER_GENERATION_PROMPT = PromptTemplate(
input_variables=["schema", "question"], template=CYPHER_GENERATION_TEMPLATE
)
chain = GraphCypherQAChain.from_llm(
ChatOpenAI(temperature=0), graph=graph, verbose=True, cypher_prompt=CYPHER_GENERATION_PROMPT
# ChatOllama(
# temperature=0,
# streaming=True,
# top_k=10,
# top_p=0.3,
# num_ctx=3072
# ),
# graph=graph,
# verbose=True,
# cypher_prompt=CYPHER_GENERATION_PROMPT
)
# result = chain('Who are people that Tina knows that dont know each other?')
# result = chain('Who are Tinas friends?')
result = chain('Who people that Tina knows?')
print(result['result'])
print(graph.schema)
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
# if __name__ == '__main__':
# print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment