Skip to content

Commit be0abca

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 aa8c3ea commit be0abca

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
@@ -213,8 +213,35 @@ async def extract_memories_from_session_thread(
213213
response_format={"type": "json_object"},
214214
)
215215

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

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

0 commit comments

Comments
 (0)