Open In Colab Open on GitHub

AG2 provides GraphRAG integration through agent capabilities. This is an example utilizing the integration of Neo4j’s native GraphRAG SDK. The Neo4j native query engine enables the construction of a knowledge graph from a single text or PDF file. Additionally, you can define custom entities, relationships, or schemas to guide the graph-building process. Once created, you can integrate the RAG capabilities into AG2 agents to query the knowledge graph effectively.

To install the neo4j GraphRAG SDK with OpenAI LLM

sudo apt-get install graphviz graphviz-dev
pip install pygraphviz
pip install "neo4j-graphrag[openai, experimental]"

Set Configuration and OpenAI API Key

By default, in order to use OpenAI LLM with Neo4j you need to have an OpenAI key in your environment variable OPENAI_API_KEY.

You can utilize an OAI_CONFIG_LIST file and extract the OpenAI API key and put it in the environment, as will be shown in the following cell.

Alternatively, you can load the environment variable yourself.

Learn more about configuring LLMs for agents here.

import os

import autogen

config_list = autogen.config_list_from_json(env_or_file="OAI_CONFIG_LIST")

# Put the OpenAI API key into the environment
os.environ["OPENAI_API_KEY"] = config_list[0]["api_key"]
# This is needed to allow nested asyncio calls for Neo4j in Jupyter
import nest_asyncio

nest_asyncio.apply()

Set up LLM models

Important

  • Default Models: - Knowledge Graph Construction OpenAI’s GPT-4o with json_object output temperature=0.0. - Question Answering: OpenAI’s GPT-4o with temperature=0.0. - Embedding: OpenAI’s text-embedding-3-large. You need to provide its dimension for the query engine later.

  • Customization: You can change these defaults by setting the following parameters on the Neo4jNativeGraphQueryEngine:

    • llm: Specify a LLM instance with a llm you like for graph construction, it must support json format response
    • query_llm: Specify a LLM instance with a llm you like for querying. Don’t use json format response.
    • embedding: Specify a Embedder instance with a embedding model.

Learn more about configuring other LLM providers for agents here.

from neo4j_graphrag.embeddings import OpenAIEmbeddings
from neo4j_graphrag.llm.openai_llm import OpenAILLM

llm = OpenAILLM(
    model_name="gpt-4o",
    model_params={
        "response_format": {"type": "json_object"},  # Json format response is required for the LLM
        "temperature": 0,
    },
)

query_llm = OpenAILLM(
    model_name="gpt-4o",
    model_params={"temperature": 0},  # Don't use json format response for the query LLM
)

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
# Imports
from autogen import ConversableAgent, UserProxyAgent
from autogen.agentchat.contrib.graph_rag.document import Document, DocumentType
from autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine import Neo4jNativeGraphQueryEngine
from autogen.agentchat.contrib.graph_rag.neo4j_native_graph_rag_capability import Neo4jNativeGraphCapability

Create a Knowledge Graph with Your Own Data

Note: You need to have a Neo4j database running. If you are running one in a Docker container, please ensure your Docker network is setup to allow access to it.

In this example, the Neo4j endpoint is set to host=“bolt://172.17.0.3” and port=7687, please adjust accordingly. For how to spin up a Neo4j with Docker, you can refer to this

A Simple Example

In this example, the graph schema is auto-generated. Entities and relationships are created as they fit into the data

Neo4j GraphRAG SDK supports single document of 2 input types – txt and pdf (images will be skipped).

We start by creating a Neo4j knowledge graph with a sample text.

# load documents
# To use text data, you need to:
# 1. Specify the type as TEXT
# 2. Pass the path to the text file

input_path = "../test/agentchat/contrib/graph_rag/BUZZ_Employee_Handbook.txt"
input_document = [Document(doctype=DocumentType.TEXT, path_or_url=input_path)]

First we need to use the query engine to initialize the database. It performs the follows steps:

  1. Clears the existing database.
  2. Extracts graph nodes and relationships from the input data to build a knowledge graph.
  3. Creates a vector index for efficient retrieval.
query_engine = Neo4jNativeGraphQueryEngine(
    host="bolt://172.17.0.3",  # Change
    port=7687,  # if needed
    username="neo4j",  # Change if you reset username
    password="password",  # Change if you reset password
    llm=llm,  # change to the LLM model you want to use
    embeddings=embeddings,  # change to the embeddings model you want to use
    query_llm=query_llm,  # change to the query LLM model you want to use
    embedding_dimension=3072,  # must match the dimension of the embeddings model
)

