DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building NL2MongoDB with Lyzr SDK

In today’s data-driven world, MongoDB stands as a cornerstone for managing vast volumes of data with flexibility and scalability. However, despite its power, crafting efficient MongoDB queries often presents a significant hurdle for developers. The intricate syntax and nuanced query structures can lead to frustration and errors, particularly when translating user requirements from natural language into MongoDB commands.

Image description

Enter Lyzr NL2MongoDB, a groundbreaking tool designed to revolutionize the way developers interact with MongoDB databases. Powered by state-of-the-art AI models and cutting-edge natural language processing techniques, Lyzr NL2MongoDB simplifies the process of translating user input into precise MongoDB queries, bridging the gap between human language and machine commands effortlessly.

Why use Lyzr SDK’s?

With Lyzr SDKs, crafting your own GenAI application is a breeze, requiring only a few lines of code to get up and running swiftly.[

Checkout the Lyzr SDK’s](https://docs.lyzr.ai/homepage)

Lets get Started!

Create a new file app.py and use that

import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent, Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
from lyzr_automata.tasks.task_literals import InputType, OutputType
import os
Enter fullscreen mode Exit fullscreen mode

This code is a Streamlit application that utilizes Lyzr Automata, a Python package for automating tasks. It imports necessary modules from Streamlit and Lyzr Automata, including an AI model from OpenAI. It also imports the PIL library for image processing. The code defines an interface where users can input natural language queries. These queries are then translated into MongoDB commands using an AI translation model. The translated commands are optimized and presented back to the user.

Subsequently, it initializes the OpenAI API key using Streamlit’s secrets management. By accessing the specific key stored securely in Streamlit’s secrets, where the OpenAI API key is securely stored, it replaces the placeholder “OPENAI_API_KEY”. This ensures secure access to the OpenAI API within the Streamlit application.

# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode
open_ai_text_completion_model = OpenAIModel(
    api_key=st.secrets["apikey"],
    parameters={
        "model": "gpt-4-turbo-preview",
        "temperature": 0.2,
        "max_tokens": 1500,
    },
)
Enter fullscreen mode Exit fullscreen mode

This line of code initializes an instance of the OpenAIModel class from the Lyzr Automata package. It configures the model with the API key obtained from Streamlit secrets, granting access to OpenAI’s services. The parameters specify the settings for the AI model, including the specific model to use (“gpt-4-turbo-preview”), the temperature parameter for controlling the randomness of the model’s predictions, and the maximum number of tokens allowed in the model’s output (set to 1500 tokens).

def code_translation(code):
    translation_agent = Agent(
        role="MongoDB QUERY TRANSLATOR expert",
        prompt_persona=f"Your task is to convert the natural language user input to MongoDB query effectively."
    )

    prompt = f"""
    You are an Expert MONGODB QUERY TRANSLATOR. Your task is to INTERPRET natural language user input and CONVERT it into precise MongoDB queries. You MUST ensure that the resulting code accurately reflects the user's intent, is SYNTACTICALLY CORRECT.

    Here is how you should approach this TASK:

    1. LISTEN carefully to the USER'S INPUT and identify KEY TERMS such as collection names, field names, and desired operations (e.g., find, insert, update).

    2. BREAK DOWN the request into logical components that correspond to MongoDB query structure: filter criteria, projection, sorting order, etc.

    3. TRANSLATE these components into a MongoDB query using the appropriate syntax for commands and operators.

    4. VERIFY that each part of the query aligns with MongoDB's best practices for efficiency and performance.

    5. PRESENT the query back to the user with a step-by-step EXPLANATION of each segment to ensure they grasp how it fulfills their request.


    """
Enter fullscreen mode Exit fullscreen mode

This function code_translation defines a process for translating natural language queries into MongoDB commands. It begins by creating an Agent object representing an expert MongoDB query translator, specifying the role and persona for the translation task. Then, it sets up a prompt containing instructions for the translation task, guiding the translator on how to interpret user input and convert it into precise MongoDB queries.


    translation_task = Task(
        name="MongoDB Translation",
        model=open_ai_text_completion_model,
        agent=translation_agent,
        instructions=prompt,
        default_input=code,
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
    ).execute()

    return translation_task 

if st.button("Convert"):
    solution = code_translation(code)
    st.markdown(solution)
Enter fullscreen mode Exit fullscreen mode

In these lines of code, a Task object named "MongoDB Translation" is created. This task involves using the open_ai_text_completion_model to translate natural language queries into MongoDB commands. The task is assigned to the translation_agent, which represents an expert MongoDB query translator.

The instructions parameter contains the prompt guiding the translation process, and the default_input parameter provides the natural language query to be translated. The output_type and input_type parameters specify the types of input and output expected for the task. Finally, the execute() method is called on the Task object to perform the translation.

When the user clicks the “Convert” button in the Streamlit interface, the code_translation function is invoked with the user-provided natural language query as input. The function executes the translation task, generating a solution containing the translated MongoDB commands.

Lyzr NL2MongoDB revolutionizes the way developers interact with MongoDB databases, making query generation intuitive and accessible. By leveraging the power of AI, Lyzr NL2MongoDB empowers developers to unleash the full potential of MongoDB without being bogged down by syntax intricacies.

App link: https://nl2mongo-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/mongodb_translation

Connect with Lyzr
To learn more about Lyzr and its SDK’s, visit our website or get in touch with our team:

Website: Lyzr.ai
Book a Demo: Book a Demo
Discord: Join our Discord community
Slack: Join our Slack channel

Top comments (0)