DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Integrate Spring With Open AI
  • Boomi Unveils Vision for Intelligent Integration and Automation at Boomi World 2024
  • Instant App Backends With API and Logic Automation
  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS

Trending

  • Top Book Picks for Site Reliability Engineers
  • DGS GraphQL and Spring Boot
  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Ethical AI in Agile
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Unlock AI Power: Generate JSON With GPT-4 and Node.js for Ultimate App Integration

Unlock AI Power: Generate JSON With GPT-4 and Node.js for Ultimate App Integration

Discover how to effectively integrate OpenAI’s API with Node.js, generating JSON outputs that enhance app functionality and leverage advanced AI technology.

By 
Pradeep kumar Saraswathi user avatar
Pradeep kumar Saraswathi
·
Aug. 21, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.6K Views

Join the DZone community and get the full member experience.

Join For Free

Generating well-structured JSON outputs can be a complex task, especially when working with large language models (LLMs). This article explores generating JSON outputs generated from LLMs with an example of using a Node.js-powered web application.

Large Language Models (LLMs)

LLMs are sophisticated AI systems designed to comprehend and produce human-like text, capable of handling tasks such as translation, summarization, and content creation. Models like GPT (Model by Open AI), BERT, and Claude have been instrumental in advancing natural language processing, making them valuable tools for chatbots and other AI-driven applications.

JavaScript Object Notation (JSON) 

JSON is a lightweight data format that's easy to read and write, both for people and computers. It organizes data into key/value pairs (objects) and ordered lists (arrays) using a text format that, while based on JavaScript, is compatible with many programming languages. JSON is commonly employed for data exchange between web servers and applications and is also popular for configuration files and storing structured data.

Open AI API

OpenAI API enables developers to integrate advanced AI functionalities into their applications, products, and services by providing access to OpenAI's state-of-the-art language models and other AI technologies.

The API follows a RESTful design, with requests and responses formatted in JSON. It supports numerous programming languages, aided by both official and community-built libraries. Pricing is usage-based, calculated in tokens (about four characters per token), with different costs for various models. Regular updates add new models and capabilities, with developers starting by acquiring an API key. Visit OpenAI's API platform and sign up or log in.

Here is an example web application powered by Node.js using Open AI API. A Node.js server script running is a web application, taking input from a user and calling Open AI API to get results from the LLM.

JavaScript
 
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;


app.use(express.static('public'));
app.use(express.json());

