Skip to content

Commit 055d4d2

Browse files
abrookinsclaude
andcommitted
Address PR feedback for query optimization
- Extract hardcoded optimization prompt to config.py setting - Add min_optimized_query_length config setting - Fix AttributeError handling for missing response.choices - Fix malformed test by properly checking hasattr before deletion - Extract magic number to class constant 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 889b446 commit 055d4d2

File tree

3 files changed

+41
-18
lines changed

3 files changed

+41
-18
lines changed

agent_memory_server/config.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,21 @@ class Settings(BaseSettings):
130130
0.7 # Fraction of context window that triggers summarization
131131
)
132132

133+
# Query optimization settings
134+
query_optimization_prompt_template: str = """Transform this natural language query into an optimized version for semantic search. The goal is to make it more effective for finding semantically similar content while preserving the original intent.
135+
136+
Guidelines:
137+
- Keep the core meaning and intent
138+
- Use more specific and descriptive terms
139+
- Remove unnecessary words like "tell me", "I want to know", "can you"
140+
- Focus on the key concepts and topics
141+
- Make it concise but comprehensive
142+
143+
Original query: {query}
144+
145+
Optimized query:"""
146+
min_optimized_query_length: int = 2
147+
133148
# Other Application settings
134149
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
135150
default_mcp_user_id: str | None = None

agent_memory_server/llms.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -449,19 +449,10 @@ async def optimize_query_for_vector_search(
449449
# Use fast model from settings if not specified
450450
effective_model = model_name or settings.fast_model
451451

452-
# Create optimization prompt
453-
optimization_prompt = f"""Transform this natural language query into an optimized version for semantic search. The goal is to make it more effective for finding semantically similar content while preserving the original intent.
454-
455-
Guidelines:
456-
- Keep the core meaning and intent
457-
- Use more specific and descriptive terms
458-
- Remove unnecessary words like "tell me", "I want to know", "can you"
459-
- Focus on the key concepts and topics
460-
- Make it concise but comprehensive
461-
462-
Original query: {query}
463-
464-
Optimized query:"""
452+
# Create optimization prompt from config template
453+
optimization_prompt = settings.query_optimization_prompt_template.format(
454+
query=query
455+
)
465456

466457
try:
467458
client = await get_model_client(effective_model)
@@ -471,7 +462,11 @@ async def optimize_query_for_vector_search(
471462
prompt=optimization_prompt,
472463
)
473464

474-
if response.choices and len(response.choices) > 0:
465+
if (
466+
hasattr(response, "choices")
467+
and response.choices
468+
and len(response.choices) > 0
469+
):
475470
optimized = ""
476471
if hasattr(response.choices[0], "message"):
477472
optimized = response.choices[0].message.content
@@ -484,7 +479,7 @@ async def optimize_query_for_vector_search(
484479
optimized = optimized.strip()
485480

486481
# Fallback to original if optimization failed
487-
if not optimized or len(optimized) < 2:
482+
if not optimized or len(optimized) < settings.min_optimized_query_length:
488483
logger.warning(f"Query optimization failed for: {query}")
489484
return query
490485

tests/test_query_optimization_errors.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
class TestQueryOptimizationErrorHandling:
1616
"""Test error handling scenarios for query optimization."""
1717

18+
VERY_LONG_QUERY_REPEAT_COUNT = 1000
19+
1820
@patch("agent_memory_server.llms.get_model_client")
1921
async def test_optimization_with_network_timeout(self, mock_get_client):
2022
"""Test graceful fallback when model API times out."""
@@ -50,12 +52,19 @@ async def test_optimization_with_malformed_response(self, mock_get_client):
5052
mock_client = AsyncMock()
5153
mock_response = MagicMock()
5254
# Malformed response - no choices attribute
53-
del mock_response.choices
55+
if hasattr(mock_response, "choices"):
56+
del mock_response.choices
5457
mock_client.create_chat_completion.return_value = mock_response
5558
mock_get_client.return_value = mock_client
5659

5760
original_query = "Find my user settings"
58-
result = await optimize_query_for_vector_search(original_query)
61+
# The function should handle AttributeError gracefully and fall back
62+
try:
63+
result = await optimize_query_for_vector_search(original_query)
64+
except AttributeError:
65+
pytest.fail(
66+
"optimize_query_for_vector_search did not handle missing choices attribute gracefully"
67+
)
5968

6069
# Should fall back to original query
6170
assert result == original_query
@@ -100,7 +109,11 @@ async def test_optimization_with_very_long_query(self, mock_get_client):
100109
mock_get_client.return_value = mock_client
101110

102111
# Create a very long query (10,000 characters)
103-
long_query = "Tell me about " + "preferences " * 1000 + "settings"
112+
long_query = (
113+
"Tell me about "
114+
+ "preferences " * self.VERY_LONG_QUERY_REPEAT_COUNT
115+
+ "settings"
116+
)
104117
result = await optimize_query_for_vector_search(long_query)
105118

106119
assert result == "long query optimized"

0 commit comments

Comments
 (0)