# initialize the database (it will delete any pre-existing data)
query_engine.init_db(input_document)
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Clearing the database...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Clearing all nodes and relationships in the database...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Database cleared successfully.
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Initializing the knowledge graph builders...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Building the knowledge graph...
INFO:neo4j_graphrag.experimental.pipeline.config.runner:PIPELINE_RUNNER: starting pipeline <neo4j_graphrag.experimental.pipeline.pipeline.Pipeline object at 0xffff735157d0> with run_params=defaultdict(<class 'dict'>, {'schema': {'entities': [], 'relations': [], 'potential_schema': None}, 'splitter': {'text': '**BUZZ Co. EMPLOYEE HANDBOOK**\n\n**EMPLOYEE RECEIPT AND ACCEPTANCE**\n\nI acknowledge receipt of the BUZZ Co. Employee Handbook and understand it is my responsibility to read and know its contents. This Handbook is not an employment contract. Unless I have a written employment agreement with BUZZ Co. that states otherwise, my employment is at-will. I can resign at any time, with or without notice or cause, and BUZZ Co. can terminate my employment at any time, with or without notice or cause.\n\nSignature: _________________________\n\nPrint Name: ________________________\n\nDate: ____________________________\n\n**CONFIDENTIALITY POLICY AND PLEDGE**\n\nAll non-public information about BUZZ Co., its members, or donors is confidential. Employees may not disclose this information to anyone outside BUZZ Co., or to other employees who do not need it to perform their duties. Disclosure of confidential information will result in disciplinary action, including possible termination.\n\nSignature: _________________________\n\nPrint Name: ________________________\n\nDate: ____________________________\n\n**TABLE OF CONTENTS**\n\nI. MISSION\nII. OVERVIEW\nIII. VOLUNTARY AT-WILL EMPLOYMENT\nIV. EQUAL EMPLOYMENT OPPORTUNITY\nV. POLICY AGAINST WORKPLACE HARASSMENT\nVI. SOLICITATION\nVII. HOURS OF WORK, ATTENDANCE, AND PUNCTUALITY\nVIII. EMPLOYMENT POLICIES AND PRACTICES\nIX. POSITION DESCRIPTION AND SALARY ADMINISTRATION\nX. WORK REVIEW\nXI. ECONOMIC BENEFITS AND INSURANCE\nXII. LEAVE BENEFITS AND OTHER WORK POLICIES\nXIII. REIMBURSEMENT OF EXPENSES\nXIV. SEPARATION\nXV. RETURN OF PROPERTY\nXVI. REVIEW OF PERSONNEL AND WORK PRACTICES\nXVII. PERSONNEL RECORDS\nXVIII. OUTSIDE EMPLOYMENT\nXIX. NON-DISCLOSURE OF CONFIDENTIAL INFORMATION\nXX. COMPUTER AND INFORMATION SECURITY\nXXI. INTERNET ACCEPTABLE USE POLICY\n\n**I. MISSION**\n\n[Insert BUZZ Co.\'s Mission Statement Here]\n\n**II. OVERVIEW**\n\nThis Handbook provides guidelines about BUZZ Co.\'s policies and procedures. It is not a contract and does not guarantee employment for any specific period. With the exception of the at-will employment policy, these guidelines may be changed by BUZZ Co. at any time without notice. The Board of Directors establishes personnel policies, and the Executive Director administers them.\n\n**III. VOLUNTARY AT-WILL EMPLOYMENT**\n\nUnless an employee has a written employment agreement stating otherwise, all employment at BUZZ Co. is "at-will." Employees may be terminated with or without cause, and employees may leave their employment with or without cause.\n\n**IV. EQUAL EMPLOYMENT OPPORTUNITY**\n\n[Content not provided in the original document, but should be included here. State BUZZ Co.\'s commitment to equal employment opportunity and non-discrimination.]\n\n**V. POLICY AGAINST WORKPLACE HARASSMENT**\n\n[Content not provided in the original document. State BUZZ Co.\'s policy against all forms of workplace harassment and the procedures for reporting such incidents.]\n\n**VI. SOLICITATION**\n\nEmployees may not solicit for any unauthorized purpose during work time. Non-working employees may not solicit working employees. Non-employees may not solicit on BUZZ Co. premises. Distribution of materials requires prior approval from the Executive Director.\n\n**VII. HOURS OF WORK, ATTENDANCE, AND PUNCTUALITY**\n\n**A. Hours of Work:**\nNormal work week is five 7-hour days, typically 9:00 a.m. - 5:00 p.m., Monday-Friday, with a one-hour unpaid lunch. Work schedules may vary with Executive Director approval.\n\n**B. Attendance and Punctuality:**\nRegular attendance is expected. Notify your supervisor and the office manager as soon as possible if you are absent, late, or need to leave early. For absences longer than one day, call your supervisor before each workday. Excessive absences or tardiness may result in disciplinary action, up to termination.\n\n**C. Overtime:**\nNon-Exempt Employees will be paid overtime (1.5 times the regular rate) for hours worked over 40 in a work week, or double time for work on Sundays or holidays. Overtime must be pre-approved by the Executive Director.\n\n**VIII. EMPLOYMENT POLICIES AND PRACTICES**\n\n**A. Definition of Terms:**\n\n1. **Employer:** BUZZ Co.\n2. **Full-Time Employee:** Works 35+ hours/week.\n3. **Part-Time Employee:** Works 17.5 - 35 hours/week.\n4. **Exempt Employee:** Salaried, exempt from FLSA overtime rules.\n5. **Non-Exempt Employee:** Hourly, non-exempt from FLSA overtime rules.\n6. **Temporary Employee:** Employed for a specific period less than six months.\n\n**IX. POSITION DESCRIPTION AND SALARY ADMINISTRATION**\n\nEach position has a written job description. Paychecks are distributed on the 15th and last day of each month. Timesheets are due within two days of each pay period.\n\n**X. WORK REVIEW**\n\nOngoing work review with supervisors. Annual performance reviews provide an opportunity to discuss the past year, set goals, and strengthen the working relationship.\n\n**XI. ECONOMIC BENEFITS AND INSURANCE**\n\n**A. Health/Life Insurance:**\nBUZZ Co. offers health and dental insurance to eligible full-time and part-time employees after the first full month of employment.\n\n**B. Social Security/Medicare/Medicaid:**\nBUZZ Co. participates in these programs.\n\n**C. Workers\' Compensation and Unemployment Insurance:**\nEmployees are covered by Workers\' Compensation. BUZZ Co. participates in the District of Columbia unemployment program.\n\n**D. Retirement Plan:**\nAvailable to eligible full-time and part-time employees (21+ years old). BUZZ Co. contributes after one year of vested employment.\n\n**E. Tax Deferred Annuity Plan:**\nOffered through payroll deduction at the employee\'s expense.\n\n**XII. LEAVE BENEFITS AND OTHER WORK POLICIES**\n\n**A. Holidays:**\n11.5 paid holidays per year for Full-Time Employees, pro-rated for Part-Time.\n\n**B. Vacation:**\nFull-time employees earn 10 days after the first year, 15 days after the third year and 20 days after the fourth year. Prorated for Part-Time employees.\n\n**C. Sick Leave:**\nOne day per month for Full-Time, pro-rated for Part-Time, up to a 30-day maximum.\n\n**D. Personal Leave:**\n3 days per year after six months of employment for Full-Time, pro-rated for Part-Time.\n\n**E. Military Leave:**\nUnpaid leave in accordance with applicable law.\n\n**F. Civic Responsibility:**\nBUZZ Co. will pay employees the difference between his or her salary and any amount paid by the government, unless prohibited by law, up to a maximum of ten days of jury duty.\nBUZZ Co. will pay employees the difference between his or her salary and any amount paid by the government or any other source, unless prohibited by law for serving as an Election Day worker at the polls on official election days (not to exceed two elections in one given calendar year).\n\n**G. Parental Leave:**\n24 hours of unpaid leave per year for school-related events under the DC Parental Leave Act.\n\n**H. Bereavement Leave:**\n5 days for immediate family, 3 days for other close relatives.\n\n**I. Extended Personal Leave:**\nUp to eight weeks unpaid leave may be granted after one year of employment.\n\n**J. Severe Weather Conditions:**\nBUZZ Co. follows Federal Government office closures.\n\n**K. Meetings and Conferences:**\nTime off with pay may be granted for work-related educational opportunities.\n\n**XIII. REIMBURSEMENT OF EXPENSES**\n\nReimbursement for reasonable and necessary business expenses, including travel, with prior approval and receipts.\n\n**XIV. SEPARATION**\n\nEmployees are encouraged to give at least 10 business days\' written notice. Exit interviews will be scheduled. Employees who resign or are terminated will receive accrued, unused vacation benefits.\n\n**XV. RETURN OF PROPERTY**\n\nEmployees must return all BUZZ Co. property upon separation or request.\n\n**XVI. REVIEW OF PERSONNEL ACTION**\n\nEmployees may request a review of personnel actions, first with their supervisor, then with the Executive Director.\n\n**XVII. PERSONNEL RECORDS**\n\nPersonnel records are confidential. Employees must promptly report changes in personnel data. Accurate time records are required.\n\n**XVIII. OUTSIDE EMPLOYMENT**\n\nOutside employment is permitted as long as it does not interfere with BUZZ Co. job performance or create a conflict of interest.\n\n**XIX. NON-DISCLOSURE OF CONFIDENTIAL INFORMATION**\n\nEmployees must sign a non-disclosure agreement. Unauthorized disclosure of confidential information is prohibited.\n\n**XX. COMPUTER AND INFORMATION SECURITY**\n\nBUZZ Co. computer systems are for business use, with limited personal use allowed. All data is BUZZ Co. property and may be monitored. Do not use systems for offensive or illegal activities. Follow security procedures.\n\n**XXI. INTERNET ACCEPTABLE USE POLICY**\n\nInternet access is for business use. Do not use the Internet for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.\n\nRevised {Date}\n\nApproved by the Executive Committee of the BUZZ Co. Board of Directors\n'}})
INFO:neo4j_graphrag.experimental.components.lexical_graph:Document node not created in the lexical graph because no document metadata is provided
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE RANGE INDEX __entity__id IF NOT EXISTS FOR (e:__KGBuilder__) ON (e.id)` has no effect.} {description: `RANGE INDEX __entity__id FOR (e:__KGBuilder__) ON (e.id)` already exists.} {position: None} for query: 'CREATE INDEX __entity__id IF NOT EXISTS  FOR (n:__KGBuilder__) ON (n.id)'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Knowledge graph built successfully.
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Creating vector index 'vector-index-name'...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Creating vector index 'vector-index-name'...
INFO:neo4j_graphrag.indexes:Creating vector index named 'vector-index-name'
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE VECTOR INDEX `vector-index-name` IF NOT EXISTS FOR (e:Chunk) ON (e.embedding) OPTIONS {indexConfig: {`vector.dimensions`: toInteger($dimensions), `vector.similarity_function`: $similarity_fn}}` has no effect.} {description: `VECTOR INDEX `vector-index-name` FOR (e:Chunk) ON (e.embedding)` already exists.} {position: None} for query: 'CREATE VECTOR INDEX $name IF NOT EXISTS FOR (n:Chunk) ON n.embedding OPTIONS { indexConfig: { `vector.dimensions`: toInteger($dimensions), `vector.similarity_function`: $similarity_fn } }'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Vector index 'vector-index-name' created successfully.

Add capability to a ConversableAgent and query them

The rag capability enables the agent to perform local search on the knowledge graph using the vector index created in the previous step.

# Create a ConversableAgent (no LLM configuration)
graph_rag_agent = ConversableAgent(
    name="buzz_agent",
    human_input_mode="NEVER",
)

# Associate the capability with the agent
graph_rag_capability = Neo4jNativeGraphCapability(query_engine)
graph_rag_capability.add_to_agent(graph_rag_agent)

# Create a user proxy agent to converse with our RAG agent
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="ALWAYS",
)

user_proxy.initiate_chat(graph_rag_agent, message="Who is the employer?")
user_proxy (to buzz_agent):

Who is the employer?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

The employer is BUZZ Co.

--------------------------------------------------------------------------------
user_proxy (to buzz_agent):

What benefits are entitled to employees?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

Employees at BUZZ Co. are entitled to several benefits, including:

1. **Health/Life Insurance:** Health and dental insurance are offered to eligible full-time and part-time employees after the first full month of employment.
2. **Social Security/Medicare/Medicaid:** BUZZ Co. participates in these programs.
3. **Workers' Compensation and Unemployment Insurance:** Employees are covered by Workers' Compensation, and BUZZ Co. participates in the District of Columbia unemployment program.
4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.
5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.
6. **Leave Benefits:** Includes paid holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.
7. **Reimbursement of Expenses:** Reimbursement for reasonable and necessary business expenses, including travel, with prior approval and receipts.

