2023-10-27 02:44:30 +00:00
|
|
|
from typing import List, Optional
|
|
|
|
|
2024-01-02 21:47:11 +00:00
|
|
|
from langchain_community.graphs import Neo4jGraph
|
2024-02-22 23:58:44 +00:00
|
|
|
from langchain_core.documents import Document
|
2024-03-14 23:00:42 +00:00
|
|
|
from langchain_experimental.graph_transformers import LLMGraphTransformer
|
|
|
|
from langchain_openai import ChatOpenAI
|
2023-10-26 01:47:42 +00:00
|
|
|
|
|
|
|
graph = Neo4jGraph()
|
|
|
|
|
|
|
|
|
|
|
|
llm = ChatOpenAI(model="gpt-3.5-turbo-16k", temperature=0)
|
|
|
|
|
|
|
|
|
|
|
|
def chain(
|
|
|
|
text: str,
|
|
|
|
allowed_nodes: Optional[List[str]] = None,
|
|
|
|
allowed_relationships: Optional[List[str]] = None,
|
|
|
|
) -> str:
|
|
|
|
"""
|
|
|
|
Process the given text to extract graph data and constructs a graph document from the extracted information.
|
|
|
|
The constructed graph document is then added to the graph.
|
|
|
|
|
|
|
|
Parameters:
|
|
|
|
- text (str): The input text from which the information will be extracted to construct the graph.
|
|
|
|
- allowed_nodes (Optional[List[str]]): A list of node labels to guide the extraction process.
|
|
|
|
If not provided, extraction won't have specific restriction on node labels.
|
|
|
|
- allowed_relationships (Optional[List[str]]): A list of relationship types to guide the extraction process.
|
|
|
|
If not provided, extraction won't have specific restriction on relationship types.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: A confirmation message indicating the completion of the graph construction.
|
2023-10-27 02:44:30 +00:00
|
|
|
""" # noqa: E501
|
2024-03-14 23:00:42 +00:00
|
|
|
# Construct document based on text
|
|
|
|
documents = [Document(page_content=text)]
|
2023-10-26 01:47:42 +00:00
|
|
|
# Extract graph data using OpenAI functions
|
2024-03-14 23:00:42 +00:00
|
|
|
llm_graph_transformer = LLMGraphTransformer(
|
|
|
|
llm=llm,
|
|
|
|
allowed_nodes=allowed_nodes,
|
|
|
|
allowed_relationships=allowed_relationships,
|
2023-10-26 01:47:42 +00:00
|
|
|
)
|
2024-03-14 23:00:42 +00:00
|
|
|
graph_documents = llm_graph_transformer.convert_to_graph_documents(documents)
|
2023-10-26 01:47:42 +00:00
|
|
|
# Store information into a graph
|
2024-03-14 23:00:42 +00:00
|
|
|
graph.add_graph_documents(graph_documents)
|
2023-10-26 01:47:42 +00:00
|
|
|
return "Graph construction finished"
|