Skip to content

Commit a27299d

Browse files
committed
Refactor prime number calculation to streamline logic and enhance structured output handling with the Instructor library in strict mode.
1 parent e07e3f4 commit a27299d

File tree

1 file changed

+30
-60
lines changed

1 file changed

+30
-60
lines changed

main.py

Lines changed: 30 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,50 @@
11
# Prime Numbers Calculation Script by TLIEPE
2-
# Showcase STRUCTURED OUTPUT LLM using Instructor library (stable version) https://python.useinstructor.com/integrations/openai/
2+
# Updated to use Instructor library with OpenAI API (strict structured output) https://python.useinstructor.com/integrations/openai/
33
# Designed for macOS environment
44

55
import os
66
import openai
77
import instructor
88
from pydantic import BaseModel
9-
import sympy
9+
from openai import OpenAIError
1010

1111
# Set the OpenAI API Key from environment variable
1212
openai.api_key = os.environ['OPENAI_API_KEY']
1313

14-
# Define a Pydantic model to validate the response from the OpenAI API
14+
# Initialize the OpenAI client with Instructor, strict validation enabled
15+
client = instructor.from_openai(openai.OpenAI(), mode=instructor.Mode.TOOLS_STRICT)
16+
17+
# Pydantic model for validating the structured response
1518
class PrimeNumberResponse(BaseModel):
1619
primes: list[int]
1720

18-
def ask_user_limit():
19-
try:
20-
limit = int(input("Please enter the upper limit for prime numbers: "))
21-
if limit <= 1:
22-
print("The limit should be at least 2 to find prime numbers.")
23-
return None
24-
return limit
25-
except ValueError:
26-
print("Please enter a valid integer.")
27-
return None
28-
29-
def get_prime_numbers_using_openai(limit):
30-
try:
31-
client = instructor.from_openai(openai.OpenAI())
32-
completion = client.chat.completions.create(
33-
model="gpt-4o-2024-08-06",
34-
messages=[
35-
{"role": "system", "content": "You are a helpful assistant that generates prime numbers."},
36-
{"role": "user", "content": f"Provide all prime numbers less than or equal to {limit} as a comma-separated list of integers."}
37-
],
38-
response_model=PrimeNumberResponse,
39-
)
40-
primes = completion.primes
41-
# With GenAI, it can happen that a number exceeding the limit is returned (e.g., 5 for limit=3),
42-
# so we filter out any numbers greater than the limit here.
43-
return [p for p in primes if p <= limit]
44-
except Exception as e:
45-
print(f"Error using OpenAI API: {e}")
46-
return None
47-
48-
def get_prime_numbers_locally(limit):
49-
return list(sympy.primerange(2, limit + 1))
50-
51-
def format_primes_for_side_by_side_display(primes_openai, primes_local):
52-
max_length = max(len(primes_openai), len(primes_local))
53-
formatted_output = []
54-
for i in range(max_length):
55-
openai_prime = str(primes_openai[i]) if i < len(primes_openai) else ""
56-
local_prime = str(primes_local[i]) if i < len(primes_local) else ""
57-
formatted_output.append(f"OpenAI: {openai_prime:<5} | Local: {local_prime}")
58-
return '\n'.join(formatted_output)
21+
def get_prime_numbers(limit):
22+
"""Get prime numbers up to a limit using OpenAI with strict schema validation."""
23+
completion = client.chat.completions.create(
24+
model="gpt-4o-2024-08-06",
25+
messages=[
26+
{"role": "system", "content": "You generate prime numbers."},
27+
{"role": "user", "content": f"List all prime numbers less than or equal to {limit}."}
28+
],
29+
response_model=PrimeNumberResponse
30+
)
31+
return completion.primes
5932

6033
def main():
61-
user_limit = ask_user_limit()
62-
if user_limit is None:
63-
return
64-
65-
primes_openai = get_prime_numbers_using_openai(user_limit)
66-
if primes_openai is None:
67-
return
68-
69-
primes_local = get_prime_numbers_locally(user_limit)
34+
try:
35+
limit = int(input("Enter the upper limit for prime numbers: "))
36+
primes = get_prime_numbers(limit)
37+
print(f"\nPrime numbers up to {limit}:\n{primes}")
7038

71-
print("\nPrime Numbers Comparison:\n")
72-
print(format_primes_for_side_by_side_display(primes_openai, primes_local))
39+
except OpenAIError as e:
40+
if hasattr(e, 'status_code') and e.status_code == 400:
41+
print("\nThe model failed to return correctly structured data (HTTP 400 Error).\n"
42+
"This usually happens if the model could not strictly follow the expected format.")
43+
else:
44+
print(f"\nAn OpenAI API error occurred: {e}")
7345

74-
if primes_openai == primes_local:
75-
print("\nBoth results match!")
76-
else:
77-
print("\nThe results differ. Please verify the calculations.")
46+
except Exception as e:
47+
print(f"\nAn unexpected error occurred: {e}")
7848

7949
if __name__ == "__main__":
80-
main()
50+
main()

0 commit comments

Comments
 (0)