--------------------------------------------------------------------------------
user_proxy (to buzz_agent):

What responsibilities apply to employees?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

Employees at BUZZ Co. have several responsibilities, including:

1. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure can lead to disciplinary action, including termination.

2. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may result in disciplinary action.

3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.

4. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.

5. **Outside Employment:** Employees can engage in outside employment as long as it does not interfere with their job performance at BUZZ Co. or create a conflict of interest.

6. **Non-Disclosure Agreement:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.

7. **Computer and Information Security:** Employees must use BUZZ Co. computer systems primarily for business purposes, with limited personal use allowed. They must follow security procedures and not use systems for offensive or illegal activities.

8. **Internet Use:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.

9. **Reimbursement of Expenses:** Employees must obtain prior approval and provide receipts for reimbursement of reasonable and necessary business expenses, including travel.

These responsibilities ensure the smooth operation and integrity of BUZZ Co.'s work environment.

--------------------------------------------------------------------------------
ChatResult(chat_id=None, chat_history=[{'content': 'Who is the employer?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'The employer is BUZZ Co.', 'role': 'user', 'name': 'buzz_agent'}, {'content': 'What benefits are entitled to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': "Employees at BUZZ Co. are entitled to several benefits, including:\n\n1. **Health/Life Insurance:** Health and dental insurance are offered to eligible full-time and part-time employees after the first full month of employment.\n2. **Social Security/Medicare/Medicaid:** BUZZ Co. participates in these programs.\n3. **Workers' Compensation and Unemployment Insurance:** Employees are covered by Workers' Compensation, and BUZZ Co. participates in the District of Columbia unemployment program.\n4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.\n5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.\n6. **Leave Benefits:** Includes paid holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.\n7. **Reimbursement of Expenses:** Reimbursement for reasonable and necessary business expenses, including travel, with prior approval and receipts.", 'role': 'user', 'name': 'buzz_agent'}, {'content': 'What responsibilities apply to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': "Employees at BUZZ Co. have several responsibilities, including:\n\n1. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure can lead to disciplinary action, including termination.\n\n2. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may result in disciplinary action.\n\n3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.\n\n4. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.\n\n5. **Outside Employment:** Employees can engage in outside employment as long as it does not interfere with their job performance at BUZZ Co. or create a conflict of interest.\n\n6. **Non-Disclosure Agreement:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.\n\n7. **Computer and Information Security:** Employees must use BUZZ Co. computer systems primarily for business purposes, with limited personal use allowed. They must follow security procedures and not use systems for offensive or illegal activities.\n\n8. **Internet Use:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.\n\n9. **Reimbursement of Expenses:** Employees must obtain prior approval and provide receipts for reimbursement of reasonable and necessary business expenses, including travel.\n\nThese responsibilities ensure the smooth operation and integrity of BUZZ Co.'s work environment.", 'role': 'user', 'name': 'buzz_agent'}], summary="Employees at BUZZ Co. have several responsibilities, including:\n\n1. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure can lead to disciplinary action, including termination.\n\n2. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may result in disciplinary action.\n\n3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.\n\n4. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.\n\n5. **Outside Employment:** Employees can engage in outside employment as long as it does not interfere with their job performance at BUZZ Co. or create a conflict of interest.\n\n6. **Non-Disclosure Agreement:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.\n\n7. **Computer and Information Security:** Employees must use BUZZ Co. computer systems primarily for business purposes, with limited personal use allowed. They must follow security procedures and not use systems for offensive or illegal activities.\n\n8. **Internet Use:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.\n\n9. **Reimbursement of Expenses:** Employees must obtain prior approval and provide receipts for reimbursement of reasonable and necessary business expenses, including travel.\n\nThese responsibilities ensure the smooth operation and integrity of BUZZ Co.'s work environment.", cost={'usage_including_cached_inference': {'total_cost': 0}, 'usage_excluding_cached_inference': {'total_cost': 0}}, human_input=['What benefits are entitled to employees?', 'What responsibilities apply to employees?', 'exit'])

Revisit the example by defining custom entities, relations and schema

By providing custom entities, relations and schema, you could guide the engine to create a graph that better extracts the structure within the data. Custom schema must use provided entities and relations.

# Custom entities, relations and schema that fits the document

entities = ["EMPLOYEE", "EMPLOYER", "POLICY", "BENEFIT", "POSITION", "DEPARTMENT", "CONTRACT", "RESPONSIBILITY"]
relations = [
    "FOLLOWS",
    "PROVIDES",
    "APPLIES_TO",
    "ASSIGNED_TO",
    "PART_OF",
    "REQUIRES",
    "ENTITLED_TO",
    "REPORTS_TO",
]

potential_schema = [
    ("EMPLOYEE", "FOLLOWS", "POLICY"),
    ("EMPLOYEE", "ASSIGNED_TO", "POSITION"),
    ("EMPLOYEE", "REPORTS_TO", "DEPARTMENT"),
    ("EMPLOYER", "PROVIDES", "BENEFIT"),
    ("EMPLOYER", "REQUIRES", "RESPONSIBILITY"),
    ("POLICY", "APPLIES_TO", "EMPLOYEE"),
    ("POLICY", "APPLIES_TO", "CONTRACT"),
    ("POLICY", "REQUIRES", "RESPONSIBILITY"),
    ("BENEFIT", "ENTITLED_TO", "EMPLOYEE"),
    ("POSITION", "PART_OF", "DEPARTMENT"),
    ("POSITION", "ASSIGNED_TO", "EMPLOYEE"),
    ("CONTRACT", "REQUIRES", "RESPONSIBILITY"),
    ("CONTRACT", "APPLIES_TO", "EMPLOYEE"),
    ("RESPONSIBILITY", "ASSIGNED_TO", "POSITION"),
]
query_engine = Neo4jNativeGraphQueryEngine(
    host="bolt://172.17.0.3",  # Change
    port=7687,  # if needed
    username="neo4j",  # Change if you reset username
    password="password",  # Change if you reset password
    llm=llm,  # change to the LLM model you want to use
    embeddings=embeddings,  # change to the embeddings model you want to use
    query_llm=query_llm,  # change to the query LLM model you want to use
    embedding_dimension=3072,  # must match the dimension of the embeddings model
    entities=entities,
    relations=relations,
    potential_schema=potential_schema,
)

# initialize the database (it will delete any pre-existing data)
query_engine.init_db(input_document)
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Clearing the database...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Clearing all nodes and relationships in the database...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Database cleared successfully.
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Initializing the knowledge graph builders...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Building the knowledge graph...
INFO:neo4j_graphrag.experimental.pipeline.config.runner:PIPELINE_RUNNER: starting pipeline <neo4j_graphrag.experimental.pipeline.pipeline.Pipeline object at 0xffff71aeae90> with run_params=defaultdict(<class 'dict'>, {'schema': {'entities': [SchemaEntity(label='EMPLOYEE', description='', properties=[]), SchemaEntity(label='EMPLOYER', description='', properties=[]), SchemaEntity(label='POLICY', description='', properties=[]), SchemaEntity(label='BENEFIT', description='', properties=[]), SchemaEntity(label='POSITION', description='', properties=[]), SchemaEntity(label='DEPARTMENT', description='', properties=[]), SchemaEntity(label='CONTRACT', description='', properties=[]), SchemaEntity(label='RESPONSIBILITY', description='', properties=[])], 'relations': [SchemaRelation(label='FOLLOWS', description='', properties=[]), SchemaRelation(label='PROVIDES', description='', properties=[]), SchemaRelation(label='APPLIES_TO', description='', properties=[]), SchemaRelation(label='ASSIGNED_TO', description='', properties=[]), SchemaRelation(label='PART_OF', description='', properties=[]), SchemaRelation(label='REQUIRES', description='', properties=[]), SchemaRelation(label='ENTITLED_TO', description='', properties=[]), SchemaRelation(label='REPORTS_TO', description='', properties=[])], 'potential_schema': [('EMPLOYEE', 'FOLLOWS', 'POLICY'), ('EMPLOYEE', 'ASSIGNED_TO', 'POSITION'), ('EMPLOYEE', 'REPORTS_TO', 'DEPARTMENT'), ('EMPLOYER', 'PROVIDES', 'BENEFIT'), ('EMPLOYER', 'REQUIRES', 'RESPONSIBILITY'), ('POLICY', 'APPLIES_TO', 'EMPLOYEE'), ('POLICY', 'APPLIES_TO', 'CONTRACT'), ('POLICY', 'REQUIRES', 'RESPONSIBILITY'), ('BENEFIT', 'ENTITLED_TO', 'EMPLOYEE'), ('POSITION', 'PART_OF', 'DEPARTMENT'), ('POSITION', 'ASSIGNED_TO', 'EMPLOYEE'), ('CONTRACT', 'REQUIRES', 'RESPONSIBILITY'), ('CONTRACT', 'APPLIES_TO', 'EMPLOYEE'), ('RESPONSIBILITY', 'ASSIGNED_TO', 'POSITION')]}, 'splitter': {'text': '**BUZZ Co. EMPLOYEE HANDBOOK**\n\n**EMPLOYEE RECEIPT AND ACCEPTANCE**\n\nI acknowledge receipt of the BUZZ Co. Employee Handbook and understand it is my responsibility to read and know its contents. This Handbook is not an employment contract. Unless I have a written employment agreement with BUZZ Co. that states otherwise, my employment is at-will. I can resign at any time, with or without notice or cause, and BUZZ Co. can terminate my employment at any time, with or without notice or cause.\n\nSignature: _________________________\n\nPrint Name: ________________________\n\nDate: ____________________________\n\n**CONFIDENTIALITY POLICY AND PLEDGE**\n\nAll non-public information about BUZZ Co., its members, or donors is confidential. Employees may not disclose this information to anyone outside BUZZ Co., or to other employees who do not need it to perform their duties. Disclosure of confidential information will result in disciplinary action, including possible termination.\n\nSignature: _________________________\n\nPrint Name: ________________________\n\nDate: ____________________________\n\n**TABLE OF CONTENTS**\n\nI. MISSION\nII. OVERVIEW\nIII. VOLUNTARY AT-WILL EMPLOYMENT\nIV. EQUAL EMPLOYMENT OPPORTUNITY\nV. POLICY AGAINST WORKPLACE HARASSMENT\nVI. SOLICITATION\nVII. HOURS OF WORK, ATTENDANCE, AND PUNCTUALITY\nVIII. EMPLOYMENT POLICIES AND PRACTICES\nIX. POSITION DESCRIPTION AND SALARY ADMINISTRATION\nX. WORK REVIEW\nXI. ECONOMIC BENEFITS AND INSURANCE\nXII. LEAVE BENEFITS AND OTHER WORK POLICIES\nXIII. REIMBURSEMENT OF EXPENSES\nXIV. SEPARATION\nXV. RETURN OF PROPERTY\nXVI. REVIEW OF PERSONNEL AND WORK PRACTICES\nXVII. PERSONNEL RECORDS\nXVIII. OUTSIDE EMPLOYMENT\nXIX. NON-DISCLOSURE OF CONFIDENTIAL INFORMATION\nXX. COMPUTER AND INFORMATION SECURITY\nXXI. INTERNET ACCEPTABLE USE POLICY\n\n**I. MISSION**\n\n[Insert BUZZ Co.\'s Mission Statement Here]\n\n**II. OVERVIEW**\n\nThis Handbook provides guidelines about BUZZ Co.\'s policies and procedures. It is not a contract and does not guarantee employment for any specific period. With the exception of the at-will employment policy, these guidelines may be changed by BUZZ Co. at any time without notice. The Board of Directors establishes personnel policies, and the Executive Director administers them.\n\n**III. VOLUNTARY AT-WILL EMPLOYMENT**\n\nUnless an employee has a written employment agreement stating otherwise, all employment at BUZZ Co. is "at-will." Employees may be terminated with or without cause, and employees may leave their employment with or without cause.\n\n**IV. EQUAL EMPLOYMENT OPPORTUNITY**\n\n[Content not provided in the original document, but should be included here. State BUZZ Co.\'s commitment to equal employment opportunity and non-discrimination.]\n\n**V. POLICY AGAINST WORKPLACE HARASSMENT**\n\n[Content not provided in the original document. State BUZZ Co.\'s policy against all forms of workplace harassment and the procedures for reporting such incidents.]\n\n**VI. SOLICITATION**\n\nEmployees may not solicit for any unauthorized purpose during work time. Non-working employees may not solicit working employees. Non-employees may not solicit on BUZZ Co. premises. Distribution of materials requires prior approval from the Executive Director.\n\n**VII. HOURS OF WORK, ATTENDANCE, AND PUNCTUALITY**\n\n**A. Hours of Work:**\nNormal work week is five 7-hour days, typically 9:00 a.m. - 5:00 p.m., Monday-Friday, with a one-hour unpaid lunch. Work schedules may vary with Executive Director approval.\n\n**B. Attendance and Punctuality:**\nRegular attendance is expected. Notify your supervisor and the office manager as soon as possible if you are absent, late, or need to leave early. For absences longer than one day, call your supervisor before each workday. Excessive absences or tardiness may result in disciplinary action, up to termination.\n\n**C. Overtime:**\nNon-Exempt Employees will be paid overtime (1.5 times the regular rate) for hours worked over 40 in a work week, or double time for work on Sundays or holidays. Overtime must be pre-approved by the Executive Director.\n\n**VIII. EMPLOYMENT POLICIES AND PRACTICES**\n\n**A. Definition of Terms:**\n\n1. **Employer:** BUZZ Co.\n2. **Full-Time Employee:** Works 35+ hours/week.\n3. **Part-Time Employee:** Works 17.5 - 35 hours/week.\n4. **Exempt Employee:** Salaried, exempt from FLSA overtime rules.\n5. **Non-Exempt Employee:** Hourly, non-exempt from FLSA overtime rules.\n6. **Temporary Employee:** Employed for a specific period less than six months.\n\n**IX. POSITION DESCRIPTION AND SALARY ADMINISTRATION**\n\nEach position has a written job description. Paychecks are distributed on the 15th and last day of each month. Timesheets are due within two days of each pay period.\n\n**X. WORK REVIEW**\n\nOngoing work review with supervisors. Annual performance reviews provide an opportunity to discuss the past year, set goals, and strengthen the working relationship.\n\n**XI. ECONOMIC BENEFITS AND INSURANCE**\n\n**A. Health/Life Insurance:**\nBUZZ Co. offers health and dental insurance to eligible full-time and part-time employees after the first full month of employment.\n\n**B. Social Security/Medicare/Medicaid:**\nBUZZ Co. participates in these programs.\n\n**C. Workers\' Compensation and Unemployment Insurance:**\nEmployees are covered by Workers\' Compensation. BUZZ Co. participates in the District of Columbia unemployment program.\n\n**D. Retirement Plan:**\nAvailable to eligible full-time and part-time employees (21+ years old). BUZZ Co. contributes after one year of vested employment.\n\n**E. Tax Deferred Annuity Plan:**\nOffered through payroll deduction at the employee\'s expense.\n\n**XII. LEAVE BENEFITS AND OTHER WORK POLICIES**\n\n**A. Holidays:**\n11.5 paid holidays per year for Full-Time Employees, pro-rated for Part-Time.\n\n**B. Vacation:**\nFull-time employees earn 10 days after the first year, 15 days after the third year and 20 days after the fourth year. Prorated for Part-Time employees.\n\n**C. Sick Leave:**\nOne day per month for Full-Time, pro-rated for Part-Time, up to a 30-day maximum.\n\n**D. Personal Leave:**\n3 days per year after six months of employment for Full-Time, pro-rated for Part-Time.\n\n**E. Military Leave:**\nUnpaid leave in accordance with applicable law.\n\n**F. Civic Responsibility:**\nBUZZ Co. will pay employees the difference between his or her salary and any amount paid by the government, unless prohibited by law, up to a maximum of ten days of jury duty.\nBUZZ Co. will pay employees the difference between his or her salary and any amount paid by the government or any other source, unless prohibited by law for serving as an Election Day worker at the polls on official election days (not to exceed two elections in one given calendar year).\n\n**G. Parental Leave:**\n24 hours of unpaid leave per year for school-related events under the DC Parental Leave Act.\n\n**H. Bereavement Leave:**\n5 days for immediate family, 3 days for other close relatives.\n\n**I. Extended Personal Leave:**\nUp to eight weeks unpaid leave may be granted after one year of employment.\n\n**J. Severe Weather Conditions:**\nBUZZ Co. follows Federal Government office closures.\n\n**K. Meetings and Conferences:**\nTime off with pay may be granted for work-related educational opportunities.\n\n**XIII. REIMBURSEMENT OF EXPENSES**\n\nReimbursement for reasonable and necessary business expenses, including travel, with prior approval and receipts.\n\n**XIV. SEPARATION**\n\nEmployees are encouraged to give at least 10 business days\' written notice. Exit interviews will be scheduled. Employees who resign or are terminated will receive accrued, unused vacation benefits.\n\n**XV. RETURN OF PROPERTY**\n\nEmployees must return all BUZZ Co. property upon separation or request.\n\n**XVI. REVIEW OF PERSONNEL ACTION**\n\nEmployees may request a review of personnel actions, first with their supervisor, then with the Executive Director.\n\n**XVII. PERSONNEL RECORDS**\n\nPersonnel records are confidential. Employees must promptly report changes in personnel data. Accurate time records are required.\n\n**XVIII. OUTSIDE EMPLOYMENT**\n\nOutside employment is permitted as long as it does not interfere with BUZZ Co. job performance or create a conflict of interest.\n\n**XIX. NON-DISCLOSURE OF CONFIDENTIAL INFORMATION**\n\nEmployees must sign a non-disclosure agreement. Unauthorized disclosure of confidential information is prohibited.\n\n**XX. COMPUTER AND INFORMATION SECURITY**\n\nBUZZ Co. computer systems are for business use, with limited personal use allowed. All data is BUZZ Co. property and may be monitored. Do not use systems for offensive or illegal activities. Follow security procedures.\n\n**XXI. INTERNET ACCEPTABLE USE POLICY**\n\nInternet access is for business use. Do not use the Internet for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.\n\nRevised {Date}\n\nApproved by the Executive Committee of the BUZZ Co. Board of Directors\n'}})
INFO:neo4j_graphrag.experimental.components.lexical_graph:Document node not created in the lexical graph because no document metadata is provided
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE RANGE INDEX __entity__id IF NOT EXISTS FOR (e:__KGBuilder__) ON (e.id)` has no effect.} {description: `RANGE INDEX __entity__id FOR (e:__KGBuilder__) ON (e.id)` already exists.} {position: None} for query: 'CREATE INDEX __entity__id IF NOT EXISTS  FOR (n:__KGBuilder__) ON (n.id)'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Knowledge graph built successfully.
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Creating vector index 'vector-index-name'...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Creating vector index 'vector-index-name'...
INFO:neo4j_graphrag.indexes:Creating vector index named 'vector-index-name'
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE VECTOR INDEX `vector-index-name` IF NOT EXISTS FOR (e:Chunk) ON (e.embedding) OPTIONS {indexConfig: {`vector.dimensions`: toInteger($dimensions), `vector.similarity_function`: $similarity_fn}}` has no effect.} {description: `VECTOR INDEX `vector-index-name` FOR (e:Chunk) ON (e.embedding)` already exists.} {position: None} for query: 'CREATE VECTOR INDEX $name IF NOT EXISTS FOR (n:Chunk) ON n.embedding OPTIONS { indexConfig: { `vector.dimensions`: toInteger($dimensions), `vector.similarity_function`: $similarity_fn } }'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Vector index 'vector-index-name' created successfully.

Query the graph rag agent again

If you inspect the database, you should find more nodes are created in the graph for each chunk of data this time. However, given the simple structure of input, the difference is not apparent in querying.

# Create a ConversableAgent (no LLM configuration)
graph_rag_agent = ConversableAgent(
    name="buzz_agent",
    human_input_mode="NEVER",
)

# Associate the capability with the agent
graph_rag_capability = Neo4jNativeGraphCapability(query_engine)
graph_rag_capability.add_to_agent(graph_rag_agent)

# Create a user proxy agent to converse with our RAG agent
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="ALWAYS",
)

user_proxy.initiate_chat(graph_rag_agent, message="Who is the employer?")
user_proxy (to buzz_agent):

Who is the employer?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

The employer is BUZZ Co.

--------------------------------------------------------------------------------
user_proxy (to buzz_agent):

What benefits are entitled to employees?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

Employees at BUZZ Co. are entitled to several benefits, including:

1. **Health/Life Insurance:** Health and dental insurance are offered to eligible full-time and part-time employees after the first full month of employment.

2. **Social Security/Medicare/Medicaid:** BUZZ Co. participates in these programs.

3. **Workers' Compensation and Unemployment Insurance:** Employees are covered by Workers' Compensation, and BUZZ Co. participates in the District of Columbia unemployment program.

4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.

5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.

6. **Leave Benefits:** Includes paid holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.

7. **Reimbursement of Expenses:** Reimbursement for reasonable and necessary business expenses, including travel, with prior approval and receipts.

--------------------------------------------------------------------------------
user_proxy (to buzz_agent):

What responsibilities apply to employees?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

Employees at BUZZ Co. have several responsibilities, including:

1. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure can result in disciplinary action, including termination.

2. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may lead to disciplinary action.

3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.

4. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.

5. **Outside Employment:** Employees can engage in outside employment as long as it does not interfere with their job performance at BUZZ Co. or create a conflict of interest.

6. **Non-Disclosure Agreement:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.

7. **Computer and Information Security:** Employees must use BUZZ Co. computer systems primarily for business purposes, with limited personal use allowed. They must follow security procedures and not use systems for offensive or illegal activities.

8. **Internet Use:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.

--------------------------------------------------------------------------------
ChatResult(chat_id=None, chat_history=[{'content': 'Who is the employer?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'The employer is BUZZ Co.', 'role': 'user', 'name': 'buzz_agent'}, {'content': 'What benefits are entitled to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': "Employees at BUZZ Co. are entitled to several benefits, including:\n\n1. **Health/Life Insurance:** Health and dental insurance are offered to eligible full-time and part-time employees after the first full month of employment.\n\n2. **Social Security/Medicare/Medicaid:** BUZZ Co. participates in these programs.\n\n3. **Workers' Compensation and Unemployment Insurance:** Employees are covered by Workers' Compensation, and BUZZ Co. participates in the District of Columbia unemployment program.\n\n4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.\n\n5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.\n\n6. **Leave Benefits:** Includes paid holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.\n\n7. **Reimbursement of Expenses:** Reimbursement for reasonable and necessary business expenses, including travel, with prior approval and receipts.", 'role': 'user', 'name': 'buzz_agent'}, {'content': 'What responsibilities apply to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'Employees at BUZZ Co. have several responsibilities, including:\n\n1. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure can result in disciplinary action, including termination.\n\n2. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may lead to disciplinary action.\n\n3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.\n\n4. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.\n\n5. **Outside Employment:** Employees can engage in outside employment as long as it does not interfere with their job performance at BUZZ Co. or create a conflict of interest.\n\n6. **Non-Disclosure Agreement:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.\n\n7. **Computer and Information Security:** Employees must use BUZZ Co. computer systems primarily for business purposes, with limited personal use allowed. They must follow security procedures and not use systems for offensive or illegal activities.\n\n8. **Internet Use:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.', 'role': 'user', 'name': 'buzz_agent'}], summary='Employees at BUZZ Co. have several responsibilities, including:\n\n1. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure can result in disciplinary action, including termination.\n\n2. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may lead to disciplinary action.\n\n3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.\n\n4. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.\n\n5. **Outside Employment:** Employees can engage in outside employment as long as it does not interfere with their job performance at BUZZ Co. or create a conflict of interest.\n\n6. **Non-Disclosure Agreement:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.\n\n7. **Computer and Information Security:** Employees must use BUZZ Co. computer systems primarily for business purposes, with limited personal use allowed. They must follow security procedures and not use systems for offensive or illegal activities.\n\n8. **Internet Use:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.', cost={'usage_including_cached_inference': {'total_cost': 0}, 'usage_excluding_cached_inference': {'total_cost': 0}}, human_input=['What benefits are entitled to employees?', 'What responsibilities apply to employees?', 'exit'])

Another example with pdf format input

# load documents

# To use pdf data, you need to
# 1. Specify the type as PDF
# 2. Pass the path to the PDF file
input_path = "../test/agentchat/contrib/graph_rag/BUZZ_Employee_Handbook.pdf"
input_document = [Document(doctype=DocumentType.PDF, path_or_url=input_path)]
query_engine = Neo4jNativeGraphQueryEngine(
    host="bolt://172.17.0.3",  # Change
    port=7687,  # if needed
    username="neo4j",  # Change if you reset username
    password="password",  # Change if you reset password
    llm=llm,  # change to the LLM model you want to use
    embeddings=embeddings,  # change to the embeddings model you want to use
    query_llm=query_llm,  # change to the query LLM model you want to use
    embedding_dimension=3072,  # must match the dimension of the embeddings model
)

# initialize the database (it will delete any pre-existing data)
query_engine.init_db(input_document)
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Clearing the database...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Clearing all nodes and relationships in the database...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Database cleared successfully.
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Initializing the knowledge graph builders...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Building the knowledge graph...
INFO:neo4j_graphrag.experimental.pipeline.config.runner:PIPELINE_RUNNER: starting pipeline <neo4j_graphrag.experimental.pipeline.pipeline.Pipeline object at 0xffff70e60390> with run_params=defaultdict(<class 'dict'>, {'schema': {'entities': [], 'relations': [], 'potential_schema': None}, 'pdf_loader': {'filepath': '../test/agentchat/contrib/graph_rag/BUZZ_Employee_Handbook.pdf'}})
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE RANGE INDEX __entity__id IF NOT EXISTS FOR (e:__KGBuilder__) ON (e.id)` has no effect.} {description: `RANGE INDEX __entity__id FOR (e:__KGBuilder__) ON (e.id)` already exists.} {position: None} for query: 'CREATE INDEX __entity__id IF NOT EXISTS  FOR (n:__KGBuilder__) ON (n.id)'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Knowledge graph built successfully.
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Creating vector index 'vector-index-name'...
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Creating vector index 'vector-index-name'...
INFO:neo4j_graphrag.indexes:Creating vector index named 'vector-index-name'
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE VECTOR INDEX `vector-index-name` IF NOT EXISTS FOR (e:Chunk) ON (e.embedding) OPTIONS {indexConfig: {`vector.dimensions`: toInteger($dimensions), `vector.similarity_function`: $similarity_fn}}` has no effect.} {description: `VECTOR INDEX `vector-index-name` FOR (e:Chunk) ON (e.embedding)` already exists.} {position: None} for query: 'CREATE VECTOR INDEX $name IF NOT EXISTS FOR (n:Chunk) ON n.embedding OPTIONS { indexConfig: { `vector.dimensions`: toInteger($dimensions), `vector.similarity_function`: $similarity_fn } }'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Vector index 'vector-index-name' created successfully.
# Create a ConversableAgent (no LLM configuration)
graph_rag_agent = ConversableAgent(
    name="buzz_agent",
    human_input_mode="NEVER",
)

