How to Integrate Neo4j with OpenAI's GPT Assistants
Tags: neo4j, openai, gptassistanttools, graphdatabases
Published: 2023-12-01 20:56:00

---
title: "How to Integrate Neo4j with OpenAI's GPT Assistants"
published: true
description: "This detailed guide walks you through setting up the example 'GraphKnowledgeBot', an OpenAI Assistant that can interact with Neo4j graph databases. It encompasses everything from initial setup and application execution, to mastering the assistant for cutting-edge AI queries. Gain the skills to combine the analytical prowess of GPT-4 with Neo4j for intelligent data querying, offering an essential toolkit for developers eager to combine AI with graph database technologies."
tags: ["Neo4j", "OpenAI", "GPTAssistantTools", "GraphDatabases"]
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
published_at: 2023-12-01 20:56 +0000
---
![Blog post cover image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hqvz3a6hx4o71ess805p.jpg)

This blog post offers a gentle introduction to integrating Neo4j with GPT Assistants, setting the stage for exploring more sophisticated applications, especially in light of Neo4j's recent [strategic collaboration with AWS](https://neo4j.com/press-releases/neo4j-aws-bedrock-integration/). This partnership enhances the potential for advanced AI queries by integrating knowledge graphs with the power of AWS, providing a foundation for more complex use cases.

You'll learn how a knowledge graph, implemented with Neo4j, can ground an LLM (Large Language Model) in factual truth, enhancing the accuracy, transparency, and explainability of AI results. This integration is pivotal in diverse fields, from healthcare personalization to e-commerce recommendation systems, showcasing its broad applicability and transformative potential.

The complete, runnable code for this blog post is available at the [companion GitHub repository](https://github.com/stephenc222/example-openai-assistants-neo4j-integration).

## Setting Up Your Environment

Let's first cover the prerequisites that we need for this tutorial.

### Prerequisites

- Node.js `v20` or higher
- [Docker](https://www.docker.com/get-started/) installed on your system
- [OpenAI API key](https://platform.openai.com/api-keys)

### Installation Steps

1. **Clone the Repository**: Obtain the code by cloning [this repository](https://github.com/stephenc222/example-openai-assistants-neo4j-integration) to your local environment.
2. **Install Dependencies**: Run `npm install` at the project root to install necessary packages.
3. **Environment Variables**: Set up a `.env` file as per the `example.env` provided, ensuring you have your Neo4j database credentials and OpenAI API key correctly inputted.

## Running the Application

Next, we'll cover how to start the example application, and afterwards we'll cover briefly how the Neo4j integration with OpenAI Assistants works.

### Starting the Application

1. **Docker Container**: Initialize your Neo4j database in a Docker container using `sh build.sh` followed by `sh start.sh` to start it.
2. **Start the Application**: Run `npm start` in a separate terminal. This will bring the app online, connecting it to your Neo4j database and creating an OpenAI Assistant, running through an example user interaction, and then exit.

## Code Breakdown: Integrating Neo4j with OpenAI's GPT Assistants

Here are the key components of this example project:

- `GraphDB Class`: Manages interactions with the Neo4j database, including initialization, query execution, and closing connections.
- `OpenAI GPT Assistant`: This integrates the OpenAI GPT Assistant API to create the `GraphKnowledgeBot`, which processes user queries and communicates with Neo4j through a `graphSearch` [Tool](https://platform.openai.com/docs/assistants/tools).

### GraphDB Class

This section of the code defines the `GraphDB` class, responsible for managing interactions with the Neo4j graph database. Key functions include:

- **Initialization (`initDB`)**: Reading and executing Cypher statements from `seed.cyp` to seed the database.
- **Graph Search (`graphSearch`)**: Running a given Cypher query and returning results. This method on a `GraphDB` instance is passed directly as the Tool for the Assistant to use.
- **Closing Database (`closeDB`)**: Shutting down the session and driver connection.

### Understanding and Integrating GraphKnowledgeBot with OpenAI

In this section, I'll briefly outline the inner workings of `GraphKnowledgeBot`, our example custom GPT Assistant, and its integration using the OpenAI GPT Assistant API.

#### Functionality of GraphKnowledgeBot

`GraphKnowledgeBot` is designed to interpret and respond to user queries by interacting with the Neo4j database. It operates in three main steps:

1. **Query Parsing**: The assistant initially understands the context and necessary information from your query.
2. **Cypher Query Formulation**: Leveraging [Cypher](https://neo4j.com/docs/getting-started/cypher-intro/), the assistant formulates a query to retrieve the relevant data from the Neo4j database.
3. **Result Presentation**: It then presents the results in an easily understandable format, ensuring clarity and precision in the information relayed.

#### Integration Process with OpenAI

The creation of `GraphKnowledgeBot` involves integrating it with the OpenAI GPT Assistant API, enabling it to process and respond to queries effectively.

- **OpenAI Client Setup**: The process begins with initializing the OpenAI client using your OpenAI API key. This is crucial for establishing a connection between the custom GPT Assistant and OpenAI’s API.
- **User Prompt**: For demonstration purposes, a predefined user query is set up. This serves as a basis for illustrating how `GraphKnowledgeBot` processes and responds to inquiries.
- **Instructions for GraphKnowledgeBot**: Detailed instructions are embedded within the GPT Assistant, guiding it on how to accurately process queries using the `graph_search` tool. This includes understanding the query context, formulating appropriate Cypher queries, and presenting the results back to the user.

### The Main Function

This `main` function orchestrates the entire process:

- **Initializing GraphDB**: Setting up the database connection.
- **Creating GPT-4 Assistant**: Configuring the assistant with specific instructions and tool for Neo4j interaction.
- **Handling Queries**: Managing user queries and GPT Assistant responses.
- **Tool Execution**: Running the `graph_search` function as required by the assistant.
- **Error Handling**: Catching and logging any errors encountered during execution.

This setup ensures effective integration between Neo4j and our OpenAI's GPT Assistant, enabling sophisticated AI-driven queries on graph databases, giving you an example to model after for your own applications using GPT Assistants and Neo4j.

## Conclusion

The GraphKnowledgeBot is a fusion of Neo4j's graph database capabilities and OpenAI's GPT Assistants, designed to facilitate AI queries backed by a graph database.

This tutorial has walked you through the process of setting up and utilizing this graph search tool, from establishing a Neo4j database environment and integrating the OpenAI GPT-4 model, to handling complex queries with natural language processing.

With this knowledge, you are now equipped to create applications that not only simplify complex database queries but also leverage the latest advancements in AI and graph database technologies for more accurate, transparent, and contextually rich data interactions.