Skip to content

fix: guard keyword_optimizer.optimize_keywords() against unexpected exceptions#658

Open
octo-patch wants to merge 1 commit into
666ghj:mainfrom
octo-patch:fix/issue-657-optimized-response-unbound
Open

fix: guard keyword_optimizer.optimize_keywords() against unexpected exceptions#658
octo-patch wants to merge 1 commit into
666ghj:mainfrom
octo-patch:fix/issue-657-optimized-response-unbound

Conversation

@octo-patch

Copy link
Copy Markdown
Contributor

Fixes #657

Problem

execute_search_tool in InsightEngine/agent.py called keyword_optimizer.optimize_keywords() without any exception guard. If the call raised an unexpected exception, the optimized_response variable was left unbound, producing:

UnboundLocalError: cannot access local variable 'optimized_response' where it is not associated with a value

Solution

Wrap the keyword_optimizer.optimize_keywords() call in a try/except. On any exception, construct a fallback KeywordOptimizationResponse using the original query as the sole keyword, so the search continues with a best-effort keyword set instead of crashing.

KeywordOptimizationResponse is also added to the direct imports from .tools.

Testing

Added tests/test_optimized_response_fallback.py with 4 tests covering the normal optimisation path and exception fallback scenarios.

…xceptions

Fixes 666ghj#657

An UnboundLocalError could occur at the optimized_keywords access site when
keyword_optimizer.optimize_keywords() raised an unexpected exception, because
the assignment was skipped and the variable was left unbound.

The fix wraps the call in a try/except block: on any exception the code falls
back to a KeywordOptimizationResponse that uses the original query as the sole
keyword, so optimized_response is always bound and the search can continue
with a best-effort keyword set instead of crashing.

Also imports KeywordOptimizationResponse directly in agent.py so the fallback
can construct the response without a relative import chain.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Insight Engine Streamlit App] 研究过程中发生错误: cannot access local variable 'optimized

1 participant