Created
October 14, 2024 18:56
-
-
Save darko-mesaros/9be05c0721be47a8ce59075bcc338375 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from typing import List, Dict, Optional | |
def parse_and_validate_recommendations(llm_output: str) -> List[Dict[str, str]]: | |
try: | |
# Attempt to parse the JSON output | |
data = json.loads(llm_output) | |
# Validate the structure of the parsed data | |
if not isinstance(data, list): | |
raise ValueError("Output should be a list of recommendations") | |
validated_recommendations = [] | |
for item in data: | |
if not isinstance(item, dict): | |
raise ValueError("Each recommendation should be a dictionary") | |
# Ensure all required fields are present and have the correct types | |
name = item.get('name') | |
description = item.get('description') | |
price = item.get('price') | |
if not all([isinstance(name, str), isinstance(description, str), isinstance(price, (int, float))]): | |
raise ValueError("Invalid data types in recommendation") | |
# Add additional validation as needed (e.g., price > 0) | |
if price <= 0: | |
raise ValueError("Price must be greater than zero") | |
# If all checks pass, add the validated item to our result | |
validated_recommendations.append({ | |
'name': name, | |
'description': description, | |
'price': price | |
}) | |
return validated_recommendations | |
except json.JSONDecodeError: | |
print("Failed to parse LLM output as JSON") | |
return [] | |
except ValueError as e: | |
print(f"Validation error: {str(e)}") | |
return [] | |
except Exception as e: | |
print(f"Unexpected error during parsing and validation: {str(e)}") | |
return [] | |
# Example usage | |
llm_output = ''' | |
[ | |
{"name": "Wireless Earbuds", "description": "High-quality sound with noise cancellation", "price": 99.99}, | |
{"name": "Smartwatch", "description": "Fitness tracking and notifications", "price": 199.99}, | |
{"name": "Portable Charger", "description": "10000mAh capacity for multiple device charges", "price": 49.99} | |
] | |
''' | |
recommendations = parse_and_validate_recommendations(llm_output) | |
if recommendations: | |
print("Valid recommendations:") | |
for rec in recommendations: | |
print(f"- {rec['name']}: ${rec['price']}") | |
else: | |
print("No valid recommendations found") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment