avatarJake Cyr

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2374

Abstract

ring">"type"</span>: <span class="hljs-string">"json_object"</span> }, messages=[ {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: system_prompt}, {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"A tech AI company that’s working towards AGI!"</span>} ] )

parsed_response = json.loads(completion.choices[<span class="hljs-number">0</span>].message) <span class="hljs-built_in">print</span>(parsed_response[<span class="hljs-string">"name"</span>])</pre></div><p id="5172">In this Python example, the API call is configured to return responses in a JSON format. The response_format parameter is crucial for specifying the desired response structure.</p><h2 id="120c">NodeJS Example</h2><div id="18e1"><pre><span class="hljs-keyword">import</span> <span class="hljs-title class_">OpenAI</span> <span class="hljs-keyword">from</span> <span class="hljs-string">"openai"</span>;

<span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> <span class="hljs-title class_">OpenAI</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> systemPrompt = <span class="hljs-string">` You are a helpful assistant who returns funny company names given a description of a company. Return a JSON object.

Example output format:
{ "name": "Some funny name" }

`</span>; <span class="hljs-keyword">const</span> completion = <span class="hljs-keyword">await</span> openai.<span class="hljs-property">chat</span>.<span class="hljs-property">completions</span>.<span class="hljs-title function_">create</span>({ <span class="hljs-attr">messages</span>: [ { <span class="hljs-attr">role</span>: <span class="hljs-string">"system"</span>, <span class="hljs-attr">content</span>: systemPrompt }, { <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>, <span class="hljs-attr">content</span>: <span class="hljs-string">"A tech news company"</span> }, ], <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-3.5-turbo"</spa

Options

n>, <span class="hljs-attr">response_format</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">"json_object"</span> }, });

<span class="hljs-keyword">const</span> jsonResponse = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(completion.<span class="hljs-property">choices</span>[<span class="hljs-number">0</span>].<span class="hljs-property">message</span>.<span class="hljs-property">content</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">Company name: <span class="hljs-subst">${jsonResponse.name}</span></span>); }

<span class="hljs-title function_">main</span>();</pre></div><p id="b555">For NodeJS, the implementation is similar, with adjustments to fit JavaScript syntax. The response_format parameter remains key to obtaining JSON structured responses.</p><h1 id="d259">Real-World Application Scenarios</h1><p id="b712">From automating customer service chatbots to enhancing data analysis tools, the JSON mode has broad applications. Industries like healthcare, finance, and education can leverage structured AI responses for more precise outcomes.</p><h1 id="5012">Advantages and Best Practices</h1><p id="47a1">The JSON mode simplifies data handling and enables complex AI applications. Developers should focus on understanding the structure of JSON responses and integrating them effectively into their systems.</p><h1 id="c7ae">Conclusion</h1><p id="7811">OpenAI’s JSON mode in the chat completion API is a transformative tool for AI integration, offering structured, predictable responses that open up new possibilities in AI application development.</p><h1 id="2ea3">Stackademic</h1><p id="9b7c"><i>Thank you for reading until the end. Before you go:</i></p><ul><li><i>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</i></li><li><i>Follow us on <a href="https://twitter.com/stackademichq"><b>Twitter(X)</b></a>, <a href="https://www.linkedin.com/company/stackademic"><b>LinkedIn</b></a>, and <a href="https://www.youtube.com/c/stackademic"><b>YouTube</b></a><b>.</b></i></li><li><i>Visit <a href="http://stackademic.com/"><b>Stackademic.com</b></a> to find out more about how we are democratizing free programming education around the world.</i></li></ul></article></body>

Navigating OpenAI’s JSON Mode for Structured Output

A Developer’s Deep Dive into the Chat Completion API

Photo by Greg Rakozy on Unsplash

Introduction

OpenAI’s API has continually evolved, meeting the growing demand for more sophisticated AI interactions. The introduction of a JSON mode in the chat completion API marks a pivotal development, offering a more structured way of receiving AI responses. This feature is especially crucial for developers seeking consistency and ease of integration in their AI-powered applications.

The Pre-JSON Era: Challenges in Structured Responses

Before the advent of JSON mode, developers often grappled with irregular and unpredictable response formats from AI models. This lack of standardization led to increased complexity in parsing AI responses, limiting the scope and efficiency of AI integrations.

Some previous approaches include providing many examples to the model in the input prompt and going the model returns the expected format. Langchain also offers various output parsers to get structured data from LLMs, but I’ve had mixed success with it.

The JSON Mode Breakthrough

The response_format parameter with a value of { type: “json_object” } is a significant innovation in OpenAI’s API. It allows developers to receive responses in a structured, JSON format, streamlining data parsing and application integration.

Step-by-Step Implementation

Python Implementation

from openai import OpenAI
import json

client = OpenAI(api_key="...")

system_prompt = """
You are a helpful assistant who returns
funny company names given a description of
a company. Return a JSON object.

Example output format:
{ "name": "Some funny name" }
"""

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  response_format={ "type": "json_object" },
  messages=[
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "A tech AI company that’s working towards AGI!"}
  ]
)

parsed_response = json.loads(completion.choices[0].message)
print(parsed_response["name"])

In this Python example, the API call is configured to return responses in a JSON format. The response_format parameter is crucial for specifying the desired response structure.

NodeJS Example

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const systemPrompt = `
    You are a helpful assistant who returns
    funny company names given a description of
    a company. Return a JSON object.

    Example output format:
    { "name": "Some funny name" }
  `;
  const completion = await openai.chat.completions.create({
    messages: [
       { role: "system", content: systemPrompt },
       { role: "user", content: "A tech news company" },
    ],
    model: "gpt-3.5-turbo",
    response_format: { type: "json_object" },
  });

  const jsonResponse = JSON.parse(completion.choices[0].message.content);

  console.log(`Company name: ${jsonResponse.name}`);
}

main();

For NodeJS, the implementation is similar, with adjustments to fit JavaScript syntax. The response_format parameter remains key to obtaining JSON structured responses.

Real-World Application Scenarios

From automating customer service chatbots to enhancing data analysis tools, the JSON mode has broad applications. Industries like healthcare, finance, and education can leverage structured AI responses for more precise outcomes.

Advantages and Best Practices

The JSON mode simplifies data handling and enables complex AI applications. Developers should focus on understanding the structure of JSON responses and integrating them effectively into their systems.

Conclusion

OpenAI’s JSON mode in the chat completion API is a transformative tool for AI integration, offering structured, predictable responses that open up new possibilities in AI application development.

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.
Machine Learning
Nodejs
Python
OpenAI
Programming
Recommended from ReadMedium