# Associate the capability with the agent
graph_rag_capability = Neo4jNativeGraphCapability(query_engine)
graph_rag_capability.add_to_agent(graph_rag_agent)

# Create a user proxy agent to converse with our RAG agent
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="ALWAYS",
)

user_proxy.initiate_chat(graph_rag_agent, message="Who is the employer?")
user_proxy (to buzz_agent):

Who is the employer?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

The employer is BUZZ Co.

--------------------------------------------------------------------------------
user_proxy (to buzz_agent):

What benefits are entitled to employees?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

Employees at BUZZ Co. are entitled to several benefits, including:

1. **Health/Life Insurance:** Offered to eligible full-time and part-time employees after the first full month of employment.
2. **Social Security/Medicare/Medicaid:** Participation in these programs.
3. **Workers' Compensation and Unemployment Insurance:** Coverage under Workers' Compensation and participation in the District of Columbia unemployment program.
4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.
5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.
6. **Leave Benefits:** Including paid holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.
7. **Reimbursement of Expenses:** For reasonable and necessary business expenses, including travel, with prior approval and receipts.

--------------------------------------------------------------------------------
user_proxy (to buzz_agent):

What responsibilities apply to employees?

--------------------------------------------------------------------------------
buzz_agent (to user_proxy):

Employees at BUZZ Co. have several responsibilities, including:

1. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may result in disciplinary action, up to termination.

2. **Overtime:** Non-exempt employees must have overtime pre-approved by the Executive Director.

3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.

4. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure will result in disciplinary action, including possible termination.

5. **Outside Employment:** Permitted as long as it does not interfere with BUZZ Co. job performance or create a conflict of interest.

6. **Non-Disclosure of Confidential Information:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.

7. **Computer and Information Security:** BUZZ Co. computer systems are for business use, with limited personal use allowed. Employees must follow security procedures and not use systems for offensive or illegal activities.

8. **Internet Acceptable Use Policy:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.

9. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.

10. **Reimbursement of Expenses:** Employees must obtain prior approval and provide receipts for reimbursement of reasonable and necessary business expenses, including travel.

--------------------------------------------------------------------------------
ChatResult(chat_id=None, chat_history=[{'content': 'Who is the employer?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'The employer is BUZZ Co.', 'role': 'user', 'name': 'buzz_agent'}, {'content': 'What benefits are entitled to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': "Employees at BUZZ Co. are entitled to several benefits, including:\n\n1. **Health/Life Insurance:** Offered to eligible full-time and part-time employees after the first full month of employment.\n2. **Social Security/Medicare/Medicaid:** Participation in these programs.\n3. **Workers' Compensation and Unemployment Insurance:** Coverage under Workers' Compensation and participation in the District of Columbia unemployment program.\n4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.\n5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.\n6. **Leave Benefits:** Including paid holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.\n7. **Reimbursement of Expenses:** For reasonable and necessary business expenses, including travel, with prior approval and receipts.", 'role': 'user', 'name': 'buzz_agent'}, {'content': 'What responsibilities apply to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'Employees at BUZZ Co. have several responsibilities, including:\n\n1. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may result in disciplinary action, up to termination.\n\n2. **Overtime:** Non-exempt employees must have overtime pre-approved by the Executive Director.\n\n3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.\n\n4. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure will result in disciplinary action, including possible termination.\n\n5. **Outside Employment:** Permitted as long as it does not interfere with BUZZ Co. job performance or create a conflict of interest.\n\n6. **Non-Disclosure of Confidential Information:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.\n\n7. **Computer and Information Security:** BUZZ Co. computer systems are for business use, with limited personal use allowed. Employees must follow security procedures and not use systems for offensive or illegal activities.\n\n8. **Internet Acceptable Use Policy:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.\n\n9. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.\n\n10. **Reimbursement of Expenses:** Employees must obtain prior approval and provide receipts for reimbursement of reasonable and necessary business expenses, including travel.', 'role': 'user', 'name': 'buzz_agent'}], summary='Employees at BUZZ Co. have several responsibilities, including:\n\n1. **Attendance and Punctuality:** Regular attendance is expected. Employees must notify their supervisor and the office manager if they are absent, late, or need to leave early. Excessive absences or tardiness may result in disciplinary action, up to termination.\n\n2. **Overtime:** Non-exempt employees must have overtime pre-approved by the Executive Director.\n\n3. **Return of Property:** Employees must return all BUZZ Co. property upon separation or request.\n\n4. **Confidentiality:** Employees must not disclose non-public information about BUZZ Co., its members, or donors. Unauthorized disclosure will result in disciplinary action, including possible termination.\n\n5. **Outside Employment:** Permitted as long as it does not interfere with BUZZ Co. job performance or create a conflict of interest.\n\n6. **Non-Disclosure of Confidential Information:** Employees must sign a non-disclosure agreement and are prohibited from unauthorized disclosure of confidential information.\n\n7. **Computer and Information Security:** BUZZ Co. computer systems are for business use, with limited personal use allowed. Employees must follow security procedures and not use systems for offensive or illegal activities.\n\n8. **Internet Acceptable Use Policy:** Internet access is for business use, and employees must not use it for illegal, offensive, or unauthorized personal activities. BUZZ Co. may monitor Internet usage.\n\n9. **Personnel Records:** Employees must promptly report changes in personnel data and maintain accurate time records.\n\n10. **Reimbursement of Expenses:** Employees must obtain prior approval and provide receipts for reimbursement of reasonable and necessary business expenses, including travel.', cost={'usage_including_cached_inference': {'total_cost': 0}, 'usage_excluding_cached_inference': {'total_cost': 0}}, human_input=['What benefits are entitled to employees?', 'What responsibilities apply to employees?', 'exit'])

