This script is a showcase of a new approach to generating structured output using OpenAI's beta capabilities for structured outputs in its API. The script demonstrates a comparison between prime numbers generated locally and those generated through the OpenAI API using structured outputs.
The structured output capability of OpenAI helps ensure responses adhere to a defined format, validated using tools like Pydantic. In this case, it ensures a list of prime numbers is returned in a consistent manner.
The script calculates prime numbers in two different ways:
-
OpenAI API (with structured output): The script sends a request to OpenAI's API to provide all prime numbers up to a user-specified limit. The response is validated using a Pydantic model (
PrimeNumberResponse
) to ensure structured and predictable output. -
Local Calculation: The script uses the SymPy library to compute the same prime numbers locally.
Both results are displayed side by side, allowing you to compare the numbers generated by the OpenAI API and the local computation.
- API Key Setup: The OpenAI API key is set using an environment variable named
OPENAI_API_KEY
. Make sure this variable is set correctly before running the script. - 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.
- Local Computation: The script also calculates the prime numbers locally using SymPy's
primerange
function. - Comparison Display: Both sets of results are displayed side by side for easy comparison, indicating whether they match.
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:
pip install openai pydantic sympy
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
- Structured Output Beta Feature: This script leverages OpenAI's beta feature for structured outputs, as detailed here.
- 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.
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.