| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import inspect |
| 8 | import json |
| 9 | from enum import Enum |
| 10 | |
| 11 | from typing import Any, get_args, get_origin, List, Literal, Optional, Type, Union |
| 12 | |
| 13 | from pydantic import BaseModel |
| 14 | from pydantic.fields import FieldInfo |
| 15 | from pydantic_core import PydanticUndefinedType |
| 16 | |
| 17 | from typing_extensions import Annotated |
| 18 | |
| 19 | |
| 20 | def is_list_of_primitives(field_type): |
| 21 | """Check if a field type is a List of primitive types.""" |
| 22 | origin = get_origin(field_type) |
| 23 | if origin is List or origin is list: |
| 24 | args = get_args(field_type) |
| 25 | if len(args) == 1 and args[0] in (int, float, str, bool): |
| 26 | return True |
| 27 | return False |
| 28 | |
| 29 | |
| 30 | def is_basemodel_without_fields(typ): |
| 31 | return ( |
| 32 | inspect.isclass(typ) and issubclass(typ, BaseModel) and len(typ.__fields__) == 0 |
| 33 | ) |
| 34 | |
| 35 | |
| 36 | def can_recurse(typ): |
| 37 | return ( |
| 38 | inspect.isclass(typ) and issubclass(typ, BaseModel) and len(typ.__fields__) > 0 |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | def get_literal_values(field): |
| 43 | """Extract literal values from a field if it's a Literal type.""" |
| 44 | if get_origin(field.annotation) is Literal: |
| 45 | return get_args(field.annotation) |
| 46 | return None |
| 47 | |
| 48 | |
| 49 | def is_optional(field_type): |
| 50 | """Check if a field type is Optional.""" |
| 51 | return get_origin(field_type) is Union and type(None) in get_args(field_type) |
| 52 | |
| 53 | |
| 54 | def get_non_none_type(field_type): |
| 55 | """Get the non-None type from an Optional type.""" |
| 56 | return next(arg for arg in get_args(field_type) if arg is not type(None)) |
| 57 | |
| 58 | |
| 59 | def manually_validate_field(model: Type[BaseModel], field_name: str, value: Any): |
| 60 | validators = model.__pydantic_decorators__.field_validators |
| 61 | for _name, validator in validators.items(): |
| 62 | if field_name in validator.info.fields: |
| 63 | validator.func(value) |
| 64 | |
| 65 | return value |
| 66 | |
| 67 | |
| 68 | def is_discriminated_union(typ) -> bool: |
| 69 | if isinstance(typ, FieldInfo): |
| 70 | return typ.discriminator |
| 71 | else: |
| 72 | if not (get_origin(typ) is Annotated): |
| 73 | return False |
| 74 | args = get_args(typ) |
| 75 | return len(args) >= 2 and args[1].discriminator |
| 76 | |
| 77 | |
| 78 | def prompt_for_discriminated_union( |
| 79 | field_name, |
| 80 | typ, |
| 81 | existing_value, |
| 82 | ): |
| 83 | if isinstance(typ, FieldInfo): |
| 84 | inner_type = typ.annotation |
| 85 | discriminator = typ.discriminator |
| 86 | default_value = typ.default |
| 87 | else: |
| 88 | args = get_args(typ) |
| 89 | inner_type = args[0] |
| 90 | discriminator = args[1].discriminator |
| 91 | default_value = args[1].default |
| 92 | |
| 93 | union_types = get_args(inner_type) |
| 94 | # Find the discriminator field in each union type |
| 95 | type_map = {} |
| 96 | for t in union_types: |
| 97 | disc_field = t.__fields__[discriminator] |
| 98 | literal_values = get_literal_values(disc_field) |
| 99 | if literal_values: |
| 100 | for value in literal_values: |
| 101 | type_map[value] = t |
| 102 | |
| 103 | while True: |
| 104 | prompt = f"Enter `{discriminator}` for {field_name} (options: {', '.join(type_map.keys())})" |
| 105 | if default_value is not None: |
| 106 | prompt += f" (default: {default_value})" |
| 107 | |
| 108 | discriminator_value = input(f"{prompt}: ") |
| 109 | if discriminator_value == "" and default_value is not None: |
| 110 | discriminator_value = default_value |
| 111 | |
| 112 | if discriminator_value in type_map: |
| 113 | chosen_type = type_map[discriminator_value] |
| 114 | print(f"\nConfiguring {chosen_type.__name__}:") |
| 115 | |
| 116 | if existing_value and ( |
| 117 | getattr(existing_value, discriminator) != discriminator_value |
| 118 | ): |
| 119 | existing_value = None |
| 120 | |
| 121 | sub_config = prompt_for_config(chosen_type, existing_value) |
| 122 | # Set the discriminator field in the sub-config |
| 123 | setattr(sub_config, discriminator, discriminator_value) |
| 124 | return sub_config |
| 125 | else: |
| 126 | print(f"Invalid {discriminator}. Please try again.") |
| 127 | |
| 128 | |
| 129 | # This is somewhat elaborate, but does not purport to be comprehensive in any way. |
| 130 | # We should add handling for the most common cases to tide us over. |
| 131 | # |
| 132 | # doesn't support List[nested_class] yet or Dicts of any kind. needs a bunch of |
| 133 | # unit tests for coverage. |
| 134 | def prompt_for_config( |
| 135 | config_type: type[BaseModel], existing_config: Optional[BaseModel] = None |
| 136 | ) -> BaseModel: |
| 137 | """ |
| 138 | Recursively prompt the user for configuration values based on a Pydantic BaseModel. |
| 139 | |
| 140 | Args: |
| 141 | config_type: A Pydantic BaseModel class representing the configuration structure. |
| 142 | |
| 143 | Returns: |
| 144 | An instance of the config_type with user-provided values. |
| 145 | """ |
| 146 | config_data = {} |
| 147 | |
| 148 | for field_name, field in config_type.__fields__.items(): |
| 149 | field_type = field.annotation |
| 150 | existing_value = ( |
| 151 | getattr(existing_config, field_name) if existing_config else None |
| 152 | ) |
| 153 | if existing_value: |
| 154 | default_value = existing_value |
| 155 | else: |
| 156 | default_value = ( |
| 157 | field.default |
| 158 | if not isinstance(field.default, PydanticUndefinedType) |
| 159 | else None |
| 160 | ) |
| 161 | is_required = field.is_required |
| 162 | |
| 163 | # Skip fields with Literal type |
| 164 | if get_origin(field_type) is Literal: |
| 165 | continue |
| 166 | |
| 167 | # Skip fields with no type annotations |
| 168 | if is_basemodel_without_fields(field_type): |
| 169 | config_data[field_name] = field_type() |
| 170 | continue |
| 171 | |
| 172 | if inspect.isclass(field_type) and issubclass(field_type, Enum): |
| 173 | prompt = f"Choose {field_name} (options: {', '.join(e.name for e in field_type)}):" |
| 174 | while True: |
| 175 | # this branch does not handle existing and default values yet |
| 176 | user_input = input(prompt + " ") |
| 177 | try: |
| 178 | value = field_type[user_input] |
| 179 | validated_value = manually_validate_field(config_type, field, value) |
| 180 | config_data[field_name] = validated_value |
| 181 | break |
| 182 | except KeyError: |
| 183 | print( |
| 184 | f"Invalid choice. Please choose from: {', '.join(e.name for e in field_type)}" |
| 185 | ) |
| 186 | continue |
| 187 | |
| 188 | if is_discriminated_union(field): |
| 189 | config_data[field_name] = prompt_for_discriminated_union( |
| 190 | field_name, field, existing_value |
| 191 | ) |
| 192 | continue |
| 193 | |
| 194 | if is_optional(field_type) and can_recurse(get_non_none_type(field_type)): |
| 195 | prompt = f"Do you want to configure {field_name}? (y/n): " |
| 196 | if input(prompt).lower() == "n": |
| 197 | config_data[field_name] = None |
| 198 | continue |
| 199 | nested_type = get_non_none_type(field_type) |
| 200 | print(f"Entering sub-configuration for {field_name}:") |
| 201 | config_data[field_name] = prompt_for_config(nested_type, existing_value) |
| 202 | elif is_optional(field_type) and is_discriminated_union( |
| 203 | get_non_none_type(field_type) |
| 204 | ): |
| 205 | prompt = f"Do you want to configure {field_name}? (y/n): " |
| 206 | if input(prompt).lower() == "n": |
| 207 | config_data[field_name] = None |
| 208 | continue |
| 209 | nested_type = get_non_none_type(field_type) |
| 210 | config_data[field_name] = prompt_for_discriminated_union( |
| 211 | field_name, |
| 212 | nested_type, |
| 213 | existing_value, |
| 214 | ) |
| 215 | elif can_recurse(field_type): |
| 216 | print(f"\nEntering sub-configuration for {field_name}:") |
| 217 | config_data[field_name] = prompt_for_config( |
| 218 | field_type, |
| 219 | existing_value, |
| 220 | ) |
| 221 | else: |
| 222 | prompt = f"Enter value for {field_name}" |
| 223 | if existing_value is not None: |
| 224 | prompt += f" (existing: {existing_value})" |
| 225 | elif default_value is not None: |
| 226 | prompt += f" (default: {default_value})" |
| 227 | if is_optional(field_type): |
| 228 | prompt += " (optional)" |
| 229 | elif is_required: |
| 230 | prompt += " (required)" |
| 231 | prompt += ": " |
| 232 | |
| 233 | while True: |
| 234 | user_input = input(prompt) |
| 235 | if user_input == "": |
| 236 | if default_value is not None: |
| 237 | config_data[field_name] = default_value |
| 238 | break |
| 239 | elif is_optional(field_type) or not is_required: |
| 240 | config_data[field_name] = None |
| 241 | break |
| 242 | else: |
| 243 | print("This field is required. Please provide a value.") |
| 244 | continue |
| 245 | else: |
| 246 | try: |
| 247 | # Handle Optional types |
| 248 | if is_optional(field_type): |
| 249 | if user_input.lower() == "none": |
| 250 | value = None |
| 251 | else: |
| 252 | field_type = get_non_none_type(field_type) |
| 253 | value = user_input |
| 254 | |
| 255 | # Handle List of primitives |
| 256 | elif is_list_of_primitives(field_type): |
| 257 | try: |
| 258 | value = json.loads(user_input) |
| 259 | if not isinstance(value, list): |
| 260 | raise ValueError( |
| 261 | "Input must be a JSON-encoded list" |
| 262 | ) |
| 263 | element_type = get_args(field_type)[0] |
| 264 | value = [element_type(item) for item in value] |
| 265 | |
| 266 | except json.JSONDecodeError: |
| 267 | print( |
| 268 | 'Invalid JSON. Please enter a valid JSON-encoded list e.g., ["foo","bar"]' |
| 269 | ) |
| 270 | continue |
| 271 | except ValueError as e: |
| 272 | print(f"{str(e)}") |
| 273 | continue |
| 274 | |
| 275 | elif get_origin(field_type) is dict: |
| 276 | try: |
| 277 | value = json.loads(user_input) |
| 278 | if not isinstance(value, dict): |
| 279 | raise ValueError( |
| 280 | "Input must be a JSON-encoded dictionary" |
| 281 | ) |
| 282 | |
| 283 | except json.JSONDecodeError: |
| 284 | print( |
| 285 | "Invalid JSON. Please enter a valid JSON-encoded dict." |
| 286 | ) |
| 287 | continue |
| 288 | |
| 289 | # Convert the input to the correct type |
| 290 | elif inspect.isclass(field_type) and issubclass( |
| 291 | field_type, BaseModel |
| 292 | ): |
| 293 | # For nested BaseModels, we assume a dictionary-like string input |
| 294 | import ast |
| 295 | |
| 296 | value = field_type(**ast.literal_eval(user_input)) |
| 297 | else: |
| 298 | value = field_type(user_input) |
| 299 | |
| 300 | except ValueError: |
| 301 | print( |
| 302 | f"Invalid input. Expected type: {getattr(field_type, '__name__', str(field_type))}" |
| 303 | ) |
| 304 | continue |
| 305 | |
| 306 | try: |
| 307 | # Validate the field using our manual validation function |
| 308 | validated_value = manually_validate_field( |
| 309 | config_type, field_name, value |
| 310 | ) |
| 311 | config_data[field_name] = validated_value |
| 312 | break |
| 313 | except ValueError as e: |
| 314 | print(f"Validation error: {str(e)}") |
| 315 | |
| 316 | return config_type(**config_data) |