├── src ├── __init__.py ├── neo4j_graph │ ├── __init__.py │ ├── utils.py │ ├── model.py │ ├── repository.py │ └── entity_graph.py ├── main.py ├── config.py ├── prompt.py ├── neo4j_langchain_bot.py └── memory.py ├── requirement.txt ├── .gitignore ├── .env.example ├── neo4j_db └── docker-compose.yml ├── scripts └── add_index_for_neo4j_db.py ├── README.md └── LICENSE /src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/neo4j_graph/__init__.py: -------------------------------------------------------------------------------- 1 | from .entity_graph import Neo4jEntityGraph -------------------------------------------------------------------------------- /requirement.txt: -------------------------------------------------------------------------------- 1 | python-dotenv==1.0.0 2 | openai==0.27.4 3 | langchain==0.0.180 4 | neo4j==5.8.0 5 | networkx==3.1 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | venv 3 | **/__pycache__ 4 | 5 | # App Specific 6 | .env 7 | 8 | # IDE 9 | .vscode 10 | 11 | # Neo4j local DB 12 | 13 | neo4j_db/data 14 | neo4j_db/plugins -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY= 2 | CHATGPT_MODEL=gpt-3.5-turbo 3 | NEO4J_DB_URI=neo4j://localhost:7687 4 | NEO4J_DB_NAME=neo4j 5 | NEO4J_DB_USER= 6 | NEO4J_DB_PASS= 7 | NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME=idx_node_entity_name_fulltext 8 | -------------------------------------------------------------------------------- /neo4j_db/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.5' 2 | 3 | services: 4 | neo4j: 5 | image: neo4j:5.7.0 6 | ports: 7 | - "7474:7474" 8 | - "7687:7687" 9 | volumes: 10 | - ./data:/data 11 | - ./plugins:/plugins 12 | environment: 13 | - NEO4J_apoc_import_file_use__neo4j__config=true 14 | - NEO4J_PLUGINS=["apoc"] 15 | - NEO4J_dbms_security_procedures_unrestricted=apoc.* -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | from neo4j_langchain_bot import Neo4jLangchainBot 2 | 3 | 4 | def main(): 5 | chatbot = Neo4jLangchainBot() 6 | while True: 7 | message = input("You: ") 8 | response = chatbot.chat_completion(message) 9 | print("Chatbot: ", response) 10 | 11 | 12 | if __name__ == "__main__": 13 | try: 14 | main() 15 | except KeyboardInterrupt: 16 | print("Keyboard interrupt, quitting") 17 | pass 18 | -------------------------------------------------------------------------------- /src/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | 4 | # Load env var from .env 5 | load_dotenv() 6 | 7 | OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") 8 | CHATGPT_MODEL = os.getenv("CHATGPT_MODEL") 9 | 10 | # Neo4j database connection config 11 | NEO4J_DB_URI = os.getenv("NEO4J_DB_URI") 12 | NEO4J_DB_NAME = os.getenv("NEO4J_DB_NAME") 13 | NEO4J_DB_USER = os.getenv("NEO4J_DB_USER") 14 | NEO4J_DB_PASS = os.getenv("NEO4J_DB_PASS") 15 | NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME = os.getenv("NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME") 16 | -------------------------------------------------------------------------------- /src/prompt.py: -------------------------------------------------------------------------------- 1 | SUFFIX_WITH_ENTITIES = """TOOLS 2 | ------ 3 | Assistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are: 4 | 5 | {{tools}} 6 | 7 | {format_instructions} 8 | 9 | USERS IN CONVERSATION 10 | ------ 11 | Here is a list of users involved in the conversation: 12 | {{{{entities}}}} 13 | 14 | USER'S INPUT 15 | -------------------- 16 | Here is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else): 17 | 18 | {{{{input}}}}""" -------------------------------------------------------------------------------- /src/neo4j_graph/utils.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import networkx as nx 3 | from .model import Neo4jEdge 4 | 5 | 6 | def add_neo4j_edges_to_networkx_graph(graph: nx.DiGraph, edge_records: List[Neo4jEdge]): 7 | for record in edge_records: 8 | if not graph.has_node(record.src["name"]): 9 | graph.add_node(record.src["name"]) 10 | if not graph.has_node(record.sink["name"]): 11 | graph.add_node(record.sink["name"]) 12 | graph.add_edge( 13 | record.src["name"], 14 | record.sink["name"], 15 | relation=record.relation["name"], 16 | ) -------------------------------------------------------------------------------- /scripts/add_index_for_neo4j_db.py: -------------------------------------------------------------------------------- 1 | import os 2 | from neo4j import GraphDatabase 3 | from dotenv import load_dotenv 4 | 5 | # Load env var from .env 6 | load_dotenv() 7 | 8 | 9 | def main(): 10 | driver = GraphDatabase.driver( 11 | uri=os.getenv("NEO4J_DB_URI"), 12 | auth=(os.getenv("NEO4J_DB_USER"), os.getenv("NEO4J_DB_PASS")), 13 | database=os.getenv("NEO4J_DB_NAME"), 14 | ) 15 | 16 | with driver.session() as session: 17 | session.run( 18 | "CREATE TEXT INDEX idx_node_entity_name IF NOT EXISTS FOR (n:Entity) ON (n.name)" 19 | ) 20 | session.run( 21 | f"CREATE FULLTEXT INDEX {os.getenv('NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME')} IF NOT EXISTS " 22 | + "FOR (n:Entity) " 23 | + "ON EACH [n.name] " 24 | + "OPTIONS {indexConfig: {`fulltext.analyzer`: 'cjk'}}" 25 | ) 26 | 27 | 28 | # Run the main function of the app 29 | if __name__ == "__main__": 30 | try: 31 | main() 32 | except KeyboardInterrupt: 33 | print("Keyboard interrupt, quitting") 34 | pass 35 | -------------------------------------------------------------------------------- /src/neo4j_graph/model.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Optional, List, Dict, NamedTuple 2 | 3 | 4 | class Node(NamedTuple): 5 | name: str 6 | metadata: Optional[Dict[str, Any]] = None 7 | 8 | 9 | class Edge(NamedTuple): 10 | relation: str 11 | metadata: Optional[Dict[str, Any]] = None 12 | 13 | 14 | class Neo4jEdge(NamedTuple): 15 | src: Dict[str, Any] 16 | relation: Dict[str, Any] 17 | sink: Dict[str, Any] 18 | 19 | def to_statement(self) -> str: 20 | return " ".join( 21 | [ 22 | self.src["name"], 23 | self.relation["name"], 24 | self.sink["name"], 25 | ] 26 | ) 27 | 28 | 29 | class Neo4jMultiEdge(NamedTuple): 30 | src: Dict[str, Any] 31 | relations: List[Any] 32 | sink: Dict[str, Any] 33 | 34 | def to_statement(self) -> str: 35 | statement_parts: List[str] = [] 36 | statement_parts.append(self.src["name"]) 37 | for relation in self.relations: 38 | statement_parts.append(relation["name"]) 39 | rel_sink = relation.nodes[1] 40 | statement_parts.append(rel_sink["name"]) 41 | 42 | return " ".join(statement_parts) -------------------------------------------------------------------------------- /src/neo4j_langchain_bot.py: -------------------------------------------------------------------------------- 1 | from langchain.agents import ( 2 | ConversationalChatAgent, 3 | AgentExecutor, 4 | ) 5 | from langchain.chat_models import ChatOpenAI 6 | from config import ( 7 | OPENAI_API_KEY, 8 | CHATGPT_MODEL, 9 | ) 10 | from prompt import SUFFIX_WITH_ENTITIES 11 | from memory import ConversationEntityKGMemory 12 | from neo4j_graph import Neo4jEntityGraph 13 | 14 | 15 | class Neo4jLangchainBot: 16 | def __init__(self): 17 | input_variables = ["input", "chat_history", "entities", "agent_scratchpad"] 18 | llm = ChatOpenAI( 19 | client=None, 20 | openai_api_key=OPENAI_API_KEY, 21 | model=CHATGPT_MODEL, 22 | temperature=0, 23 | ) 24 | tools = [] 25 | agent = ConversationalChatAgent.from_llm_and_tools( 26 | llm=llm, 27 | tools=tools, 28 | human_message=SUFFIX_WITH_ENTITIES, 29 | input_variables=input_variables, 30 | ) 31 | memory = ConversationEntityKGMemory( 32 | llm=llm, 33 | kg=Neo4jEntityGraph(), 34 | chat_history_key="chat_history", 35 | return_messages=True, 36 | ) 37 | self.agent_executor = AgentExecutor.from_agent_and_tools( 38 | agent=agent, 39 | tools=tools, 40 | max_iteration=10, 41 | memory=memory, 42 | verbose=True, 43 | ) 44 | 45 | def chat_completion(self, input: str) -> str: 46 | print("Requesting chat completion with input:") 47 | print(input) 48 | 49 | text_output = self.agent_executor.run(input=input) 50 | 51 | print("Finished chat completion with response") 52 | print(text_output) 53 | return text_output 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Langchain Neo4j Knowledge Graph Demo 2 | 3 | This project aims to demonstrate the potential use of Neo4j graph database as memory of Langchain agent, which contains 4 | 5 | 1. An implementation of entity graph similar to `NetworkxEntityGraph`, with Neo4j as storage 6 | 2. An implementation of `BaseChatMemory` which make use Neo4j knowledge graph, extending existing `ConversationKGMemory` which uses `NetworkxEntityGraph` (in memory entity graph implemented with NetworkX) 7 | 8 | # Prerequisite 9 | 10 | 1. Docker + Docker Compose, or a Neo4j database instance 11 | 2. Python 12 | 3. (Optional) venv 13 | 14 | # Setup 15 | 16 | 1. Start the Neo4j database container with docker-compose, or prepare a Neo4j database instance (e.g. Neo4j Desktop, cloud instance etc.). 17 | 2. Access your Neo4j database with browser with `http://localhost:7474/browser/` (assuming that Neo4j database is hosted locally) and follow instructions in web UI to reset password. (Hint: initial username and password are both `neo4j`) 18 | 3. Copy .env.example to .env and fill in the variables, namely Neo4j database connection config, and OpenAI API secret key. 19 | 4. Initiate virtual environment and install dependencies (or manage dependencies in other way) 20 | 21 | ```powershell 22 | python -m venv ./venv 23 | pip install -r ./requirement.txt 24 | ``` 25 | 26 | 5. Make sure that environment variable for Neo4j connection is configured properly, and Neo4j database is started without error, run the script `{PROJECT_ROOT}/scripts/add_index_for_neo4j_db.py` to create index needed for performing full-text search in Neo4j knowledge graph 27 | 28 | ```powershell 29 | # In project root 30 | python ./scripts/add_index_for_neo4j_db.py 31 | ``` 32 | 33 | 6. Run the app with `python ./src/main.py` in project root. 34 | 35 | 36 | # Notes 37 | 38 | 1. As the graph is stored in Neo4j database, it is persisted even after the bot is shutted down 39 | 2. To see the most updated knowledge graph, run `MATCH (n) RETURN n` query in web UI of Neo4j to dump all nodes and edges. Beware that this query is slow if you have many nodes -------------------------------------------------------------------------------- /src/memory.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, Any, Union, List 2 | from langchain.memory import ( 3 | ConversationKGMemory, 4 | ) 5 | from langchain.schema import ( 6 | get_buffer_string, 7 | ) 8 | 9 | 10 | class ConversationEntityKGMemory(ConversationKGMemory): 11 | """ 12 | Extending ConversationKGMemory providing both chat history 13 | knowledge of enttiy involved with knowledge graph. 14 | Supported input key: chat_history_key (default "history") and "entities" 15 | """ 16 | 17 | chat_history_key: str = "history" #: :meta private: 18 | 19 | def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: 20 | entities = self._get_current_entities(inputs) 21 | 22 | if self.return_messages: 23 | message_buffer = self.chat_memory.messages[-self.k * 2 :] 24 | else: 25 | message_buffer = get_buffer_string( 26 | self.chat_memory.messages[-self.k * 2 :], 27 | human_prefix=self.human_prefix, 28 | ai_prefix=self.ai_prefix, 29 | ) 30 | 31 | entity_strings = [] 32 | for entity in entities: 33 | knowledge = self.kg.get_entity_knowledge(entity) 34 | if knowledge: 35 | summary = f"On {entity}: {'. '.join(knowledge)}." 36 | entity_strings.append(summary) 37 | entity_info: Union[str, List] 38 | if not entity_strings: 39 | entity_info = [] if self.return_messages else "" 40 | elif self.return_messages: 41 | entity_info = [ 42 | self.summary_message_cls(content=text) for text in entity_strings 43 | ] 44 | else: 45 | entity_info = "\n".join(entity_strings) 46 | 47 | print(f"Loaded chat history: {message_buffer}") 48 | print(f"Loaded entity info: {entity_info}") 49 | 50 | return { 51 | self.chat_history_key: message_buffer, 52 | "entities": entity_info, 53 | } 54 | 55 | @property 56 | def memory_variables(self) -> List[str]: 57 | """Will always return list of memory variables. 58 | 59 | :meta private: 60 | """ 61 | return [self.chat_history_key, "entities"] 62 | -------------------------------------------------------------------------------- /src/neo4j_graph/repository.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from neo4j import ManagedTransaction, Record 3 | from config import NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME 4 | from .model import ( 5 | Node, 6 | Edge, 7 | Neo4jEdge, 8 | Neo4jMultiEdge, 9 | ) 10 | 11 | 12 | def find_nodes( 13 | tx: ManagedTransaction, 14 | q: str, 15 | ) -> List[Record]: 16 | query = "MATCH (m:Entity {name: $name})" 17 | result = tx.run(query, name=q) 18 | return list(result) 19 | 20 | 21 | def fulltext_search_nodes( 22 | tx: ManagedTransaction, 23 | q: str, 24 | ) -> List[Record]: 25 | query = "CALL db.index.fulltext.queryNodes($idx_name, $q)" 26 | results = tx.run( 27 | query, 28 | idx_name=NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME, 29 | q=q, 30 | ) 31 | return list(results) 32 | 33 | 34 | def find_surrounding_edges( 35 | tx: ManagedTransaction, 36 | q: str, 37 | depth: int, 38 | ) -> List[Neo4jMultiEdge]: 39 | query = f"MATCH (a:Entity {{name: $name}})-[r*..{depth}]->(b) RETURN a, r, b" 40 | results: list[Neo4jMultiEdge] = [] 41 | for record in tx.run(query, name=q): # type: ignore 42 | results.append( 43 | Neo4jMultiEdge( 44 | src=record["a"], 45 | relations=record["r"], 46 | sink=record["b"], 47 | ) 48 | ) 49 | 50 | return results 51 | 52 | 53 | def fulltext_search_surrounding_edges( 54 | tx: ManagedTransaction, 55 | q: str, 56 | depth: int, 57 | ) -> List[Neo4jMultiEdge]: 58 | query = ( 59 | "CALL db.index.fulltext.queryNodes($idx_name, $q, {limit: 1}) YIELD node AS a " 60 | f"MATCH (a)-[r*..{depth}]->(b) RETURN a, r, b" 61 | ) 62 | resp = tx.run( 63 | query, # type: ignore 64 | idx_name=NEO4J_ENTITY_NAME_FULLTEXT_INDEX_NAME, 65 | q=q, 66 | ) 67 | results: List[Neo4jMultiEdge] = [] 68 | for record in resp: # type: ignore 69 | results.append( 70 | Neo4jMultiEdge( 71 | src=record["a"], 72 | relations=record["r"], 73 | sink=record["b"], 74 | ) 75 | ) 76 | 77 | return results 78 | 79 | 80 | def find_all_edges(tx: ManagedTransaction) -> List[Neo4jEdge]: 81 | query = "MATCH (a:Entity)-[r:RELATION]->(b:Entity) RETURN a, r, b" 82 | results: list[Neo4jEdge] = [] 83 | for record in tx.run(query): 84 | results.append( 85 | Neo4jEdge( 86 | src=record["a"], 87 | relation=record["r"], 88 | sink=record["b"], 89 | ) 90 | ) 91 | 92 | return results 93 | 94 | 95 | def add_node_if_not_exist( 96 | tx: ManagedTransaction, 97 | node: Node, 98 | ): 99 | query = "MERGE (n:Entity {name: $name})" 100 | tx.run(query, name=node.name) 101 | 102 | 103 | def add_edge_and_node_if_not_exists( 104 | tx: ManagedTransaction, 105 | src: Node, 106 | relation: Edge, 107 | sink: Node, 108 | ): 109 | query = ( 110 | "MERGE (a:Entity {name: $src_name}) " 111 | "MERGE (b:Entity {name: $sink_name}) " 112 | "MERGE (a)-[r:RELATION {name: $relation}]->(b)" 113 | ) 114 | tx.run( 115 | query, 116 | src_name=src.name, 117 | relation=relation.relation, 118 | sink_name=sink.name, 119 | ) 120 | 121 | 122 | def delete_node( 123 | tx: ManagedTransaction, 124 | name: str, 125 | ): 126 | query = "MATCH (m:Entity {name: $name}) DETACH DELETE m" 127 | tx.run(query, name=name) 128 | 129 | 130 | def delete_edge( 131 | tx: ManagedTransaction, 132 | src: Node, 133 | relation: Edge, 134 | sink: Node, 135 | ): 136 | query = ( 137 | "MATCH (a:Entity {name: $src_name})-[r:RELATION {name: $relation}]->(b:Entity {name: $sink_name}) " 138 | "DELETE r " 139 | "OPTIONAL MATCH (n:Entity {name: $src_name}) WHERE NOT (n)--() " 140 | "DELETE n " 141 | "OPTIONAL MATCH (n:Entity {name: $sink_name}) WHERE NOT (n)--() " 142 | "DELETE n" 143 | ) 144 | tx.run( 145 | query, 146 | src_name=src.name, 147 | relation=relation.relation, 148 | sink_name=sink.name, 149 | ) 150 | 151 | 152 | def clear_all( 153 | tx: ManagedTransaction, 154 | ): 155 | query = "MATCH (n:Entity) DETACH DELETE n" 156 | tx.run(query) 157 | -------------------------------------------------------------------------------- /src/neo4j_graph/entity_graph.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple, Literal 2 | from neo4j import ( 3 | GraphDatabase, 4 | Driver, 5 | ) 6 | import networkx as nx 7 | from langchain.graphs.networkx_graph import ( 8 | NetworkxEntityGraph, 9 | KnowledgeTriple, 10 | ) 11 | from config import ( 12 | NEO4J_DB_URI, 13 | NEO4J_DB_NAME, 14 | NEO4J_DB_USER, 15 | NEO4J_DB_PASS, 16 | ) 17 | from .repository import ( 18 | add_edge_and_node_if_not_exists, 19 | clear_all, 20 | delete_edge, 21 | find_all_edges, 22 | find_surrounding_edges, 23 | fulltext_search_surrounding_edges, 24 | ) 25 | from .model import ( 26 | Node, 27 | Edge, 28 | ) 29 | from .utils import add_neo4j_edges_to_networkx_graph 30 | 31 | SearchMode = Literal["exact", "fulltext"] 32 | 33 | 34 | class Neo4jEntityGraph(NetworkxEntityGraph): 35 | driver: Driver 36 | search_mode: SearchMode 37 | 38 | def __init__( 39 | self, 40 | *, 41 | search_mode: SearchMode = "fulltext", 42 | verbose: bool = True, 43 | ): 44 | print("Initiating neo4j driver...") 45 | self.driver = GraphDatabase.driver( 46 | uri=NEO4J_DB_URI, 47 | auth=(NEO4J_DB_USER, NEO4J_DB_PASS), 48 | database=NEO4J_DB_NAME, 49 | ) 50 | self.search_mode = search_mode 51 | print("Initiated entity graph.") 52 | 53 | def __del__(self): 54 | print("Closing neo4j driver...") 55 | self.driver.close() 56 | 57 | def add_triple(self, knowledge_triple: KnowledgeTriple) -> None: 58 | print(f"Adding triple {knowledge_triple}...") 59 | with self.driver.session() as session: 60 | session.execute_write( 61 | add_edge_and_node_if_not_exists, 62 | src=Node(knowledge_triple.subject), 63 | relation=Edge(knowledge_triple.predicate), 64 | sink=Node(knowledge_triple.object_), 65 | ) 66 | 67 | def delete_triple(self, knowledge_triple: KnowledgeTriple) -> None: 68 | print(f"Deleting triple {knowledge_triple}...") 69 | with self.driver.session() as session: 70 | session.execute_write( 71 | delete_edge, 72 | src=Node(knowledge_triple.subject), 73 | relation=Edge(knowledge_triple.predicate), 74 | sink=Node(knowledge_triple.object_), 75 | ) 76 | 77 | def get_triples(self) -> List[Tuple[str, str, str]]: 78 | with self.driver.session() as session: 79 | resp = session.execute_read(find_all_edges) 80 | triples: List[Tuple[str, str, str]] = [] 81 | for record in resp: 82 | triples.append( 83 | ( 84 | record.src["name"], 85 | record.sink["name"], 86 | record.relation["name"], 87 | ) 88 | ) 89 | return triples 90 | 91 | def get_entity_knowledge(self, entity: str, depth: int = 1) -> List[str]: 92 | print(f"Searching knowledge graph for entity {entity}") 93 | with self.driver.session() as session: 94 | if self.search_mode == "exact": 95 | search_func = find_surrounding_edges 96 | elif self.search_mode == "fulltext": 97 | search_func = fulltext_search_surrounding_edges 98 | else: 99 | raise NotImplementedError( 100 | f"search mode {self.search_mode} is not supported" 101 | ) 102 | resp = session.execute_read( 103 | search_func, 104 | q=entity, 105 | depth=depth, 106 | ) 107 | 108 | print("Found the following from knowledge graph:") 109 | statements: List[str] = [] 110 | for record in resp: 111 | statement = record.to_statement() 112 | print(statement) 113 | statements.append(statement) 114 | 115 | return statements 116 | 117 | def write_to_gml(self, path: str) -> None: 118 | print("Loading the entire knowledge graph...") 119 | with self.driver.session() as session: 120 | resp = session.execute_read( 121 | find_all_edges, 122 | ) 123 | 124 | print("Constructing NetworkX graph...") 125 | networkx_graph = nx.DiGraph() 126 | add_neo4j_edges_to_networkx_graph( 127 | graph=networkx_graph, 128 | edge_records=resp, 129 | ) 130 | 131 | print(f"Writing gml file to path: {path}...") 132 | nx.gml.write_gml(networkx_graph, path=path) 133 | print("Written graph to gml file.") 134 | 135 | def clear(self) -> None: 136 | print("Clearing the entire knowledge graph...") 137 | with self.driver.session() as session: 138 | session.execute_write(clear_all) 139 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------