app.post('/api/fetch', async (req, res) => {
    try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4-turbo",
            messages: [{ role: "system", content: "You are a helpful assistant." }, { role: "user", content: req.body.prompt }]
        }, {
            headers: {
                'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        const messageContent = response.data.choices[0].message.content;
        res.json({ message: messageContent });

    } catch (error) {
        res.status(500).json({ error: 'Failure to get response from OpenAI', details: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});


The above code runs the web app server, but whenever the user enters the query, the response is returned in text format. Here is how it looks when integrated with the User Interface that asks the user for text.
Text Response from Open AI API using gpt-4-turbo

Text Response from Open AI API using gpt-4-turbo 

It would have been helpful if the Open AI API had responded using JSON with location details which would allow the User Interface to be more intuitive and actionable so that seamless integrations with other applications would be helpful for the user.

Open AI API JSON Response Format

Open AI API supports the response_format parameter in API, where the type can be defined.

JavaScript
 
response_format: { type: "json_object" }


JavaScript
 
  const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4-turbo",
            response_format: { type: "json_object" },
            messages: [{ role: "system", content: "You are a helpful assistant. return results in json format" }, { role: "user", content: req.body.prompt }]
        }, {
            headers: {
                'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
                'Content-Type': 'application/json'
            }
        });


Improving the previous code with response format to be a JSON object will look as follows. However, just modifying the response format will not return results in JSON. The messages passed in Open AI API should convey the JSON format to be returned.

Here is the modified code which will return results in JSON format:

JavaScript
 
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;


app.use(express.static('public'));
app.use(express.json());

app.post('/api/fetch', async (req, res) => {
    try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4-turbo",
            response_format: { type: "json_object" },
            messages: [{ role: "system", content: "You are a helpful assistant. return results in json format" }, { role: "user", content: req.body.prompt }]
        }, {
            headers: {
                'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        const messageContent = response.data.choices[0].message.content;
        res.json({ message: messageContent });

    } catch (error) {
        res.status(500).json({ error: 'Failure to get response from OpenAI', details: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`Web app Server running on http://localhost:${PORT}`);
    console.log(`Using OpenAI API Key: ${process.env.OPENAI_API_KEY}`);
});


The above code runs the web app server, but whenever the user enters the query, the response is returned in JSON format as shown below, which would allow parsing the JSON response in the user interface and then integrating with third-party widgets to provide actionable User Interfaces.

Text Response from Open AI API using gpt-4-turbo

Text Response from Open AI API using gpt-4-turbo

Open AI API JSON Response With Function Calling

Function calling is a powerful method for generating structured JSON responses. It lets developers define specific functions with preset parameters and return types. This helps the language model understand the function's purpose and produce responses that fit the required structure. By narrowing down the output to match the expected format, this technique boosts both accuracy and consistency in API interactions.

Here is the modified version of the previous code using function calling:

JavaScript
 
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;


app.use(express.static('public'));
app.use(express.json());

app.post('/api/fetch', async (req, res) => {
    try {
        const tools = [
            {
              "type": "function",
              "function": {
                "name": "get_places_in_city",
                "description": "Get the places to visit in city",
                "parameters": {
                  "type": "object",
                  "properties": {
                    "name": {
                      "type": "string",
                      "description": "Name of the place",
                    },
                    "description": {
                        "type": "string", 
                        "description": "description of the place",
                    },
                    "type":{
                        "type": "string", 
                        "description": "type of the place",
                    }
                  },
                  "required": ["name","description","type" ],
                  additionalProperties: false
                },
              }
            }
        ];
        //const func = {"role": "function", "name": "get_places_in_city", "content": "{\"name\": \"\", \"description\": \"\", \"type\": \"\"}"};
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4o",
            messages: [{ role: "system", content: "You are a helpful assistant. return results in json format" }, { role: "user", content: req.body.prompt }],
            tools: tools
        }, {
            headers: {
                'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        console.error('Error in response of OpenAI API:', response.data.choices[0].message? JSON.stringify(response.data.choices[0].message, null, 2) : error.message);
        const toolCalls = response.data.choices[0].message.tool_calls;
        let messageContent = '';
        if(toolCalls){
            toolCalls.forEach((functionCall)=>{
                messageContent += functionCall.function.arguments;
            });
        }
        res.json({ message: messageContent });

    } catch (error) {
        res.status(500).json({ error: 'Failure to get response from OpenAI', details: error.message });
    }
});

app.listen(PORT, () => {});


This code launches a web app server, and whenever the user submits a query, the server responds with data in JSON format. This response can then be parsed within the user interface, making it possible to integrate third-party widgets for creating actionable, interactive elements.

JSON response from OpenAIGPT with function calling

JSON response from OpenAIGPT with function calling

Conclusion

This article with examples demonstrates how to modify API calls to OpenAI to request JSON-formatted responses. This approach significantly enhances the usability of LLM outputs, enabling more intuitive and actionable user interfaces. By specifying the response_format parameter or by using a function calling approach and crafting appropriate system messages, developers can ensure that LLM responses are returned in a structured JSON format.

This method of generating JSON outputs from LLMs facilitates seamless integration with other applications and allows for more sophisticated parsing and manipulation of AI-generated content. As AI continues to evolve, the ability to work with structured data formats like JSON will become increasingly valuable, enabling developers to create more powerful and user-friendly AI-driven applications.

AI API JSON app Integration

Opinions expressed by DZone contributors are their own.

Related

  • Integrate Spring With Open AI
  • Boomi Unveils Vision for Intelligent Integration and Automation at Boomi World 2024
  • Instant App Backends With API and Logic Automation
  • Unleashing the Power of GPT: A Comprehensive Guide To Implementing OpenAI’s GPT in ReactJS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!