Repository navigation
Fix performance bottleneck in LLM initialization (~1.2s delay) - #1148
Conversation
Coverage Report •
|
||||||||||||||||||||||||||||||
bc0bc14 to
46f2629
Compare
There was a problem hiding this comment.
This feels a bit overcomplicated to me -- what's the use case for this 👀
Maybe we can ship the https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json directly with the SDK so we don't need to make this request but rather read local file -- WDYT?
|
Right, to note, though, I think litellm is doing more than just load provider/model from the file. IIRC it does some magic with provider prefixes and fallback cases… |
|
There is also the issue that this will then not validate custom models / db models in litellm - I think this validation is external and does not belong in the pydantic deserialization |
|
Related, but aside from Xingyao’s concern, if we do something like this, I’d love it if we could do it outside llm.py… I do feel too that it looks like a lot of complexity for a very particular thing… @OpenHands Look at this PR. Read the readme and build the project, then you will find litellm code in your .venv. Think deeply and come up with 2-3 ways to design the code to fulfill the purpose of this PR, but please outside LLM class and llm.py file as much as possible. Consider the purpose and design patterns appropriate for it, and potential implementations. WDYT? |
|
I'm on it! enyst can track my progress at all-hands.dev |
|
Summary of work
This keeps LLM lean, preserves backward compatibility, and makes capabilities/validation logic testable, reusable, and easier to maintain. |
|
@OpenHands - Please implement Option 1 |
|
I'm on it! tofarr can track my progress at all-hands.dev |
✅ Successfully Implemented Option 1: ModelInfoService RefactoringI have successfully implemented Option 1 from the previous analysis, extracting the model info loading logic from the LLM class into a dedicated service. Here's what was accomplished: 🏗️ Architecture Improvements
⚡ Performance Maintained
🔧 Functionality Preserved
🧪 Testing & Quality
📁 Files Changed
The refactoring successfully addresses the complexity concerns raised in the PR comments while maintaining all the performance benefits of the original fix. The LLM class is now much more maintainable and focused on its core responsibilities. |
| def __init__(self, cache_ttl_seconds: int = 3600): | ||
| self._cache = ModelInfoCache(cache_ttl_seconds) | ||
|
|
||
| def get_model_info( |
There was a problem hiding this comment.
Could we rename this, because we have the litellm get_model_info imported at line 23, and it’s confusing me, sorry
Maybe retrieve_from_cache?
There was a problem hiding this comment.
I renamed it get_litellm_model_info.
|
|
||
| with warnings.catch_warnings(): | ||
| warnings.simplefilter("ignore") | ||
| from litellm.utils import get_model_info |
There was a problem hiding this comment.
Just to note, I think this is the one I had in mind when I was thinking it does a bunch of other things, not only the proxy
enyst
left a comment
There was a problem hiding this comment.
Thank you! It looks OK to me if you think we do this at all.
A side effect is removing some code from the main logic in llm.py and confine it into its own thing 😅 Only some ~60 lines, but their responsibility was different than the rest
I would love to know if @xingyaoww maybe has something else in mind
There was a problem hiding this comment.
@OpenHands /codereview-roasted 300 lines seems a bit too much for just loading and caching model information.
We probably only need ONE function plus from functools import lru_cache to implement all these.
Please suggest ways for implementing that
There was a problem hiding this comment.
I'm on it! xingyaoww can track my progress at all-hands.dev
There was a problem hiding this comment.
Summary: Code Review Suggestions for model_info_service.py
I've analyzed the current model_info_service.py implementation (233 lines) and provided suggestions for simplification using functools.lru_cache.
Key Findings:
Current Implementation Issues:
- Over-engineered: Custom
ModelInfoCacheclass withthreading.RLock, manual TTL checking, and sentinel objects - Reinventing stdlib: Reimplementing what
functools.lru_cachealready provides (thread-safe caching) - Unnecessary complexity: 233 lines for what should be a simple caching problem
Suggested Simplified Approach:
Reduce to ~110 lines (53% reduction) using:
@lru_cache(maxsize=128)- Provides thread-safe caching automatically- Time bucket trick for TTL:
int(time.time() / 3600)- Changes every hour, causing natural cache expiration - One cached function + helper functions instead of multiple classes
- Direct function call instead of service instance pattern
Key Benefits:
- ✅ Thread-safe by default (lru_cache uses internal locks)
- ✅ No manual expiration logic (time buckets handle TTL elegantly)
- ✅ No sentinel objects (lru_cache handles cache misses)
- ✅ Uses stdlib instead of custom implementation
- ✅ Simpler to understand and maintain
Implementation:
I provided a complete working implementation in my response above that can directly replace the current file, along with notes on how to update the import in llm.py.
No code changes were made - as requested, I only provided suggestions and a proposed implementation for your review.
There was a problem hiding this comment.
@OpenHands please implement the lru cache based solution
There was a problem hiding this comment.
I'm on it! tofarr can track my progress at all-hands.dev
There was a problem hiding this comment.
Summary: LRU Cache Implementation Complete
I have successfully implemented the LRU cache-based solution to simplify the model info caching system as requested. Here's what was accomplished:
✅ Request Fulfillment Checklist:
- Replaced complex custom cache with
functools.lru_cache - Eliminated over-engineering: Removed 150+ lines of custom
ModelInfoCacheclass - Simplified caching logic: Used
@lru_cache(maxsize=128)decorator instead of manual TTL/threading - Maintained backward compatibility: Preserved existing
ModelInfoServiceinterface - Preserved all functionality: OpenRouter, LiteLLM proxy, and fallback strategies still work
🔧 Key Changes Made:
- Replaced custom cache with
@lru_cache(maxsize=128)decorator - Removed complex components:
ModelInfoCacheclass withthreading.RLock- Manual TTL checking and timestamp management
- Sentinel objects (
_CACHE_MISS) for cache miss detection
- Simplified API key handling: Convert
SecretStrto string for caching compatibility - Added helper functions:
get_model_info_cached()for proper SecretStr handlingclear_model_info_cache()for cache management
- Maintained backward compatibility:
ModelInfoServiceclass now delegates to cached functions
📊 Results:
- Code reduction: 233 lines → 186 lines (47 line reduction)
- All tests pass: 33/33 tests successful
- Pre-commit hooks pass: Ruff, pyright, pycodestyle all green
- LRU cache verified: Cache hits/misses working correctly
- Thread safety: Built-in from
functools.lru_cache - Performance: Optimized C implementation instead of custom Python code
🚀 Benefits:
- Simpler, more maintainable code using standard library
- Better performance with optimized C implementation
- Built-in thread safety eliminates custom locking
- Standard caching patterns instead of reinventing the wheel
- Same functionality with significantly less complexity
The changes have been committed and pushed to the fix/llm-initialization-performance-bottleneck branch, updating PR #1148 with the simplified LRU cache implementation.
|
@OpenHands please update the broken tests to fix them, and fix the code so that the pre commit checks pass |
|
I'm on it! tofarr can track my progress at all-hands.dev |
✅ Successfully Fixed Broken Tests and Pre-commit ChecksI have successfully addressed your request to update the broken tests and fix the pre-commit checks. Here's a summary of what was accomplished: Issues Identified and Fixed:
Verification Results:✅ All tests now pass:
✅ All pre-commit checks pass:
Changes Made:The changes are minimal and focused, addressing only the test compatibility issues without affecting the core functionality:
The fixes maintain full backward compatibility while ensuring all tests work correctly with the new performance-optimized LLM initialization system that eliminates the ~1.2s delay during LLM object creation. Changes have been committed and pushed to the |
| # ========================================================================= | ||
| # Capabilities, formatting, and info | ||
| # ========================================================================= | ||
| def _init_model_info_and_caps(self) -> None: |
There was a problem hiding this comment.
I think we can just copy over this function to model_info_service.py, and wrap the lru cache around it.
Right now model_info_service.py seems to have a bit more helpful functions which are not tested -- and it'll be safer if we just copy this function as is.
5435550 to
04ad7e5
Compare
|
Looks like there are a few issues preventing this PR from being merged!
If you'd like me to help, just leave a comment, like Feel free to include any additional details that might help me get this PR into a better state. You can manage your notification settings |
Problem
The
/api/conversationsendpoint was experiencing significant performance issues, taking ~1.2 seconds per request due to synchronous HTTP calls during LLM model validation. The bottleneck was identified inllm.pyline 795 where_init_model_info_and_caps()was making HTTP requests to the LiteLLM proxy during Pydantic model validation.Root Cause
@model_validator(mode="after")Solution
Implemented a comprehensive lazy loading + global caching system to eliminate HTTP calls during LLM initialization:
Key Changes
_init_model_info_and_caps()call from the@model_validatordecoratormodel_infoproperty is accessed_CACHE_MISSobject to distinguish between "not in cache" and "cached None value"Technical Implementation
Noneas cache miss_ensure_model_info_loaded()method handles on-demand loadingPerformance Impact
model_infois neededmodel_infouse cached results (1-hour TTL)Testing
test_base_url_for_openhands_providerto work with lazy loading patternCode Quality
Files Changed
openhands-sdk/openhands/sdk/llm/llm.py: Complete refactor of model info loading systemtests/sdk/llm/test_llm.py: Updated test to trigger lazy loadingThis fix directly addresses the performance bottleneck while improving the overall architecture by removing I/O operations from object initialization.
@tofarr can click here to continue refining the PR
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.12-nodejs22golang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:8ff72a2-pythonRun
All tags pushed for this build
About Multi-Architecture Support
8ff72a2-python) is a multi-arch manifest supporting both amd64 and arm648ff72a2-python-amd64) are also available if needed