⚡️ Speed up function get_cost_for_web_search_request by 26%
          #183
        
          
      
  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.
  
    
  
    
📄 26% (0.26x) speedup for
get_cost_for_web_search_requestinlitellm/llms/__init__.py⏱️ Runtime :
308 microseconds→245 microseconds(best of280runs)📝 Explanation and details
The optimization achieves a 25% speedup through several key improvements:
Import optimization: The most significant gain comes from moving
PromptTokensDetailsWrapperandSearchContextCostPerQueryimports to module-level instead of function-level. The line profiler shows these imports taking 27-34% of function execution time in the original code. Moving them eliminates this per-call overhead.Simplified control flow:
total_costin gemini,makes_web_search_requestin vertex_ai)ifstatements in the anthropic functionif cost_per_web_search_request is None or cost_per_web_search_request == 0.0:to the more Pythonicif not cost_per_web_search_request:which is faster for truthiness checksDirect return expressions: Instead of storing results in intermediate variables and then returning them, the optimized code returns calculated values directly, reducing memory allocations and variable lookups.
These optimizations are particularly effective for the test cases shown because:
The optimizations maintain identical functionality while reducing Python interpreter overhead through fewer operations per function call.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_cost_for_web_search_request-mhdyhzdband push.