Refactor create_llm in agent_langchain.py to reduce cyclomatic complexity #1525
+681
−52
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.
Refactor create_llm() in langchain_agent/agent_langchain.py to reduce cognitive complexity
This is in order to reduce SonarQube findings on the maintainability of the code base ( issue #212 ).
Key Changes
I've refactored
create_llm()by offloading the logical but complex-to-read if/elif chain into separate provider factory functions that can easily self-contain that logic while making the original function easier to read and understand.The refactoring splits the monolithic if/elif chain (checking provider types) into five dedicated helper functions:
_create_openai_llm()_create_azure_llm()_create_bedrock_llm()_create_ollama_llm()_create_anthropic_llm()Benefits
The key benefits of these changes are to reduce cognitive complexity of the
create_llm()function.Separating the logic like this means that we can more easily make changes to specific provider implementations without having to navigate through large logical flows that handle multiple different providers. Each provider' configuration and validation logic is now isolated and independently testable.
Files Changed
agent_runtime/langchain_agent/agent_langchain.py- main refactoringagent_runtime/langchain_agent/tests/test_agent_langchain.py- unit tests for all provider functionsTesting Notes
Comprehensive tests have been added covering:
Note: Local test suite has pre-existing import errors with langchain on both main and this branch, unrelated to these changes. The refactored code passes syntax validation and only modifies the create_llm function structure without touching imports or dependencies.