Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai python SDK General Utils

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure, Python
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for general-purpose SDK utilities provided by the openai-python SDK.

Description

The General Utils module provides a collection of helper functions used throughout the SDK. flatten() merges nested iterables into a single list. extract_files() recursively extracts file content from request dictionaries based on path specifications, mutating the dictionary in place and returning file tuples suitable for multipart uploads. required_args() is a decorator that enforces runtime validation of overloaded function signatures, ensuring that callers provide the correct combination of arguments. The module also provides type coercion functions: coerce_integer(), coerce_float(), and coerce_boolean() convert string values to their respective Python types. Additional helpers include is_given() for checking whether a value was explicitly provided (not NotGiven or Omit), deepcopy_minimal() for performant shallow-recursive copying of dicts and lists, strip_not_given() for removing unset keys, human_join() for human-readable list formatting, and lru_cache() as a type-safe wrapper around functools.lru_cache.

Usage

Use these utilities when working with SDK internals such as building request bodies, validating function arguments at runtime, extracting file uploads from nested parameter structures, or coercing environment variable strings into typed values. The extract_files() function is particularly important for multipart file upload endpoints. The required_args() decorator is used on every overloaded resource method to enforce correct argument combinations.

Code Reference

Source Location

Signature

flatten()

def flatten(t: Iterable[Iterable[_T]]) -> list[_T]: ...

extract_files()

def extract_files(
    query: Mapping[str, object],
    *,
    paths: Sequence[Sequence[str]],
) -> list[tuple[str, FileTypes]]: ...

required_args()

def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: ...

coerce_integer()

def coerce_integer(val: str) -> int: ...

coerce_float()

def coerce_float(val: str) -> float: ...

coerce_boolean()

def coerce_boolean(val: str) -> bool: ...

Import

from openai._utils._utils import flatten, extract_files, required_args, coerce_integer, coerce_float, coerce_boolean

I/O Contract

Inputs

flatten()

Name Type Required Description
t Iterable[Iterable[_T]] Yes A nested iterable to flatten into a single list.

extract_files()

Name Type Required Description
query Mapping[str, object] Yes The request parameter dictionary to extract files from. This dictionary is mutated in place.
paths Sequence[Sequence[str]] Yes A list of path specifications (e.g., [["foo", "files", "<array>", "data"]]) describing where files are located in the dictionary.

required_args()

Name Type Required Description
*variants Sequence[str] Yes One or more sequences of argument names. At least one variant must be fully satisfied by the caller.

coerce_integer() / coerce_float() / coerce_boolean()

Name Type Required Description
val str Yes The string value to coerce. For coerce_boolean, "true", "1", or "on" return True; all others return False.

Outputs

Name Type Description
return (flatten) list[_T] A flat list containing all items from the nested iterables.
return (extract_files) list[tuple[str, FileTypes]] A list of (key, file_content) tuples extracted from the dictionary.
return (required_args) Callable[[CallableT], CallableT] A decorator that wraps the target function with argument validation.
return (coerce_integer) int The integer parsed from the string (base 10).
return (coerce_float) float The float parsed from the string.
return (coerce_boolean) bool True if the string is "true", "1", or "on"; otherwise False.

Usage Examples

Flattening Nested Lists

from openai._utils._utils import flatten

result = flatten([[1, 2], [3, 4], [5]])
# result: [1, 2, 3, 4, 5]

Extracting Files from Request Data

from openai._utils._utils import extract_files

data = {"file": open("image.png", "rb"), "prompt": "describe this"}
files = extract_files(data, paths=[["file"]])
# files: [("file", <file content>)]
# data is now: {"prompt": "describe this"}

Runtime Argument Validation

from openai._utils._utils import required_args

@required_args(["a"], ["b"])
def my_func(*, a: str | None = None, b: bool | None = None) -> str:
    return "ok"

my_func(a="hello")   # works
my_func(b=True)      # works
my_func()            # raises TypeError

Coercing Environment Variables

from openai._utils._utils import coerce_integer, coerce_float, coerce_boolean

max_retries = coerce_integer("3")       # 3
temperature = coerce_float("0.7")       # 0.7
verbose = coerce_boolean("true")        # True

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment