DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building a NL2GraphQL using Lyzr SDK

As technology continues to evolve, the need for seamless communication between humans and machines becomes increasingly crucial. In the realm of databases, particularly GraphQL, translating human intent into machine-readable queries can often be challenging. Here at Lyzr, we aim to bridge that gap with our innovative application, NL2GraphQL. Built using the Lyzr SDK, this app effortlessly converts natural language prompts into accurate GraphQL queries, making database interactions smoother than ever before.

Image description

GraphQL, a query language for APIs, provides a powerful and flexible way to interact with your data. However, constructing GraphQL queries requires a certain level of expertise, which not everyone possesses. NL2GraphQL is designed to democratize access to GraphQL by allowing users to input natural language prompts and receive precise GraphQL queries in return. Whether you’re a developer looking to save time or a non-technical user needing to access data, NL2GraphQL is here to help.

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

Lets get Started!

Create an app.py file

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

The code sets up a Streamlit web application for translating natural language prompts to GraphQL queries using Lyzr Automata and OpenAI’s GPT-4-turbo model. It imports necessary libraries, sets up the OpenAI API key, adjusts CSS styles for the app’s appearance, displays a logo, and introduces the app with a title and input field. An OpenAIModel instance is configured, and a function (generation) is defined to process user input into GraphQL queries.

# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode

This line sets the OpenAI API key as an environment variable, retrieving it securely from Streamlit’s secrets for authentication.


input = st.text_input("Please enter your natural language prompt:",placeholder=f"""Type here""")
Enter fullscreen mode Exit fullscreen mode

This line creates a text input field using Streamlit’s text_input function, prompting the user to enter their natural language prompt.

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 segment initializes an instance of the OpenAIModel class, which will be used to interact with OpenAI’s GPT-4-turbo-preview model. It requires an API key, retrieved from Streamlit’s secrets management using st.secrets["apikey"]. Additionally, it specifies parameters for the model, including the model type ("gpt-4-turbo-preview"), the temperature for generating text (set to 0.2 for moderate creativity), and the maximum number of tokens in the generated text (limited to 1500 to prevent overly lengthy responses).

def generation(input):
    generator_agent = Agent(
        role=" Expert GRAPH DATABASE ENGINEER and ANALYST",
        prompt_persona=f"Your task is to TRANSLATE a natural language prompt into the corresponding GRAPHQL query, ensuring that it FULLY CAPTURES the user's intent expressed in natural language.")

    prompt = f"""
You are an Expert GRAPH DATABASE ENGINEER and ANALYST. Your task is to TRANSLATE a natural language prompt into the corresponding GRAPHQL query, ensuring that it FULLY CAPTURES the user's intent expressed in natural language.
[Prompts here]
 """
Enter fullscreen mode Exit fullscreen mode

The generation function is designed to facilitate the translation of natural language prompts into GraphQL queries. It begins by creating an Agent instance named generator_agent, which is configured with a specific role as an “Expert GRAPH DATABASE ENGINEER and ANALYST”. The agent is also provided with a prompt persona, specifying the task: to translate a natural language prompt into a corresponding GraphQL query while ensuring it fully captures the user’s intent.

A prompt string is then constructed, outlining the task in detail. It emphasizes the role of the agent and the importance of accurately translating user prompts into GraphQL queries that reflect the user’s intentions. This prompt serves as a guide for the agent’s processing of natural language input.

    generator_agent_task = Task(
        name="Generation",
        model=open_ai_text_completion_model,
        agent=generator_agent,
        instructions=prompt,
        default_input=input,
        output_type=OutputType.TEXT,
        input_type=InputType.TEXT,
    ).execute()

    return generator_agent_task 
Enter fullscreen mode Exit fullscreen mode

In this code snippet, a task titled “Generation” is initiated using the Task class from the Lyzr Automata framework. It involves configuring the task with specific parameters, including the task name, the OpenAI model to be utilized, the agent for handling the task (generator_agent), prompt instructions, default input (likely representing the user’s natural language prompt), and specifications for the input and output types (text input and output).

Subsequently, the task is executed by calling the execute() method on the task object. This triggers the processing of the user’s input by the agent and the OpenAI model, resulting in the generation of a GraphQL query based on the provided input and instructions.

Finally, the function returns the resulting generator_agent_task, which presumably encapsulates the generated GraphQL query. This returned value can then be further processed or displayed as needed.

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

Upon clicking the “Convert” button, the function generation(input) is invoked with the user's input. This input undergoes processing to generate a GraphQL query. The resulting query, stored in the solution variable, is then presented within the app interface using Streamlit's markdown function.

NL2GraphQL is more than just a tool; it’s a step towards making complex database queries accessible to everyone. Whether you’re querying a database for development purposes or extracting critical information for decision-making, NL2GraphQL simplifies the process. Try it out and experience the ease of translating your natural language prompts into precise GraphQL queries.

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

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

For any inquiries or issues, please contact Lyzr. You can learn more about Lyzr and their offerings through the following links:

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

Top comments (0)