Elffuss BraidHub

kikocis/llama-stack public

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