StringConstraints in pydantic string for structured output in OpenAI completions

When working with Pydantic models for structured output, can I use Annotated along with StringConstraints to enforce restrictions on string lengths.

Example usecase:

import os
from pydantic import BaseModel
from typing import Annotated
from pydantic.types import StringConstraints
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),  
    api_version=os.getenv("OPENAI_API_VERSION"),  
)

MaxLength50 = Annotated[str, StringConstraints(min_length=3, max_length=64)]

class User(BaseModel):
    username: MaxLength50
    email: MaxLength50

prompt = "Give a cool sounding username and email"

completion = client.beta.chat.completions.parse(
            model=os.getenv('OPENAI_MODEL_NAME'),
            messages=[
                {"role": "user", "content": prompt)},
            ],
            response_format=User,
        )
1 Like

Hi @mukeshpareek1997 and welcome to the community. My understanding (also based on my own usage) is that some of the array and string length restrictions (that are implemented in Pydantic with Annotated) are not currently supported by OpenAI’s featureset of JSON schema spec.

See here.

I have managed to some extend to control this in my system prompt, or by adding a comment in the description in the Field.

2 Likes