DEV Community

Akhil Srivastava
Akhil Srivastava

Posted on

How to get response in JSON from Gemini API

If you are creating an AI agent and any SaaS tool, and want to use an AI LLM model like Gemini to make your product very powerful, then this article is for you.

When you are working with an AI model then you need to understand prompt engineering in simple word prompt engineering is giving a command to AI model to understand the requirement and give you the extact solution. Now if you are working with AI then you have to explain AI in the best possible way so that it may give you the solution accodingly.

It very easy right

Like if you want that Gemini return the solution in JSON then you have to type

Give me the top 10 news in new york, USA. Format the response and return in JSON

So her basically you are giving command then give the top 10 news in JSON. then Gemini will do this for you.

Image description

Here is the image you can check.

and If you are working with node js then you have to use one package name that is

npm i @google/generative-ai

This is an official package by google in node js

You can create function like

const generateAiResponse = () => {
  if (!process.env.GEMINI_AI_API_KEY) {
    console.error('GENERATIVE_AI_API_KEY is not defined');
    return;
  }
const genAI = new GoogleGenerativeAI(process.env.GEMINI_AI_API_KEY);
// add the model of gemini which you wan to use
  const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
  const result = await model.generateContent(prompt);

  const responseText = await result.response.text();
  console.log("Parsed JSON Response:", responseText);
  return responseText;
}
Enter fullscreen mode Exit fullscreen mode

Hope this article helped you in your research if you really liked it then click on the like button.

For hiring me as your developer you can connect me on gmail: luvprogramming@gmail.com

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post