OneLLM 0.0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
onellm/validators.py ADDED
@@ -0,0 +1,1314 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # Unified interface for LLM providers using OpenAI format
5
+ # https://github.com/muxi-ai/onellm
6
+ #
7
+ # Copyright (C) 2025 Ran Aroussi
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """
22
+ Validation utilities for OneLLM.
23
+
24
+ This module provides validation functions for ensuring that the data passed
25
+ to the API methods is correctly formatted and within expected ranges.
26
+ """
27
+
28
+ from typing import Any, Dict, List, Optional, Union, TypeVar, Callable, Type
29
+ import re
30
+ import json
31
+ import base64
32
+ from urllib.parse import urlparse
33
+ from .errors import InvalidRequestError
34
+
35
+
36
+ # Type variable for generic type validators
37
+ T = TypeVar("T")
38
+
39
+
40
+ # -------------------- Type Validation System --------------------
41
+
42
+
43
+ def validate_type(
44
+ value: Any, expected_type: Type[T], name: str, allow_none: bool = False
45
+ ) -> T:
46
+ """
47
+ Validate that a value has the expected type.
48
+
49
+ Args:
50
+ value: Value to validate
51
+ expected_type: Expected type of the value
52
+ name: Name of the value (for error messages)
53
+ allow_none: Whether None is allowed
54
+
55
+ Returns:
56
+ The validated value
57
+
58
+ Raises:
59
+ InvalidRequestError: If the value has an incorrect type
60
+ """
61
+ # Check if value is None and handle according to allow_none parameter
62
+ if value is None:
63
+ if allow_none:
64
+ return None
65
+ raise InvalidRequestError(f"{name} cannot be None")
66
+
67
+ # Check if value is of the expected type
68
+ if not isinstance(value, expected_type):
69
+ raise InvalidRequestError(
70
+ f"{name} must be a {expected_type.__name__}, got {type(value).__name__}"
71
+ )
72
+
73
+ return value
74
+
75
+
76
+ def validate_dict(
77
+ value: Any,
78
+ name: str,
79
+ required_keys: Optional[List[str]] = None,
80
+ optional_keys: Optional[List[str]] = None,
81
+ allow_none: bool = False,
82
+ ) -> Dict[str, Any]:
83
+ """
84
+ Validate that a value is a dictionary with the expected keys.
85
+
86
+ Args:
87
+ value: Value to validate
88
+ name: Name of the value (for error messages)
89
+ required_keys: Keys that must be present
90
+ optional_keys: Keys that may be present
91
+ allow_none: Whether None is allowed
92
+
93
+ Returns:
94
+ The validated dictionary
95
+
96
+ Raises:
97
+ InvalidRequestError: If the value is not a valid dictionary
98
+ """
99
+ # Check if value is None and handle according to allow_none parameter
100
+ if value is None:
101
+ if allow_none:
102
+ return None
103
+ raise InvalidRequestError(f"{name} cannot be None")
104
+
105
+ # Check if value is a dictionary
106
+ if not isinstance(value, dict):
107
+ raise InvalidRequestError(
108
+ f"{name} must be a dictionary, got {type(value).__name__}"
109
+ )
110
+
111
+ # Default to empty lists if not provided
112
+ required_keys = required_keys or []
113
+
114
+ # Check required keys
115
+ for key in required_keys:
116
+ if key not in value:
117
+ raise InvalidRequestError(f"{name} is missing required key '{key}'")
118
+
119
+ # Check for unexpected keys in two cases:
120
+ # 1. When optional_keys is explicitly provided (even if empty)
121
+ # 2. When required_keys are specified and we want to enforce only those keys
122
+ if optional_keys is not None:
123
+ allowed_keys = set(required_keys) | set(optional_keys)
124
+ for key in value:
125
+ if key not in allowed_keys:
126
+ raise InvalidRequestError(f"{name} contains unexpected key '{key}'")
127
+
128
+ return value
129
+
130
+
131
+ def validate_list(
132
+ value: Any,
133
+ name: str,
134
+ item_validator: Optional[Callable[[Any, str], Any]] = None,
135
+ min_length: Optional[int] = None,
136
+ max_length: Optional[int] = None,
137
+ allow_none: bool = False,
138
+ ) -> List[Any]:
139
+ """
140
+ Validate that a value is a list with items of the expected type.
141
+
142
+ Args:
143
+ value: Value to validate
144
+ name: Name of the value (for error messages)
145
+ item_validator: Optional validator for list items
146
+ min_length: Minimum list length
147
+ max_length: Maximum list length
148
+ allow_none: Whether None is allowed
149
+
150
+ Returns:
151
+ The validated list
152
+
153
+ Raises:
154
+ InvalidRequestError: If the value is not a valid list
155
+ """
156
+ # Check if value is None and handle according to allow_none parameter
157
+ if value is None:
158
+ if allow_none:
159
+ return None
160
+ raise InvalidRequestError(f"{name} cannot be None")
161
+
162
+ # Check if value is a list
163
+ if not isinstance(value, list):
164
+ raise InvalidRequestError(f"{name} must be a list, got {type(value).__name__}")
165
+
166
+ # Check minimum length constraint
167
+ if min_length is not None and len(value) < min_length:
168
+ raise InvalidRequestError(f"{name} must have at least {min_length} items")
169
+
170
+ # Check maximum length constraint
171
+ if max_length is not None and len(value) > max_length:
172
+ raise InvalidRequestError(f"{name} must have at most {max_length} items")
173
+
174
+ # Validate each item in the list if a validator is provided
175
+ if item_validator:
176
+ for i, item in enumerate(value):
177
+ # Apply validator to each item, use indexed name for error context
178
+ value[i] = item_validator(item, f"{name}[{i}]")
179
+
180
+ return value
181
+
182
+
183
+ def validate_string(
184
+ value: Any,
185
+ name: str,
186
+ min_length: Optional[int] = None,
187
+ max_length: Optional[int] = None,
188
+ pattern: Optional[str] = None,
189
+ allowed_values: Optional[List[str]] = None,
190
+ allow_none: bool = False,
191
+ ) -> Optional[str]:
192
+ """
193
+ Validate that a value is a string with the expected properties.
194
+
195
+ Args:
196
+ value: Value to validate
197
+ name: Name of the value (for error messages)
198
+ min_length: Minimum string length
199
+ max_length: Maximum string length
200
+ pattern: Regex pattern the string must match
201
+ allowed_values: List of allowed values
202
+ allow_none: Whether None is allowed
203
+
204
+ Returns:
205
+ The validated string
206
+
207
+ Raises:
208
+ InvalidRequestError: If the value is not a valid string
209
+ """
210
+ # Check if value is None and handle according to allow_none parameter
211
+ if value is None:
212
+ if allow_none:
213
+ return None
214
+ raise InvalidRequestError(f"{name} cannot be None")
215
+
216
+ # Check if value is a string
217
+ if not isinstance(value, str):
218
+ raise InvalidRequestError(
219
+ f"{name} must be a string, got {type(value).__name__}"
220
+ )
221
+
222
+ # Check minimum length constraint
223
+ if min_length is not None and len(value) < min_length:
224
+ raise InvalidRequestError(
225
+ f"{name} must be at least {min_length} characters long"
226
+ )
227
+
228
+ # Check maximum length constraint
229
+ if max_length is not None and len(value) > max_length:
230
+ raise InvalidRequestError(
231
+ f"{name} must be at most {max_length} characters long"
232
+ )
233
+
234
+ # Check if string matches the required pattern
235
+ if pattern is not None and not re.match(pattern, value):
236
+ raise InvalidRequestError(f"{name} does not match the required pattern")
237
+
238
+ # Check if string is one of the allowed values
239
+ if allowed_values is not None and value not in allowed_values:
240
+ allowed_str = ", ".join(f"'{v}'" for v in allowed_values)
241
+ raise InvalidRequestError(f"{name} must be one of: {allowed_str}")
242
+
243
+ return value
244
+
245
+
246
+ def validate_number(
247
+ value: Any,
248
+ name: str,
249
+ min_value: Optional[float] = None,
250
+ max_value: Optional[float] = None,
251
+ integer_only: bool = False,
252
+ allow_none: bool = False,
253
+ ) -> Optional[Union[int, float]]:
254
+ """
255
+ Validate that a value is a number with the expected properties.
256
+
257
+ Args:
258
+ value: Value to validate
259
+ name: Name of the value (for error messages)
260
+ min_value: Minimum allowed value
261
+ max_value: Maximum allowed value
262
+ integer_only: Whether only integers are allowed
263
+ allow_none: Whether None is allowed
264
+
265
+ Returns:
266
+ The validated number
267
+
268
+ Raises:
269
+ InvalidRequestError: If the value is not a valid number
270
+ """
271
+ # Check if value is None and handle according to allow_none parameter
272
+ if value is None:
273
+ if allow_none:
274
+ return None
275
+ raise InvalidRequestError(f"{name} cannot be None")
276
+
277
+ # Check if value is an integer (but not a boolean) when integer_only is True
278
+ if integer_only:
279
+ # Exclude booleans which are a subclass of int
280
+ if not isinstance(value, int) or isinstance(value, bool):
281
+ raise InvalidRequestError(
282
+ f"{name} must be an integer, got {type(value).__name__}"
283
+ )
284
+ else:
285
+ # Check if value is a number (int or float, but not a boolean)
286
+ # Exclude booleans which are a subclass of int
287
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
288
+ raise InvalidRequestError(
289
+ f"{name} must be a number, got {type(value).__name__}"
290
+ )
291
+
292
+ # Check minimum value constraint
293
+ if min_value is not None and value < min_value:
294
+ raise InvalidRequestError(f"{name} must be at least {min_value}")
295
+
296
+ # Check maximum value constraint
297
+ if max_value is not None and value > max_value:
298
+ raise InvalidRequestError(f"{name} must be at most {max_value}")
299
+
300
+ return value
301
+
302
+
303
+ def validate_boolean(value: Any, name: str, allow_none: bool = False) -> Optional[bool]:
304
+ """
305
+ Validate that a value is a boolean.
306
+
307
+ Args:
308
+ value: Value to validate
309
+ name: Name of the value (for error messages)
310
+ allow_none: Whether None is allowed
311
+
312
+ Returns:
313
+ The validated boolean
314
+
315
+ Raises:
316
+ InvalidRequestError: If the value is not a valid boolean
317
+ """
318
+ # Check if value is None and handle according to allow_none parameter
319
+ if value is None:
320
+ if allow_none:
321
+ return None
322
+ raise InvalidRequestError(f"{name} cannot be None")
323
+
324
+ # Check if value is a boolean
325
+ if not isinstance(value, bool):
326
+ raise InvalidRequestError(
327
+ f"{name} must be a boolean, got {type(value).__name__}"
328
+ )
329
+
330
+ return value
331
+
332
+
333
+ def validate_url(
334
+ value: Any,
335
+ name: str,
336
+ allowed_schemes: Optional[List[str]] = None,
337
+ allow_none: bool = False,
338
+ ) -> Optional[str]:
339
+ """
340
+ Validate that a value is a valid URL.
341
+
342
+ Args:
343
+ value: Value to validate
344
+ name: Name of the value (for error messages)
345
+ allowed_schemes: List of allowed URL schemes
346
+ allow_none: Whether None is allowed
347
+
348
+ Returns:
349
+ The validated URL
350
+
351
+ Raises:
352
+ InvalidRequestError: If the value is not a valid URL
353
+ """
354
+ # Check if value is None and handle according to allow_none parameter
355
+ if value is None:
356
+ if allow_none:
357
+ return None
358
+ raise InvalidRequestError(f"{name} cannot be None")
359
+
360
+ # Check if value is a string
361
+ if not isinstance(value, str):
362
+ raise InvalidRequestError(
363
+ f"{name} must be a string, got {type(value).__name__}"
364
+ )
365
+
366
+ try:
367
+ # Parse the URL to check its validity
368
+ result = urlparse(value)
369
+ # A valid URL must have both scheme and netloc (domain) parts
370
+ if not all([result.scheme, result.netloc]):
371
+ raise ValueError("Missing scheme or netloc")
372
+
373
+ # Check if the URL scheme is in the list of allowed schemes
374
+ if allowed_schemes and result.scheme not in allowed_schemes:
375
+ schemes_str = ", ".join(allowed_schemes)
376
+ raise InvalidRequestError(
377
+ f"{name} must use one of the following schemes: {schemes_str}"
378
+ )
379
+ except Exception as e:
380
+ # Re-raise InvalidRequestError exceptions, wrap others
381
+ if isinstance(e, InvalidRequestError):
382
+ raise
383
+ raise InvalidRequestError(f"{name} is not a valid URL: {str(e)}")
384
+
385
+ return value
386
+
387
+
388
+ def validate_base64(
389
+ value: Any,
390
+ name: str,
391
+ allow_none: bool = False,
392
+ max_size_bytes: Optional[int] = None,
393
+ ) -> Optional[str]:
394
+ """
395
+ Validate that a value is a valid base64-encoded string.
396
+
397
+ Args:
398
+ value: Value to validate
399
+ name: Name of the value (for error messages)
400
+ allow_none: Whether None is allowed
401
+ max_size_bytes: Maximum allowed decoded size in bytes
402
+
403
+ Returns:
404
+ The validated base64 string
405
+
406
+ Raises:
407
+ InvalidRequestError: If the value is not valid base64
408
+ """
409
+ # Check if value is None and handle according to allow_none parameter
410
+ if value is None:
411
+ if allow_none:
412
+ return None
413
+ raise InvalidRequestError(f"{name} cannot be None")
414
+
415
+ # Check if value is a string
416
+ if not isinstance(value, str):
417
+ raise InvalidRequestError(
418
+ f"{name} must be a string, got {type(value).__name__}"
419
+ )
420
+
421
+ try:
422
+ # Add padding if necessary to make the base64 string valid
423
+ # Base64 strings should have a length that is a multiple of 4
424
+ padding = 4 - (len(value) % 4) if len(value) % 4 != 0 else 0
425
+ value_padded = value + ("=" * padding)
426
+
427
+ # Try to decode the base64 string to verify it's valid
428
+ decoded = base64.b64decode(value_padded)
429
+
430
+ # Check size if a maximum size is specified
431
+ if max_size_bytes is not None and len(decoded) > max_size_bytes:
432
+ raise InvalidRequestError(
433
+ f"{name} exceeds maximum allowed size of {max_size_bytes} bytes"
434
+ )
435
+ except Exception as e:
436
+ # Re-raise InvalidRequestError exceptions, wrap others
437
+ if isinstance(e, InvalidRequestError):
438
+ raise
439
+ raise InvalidRequestError(
440
+ f"{name} is not a valid base64-encoded string: {str(e)}"
441
+ )
442
+
443
+ return value
444
+
445
+
446
+ def validate_json(
447
+ value: Any,
448
+ name: str,
449
+ schema: Optional[Dict[str, Any]] = None,
450
+ allow_none: bool = False,
451
+ ) -> Optional[Union[Dict[str, Any], List[Any]]]:
452
+ """
453
+ Validate that a value is valid JSON or a JSON-serializable object.
454
+
455
+ Args:
456
+ value: Value to validate (string or object)
457
+ name: Name of the value (for error messages)
458
+ schema: Optional JSON schema to validate against
459
+ allow_none: Whether None is allowed
460
+
461
+ Returns:
462
+ The validated JSON object
463
+
464
+ Raises:
465
+ InvalidRequestError: If the value is not valid JSON
466
+ """
467
+ # Check if value is None and handle according to allow_none parameter
468
+ if value is None:
469
+ if allow_none:
470
+ return None
471
+ raise InvalidRequestError(f"{name} cannot be None")
472
+
473
+ # If the value is a string, try to parse it as JSON
474
+ if isinstance(value, str):
475
+ try:
476
+ value = json.loads(value)
477
+ except json.JSONDecodeError as e:
478
+ raise InvalidRequestError(f"{name} is not valid JSON: {str(e)}")
479
+
480
+ # Check if the value is JSON-serializable by attempting to serialize it
481
+ try:
482
+ json.dumps(value)
483
+ except (TypeError, OverflowError) as e:
484
+ raise InvalidRequestError(f"{name} is not JSON-serializable: {str(e)}")
485
+
486
+ # TODO: Add JSON schema validation if needed in the future
487
+
488
+ return value
489
+
490
+
491
+ # -------------------- Existing Validator Functions --------------------
492
+
493
+
494
+ def validate_model_name(model: str) -> str:
495
+ """
496
+ Validate that the model name has the expected provider/model format.
497
+
498
+ Args:
499
+ model: Model name to validate
500
+
501
+ Returns:
502
+ Validated model name
503
+
504
+ Raises:
505
+ InvalidRequestError: If the model name is invalid
506
+ """
507
+ # Check if model is a string
508
+ if not isinstance(model, str):
509
+ raise InvalidRequestError(f"Model must be a string, got {type(model).__name__}")
510
+
511
+ # Check if model is empty
512
+ if not model:
513
+ raise InvalidRequestError("Model name cannot be empty")
514
+
515
+ # Check if model has provider prefix (format: provider/model-name)
516
+ if "/" not in model:
517
+ raise InvalidRequestError(
518
+ f"Model name '{model}' does not contain a provider prefix. "
519
+ f"Use format 'provider/model-name' (e.g., 'openai/gpt-4')."
520
+ )
521
+
522
+ # Split the model string into provider and model name parts
523
+ provider, model_name = model.split("/", 1)
524
+
525
+ # Validate provider name format (lowercase letters, numbers, underscores, hyphens)
526
+ if not re.match(r"^[a-z0-9_-]+$", provider):
527
+ raise InvalidRequestError(
528
+ f"Invalid provider name '{provider}'. Provider names should contain only "
529
+ f"lowercase letters, numbers, underscores, and hyphens."
530
+ )
531
+
532
+ # Validate model name (non-empty)
533
+ if not model_name:
534
+ raise InvalidRequestError("Model name part cannot be empty")
535
+
536
+ return model
537
+
538
+
539
+ def validate_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
540
+ """
541
+ Validate chat messages format.
542
+
543
+ Args:
544
+ messages: List of message dictionaries to validate
545
+
546
+ Returns:
547
+ Validated messages
548
+
549
+ Raises:
550
+ InvalidRequestError: If the messages are invalid
551
+ """
552
+ # Check if messages is a list
553
+ if not isinstance(messages, list):
554
+ raise InvalidRequestError(
555
+ f"Messages must be a list, got {type(messages).__name__}"
556
+ )
557
+
558
+ # Check if messages list is empty
559
+ if not messages:
560
+ raise InvalidRequestError("Messages list cannot be empty")
561
+
562
+ # Define valid roles for messages
563
+ valid_roles = {"system", "user", "assistant", "tool", "function"}
564
+
565
+ # Validate each message in the list
566
+ for i, message in enumerate(messages):
567
+ if not isinstance(message, dict):
568
+ raise InvalidRequestError(
569
+ f"Message {i} must be a dictionary, got {type(message).__name__}"
570
+ )
571
+
572
+ # Check required fields
573
+ if "role" not in message:
574
+ raise InvalidRequestError(f"Message {i} is missing required field 'role'")
575
+
576
+ if (
577
+ "content" not in message
578
+ and "function_call" not in message
579
+ and "tool_calls" not in message
580
+ ):
581
+ raise InvalidRequestError(
582
+ f"Message {i} is missing required field 'content' (or function_call/tool_calls)"
583
+ )
584
+
585
+ # Validate role
586
+ role = message["role"]
587
+ if not isinstance(role, str):
588
+ raise InvalidRequestError(
589
+ f"Message {i} role must be a string, got {type(role).__name__}"
590
+ )
591
+
592
+ if role not in valid_roles:
593
+ raise InvalidRequestError(
594
+ f"Message {i} has invalid role '{role}'. Valid roles are: {', '.join(valid_roles)}"
595
+ )
596
+
597
+ # Validate content
598
+ content = message.get("content")
599
+ if content is not None:
600
+ # Content can be a string or a list of content parts (for multi-modal)
601
+ if not isinstance(content, (str, list)):
602
+ raise InvalidRequestError(
603
+ f"Message {i} content must be a string or list, got {type(content).__name__}"
604
+ )
605
+
606
+ # Validate multi-modal content
607
+ if isinstance(content, list):
608
+ validate_multimodal_content(content, message_index=i)
609
+
610
+ # Validate function_call if present
611
+ function_call = message.get("function_call")
612
+ if function_call is not None:
613
+ if not isinstance(function_call, dict):
614
+ raise InvalidRequestError(
615
+ f"Message {i} function_call must be a dictionary, "
616
+ f"got {type(function_call).__name__}"
617
+ )
618
+
619
+ if "name" not in function_call:
620
+ raise InvalidRequestError(
621
+ f"Message {i} function_call is missing required field 'name'"
622
+ )
623
+
624
+ if not isinstance(function_call["name"], str):
625
+ raise InvalidRequestError(
626
+ f"Message {i} function_call name must be a string, "
627
+ f"got {type(function_call['name']).__name__}"
628
+ )
629
+
630
+ # Validate tool_calls if present
631
+ tool_calls = message.get("tool_calls")
632
+ if tool_calls is not None:
633
+ if not isinstance(tool_calls, list):
634
+ raise InvalidRequestError(
635
+ f"Message {i} tool_calls must be a list, got {type(tool_calls).__name__}"
636
+ )
637
+
638
+ for j, tool_call in enumerate(tool_calls):
639
+ if not isinstance(tool_call, dict):
640
+ raise InvalidRequestError(
641
+ f"Message {i} tool_call {j} must be a dictionary, "
642
+ f"got {type(tool_call).__name__}"
643
+ )
644
+
645
+ if "id" not in tool_call:
646
+ raise InvalidRequestError(
647
+ f"Message {i} tool_call {j} is missing required field 'id'"
648
+ )
649
+
650
+ if "type" not in tool_call:
651
+ raise InvalidRequestError(
652
+ f"Message {i} tool_call {j} is missing required field 'type'"
653
+ )
654
+
655
+ if "function" not in tool_call:
656
+ raise InvalidRequestError(
657
+ f"Message {i} tool_call {j} is missing required field 'function'"
658
+ )
659
+
660
+ return messages
661
+
662
+
663
+ def validate_multimodal_content(
664
+ content: List[Dict[str, Any]], message_index: int = 0
665
+ ) -> List[Dict[str, Any]]:
666
+ """
667
+ Validate multi-modal content format.
668
+
669
+ Args:
670
+ content: List of content parts to validate
671
+ message_index: Index of the message containing this content (for error messages)
672
+
673
+ Returns:
674
+ Validated content
675
+
676
+ Raises:
677
+ InvalidRequestError: If the content is invalid
678
+ """
679
+ # Define valid content types for multi-modal messages
680
+ valid_types = {"text", "image_url", "image", "audio_url", "audio"}
681
+
682
+ # Validate each content part
683
+ for i, part in enumerate(content):
684
+ if not isinstance(part, dict):
685
+ raise InvalidRequestError(
686
+ f"Message {message_index} content part {i} must be a dictionary, "
687
+ f"got {type(part).__name__}"
688
+ )
689
+
690
+ if "type" not in part:
691
+ raise InvalidRequestError(
692
+ f"Message {message_index} content part {i} is missing required field 'type'"
693
+ )
694
+
695
+ part_type = part["type"]
696
+ if not isinstance(part_type, str):
697
+ raise InvalidRequestError(
698
+ f"Message {message_index} content part {i} type must be a string, "
699
+ f"got {type(part_type).__name__}"
700
+ )
701
+
702
+ if part_type not in valid_types:
703
+ raise InvalidRequestError(
704
+ f"Message {message_index} content part {i} has invalid type '{part_type}'. "
705
+ f"Valid types are: {', '.join(valid_types)}"
706
+ )
707
+
708
+ # Validate type-specific fields
709
+ if part_type == "text":
710
+ # Text type requires a 'text' field with a string value
711
+ if "text" not in part:
712
+ raise InvalidRequestError(
713
+ f"Message {message_index} content part {i} is missing required field 'text'"
714
+ )
715
+
716
+ if not isinstance(part["text"], str):
717
+ raise InvalidRequestError(
718
+ f"Message {message_index} content part {i} text must be a string, "
719
+ f"got {type(part['text']).__name__}"
720
+ )
721
+
722
+ elif part_type == "image_url":
723
+ # Image URL type requires 'image_url' field with a dictionary containing a 'url' field
724
+ if "image_url" not in part:
725
+ raise InvalidRequestError(
726
+ f"Message {message_index} content part {i} "
727
+ f"is missing required field 'image_url'"
728
+ )
729
+
730
+ image_url = part["image_url"]
731
+ if not isinstance(image_url, dict):
732
+ raise InvalidRequestError(
733
+ f"Message {message_index} content part {i} image_url must be a dictionary, "
734
+ f"got {type(image_url).__name__}"
735
+ )
736
+
737
+ if "url" not in image_url:
738
+ raise InvalidRequestError(
739
+ f"Message {message_index} content part {i} "
740
+ f"image_url is missing required field 'url'"
741
+ )
742
+
743
+ if not isinstance(image_url["url"], str):
744
+ raise InvalidRequestError(
745
+ f"Message {message_index} content part {i} image_url.url must be a string, "
746
+ f"got {type(image_url['url']).__name__}"
747
+ )
748
+
749
+ elif part_type == "audio_url":
750
+ # Audio URL type requires 'audio_url' field with a dictionary containing a 'url' field
751
+ if "audio_url" not in part:
752
+ raise InvalidRequestError(
753
+ f"Message {message_index} content part {i} "
754
+ f"is missing required field 'audio_url'"
755
+ )
756
+
757
+ audio_url = part["audio_url"]
758
+ if not isinstance(audio_url, dict):
759
+ raise InvalidRequestError(
760
+ f"Message {message_index} content part {i} audio_url must be a dictionary, "
761
+ f"got {type(audio_url).__name__}"
762
+ )
763
+
764
+ if "url" not in audio_url:
765
+ raise InvalidRequestError(
766
+ f"Message {message_index} content part {i} "
767
+ f"audio_url is missing required field 'url'"
768
+ )
769
+
770
+ if not isinstance(audio_url["url"], str):
771
+ raise InvalidRequestError(
772
+ f"Message {message_index} content part {i} audio_url.url must be a string, "
773
+ f"got {type(audio_url['url']).__name__}"
774
+ )
775
+
776
+ return content
777
+
778
+
779
+ def validate_temperature(temperature: Optional[float]) -> Optional[float]:
780
+ """
781
+ Validate temperature parameter.
782
+
783
+ Args:
784
+ temperature: Temperature value to validate
785
+
786
+ Returns:
787
+ Validated temperature
788
+
789
+ Raises:
790
+ InvalidRequestError: If the temperature is invalid
791
+ """
792
+ # Return None if temperature is None (use default)
793
+ if temperature is None:
794
+ return None
795
+
796
+ # Check if temperature is a number (int or float)
797
+ if not isinstance(temperature, (int, float)):
798
+ raise InvalidRequestError(
799
+ f"Temperature must be a number, got {type(temperature).__name__}"
800
+ )
801
+
802
+ # Convert to float for consistency
803
+ temperature = float(temperature)
804
+
805
+ # Check range (typically between 0 and 2 for LLM temperature)
806
+ if temperature < 0 or temperature > 2:
807
+ raise InvalidRequestError("Temperature must be between 0 and 2")
808
+
809
+ return temperature
810
+
811
+
812
+ def validate_top_p(top_p: Optional[float]) -> Optional[float]:
813
+ """
814
+ Validate top_p parameter.
815
+
816
+ Args:
817
+ top_p: Top-p value to validate
818
+
819
+ Returns:
820
+ Validated top_p
821
+
822
+ Raises:
823
+ InvalidRequestError: If the top_p is invalid
824
+ """
825
+ # Return None if top_p is None (use default)
826
+ if top_p is None:
827
+ return None
828
+
829
+ # Check if top_p is a number (int or float)
830
+ if not isinstance(top_p, (int, float)):
831
+ raise InvalidRequestError(f"Top_p must be a number, got {type(top_p).__name__}")
832
+
833
+ # Convert to float for consistency
834
+ top_p = float(top_p)
835
+
836
+ # Check range (top_p must be between 0 and 1)
837
+ if top_p < 0 or top_p > 1:
838
+ raise InvalidRequestError("Top_p must be between 0 and 1")
839
+
840
+ return top_p
841
+
842
+
843
+ def validate_presence_penalty(presence_penalty: Optional[float]) -> Optional[float]:
844
+ """
845
+ Validate presence_penalty parameter.
846
+
847
+ Args:
848
+ presence_penalty: Presence penalty value to validate
849
+
850
+ Returns:
851
+ Validated presence_penalty
852
+
853
+ Raises:
854
+ InvalidRequestError: If the presence_penalty is invalid
855
+ """
856
+ # Return None if presence_penalty is None (use default)
857
+ if presence_penalty is None:
858
+ return None
859
+
860
+ # Check if presence_penalty is a number (int or float)
861
+ if not isinstance(presence_penalty, (int, float)):
862
+ raise InvalidRequestError(
863
+ f"Presence_penalty must be a number, got {type(presence_penalty).__name__}"
864
+ )
865
+
866
+ # Convert to float for consistency
867
+ presence_penalty = float(presence_penalty)
868
+
869
+ # Check range (typically between -2 and 2 for presence penalty)
870
+ if presence_penalty < -2 or presence_penalty > 2:
871
+ raise InvalidRequestError("Presence_penalty must be between -2 and 2")
872
+
873
+ return presence_penalty
874
+
875
+
876
+ def validate_frequency_penalty(frequency_penalty: Optional[float]) -> Optional[float]:
877
+ """
878
+ Validate frequency_penalty parameter.
879
+
880
+ Args:
881
+ frequency_penalty: Frequency penalty value to validate
882
+
883
+ Returns:
884
+ Validated frequency_penalty
885
+
886
+ Raises:
887
+ InvalidRequestError: If the frequency_penalty is invalid
888
+ """
889
+ # Return None if frequency_penalty is None (use default)
890
+ if frequency_penalty is None:
891
+ return None
892
+
893
+ # Check if frequency_penalty is a number (int or float)
894
+ if not isinstance(frequency_penalty, (int, float)):
895
+ raise InvalidRequestError(
896
+ f"Frequency_penalty must be a number, got {type(frequency_penalty).__name__}"
897
+ )
898
+
899
+ # Convert to float for consistency
900
+ frequency_penalty = float(frequency_penalty)
901
+
902
+ # Check range (typically between -2 and 2 for frequency penalty)
903
+ if frequency_penalty < -2 or frequency_penalty > 2:
904
+ raise InvalidRequestError("Frequency_penalty must be between -2 and 2")
905
+
906
+ return frequency_penalty
907
+
908
+
909
+ def validate_max_tokens(max_tokens: Optional[int]) -> Optional[int]:
910
+ """
911
+ Validate max_tokens parameter.
912
+
913
+ Args:
914
+ max_tokens: Max tokens value to validate
915
+
916
+ Returns:
917
+ Validated max_tokens
918
+
919
+ Raises:
920
+ InvalidRequestError: If the max_tokens is invalid
921
+ """
922
+ # Return None if max_tokens is None (use default)
923
+ if max_tokens is None:
924
+ return None
925
+
926
+ # Check if max_tokens is an integer
927
+ if not isinstance(max_tokens, int):
928
+ raise InvalidRequestError(
929
+ f"Max_tokens must be an integer, got {type(max_tokens).__name__}"
930
+ )
931
+
932
+ # Check range (must be positive)
933
+ if max_tokens < 1:
934
+ raise InvalidRequestError("Max_tokens must be greater than 0")
935
+
936
+ return max_tokens
937
+
938
+
939
+ def validate_n(n: Optional[int]) -> Optional[int]:
940
+ """
941
+ Validate n parameter (number of completions).
942
+
943
+ Args:
944
+ n: Number of completions to validate
945
+
946
+ Returns:
947
+ Validated n
948
+
949
+ Raises:
950
+ InvalidRequestError: If n is invalid
951
+ """
952
+ # Return None if n is None (use default)
953
+ if n is None:
954
+ return None
955
+
956
+ # Check if n is an integer
957
+ if not isinstance(n, int):
958
+ raise InvalidRequestError(f"N must be an integer, got {type(n).__name__}")
959
+
960
+ # Check range (must be positive)
961
+ if n < 1:
962
+ raise InvalidRequestError("N must be greater than 0")
963
+
964
+ return n
965
+
966
+
967
+ def validate_stop(
968
+ stop: Optional[Union[str, List[str]]],
969
+ ) -> Optional[Union[str, List[str]]]:
970
+ """
971
+ Validate stop parameter.
972
+
973
+ Args:
974
+ stop: Stop sequence(s) to validate
975
+
976
+ Returns:
977
+ Validated stop
978
+
979
+ Raises:
980
+ InvalidRequestError: If stop is invalid
981
+ """
982
+ # Return None if stop is None (use default)
983
+ if stop is None:
984
+ return None
985
+
986
+ # Handle single string stop sequence
987
+ if isinstance(stop, str):
988
+ # Single string is fine
989
+ return stop
990
+
991
+ # Handle list of stop sequences
992
+ if isinstance(stop, list):
993
+ # Check that all elements are strings
994
+ for i, s in enumerate(stop):
995
+ if not isinstance(s, str):
996
+ raise InvalidRequestError(
997
+ f"Stop sequence at index {i} must be a string, got {type(s).__name__}"
998
+ )
999
+
1000
+ # Check list length (OpenAI API typically limits to 4 stop sequences)
1001
+ if len(stop) > 4:
1002
+ raise InvalidRequestError("Maximum of 4 stop sequences allowed")
1003
+
1004
+ return stop
1005
+
1006
+ # If we get here, stop is neither None, a string, nor a list
1007
+ raise InvalidRequestError(
1008
+ f"Stop must be a string or list of strings, got {type(stop).__name__}"
1009
+ )
1010
+
1011
+
1012
+ def validate_prompt(prompt: Union[str, List[str]]) -> Union[str, List[str]]:
1013
+ """
1014
+ Validate prompt parameter for text completions.
1015
+
1016
+ This function ensures that the prompt is either a non-empty string or a non-empty
1017
+ list of strings, which are the only valid formats for prompts in LLM requests.
1018
+
1019
+ Args:
1020
+ prompt: Prompt to validate (string or list of strings)
1021
+
1022
+ Returns:
1023
+ Validated prompt (unchanged if valid)
1024
+
1025
+ Raises:
1026
+ InvalidRequestError: If prompt is empty, contains non-string elements, or has invalid type
1027
+ """
1028
+ # Handle single string prompt
1029
+ if isinstance(prompt, str):
1030
+ # Check that string is not empty
1031
+ if not prompt:
1032
+ raise InvalidRequestError("Prompt cannot be empty")
1033
+ return prompt
1034
+
1035
+ # Handle list of prompts
1036
+ if isinstance(prompt, list):
1037
+ # Check that all elements are strings
1038
+ for i, p in enumerate(prompt):
1039
+ if not isinstance(p, str):
1040
+ raise InvalidRequestError(
1041
+ f"Prompt at index {i} must be a string, got {type(p).__name__}"
1042
+ )
1043
+
1044
+ # Check that list is not empty
1045
+ if not prompt:
1046
+ raise InvalidRequestError("Prompt list cannot be empty")
1047
+
1048
+ return prompt
1049
+
1050
+ # If we get here, prompt is neither a string nor a list
1051
+ raise InvalidRequestError(
1052
+ f"Prompt must be a string or list of strings, got {type(prompt).__name__}"
1053
+ )
1054
+
1055
+
1056
+ def validate_response_format(
1057
+ response_format: Optional[Dict[str, Any]],
1058
+ ) -> Optional[Dict[str, Any]]:
1059
+ """
1060
+ Validate response_format parameter.
1061
+
1062
+ This function validates the response_format parameter used in completion requests,
1063
+ ensuring it has the correct structure and valid values for the 'type' field.
1064
+
1065
+ Args:
1066
+ response_format: Response format to validate (dictionary or None)
1067
+
1068
+ Returns:
1069
+ Validated response_format (unchanged if valid)
1070
+
1071
+ Raises:
1072
+ InvalidRequestError: If response_format has invalid structure or values
1073
+ """
1074
+ # None is a valid value (use default response format)
1075
+ if response_format is None:
1076
+ return None
1077
+
1078
+ # Must be a dictionary
1079
+ if not isinstance(response_format, dict):
1080
+ raise InvalidRequestError(
1081
+ f"Response_format must be a dictionary, got {type(response_format).__name__}"
1082
+ )
1083
+
1084
+ # Check required fields
1085
+ if "type" not in response_format:
1086
+ raise InvalidRequestError("Response_format is missing required field 'type'")
1087
+
1088
+ # Validate type field
1089
+ type_value = response_format["type"]
1090
+ if not isinstance(type_value, str):
1091
+ raise InvalidRequestError(
1092
+ f"Response_format type must be a string, got {type(type_value).__name__}"
1093
+ )
1094
+
1095
+ # Check that type is one of the allowed values
1096
+ valid_types = {"text", "json_object"}
1097
+ if type_value not in valid_types:
1098
+ raise InvalidRequestError(
1099
+ f"Response_format type '{type_value}' is invalid. "
1100
+ f"Valid types are: {', '.join(valid_types)}"
1101
+ )
1102
+
1103
+ return response_format
1104
+
1105
+
1106
+ def validate_input_for_embeddings(
1107
+ input_value: Union[str, List[str]],
1108
+ ) -> Union[str, List[str]]:
1109
+ """
1110
+ Validate input parameter for embeddings.
1111
+
1112
+ This function ensures that the input for embedding requests is either a non-empty
1113
+ string or a non-empty list of strings, which are the only valid formats for
1114
+ embedding inputs.
1115
+
1116
+ Args:
1117
+ input_value: Input to validate (string or list of strings)
1118
+
1119
+ Returns:
1120
+ Validated input (unchanged if valid)
1121
+
1122
+ Raises:
1123
+ InvalidRequestError: If input is empty, contains non-string elements, or has invalid type
1124
+ """
1125
+ # Handle single string input
1126
+ if isinstance(input_value, str):
1127
+ # Check that string is not empty
1128
+ if not input_value:
1129
+ raise InvalidRequestError("Input for embeddings cannot be empty")
1130
+ return input_value
1131
+
1132
+ # Handle list of inputs
1133
+ if isinstance(input_value, list):
1134
+ # Check that all elements are strings
1135
+ for i, item in enumerate(input_value):
1136
+ if not isinstance(item, str):
1137
+ raise InvalidRequestError(
1138
+ f"Input at index {i} must be a string, got {type(item).__name__}"
1139
+ )
1140
+
1141
+ # Check that list is not empty
1142
+ if not input_value:
1143
+ raise InvalidRequestError("Input list for embeddings cannot be empty")
1144
+
1145
+ return input_value
1146
+
1147
+ # If we get here, input is neither a string nor a list
1148
+ raise InvalidRequestError(
1149
+ f"Input must be a string or list of strings, got {type(input_value).__name__}"
1150
+ )
1151
+
1152
+
1153
+ def validate_stream(stream: Optional[bool]) -> Optional[bool]:
1154
+ """
1155
+ Validate stream parameter.
1156
+
1157
+ This function validates that the stream parameter is either None or a boolean value,
1158
+ which determines whether responses should be streamed or returned as a complete response.
1159
+
1160
+ Args:
1161
+ stream: Stream value to validate (boolean or None)
1162
+
1163
+ Returns:
1164
+ Validated stream value (unchanged if valid)
1165
+
1166
+ Raises:
1167
+ InvalidRequestError: If stream is not a boolean or None
1168
+ """
1169
+ # None is a valid value (use default streaming behavior)
1170
+ if stream is None:
1171
+ return None
1172
+
1173
+ # Must be a boolean
1174
+ if not isinstance(stream, bool):
1175
+ raise InvalidRequestError(
1176
+ f"Stream must be a boolean, got {type(stream).__name__}"
1177
+ )
1178
+
1179
+ return stream
1180
+
1181
+
1182
+ def validate_functions(
1183
+ functions: Optional[List[Dict[str, Any]]],
1184
+ ) -> Optional[List[Dict[str, Any]]]:
1185
+ """
1186
+ Validate functions parameter.
1187
+
1188
+ This function validates the functions parameter used in function calling requests,
1189
+ ensuring each function has the required fields and correct structure.
1190
+
1191
+ Args:
1192
+ functions: Functions to validate (list of dictionaries or None)
1193
+
1194
+ Returns:
1195
+ Validated functions (unchanged if valid)
1196
+
1197
+ Raises:
1198
+ InvalidRequestError: If functions has invalid structure or missing required fields
1199
+ """
1200
+ # None is a valid value (no functions)
1201
+ if functions is None:
1202
+ return None
1203
+
1204
+ # Must be a list
1205
+ if not isinstance(functions, list):
1206
+ raise InvalidRequestError(
1207
+ f"Functions must be a list, got {type(functions).__name__}"
1208
+ )
1209
+
1210
+ # Validate each function in the list
1211
+ for i, function in enumerate(functions):
1212
+ # Each function must be a dictionary
1213
+ if not isinstance(function, dict):
1214
+ raise InvalidRequestError(
1215
+ f"Function {i} must be a dictionary, got {type(function).__name__}"
1216
+ )
1217
+
1218
+ # Check required fields
1219
+ if "name" not in function:
1220
+ raise InvalidRequestError(f"Function {i} is missing required field 'name'")
1221
+
1222
+ # Name must be a string
1223
+ if not isinstance(function["name"], str):
1224
+ raise InvalidRequestError(
1225
+ f"Function {i} name must be a string, got {type(function['name']).__name__}"
1226
+ )
1227
+
1228
+ # Validate parameters if present
1229
+ parameters = function.get("parameters")
1230
+ if parameters is not None:
1231
+ if not isinstance(parameters, dict):
1232
+ raise InvalidRequestError(
1233
+ f"Function {i} parameters must be a dictionary, got {type(parameters).__name__}"
1234
+ )
1235
+
1236
+ return functions
1237
+
1238
+
1239
+ def validate_tools(
1240
+ tools: Optional[List[Dict[str, Any]]],
1241
+ ) -> Optional[List[Dict[str, Any]]]:
1242
+ """
1243
+ Validate tools parameter.
1244
+
1245
+ This function validates the tools parameter used in tool-using requests,
1246
+ ensuring each tool has the required fields and correct structure. Currently,
1247
+ only 'function' type tools are supported.
1248
+
1249
+ Args:
1250
+ tools: Tools to validate (list of dictionaries or None)
1251
+
1252
+ Returns:
1253
+ Validated tools (unchanged if valid)
1254
+
1255
+ Raises:
1256
+ InvalidRequestError: If tools has invalid structure or missing required fields
1257
+ """
1258
+ # None is a valid value (no tools)
1259
+ if tools is None:
1260
+ return None
1261
+
1262
+ # Must be a list
1263
+ if not isinstance(tools, list):
1264
+ raise InvalidRequestError(f"Tools must be a list, got {type(tools).__name__}")
1265
+
1266
+ # Validate each tool in the list
1267
+ for i, tool in enumerate(tools):
1268
+ # Each tool must be a dictionary
1269
+ if not isinstance(tool, dict):
1270
+ raise InvalidRequestError(
1271
+ f"Tool {i} must be a dictionary, got {type(tool).__name__}"
1272
+ )
1273
+
1274
+ # Check required fields
1275
+ if "type" not in tool:
1276
+ raise InvalidRequestError(f"Tool {i} is missing required field 'type'")
1277
+
1278
+ # Type must be a string
1279
+ if not isinstance(tool["type"], str):
1280
+ raise InvalidRequestError(
1281
+ f"Tool {i} type must be a string, got {type(tool['type']).__name__}"
1282
+ )
1283
+
1284
+ # Currently only 'function' type is supported
1285
+ if tool["type"] != "function":
1286
+ raise InvalidRequestError(
1287
+ f"Tool {i} has unsupported type '{tool['type']}'. "
1288
+ f"Currently only 'function' is supported."
1289
+ )
1290
+
1291
+ # Function field is required for function-type tools
1292
+ if "function" not in tool:
1293
+ raise InvalidRequestError(f"Tool {i} is missing required field 'function'")
1294
+
1295
+ # Function must be a dictionary
1296
+ function = tool["function"]
1297
+ if not isinstance(function, dict):
1298
+ raise InvalidRequestError(
1299
+ f"Tool {i} function must be a dictionary, got {type(function).__name__}"
1300
+ )
1301
+
1302
+ # Function name is required
1303
+ if "name" not in function:
1304
+ raise InvalidRequestError(
1305
+ f"Tool {i} function is missing required field 'name'"
1306
+ )
1307
+
1308
+ # Function name must be a string
1309
+ if not isinstance(function["name"], str):
1310
+ raise InvalidRequestError(
1311
+ f"Tool {i} function name must be a string, got {type(function['name']).__name__}"
1312
+ )
1313
+
1314
+ return tools