⚡️ Speed up function openai_model_profile
by 241%
#27
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.
📄 241% (2.41x) speedup for
openai_model_profile
inpydantic_ai_slim/pydantic_ai/profiles/openai.py
⏱️ Runtime :
1.20 milliseconds
→353 microseconds
(best of70
runs)📝 Explanation and details
REFINEMENT Here's a version of your program optimized for runtime, based on the line profiling results and analysis.
The major slow point in your program is the construction of the
OpenAIModelProfile
, which is being called thousands of times (7158
hits in profiling).Observations:
OpenAIModelProfile
and the arguments passed are pure (no side effects and depend only on arguments) and there are only a small number of possible configurations (i.e.,is_reasoning_model
is onlyTrue
orFalse
), you can cache the results.model_name.startswith('o')
only leads to two possible outcomes foropenai_supports_sampling_settings
.OpenAIModelProfile
constructor arguments is constant.Thus, memoizing/caching the return value based on the boolean
is_reasoning_model
will save a lot of time.Summary of optimizations:
@lru_cache
-decorated helper function, so theOpenAIModelProfile
object is only created at most twice (one per each type ofis_reasoning_model
).This will dramatically improve runtime for workloads where this function is called repeatedly.
If there are more than two options or you allow more variations in input, simply adjust the caching logic or the cache key.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
codeflash_concolic_6hzlqgv4/tmp0c4tax8d/test_concolic_coverage.py::test_openai_model_profile
models/test_openai.py::test_model_profile_strict_not_supported
models/test_openai_responses.py::test_model_profile_strict_not_supported
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-openai_model_profile-mdewbron
and push.