Implement a function that guarantees structured JSON output from the LLM using the 'json_object' response format.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Implementation:
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function extractUserData(text) {
const completion = await openai.chat.completions.create({
model: "gpt-4-turbo", // Or gpt-3.5-turbo-1106+
messages: [
{
role: "system",
content: "Extract user details into JSON. Always return JSON."
},
{
role: "user",
content: `extract info for John Doe, 30 years old, developer from NY: ${text}`
}
],
response_format: { type: "json_object" }
});
return JSON.parse(completion.choices[0].message.content);
}
// Usage
// const data = await extractUserData("My name is Sarah, I'm a designer living in London.");
// console.log(data); // { name: "Sarah", role: "designer", location: "London" }