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"],
},
},
});
Now the response.content
value's type is:
{
name: string;
domain: string
}
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"
}
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",
// }
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.