Incrementally add new documents to the existing knowledge graph.

We add another document and build it into the existing graph

input_path = "../test/agentchat/contrib/graph_rag/the_matrix.txt"
input_documents = [Document(doctype=DocumentType.TEXT, path_or_url=input_path)]

_ = query_engine.add_records(input_documents)
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Building the knowledge graph...
INFO:neo4j_graphrag.experimental.pipeline.config.runner:PIPELINE_RUNNER: starting pipeline <neo4j_graphrag.experimental.pipeline.pipeline.Pipeline object at 0xffffb81cd7d0> with run_params=defaultdict(<class 'dict'>, {'schema': {'entities': [], 'relations': [], 'potential_schema': None}, 'splitter': {'text': 'Signed in\nSkip to Main Content\n Rotten Tomatoes\n\nWhat\'s the Tomatometer®?\nCritics\nMOVIES  TV SHOWS  SHOP NEW  NEWS  SHOWTIMES\nTRENDING ON RT\nFuriosa First Reviews\nMost Anticipated 2025 Movies\nBest Movies of All Time\nTV Premiere Dates\nMain image for The Matrix\nThe Matrix\nR,  Now Playing,  2h 16m,  Sci-Fi/ Action\n\n LIST\nVideos\nRotten Tomatoes is Wrong About... The Matrix Sequels\n51:31\nRotten Tomatoes is Wrong About... The Matrix Sequels\nContent collapsed.\n‘The Matrix’ Government Lobby Scene | Rotten Tomatoes’ 21 Most Memorable Moments\n2:31\n‘The Matrix’ Government Lobby Scene | Rotten Tomatoes’ 21 Most Memorable Moments\nContent collapsed.\nView more videos\nmovie poster\nTomatometer\n207 Reviews\nAudience Score\n250,000+ Ratings\nNeo (Keanu Reeves) believes that Morpheus (Laurence Fishburne), an elusive figure considered to be the most dangerous man alive, can answer his question -- What is the Matrix? Neo is contacted by Trinity (Carrie-Anne Moss), a beautiful stranger who leads him into an underworld where he meets Morpheus. They fight a brutal battle for their lives against a cadre of viciously intelligent secret agents. It is a truth that could cost Neo something more precious than his life.\nContent collapsed.\nRead More\nfandango\nNow in Theaters\nNow Playing\nBuy tickets for The Matrix\nWhere to Watch\nWhat to Know\nReviews\nCast & Crew\nMore Like This\nRelated News\nVideos\nPhotos\nMedia Info\n\nNext\nWhere To Watch\nThe Matrix\nfandango\nIn Theaters\nvudu\nFandango at Home\namazon-prime-video-us\nPrime Video\nnetflix\nNetflix\nWatch The Matrix with a subscription on Netflix, rent on Fandango at Home, Prime Video, or buy on Fandango at Home, Prime Video.\nThe Matrix\nWhat To Know\n Critics Consensus\nThanks to the Wachowskis\' imaginative vision, The Matrix is a smartly crafted combination of spectacular action and groundbreaking special effects.\n\nRead Critics Reviews\nCritics Reviews\nView All (207) Critics Reviews\n Critic\'s profile\nCritic\'s Name\nMike Clark\nPublication\nUSA Today\nTOP CRITIC\nThe review\nThough The Matrix ultimately overdoses on gloom-and-doom grunge, over-elaborate cool and especially running time, it\'s just clever enough to enable [the Wachowskis] to nix the sophomore jinx following 1996\'s Bound.\nContent collapsed.\nFresh score.\nRated: 2.5/4 •\nDate\nJul 13, 2023\nFull Review\n Critic\'s profile\nCritic\'s Name\nJoe Morgenstern\nPublication\nWall Street Journal\nTOP CRITIC\nThe review\nI know almost nothing of the intricate techniques that make The Matrix as eye-filling as it is brain-numbing, but I can tell you that... [its visuals] are wondrous to behold.\nContent collapsed.\nFresh score.\nDate\nJul 13, 2023\nFull Review\n Critic\'s profile\nCritic\'s Name\nManohla Dargis\nPublication\nL.A. Weekly\nTOP CRITIC\nThe review\nThere\'s more form than content in The Matrix, but Bill Pope\'s swooping, noir-inflected cinematography is wonderfully complemented by Owen Paterson\'s inventive production design, a great soundtrack and the best fight choreography this side of Hong Kong.\nContent collapsed.\nFresh score.\nDate\nJul 13, 2023\nFull Review\n Critic\'s profile\nCritic\'s Name\nSean Axmaker\nPublication\nStream on Demand\nThe review\nThe Wachowskis proceed to turn the world as we know it into a virtual reality landscape with a 20th century tech-noir look (lit with a sickly green hue, like the glow of an old IBM computer screen) and the physics of a video game.\nContent collapsed.\nFresh score.\nDate\nSep 9, 2023\nFull Review\n Critic\'s profile\nCritic\'s Name\nDan DiNicola\nPublication\nThe Daily Gazette (Schenectady, NY)\nThe review\nA $60 million, high-tech assault on the senses and a pretentious insult to the mind.\nContent collapsed.\nRotten score.\nDate\nJul 15, 2023\nFull Review\n Critic\'s profile\nCritic\'s Name\nChristopher Brandon\nPublication\nTNT\'s Rough Cut\nThe review\nA cyberpunk thriller that\'s so much fun to watch, it could single-handedly reboot the genre.\nContent collapsed.\nFresh score.\nDate\nJul 13, 2023\nFull Review\nRead all reviews\n\nNext\nAudience Reviews\nView All (1000+) audience reviews\nCritic\'s Name\ncasearmitage\nThe review\nTwenty five years later, it still holds up. You have to see it to believe it.\nContent collapsed.\nRated 5/5 Stars •  Rated 5 out of 5 stars\nDate\n04/04/24\nFull Review\nCritic\'s Name\nNathanael\nThe review\nOf course The Matrix is absolutely amazing, but the 4DX thing was pretty cool too!\nContent collapsed.\nRated 5/5 Stars •  Rated 5 out of 5 stars\nDate\n12/14/21\nFull Review\nCritic\'s Name\nAverage P\nThe review\nSo good that you entirely forget the nutty premise that we\'re all being kept in suspended animation wired into some kind of giant mainframe which creates more energy than it requires. Oh well, whatever. Great adventure story.\nContent collapsed.\nRated 5/5 Stars •  Rated 5 out of 5 stars\nDate\n05/23/24\nFull Review\nCritic\'s Name\nFirst name L\nThe review\nEvent cinema in at it\'s best, it\'s often mocked, equally celebrated, for a reason.\nContent collapsed.\nRated 4/5 Stars •  Rated 4 out of 5 stars\nDate\n05/14/24\nFull Review\nCritic\'s Name\nJace E\nThe review\nThe Matrix is one of the most ambitious and captivating Sci-Fi films of all time. The action is electric, the characters are strong and there are legendary moments peppered throughout. Where the film is lacking is in the actual human aspect; the romance is underdeveloped and Neo\'s life in the Matrix is superficial (why do we need a scene of his boss disciplining him?). That being said, the fight sequences are incredibly entertaining and the entire idea of the Matrix plays with your mind. I honestly fell asleep multiple times watching the film and had to go back and watch it again. From the slow motion to the muted colors, it was easy to doze off. However, once the climactic moments hit, I was enthralled. The helicopter scene is great and the final fight sequences hit hard. I\'m curious where the franchise will go from here, but this film is a brilliant start. Best Character: Tank Best Quote: "There\'s a difference between knowing the path and walking the path." - Morpheus Best Scene: The Bullet Dodge Best Piece of Score: "He\'s the One Alright"\nContent collapsed.\nRated 4/5 Stars •  Rated 4 out of 5 stars\nDate\n05/13/24\nFull Review\nCritic\'s Name\nAntonio M\nThe review\nHa fatto la storia del cinema cyberpunk. Un cult intramontabile.\nContent collapsed.\nRated 5/5 Stars •  Rated 5 out of 5 stars\nDate\n05/09/24\nFull Review\nRead all reviews\n\nNext\nCast & Crew\nLilly Wachowski thumbnail image\nLilly Wachowski\nDirector\n Lana Wachowski thumbnail image\nLana Wachowski\nDirector\n Keanu Reeves thumbnail image\nKeanu Reeves\nThomas A. Anderson\n Laurence Fishburne thumbnail image\nLaurence Fishburne\nMorpheus\n Carrie-Anne Moss thumbnail image\nCarrie-Anne Moss\nTrinity\n Hugo Weaving thumbnail image\nHugo Weaving\nAgent Smith\nContent collapsed.\nShow More Cast & Crew\nMore Like This\nView All Movies in Theaters\n The Matrix Reloaded poster\nCertified fresh score.\n74%\nFresh audience score.\n72%\nThe Matrix Reloaded\n\n WATCHLIST\nThe Matrix Revolutions poster\nRotten score.\n34%\nFresh audience score.\n60%\nThe Matrix Revolutions\n\n WATCHLIST\nDemolition Man poster\nFresh score.\n63%\nFresh audience score.\n67%\nDemolition Man\n\n WATCHLIST\nUniversal Soldier: The Return poster\nRotten score.\n5%\nRotten audience score.\n24%\nUniversal Soldier: The Return\n\n WATCHLIST\nTerminator 3: Rise of the Machines poster\nFresh score.\n70%\nRotten audience score.\n46%\nTerminator 3: Rise of the Machines\n\n WATCHLIST\n\nDiscover more movies and TV shows.\nView More\n\nNext\nRelated Movie News\nView All Related Movie News\n\n25 Memorable Movie Lines of the Last 25 Years\nContent collapsed.\n\nSterling K. Brown’s Five Favorite Films\nContent collapsed.\n\nThe Matrix vs. John Wick\nContent collapsed.\n\nNext\nVideos\nView All videos\nThe Matrix\nRotten Tomatoes is Wrong About... The Matrix Sequels\n51:31\nRotten Tomatoes is Wrong About... The Matrix Sequels\nContent collapsed.\n‘The Matrix’ Government Lobby Scene | Rotten Tomatoes’ 21 Most Memorable Moments\n2:31\n‘The Matrix’ Government Lobby Scene | Rotten Tomatoes’ 21 Most Memorable Moments\nContent collapsed.\nView more videos\n\nNext\nPhotos\nView All The Matrix photos\nThe Matrix\n\nThe Matrix photo 1\n\nThe Matrix photo 2\n\nThe Matrix photo 3\n\nThe Matrix photo 4\n\nAnthony Ray Parker as Dozer, Keanu Reeves as Thomas A. Anderson/Neo, Carrie-Anne Moss as Trinity, and Laurence Fishburne as Morpheus in Nebuchadnezzer\'s cockpit.\n\nKeanu Reeves and Carrie-Anne Moss in Warner Brothers\' The Matrix.\n\nLaurence Fishburne in Warner Brothers\' The Matrix\n\nCarrie-Anne Moss and Keanu Reeves in Warner Brothers\' The Matrix\n\nCarrie-Anne Moss in Warner Brothers\' The Matrix\n\nKeanu Reeves in Warner Brothers\' The Matrix\nView more photos\n\nNext\nMovie Info\nSynopsis\nNeo (Keanu Reeves) believes that Morpheus (Laurence Fishburne), an elusive figure considered to be the most dangerous man alive, can answer his question -- What is the Matrix? Neo is contacted by Trinity (Carrie-Anne Moss), a beautiful stranger who leads him into an underworld where he meets Morpheus. They fight a brutal battle for their lives against a cadre of viciously intelligent secret agents. It is a truth that could cost Neo something more precious than his life.\nDirector\nLilly Wachowski ,  Lana Wachowski\nProducer\nJoel Silver\nScreenwriter\nLilly Wachowski ,  Lana Wachowski\nDistributor\nWarner Bros. Pictures\nProduction Co\nSilver Pictures ,  Village Roadshow Prod.\nRating\nR (Sci-Fi Violence|Brief Language)\nGenre\nSci-Fi ,  Action\nOriginal Language\nEnglish\nRelease Date (Theaters)\nMar 31, 1999, Wide\nRerelease Date (Theaters)\nSep 22, 2023\nRelease Date (Streaming)\nJan 1, 2009\nBox Office (Gross USA)\n$171.4M\nRuntime\n2h 16m\nSound Mix\nDolby Stereo ,  DTS ,  SDDS ,  Surround ,  Dolby Digital ,  Dolby SR\nAspect Ratio\nScope (2.35:1)\nWhat to Watch\nIn Theaters\nAt Home\nTV Shows\nNow Playing\nVIEW ALL NOW PLAYING\nNo score yet.\nThe Keeper\n- -\nCertified fresh score.\nThe Crow\n85%\nNo score yet.\nThe Commandant\'s Shadow\n- -\nNo score yet.\nThe Hangman\n- -\nCertified fresh score.\nIn A Violent Nature\n90%\nFresh score.\nEzra\n75%\nComing soon\nVIEW ALL COMING SOON\nNo score yet.\nJesus Thirsts: The Miracle of the Eucharist\n- -\nNo score yet.\nQueen Tut\n- -\nNo score yet.\nThe Watchers\n- -\nNo score yet.\nBad Boys: Ride or Die\n- -\nAdvertise With Us\nHelp\nAbout Rotten Tomatoes\nWhat\'s the Tomatometer®?\nCritic Submission\nLicensing\nAdvertise With Us\nCareers\nJOIN THE NEWSLETTER\n\nGet the freshest reviews, news, and more delivered right to your inbox!\n\nFOLLOW US\n\nV3.1  Privacy Policy  Terms and Policies  Cookie Notice  California Notice  Ad Choices  Accessibility\nCopyright © Fandango. All rights reserved.\n'}})
INFO:neo4j_graphrag.experimental.components.lexical_graph:Document node not created in the lexical graph because no document metadata is provided
INFO:neo4j.notifications:Received notification from DBMS server: {severity: INFORMATION} {code: Neo.ClientNotification.Schema.IndexOrConstraintAlreadyExists} {category: SCHEMA} {title: `CREATE RANGE INDEX __entity__id IF NOT EXISTS FOR (e:__KGBuilder__) ON (e.id)` has no effect.} {description: `RANGE INDEX __entity__id FOR (e:__KGBuilder__) ON (e.id)` already exists.} {position: None} for query: 'CREATE INDEX __entity__id IF NOT EXISTS  FOR (n:__KGBuilder__) ON (n.id)'
INFO:autogen.agentchat.contrib.graph_rag.neo4j_native_graph_query_engine:Knowledge graph built successfully.

