DEV Community

Luc Gagan
Luc Gagan

Posted on

Getting JSON with TypeScript types from ChatGPT response

I updated completions library to allow statically typed responses:

const response = await chat.sendMessage("Suggest a random startup name", {
  expect: {
    // These are the examples of what
    // the response should look like.
    examples: [
      {
        name: "OpenAI",
        domain: "openai.com",
      },
    ],
    // This is the schema that the
    // response must satisfy.
    schema: {
      additionalProperties: false,
      type: "object",
      properties: {
        name: { type: "string" },
        domain: { type: "string" },
      },
      required: ["name", "domain"],
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Now the response.content value's type is:

{
  name: string;
  domain: string
}
Enter fullscreen mode Exit fullscreen mode

Behind the scenes, the SDK will use the expect parameter to generate a prompt that will be sent to the API. The prompt will look like this:

Suggest a random startup name

Respond ONLY with a JSON object that satisfies the following schema:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "domain": { "type": "string" },
  },
  "required": ["name", "domain"],
}

Examples:

{
  "name": "OpenAI",
  "domain": "openai.com"
}
Enter fullscreen mode Exit fullscreen mode

The SDK will parse the response and validate it against the schema. If the response is invalid, it will throw an error. If the response is valid, it will return the response.

response.content;
// {
//   name: "Dex",
//   domain: "dex.com",
// }
Enter fullscreen mode Exit fullscreen mode

This abstraction makes it easy to get JSON response from ChatGPT and you get a typed result!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay