Skip to content

Commit 9dcc4c1

Browse files
abrookinsclaude
andcommitted
fix: add robust error handling for LLM response parsing
- Add proper error handling for malformed LLM responses in extract_memories_from_session_thread - Check response structure before accessing choices[0].message.content - Return empty list instead of crashing when response is malformed 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent a42a2a9 commit 9dcc4c1

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

agent_memory_server/long_term_memory.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,35 @@ async def extract_memories_from_session_thread(
206206
response_format={"type": "json_object"},
207207
)
208208

209-
extraction_result = json.loads(response.choices[0].message.content)
210-
memories_data = extraction_result.get("memories", [])
209+
# Extract content from response with error handling
210+
try:
211+
if (
212+
hasattr(response, "choices")
213+
and isinstance(response.choices, list)
214+
and len(response.choices) > 0
215+
):
216+
if hasattr(response.choices[0], "message") and hasattr(
217+
response.choices[0].message, "content"
218+
):
219+
content = response.choices[0].message.content
220+
else:
221+
logger.error(
222+
f"Unexpected response structure - no message.content: {response}"
223+
)
224+
return []
225+
else:
226+
logger.error(
227+
f"Unexpected response structure - no choices list: {response}"
228+
)
229+
return []
230+
231+
extraction_result = json.loads(content)
232+
memories_data = extraction_result.get("memories", [])
233+
except (json.JSONDecodeError, AttributeError, TypeError) as e:
234+
logger.error(
235+
f"Failed to parse extraction response: {e}, response: {response}"
236+
)
237+
return []
211238

212239
logger.info(
213240
f"Extracted {len(memories_data)} memories from session thread {session_id}"

0 commit comments

Comments
 (0)