Let’s query the graph about both old and new documents

# Create a ConversableAgent (no LLM configuration)
graph_rag_agent = ConversableAgent(
    name="new_agent",
    human_input_mode="NEVER",
)

# Associate the capability with the agent
graph_rag_capability = Neo4jNativeGraphCapability(query_engine)
graph_rag_capability.add_to_agent(graph_rag_agent)

# Create a user proxy agent to converse with our RAG agent
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="ALWAYS",
)

user_proxy.initiate_chat(graph_rag_agent, message="Who is the employer?")
user_proxy (to new_agent):

Who is the employer?

--------------------------------------------------------------------------------
new_agent (to user_proxy):

The employer is BUZZ Co.

--------------------------------------------------------------------------------
user_proxy (to new_agent):

What benefits are entitled to employees?

--------------------------------------------------------------------------------
new_agent (to user_proxy):

Employees at BUZZ Co. are entitled to several benefits, including:

1. **Health/Life Insurance:** Offered to eligible full-time and part-time employees after the first full month of employment.
2. **Social Security/Medicare/Medicaid:** Participation in these programs.
3. **Workers' Compensation and Unemployment Insurance:** Coverage under Workers' Compensation and participation in the District of Columbia unemployment program.
4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.
5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.
6. **Leave Benefits:** Including holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.
7. **Reimbursement of Expenses:** For reasonable and necessary business expenses, including travel, with prior approval and receipts.

