Optimized Tools._filter_custom_tools #2064
Open
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.
The optimized code replaces exception-based control flow with direct dictionary lookups, achieving a 201% speedup.
📄 202% (2.02x) speedup for
Tools._filter_custom_toolsinpython/composio/core/models/tools.py⏱️ Runtime :
1.14 milliseconds→379 microseconds(best of246runs)📝 Explanation and details
The optimized code replaces exception-based control flow with direct dictionary lookups, achieving a 201% speedup.
Key optimization: The original code used a try/except pattern to check if a tool exists in the custom tools registry:
The optimized version eliminates exceptions by:
custom_tools_registry = self._custom_tools.custom_tools_registryavoids repeated attribute lookupscustom_tool = custom_tools_registry.get(tool)returnsNonefor missing keys without raising exceptionsWhy this is significantly faster:
self._custom_tools.custom_tools_registryhappens once per method call instead of once per tooldict.get()is optimized for the common case of missing keysPerformance characteristics:
The optimization shows excellent scalability - larger improvements with more tools (326% faster for 500 standard tools, 240% faster for 1000 mixed tools). This suggests the original exception-based approach had O(n) overhead that scaled poorly, while the optimized version maintains efficient dictionary lookup performance.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
More optimizations for composio : https://github.com/aseembits93/composio/pulls, Looking to hear back from the team.