|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Example of using OpenAI's structured outputs with Pydantic models.""" |
| 3 | + |
| 4 | +import json |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import openai |
| 8 | +from pydantic import ValidationError |
| 9 | + |
| 10 | +from app import settings |
| 11 | +from app.function_schemas import ( |
| 12 | + GetCoursesParams, |
| 13 | + RegisterCourseParams, |
| 14 | + SpecializationArea, |
| 15 | +) |
| 16 | +from app.logging_config import get_logger |
| 17 | +from app.response_models import Course, CourseSearchResponse, RegistrationResponse |
| 18 | +from app.stackademy import stackademy_app |
| 19 | + |
| 20 | + |
| 21 | +logger = get_logger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +def get_courses_with_structured_output( |
| 25 | + description: Optional[str] = None, max_cost: Optional[float] = None |
| 26 | +) -> CourseSearchResponse: |
| 27 | + """ |
| 28 | + Get courses using structured output parsing. |
| 29 | +
|
| 30 | + This ensures the response conforms to our expected schema. |
| 31 | + """ |
| 32 | + try: |
| 33 | + # Convert string to enum if provided |
| 34 | + specialization_area = None |
| 35 | + if description: |
| 36 | + |
| 37 | + try: |
| 38 | + specialization_area = SpecializationArea(description) |
| 39 | + except ValueError: |
| 40 | + logger.warning("Invalid specialization area: %s", description) |
| 41 | + specialization_area = None |
| 42 | + |
| 43 | + # Validate input parameters using Pydantic |
| 44 | + params = GetCoursesParams(description=specialization_area, max_cost=max_cost) |
| 45 | + |
| 46 | + # Get raw course data |
| 47 | + courses_data = stackademy_app.get_courses( |
| 48 | + description=params.description if params.description else None, max_cost=params.max_cost |
| 49 | + ) |
| 50 | + |
| 51 | + courses = [Course(**course_dict) for course_dict in courses_data] |
| 52 | + |
| 53 | + # Create structured response |
| 54 | + return CourseSearchResponse(courses=courses, total_count=len(courses)) |
| 55 | + |
| 56 | + except ValidationError as e: |
| 57 | + logger.error("Parameter validation error: %s", e) |
| 58 | + return CourseSearchResponse(courses=[], total_count=0) |
| 59 | + # pylint: disable=broad-except |
| 60 | + except Exception as e: |
| 61 | + logger.error("Error getting courses: %s", e) |
| 62 | + return CourseSearchResponse(courses=[], total_count=0) |
| 63 | + |
| 64 | + |
| 65 | +def register_course_with_structured_output(course_code: str, email: str, full_name: str) -> RegistrationResponse: |
| 66 | + """ |
| 67 | + Register for a course using structured output. |
| 68 | + """ |
| 69 | + try: |
| 70 | + # Validate input parameters |
| 71 | + params = RegisterCourseParams(course_code=course_code, email=email, full_name=full_name) |
| 72 | + |
| 73 | + # Attempt registration |
| 74 | + success = stackademy_app.register_course( |
| 75 | + course_code=params.course_code, email=params.email, full_name=params.full_name |
| 76 | + ) |
| 77 | + |
| 78 | + if success: |
| 79 | + return RegistrationResponse( |
| 80 | + success=True, |
| 81 | + message=f"Successfully registered {full_name} for course {course_code}", |
| 82 | + registration_id=f"REG-{course_code}-{hash(email) % 10000:04d}", |
| 83 | + ) |
| 84 | + return RegistrationResponse(success=False, message="Registration failed. Please try again later.") |
| 85 | + |
| 86 | + except ValidationError as e: |
| 87 | + logger.error("Parameter validation error: %s", e) |
| 88 | + return RegistrationResponse(success=False, message=f"Invalid parameters: {e}") |
| 89 | + # pylint: disable=broad-except |
| 90 | + except Exception as e: |
| 91 | + logger.error("Registration error: %s", e) |
| 92 | + return RegistrationResponse(success=False, message="An unexpected error occurred during registration.") |
| 93 | + |
| 94 | + |
| 95 | +# Example of using OpenAI's beta structured outputs (requires openai>=1.0.0) |
| 96 | +# pylint: disable=unused-argument |
| 97 | +def completion_with_structured_output(prompt: str, response_model: type): |
| 98 | + """ |
| 99 | + Example of using OpenAI's structured output parsing. |
| 100 | +
|
| 101 | + This is available in the beta API and ensures responses conform to schemas. |
| 102 | + """ |
| 103 | + try: |
| 104 | + openai.api_key = settings.OPENAI_API_KEY |
| 105 | + |
| 106 | + # Note: This is a beta feature and may not be available in all OpenAI versions |
| 107 | + # response = openai.beta.chat.completions.parse( |
| 108 | + # model=settings.OPENAI_API_MODEL, |
| 109 | + # messages=[{"role": "user", "content": prompt}], |
| 110 | + # response_format=response_model, |
| 111 | + # ) |
| 112 | + # |
| 113 | + # return response.choices[0].message.parsed |
| 114 | + |
| 115 | + # For now, we'll return a placeholder since this is beta |
| 116 | + logger.info("Structured output parsing would be used here with model: %s", response_model.__name__) |
| 117 | + return None |
| 118 | + # pylint: disable=broad-except |
| 119 | + except Exception as e: |
| 120 | + logger.error("Structured completion error: %s", e) |
| 121 | + return None |
0 commit comments