This project now uses OpenAI's strict structured output mode. This ensures that responses must fully comply with the expected data format. If the model fails to deliver correct structured data, a clear error message (HTTP 400) is shown.
This project maintains multiple versions:
- v1 - Beta Structured Output Version
- v2 - Stable Structured Output Version
- v3 - Strict Structured Output Version
Latest release: v3 - Strict Structured Output Version
This script showcases a new approach to generating structured output using OpenAI's stable structured outputs API (TOOLS_STRICT mode). It requests prime numbers up to a user-specified limit and validates the response format using a Pydantic model.
The script works as follows:
- API Key Setup: The OpenAI API key is set using an environment variable named
OPENAI_API_KEY
. - User Input: The user is prompted to provide an upper limit for calculating prime numbers.
- OpenAI API Request: The script sends a structured request to OpenAI, asking it to generate the prime numbers up to the user-provided limit using strict schema validation.
- Display: The received list of prime numbers is displayed to the user.
- API Key Setup
- User Input
- OpenAI API Request
- Prime Numbers Display
Before running the script, you'll need to set up a virtual environment and install the required libraries.
To set up a virtual environment, follow these steps:
- Open Terminal
- Navigate to your desired directory:
cd /path/to/your/project
- Create a virtual environment named
macenv
:python3 -m venv macenv
- Activate the virtual environment:
source macenv/bin/activate
- Install the required libraries using the
requirements.txt
file:pip install -r requirements.txt
- Or install the required libraries manuel:
pip install openai instructor pydantic
After setting up the virtual environment and installing the libraries, you're ready to run the script.
- Make sure the virtual environment is activated (
source macenv/bin/activate
). - Set the OpenAI API key as an environment variable:
export OPENAI_API_KEY=your_openai_api_key_here
- Run the script:
python3 main.py
-
MIT License: This project is licensed under the MIT License, meaning you are free to use, modify, and distribute it as long as proper credit is given.
-
Strict Mode Option: OpenAI now supports a strict mode in structured output, ensuring perfect schema compliance. This project currently uses a relaxed mode for flexibility in examples. For critical applications, enabling
strict: true
is recommended to guarantee response schema adherence. -
Strict Mode Handling: Version 3 introduces strict mode for structured outputs. This enforces exact schema validation. If the OpenAI model fails to generate a correct response, the script informs the user with a detailed error message instead of trying to recover or continuing silently.
MIT License. See LICENSE
for more details.
Feel free to open issues or submit pull requests if you'd like to contribute or have ideas for improving this project.