-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Improve import startup with lazy top-level exports #2950
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fede-kamel
wants to merge
2
commits into
openai:main
Choose a base branch
from
fede-kamel:feat/import-startup-lazy-2819
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| #!/usr/bin/env python3 | ||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import os | ||
| import subprocess | ||
| import sys | ||
| import time | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| def _pythonpath_for_repo() -> str | None: | ||
| src = Path(__file__).resolve().parents[1] / "src" | ||
| if not src.exists(): | ||
| return None | ||
|
|
||
| existing = os.environ.get("PYTHONPATH") | ||
| if existing: | ||
| return f"{src}{os.pathsep}{existing}" | ||
| return str(src) | ||
|
|
||
|
|
||
| def _cold_import_seconds(repeats: int, env: dict[str, str]) -> list[float]: | ||
| samples: list[float] = [] | ||
| for _ in range(repeats): | ||
| start = time.perf_counter() | ||
| subprocess.run([sys.executable, "-c", "import openai"], check=True, env=env, stdout=subprocess.DEVNULL) | ||
| samples.append(time.perf_counter() - start) | ||
| return samples | ||
|
|
||
|
|
||
| def _importtime_output(env: dict[str, str]) -> str: | ||
| proc = subprocess.run( | ||
| [sys.executable, "-X", "importtime", "-c", "import openai"], | ||
| check=True, | ||
| env=env, | ||
| stderr=subprocess.PIPE, | ||
| stdout=subprocess.DEVNULL, | ||
| text=True, | ||
| ) | ||
| return proc.stderr | ||
|
|
||
|
|
||
| def _parse_importtime(importtime_stderr: str) -> list[tuple[int, str]]: | ||
| rows: list[tuple[int, str]] = [] | ||
| for line in importtime_stderr.splitlines(): | ||
| if "| " not in line: | ||
| continue | ||
| if "import time:" not in line: | ||
| continue | ||
| _, _, payload = line.partition("import time:") | ||
| parts = [p.strip() for p in payload.split("|")] | ||
| if len(parts) != 3: | ||
| continue | ||
| cumulative_raw = parts[1] | ||
| module = parts[2] | ||
| if not module.startswith("openai"): | ||
| continue | ||
| try: | ||
| cumulative = int(cumulative_raw) | ||
| except ValueError: | ||
| continue | ||
| rows.append((cumulative, module)) | ||
| rows.sort(reverse=True) | ||
| return rows | ||
|
|
||
|
|
||
| def main() -> int: | ||
| parser = argparse.ArgumentParser(description="Benchmark openai import time for this checkout.") | ||
| parser.add_argument("--repeats", type=int, default=5, help="Number of cold imports to sample") | ||
| parser.add_argument("--top", type=int, default=20, help="How many importtime rows to print") | ||
| args = parser.parse_args() | ||
|
|
||
| env = dict(os.environ) | ||
| pythonpath = _pythonpath_for_repo() | ||
| if pythonpath is not None: | ||
| env["PYTHONPATH"] = pythonpath | ||
|
|
||
| samples = _cold_import_seconds(repeats=args.repeats, env=env) | ||
| avg = sum(samples) / len(samples) | ||
|
|
||
| print(f"Python: {sys.executable}") | ||
| print(f"Samples (s): {[round(s, 4) for s in samples]}") | ||
| print(f"Average cold import (s): {avg:.4f}") | ||
| print() | ||
|
|
||
| rows = _parse_importtime(_importtime_output(env)) | ||
| print(f"Top {min(args.top, len(rows))} cumulative importtime rows (us):") | ||
| for cumulative, module in rows[: args.top]: | ||
| print(f"{cumulative:>8} {module}") | ||
|
|
||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| raise SystemExit(main()) |
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import sys | ||
| import importlib | ||
|
|
||
| import pytest | ||
|
|
||
|
|
||
| def _openai_modules() -> dict[str, object]: | ||
| return {name: mod for name, mod in sys.modules.items() if name == "openai" or name.startswith("openai.")} | ||
|
|
||
|
|
||
| def _restore_openai_modules(original_modules: dict[str, object]) -> None: | ||
| for name in list(sys.modules): | ||
| if name == "openai" or name.startswith("openai."): | ||
| sys.modules.pop(name, None) | ||
| sys.modules.update(original_modules) | ||
|
|
||
|
|
||
| @pytest.mark.skipif(os.environ.get("OPENAI_LIVE") != "1", reason="requires OPENAI_LIVE=1") | ||
| @pytest.mark.skipif(not os.environ.get("OPENAI_API_KEY"), reason="requires OPENAI_API_KEY") | ||
| def test_eager_import_with_live_token_allows_real_request(monkeypatch) -> None: | ||
| # Exercise eager mode in a real SDK flow behind explicit live-test flags. | ||
| monkeypatch.setenv("OPENAI_EAGER_IMPORT", "1") | ||
| original_modules = _openai_modules() | ||
|
|
||
| for name in original_modules: | ||
| sys.modules.pop(name, None) | ||
|
|
||
| client = None | ||
| try: | ||
| openai = importlib.import_module("openai") | ||
|
|
||
| assert "openai.types" in sys.modules | ||
| assert "openai.lib.azure" in sys.modules | ||
| assert "AzureOpenAI" in openai.__dict__ | ||
|
|
||
| client = openai.OpenAI(timeout=20.0) | ||
| page = client.models.list() | ||
| assert page.data is not None | ||
| finally: | ||
| if client is not None: | ||
| client.close() | ||
| _restore_openai_modules(original_modules) |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import importlib | ||
| import sys | ||
|
|
||
|
|
||
| def _openai_modules() -> dict[str, object]: | ||
| return {name: mod for name, mod in sys.modules.items() if name == "openai" or name.startswith("openai.")} | ||
|
|
||
|
|
||
| def _restore_openai_modules(original_modules: dict[str, object]) -> None: | ||
| for name in list(sys.modules): | ||
| if name == "openai" or name.startswith("openai."): | ||
| sys.modules.pop(name, None) | ||
| sys.modules.update(original_modules) | ||
|
|
||
|
|
||
| def test_openai_azure_is_lazy_imported(monkeypatch) -> None: | ||
| monkeypatch.delenv("OPENAI_EAGER_IMPORT", raising=False) | ||
| original_modules = _openai_modules() | ||
|
|
||
| for name in original_modules: | ||
| sys.modules.pop(name, None) | ||
|
|
||
| try: | ||
| openai = importlib.import_module("openai") | ||
|
|
||
| assert "openai.lib.azure" not in sys.modules | ||
|
|
||
| assert openai.AzureOpenAI is not None | ||
| assert "openai.lib.azure" in sys.modules | ||
| finally: | ||
| _restore_openai_modules(original_modules) | ||
|
|
||
|
|
||
| def test_openai_eager_import_resolves_lazy_exports(monkeypatch) -> None: | ||
| original_modules = _openai_modules() | ||
| monkeypatch.setenv("OPENAI_EAGER_IMPORT", "1") | ||
|
|
||
| for name in original_modules: | ||
| sys.modules.pop(name, None) | ||
|
|
||
| try: | ||
| openai = importlib.import_module("openai") | ||
|
|
||
| assert "openai.types" in sys.modules | ||
| assert "openai.lib.azure" in sys.modules | ||
| assert "AzureOpenAI" in openai.__dict__ | ||
| assert "AsyncAzureOpenAI" in openai.__dict__ | ||
| assert "pydantic_function_tool" in openai.__dict__ | ||
| assert "AssistantEventHandler" in openai.__dict__ | ||
| assert "AsyncAssistantEventHandler" in openai.__dict__ | ||
| finally: | ||
| _restore_openai_modules(original_modules) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This
AttributeErrornow interpolates__name__, but earlier in the module a loop assignsfor __name in __all__, so__name__is no longer'openai'by the time this runs. As a result, unknown-attribute failures can report the wrong module name, which makes debugging and import error messages misleading.Useful? React with 👍 / 👎.