To ensure programmatic processing of model responses, you can use the responseConstraint option in session.prompt(). This allows you to force the model to adhere to a specific structure or pattern.
JSON Schema
Pass a valid JSON schema object. The returned string can be parsed with JSON.parse(). If the model cannot produce a compliant response, a SyntaxError is thrown.
Regular Expressions
Pass a RegExp object. The returned string will match the pattern. If the model cannot produce a matching response, a SyntaxError is thrown.
Optimizing Context Usage
By default, the constraint is included in the prompt, consuming tokens. To avoid this, use omitResponseConstraintInput: true and include the instructions manually in your prompt string.
Note: If omitResponseConstraintInput is true but responseConstraint is not set, a TypeError occurs.
// Using JSON Schema
const schema = {
type: "object",
required: ["rating"],
additionalProperties: false,
properties: {
rating: { type: "number", minimum: 0, maximum: 5 },
},
};
const result = await session.prompt("Summarize this feedback into a rating between 0-5: The food was delicious.", {
responseConstraint: schema
});
const { rating } = JSON.parse(result);
// Using RegExp
const emailRegExp = /^[a-zA-Z0-9.!#$%&'*+\/:=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]{0,61}[a-zA-Z0-9])?$/;
const emailAddress = await session.prompt(
`Create a fictional email address for ${characterName}.`,
{ responseConstraint: emailRegExp }
);
// Using omitResponseConstraintInput to save tokens
const result = await session.prompt(
`Summarize this feedback into a rating between 0-5, only outputting a JSON object { rating }, with a single property whose value is a number: The food was delicious.`,
{ responseConstraint: schema, omitResponseConstraintInput: true }
);