Docs Menu
Docs Home
/
Atlas
/ / /

Query Atlas with Natural Language Using LangChain and LangGraph

You can use the LangChain MongoDB integration to run natural language MongoDB queries. In this tutorial, you build a basic AI agent that converts natural language to MQL by using the ReAct Agent framework and the MongoDB Agent Toolkit.

Work with a runnable version of this tutorial as a Python notebook.

  • Have a Atlas cluster and user.

  • Add the Restaurants sample dataset to your Atlas cluster.

  • Have an OpenAI API key.

  • Run the following to install required dependencies:

    pip install langchain-mongodb langchain-openai langgraph

This agent leverages a predefined set of tools with which it executes a step-by-step plan defined by a LLM. When a user submits a prompt to the agent, the agent sends a request to the LLM that details its available tools and the user's desired outcome. With that information, the LLM generates a specific series of steps that leverage the agent's available toolset to achieve the user's desired outcome.

The agent then executes the steps and confirms success, or executes updated steps as needed, by sending intermediate results back to the LLM for analysis. And finally, the system's results are returned to the user.

1

In your terminal, populate and run the following command to set the required environment variable.

export OPENAI_API_KEY=<your-openai-api-key>
2

Copy and paste the following into a local file called natural_language_to_mql.py.

Key Points

  • self.toolkit, the tools that the agent can use, is an instance of the MongoDB Toolkit.

  • self.agent, the agent itself, is an instance of the ReAct Agent framework, which takes self.toolkit as a parameter.

1import os
2from langchain_openai import ChatOpenAI
3from langgraph.prebuilt import create_react_agent
4from langchain_mongodb.agent_toolkit import (
5 MONGODB_AGENT_SYSTEM_PROMPT,
6 MongoDBDatabase,
7 MongoDBDatabaseToolkit,
8)
9
10ATLAS_CONNECTION_STRING = '<connection-string>'
11ATLAS_DB_NAME = 'sample_restaurants'
12NATURAL_LANGUAGE_QUERY = 'Find all restaurants that serve hamburgers.'
13
14class NaturalLanguageToMQL:
15 def __init__(self):
16 self.llm = ChatOpenAI(model="gpt-4o-mini", timeout=60)
17 self.system_message = MONGODB_AGENT_SYSTEM_PROMPT.format(top_k=5)
18 self.db_wrapper = MongoDBDatabase.from_connection_string(
19 ATLAS_CONNECTION_STRING,
20 database=ATLAS_DB_NAME)
21 self.toolkit = MongoDBDatabaseToolkit(db=self.db_wrapper, llm=self.llm)
22 self.agent = create_react_agent(
23 self.llm,
24 self.toolkit.get_tools(),
25 state_modifier=self.system_message)
26 self.messages = []
27
28 def convert_to_mql_and_execute_query(self, query):
29 # Start the agent with the agent.stream() method
30 events = self.agent.stream(
31 {"messages": [("user", query)]},
32 stream_mode="values",
33 )
34 # Add output (events) from the agent to the self.messages list
35 for event in events:
36 self.messages.extend(event["messages"])
37
38 def print_results(self):
39 # Print the the end-user's expected output from
40 # the final message produced by the agent.
41 print(self.messages[-1].content)
42
43def main():
44 converter = NaturalLanguageToMQL()
45 converter.convert_to_mql_and_execute_query(NATURAL_LANGUAGE_QUERY)
46 converter.print_results()
47
48if __name__ == '__main__':
49 main()
3

Replace the <connection-string> placeholder value with the SRV connection string for your Atlas cluster.

Your connection string should use the following format:

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

From the directory in which you saved the local file, run the following command. Your results might vary.

python natural_language_to_mql.py
Here are some restaurants that serve hamburgers:
1. **Wendy's**
- Address: 469 Flatbush Avenue, Brooklyn, NY 11225
- Borough: Brooklyn
2. **White Castle**
- Address: 531 Myrtle Avenue, Brooklyn, NY 11205
- Borough: Brooklyn
3. **McDonald's**
- Address: 75-50 101 Avenue, Queens, NY 11416
- Borough: Queens
4. **McDonald's**
- Address: 943 Flatbush Avenue, Brooklyn, NY 11226
- Borough: Brooklyn
5. **McDonald's**
- Address: 395 Flatbush Avenue Extension, Brooklyn, NY 11201
- Borough: Brooklyn
Let me know if you'd like more details or additional results!

Back

GraphRAG

On this page