Natural Language Query to GraphQL

Suchismita Sahu
5 min readJan 6, 2025

--

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. I aimed 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.

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.

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

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"]

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""")

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,
},
)

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]
"""

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

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)

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.

Complete Code

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

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

st.markdown(
"""
<style>
.app-header { visibility: hidden; }
.css-18e3th9 { padding-top: 0; padding-bottom: 0; }
.css-1d391kg { padding-top: 1rem; padding-right: 1rem; padding-bottom: 1rem; padding-left: 1rem; }
</style>
""",
unsafe_allow_html=True,
)

image = Image.open("./logo/lyzr-logo.png")
st.image(image, width=150)

# App title and introduction
st.title("NL2GraphQL")
st.markdown("Built using Lyzr SDK🚀")
st.markdown("Welcome to NL2GraphQL! Translate natural language prompts into accurate GraphQL queries effortlessly.")
input = st.text_input("Please enter your natural language prompt:",placeholder=f"""Type here""")

open_ai_text_completion_model = OpenAIModel(
api_key=st.secrets["apikey"],
parameters={
"model": "gpt-4-turbo-preview",
"temperature": 0.2,
"max_tokens": 1500,
},
)


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.

Follow these steps for SUCCESSFUL execution:

1. Carefully READ and UNDERSTAND the natural language prompt provided by the user, identifying KEY COMPONENTS such as requested entities, attributes, and relationships.

2. CONVERT these components into a structured GRAPHQL query, paying close attention to SYNTAX and SEMANTICS that reflect the user’s intent.

3. Before DISPLAYING the GRAPHQL query, VERIFY its relevance by cross-referencing it with the original user input to ENSURE ACCURACY.

You MUST provide an EXPLANATION for each segment of your query to help users understand how their natural language input was interpreted.

"""

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

if st.button("Convert"):
solution = generation(input)
st.markdown(solution)

with st.expander("ℹ️ - About this App"):
st.markdown("""
This app uses Lyzr Automata Agent . For any inquiries or issues, please contact Lyzr.

""")
st.link_button("Lyzr", url='https://www.lyzr.ai/', use_container_width=True)
st.link_button("Book a Demo", url='https://www.lyzr.ai/book-demo/', use_container_width=True)
st.link_button("Discord", url='https://discord.gg/nm7zSyEFA2', use_container_width=True)
st.link_button("Slack",
url='https://join.slack.com/t/genaiforenterprise/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw',
use_container_width=True)

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.

--

--

Suchismita Sahu
Suchismita Sahu

Written by Suchismita Sahu

Working as a Technical Product Manager at Jumio corporation, India. Passionate about Technology, Business and System Design.

No responses yet