--------------------------------------------------------------------------------
user_proxy (to new_agent):

List the actors in the Matirx.

--------------------------------------------------------------------------------
new_agent (to user_proxy):

The actors in "The Matrix" include:

1. Keanu Reeves as Thomas A. Anderson/Neo
2. Laurence Fishburne as Morpheus
3. Carrie-Anne Moss as Trinity
4. Hugo Weaving as Agent Smith
5. Anthony Ray Parker as Dozer

--------------------------------------------------------------------------------
ChatResult(chat_id=None, chat_history=[{'content': 'Who is the employer?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'The employer is BUZZ Co.', 'role': 'user', 'name': 'new_agent'}, {'content': 'What benefits are entitled to employees?', 'role': 'assistant', 'name': 'user_proxy'}, {'content': "Employees at BUZZ Co. are entitled to several benefits, including:\n\n1. **Health/Life Insurance:** Offered to eligible full-time and part-time employees after the first full month of employment.\n2. **Social Security/Medicare/Medicaid:** Participation in these programs.\n3. **Workers' Compensation and Unemployment Insurance:** Coverage under Workers' Compensation and participation in the District of Columbia unemployment program.\n4. **Retirement Plan:** Available to eligible full-time and part-time employees (21+ years old), with BUZZ Co. contributing after one year of vested employment.\n5. **Tax Deferred Annuity Plan:** Offered through payroll deduction at the employee's expense.\n6. **Leave Benefits:** Including holidays, vacation, sick leave, personal leave, military leave, civic responsibility leave, parental leave, bereavement leave, and extended personal leave.\n7. **Reimbursement of Expenses:** For reasonable and necessary business expenses, including travel, with prior approval and receipts.", 'role': 'user', 'name': 'new_agent'}, {'content': 'List the actors in the Matirx.', 'role': 'assistant', 'name': 'user_proxy'}, {'content': 'The actors in "The Matrix" include:\n\n1. Keanu Reeves as Thomas A. Anderson/Neo\n2. Laurence Fishburne as Morpheus\n3. Carrie-Anne Moss as Trinity\n4. Hugo Weaving as Agent Smith\n5. Anthony Ray Parker as Dozer', 'role': 'user', 'name': 'new_agent'}], summary='The actors in "The Matrix" include:\n\n1. Keanu Reeves as Thomas A. Anderson/Neo\n2. Laurence Fishburne as Morpheus\n3. Carrie-Anne Moss as Trinity\n4. Hugo Weaving as Agent Smith\n5. Anthony Ray Parker as Dozer', cost={'usage_including_cached_inference': {'total_cost': 0}, 'usage_excluding_cached_inference': {'total_cost': 0}}, human_input=['What benefits are entitled to employees?', 'List the actors in the Matirx.', 'exit'])