sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] ModelExtractor custom `system_prompt` silently breaks extraction when JSON format instructions are missing

Open ctoh-skechers opened this issue 4 months ago • 4 comments

Checks

  • [x] I have updated to the lastest minor and patch version of Strands
  • [x] I have checked the documentation and this is not expected behavior
  • [x] I have searched ./issues and there are no duplicates of my issue

SDK Language

Python

Strands Version

1.50.2

Language Runtime Version

Python 3.12

Operating System

Amazon Linux 2 (EC2), also reproduced on Windows 11

Installation Method

pip

Steps to Reproduce

  1. Configure a BedrockKnowledgeBaseStore with a custom system_prompt on the ModelExtractor:
from strands.memory import MemoryManager
from strands.memory.extraction.model_extractor import ModelExtractor
from strands.memory.extraction.triggers import InvocationTrigger
from strands.memory.extraction.types import ExtractionConfig
from strands.models import BedrockModel
from strands.vended_memory_stores import BedrockKnowledgeBaseStore

EXTRACTION_PROMPT = """
    Extract only durable user preferences, work patterns, and
    factual information about the user. Exclude greetings,
    clarifying questions, and task-specific instructions that
    do not reflect enduring user attributes.
"""

store = BedrockKnowledgeBaseStore(
    name="user-memory",
    description="Personal memories about the user",
    scope="user-123",
    writable=True,
    extraction=ExtractionConfig(
        trigger=InvocationTrigger(),
        extractor=ModelExtractor(
            model=BedrockModel(model_id="global.anthropic.claude-haiku-4-5-20251001-v1:0"),
            system_prompt=EXTRACTION_PROMPT,
        ),
    ),
    config={
        "knowledge_base_id": "ABCDEFGHIJ",
        "data_source_type": "S3",
        "data_source_id": "DATASOURCE123",
        "s3": {"bucket": "my-bucket", "prefix": "memories/"},
    },
)

memory_manager = MemoryManager(stores=[store])
agent = Agent(model=model, memory_manager=memory_manager)
agent("My favorite color is blue")
  1. Send multiple messages to the agent
  2. Check the S3 bucket — no memories are written

Expected Behavior

The ModelExtractor should extract facts from the conversation and write them to the store, regardless of whether the system_prompt explicitly includes JSON format instructions. The system_prompt parameter is documented as "System prompt steering what counts as a fact" — implying it's meant for guiding extraction focus, not for controlling output format.

At minimum, the documentation for system_prompt should clearly state that the prompt MUST include JSON format instructions (Return ONLY a JSON array of objects, each: {"content": string}) for extraction to work.

Actual Behavior

When a custom system_prompt is provided that doesn't include JSON format instructions, the model returns prose text instead of a JSON array. The _parse_entries function in model_extractor.py silently discards the result:

json_text = _extract_json_array(text)
if json_text is None:
    logger.warning("ModelExtractor: no JSON array in model output, skipping")
    return []

This warning is only logged at WARNING level and is swallowed by the ExtractionCoordinator's error handling. No memories are ever written, and the developer has no indication that their extraction config is broken unless they explicitly enable strands.memory debug logging.

Additional Context

The DEFAULT_SYSTEM_PROMPT works because it contains the critical format instruction:

DEFAULT_SYSTEM_PROMPT = (
    "You extract durable facts worth remembering across future conversations from a transcript.\n"
    "\n"
    'Return ONLY a JSON array of objects, each: {"content": string}. ...'
)

The issue is that when a user provides a custom system_prompt, this JSON format requirement is never communicated — not in the docstring, not in the parameter description, and not enforced programmatically.

Additionally, the failure is completely silent in production. The ExtractionCoordinator swallows all exceptions from extraction, so the only evidence is a WARNING-level log from a strands.memory.extraction.model_extractor logger that most users won't have configured.

Possible Solution

Possible Solution:

Any of these would address the issue (they're not mutually exclusive):

  1. Append the JSON format instruction automatically — Always append the format requirement to whatever custom system_prompt is provided, so the model always knows to return JSON:
self._system_prompt = (system_prompt or DEFAULT_SYSTEM_PROMPT)
if system_prompt and '{"content"' not in system_prompt:
    self._system_prompt += (
        '\n\nReturn ONLY a JSON array of objects, each: {"content": string}. '
        "If there is nothing worth remembering, return []."
    )
  1. Split the interface into system_prompt and format_instructions — Separate what guides extraction focus from the output format, and always append format instructions internally.

  2. Document the requirement clearly — At minimum, the system_prompt docstring should say: "Must include instructions to return a JSON array of {\"content\": string} objects."

  3. Log at ERROR level or raise — When _parse_entries can't find a JSON array, this should be more visible than a WARNING on a logger nobody configures.

Related Issues

No response

ctoh-skechers avatar Jul 30 '26 22:07 ctoh-skechers

Reproduced the swallow mechanism at HEAD 526692f in a clean python:3.12-slim container: pip install -e strands-py, then called ModelExtractor.extract() end to end with event_loop.streaming.stream_messages stubbed to return prose (no JSON array) for a custom system_prompt. Result: extract() returns [], no exception, only the WARNING at model_extractor.py:140.

Line numbers on this HEAD match the report exactly: :60 (self._system_prompt = system_prompt or DEFAULT_SYSTEM_PROMPT, a full replacement, no format instruction appended when a custom prompt is given) and :138-141 (_parse_entries returns [] on a missing JSON array, logged at WARNING only).

History check (unshallowed clone): git log -G on _parse_entries's own text (no JSON array in model output, system_prompt or DEFAULT_SYSTEM_PROMPT) returns exactly one commit, 713a6de3a (#2740, the Python port of memory manager/extraction from the TS SDK). No later revert or nearby rationale comment, so this reads as carried over from the port rather than a deliberate choice to let a custom prompt drop the JSON contract.

Of the fixes proposed, option 1 (append the format instruction when the custom prompt doesn't already carry one) looks like the smallest change that keeps system_prompt's documented job, steering what counts as a fact, without also making every caller responsible for the output-format contract.

AmirF194 avatar Jul 31 '26 01:07 AmirF194

I’d like to work on a focused fix for this if maintainers agree with the direction.

I reproduced it on current main with Python 3.12 using the real ModelExtractor.extract() path and MockedModelProvider. With a custom steering prompt ("Extract only durable user preferences.") and a prose model response, the effective system prompt remained exactly that string, _parse_entries logged no JSON array in model output, and extract() returned [].

My proposed minimal scope is:

  • keep the caller’s custom prompt as extraction steering;
  • append an internal, fixed JSON response contract so callers cannot accidentally remove the parser’s required format;
  • add a regression test that records the system prompt passed to the model and verifies it contains both the custom steering text and the JSON contract;
  • clarify the system_prompt docstring accordingly.

I would keep this Python-only and focused on #3578 unless maintainers prefer a cross-SDK parity change.

AI assistance was used to inspect the repository and prepare the reproduction; I ran and reviewed the reproduction and proposed scope myself. Would this direction be acceptable?

kinKingen avatar Aug 03 '26 02:08 kinKingen

Just want to state that Possible Solution 1 is inherently unreliable as it relies on an LLM to correctly return JSON. However, if maintainers have an efficient and reliable way to enforce this without impacting performance, then I would go with that option.

ctoh-skechers avatar Aug 03 '26 16:08 ctoh-skechers

Thank you @AmirF194 for the clear reproduction and history check.

This is fixed in #5269: ModelExtractor now always appends the JSON output format after a custom system_prompt, so the parser always receives it. It is released in python/v1.62.0, and details are in Triggers and extractors.

If you still see empty extraction results on that release, please open a new issue with a minimal reproduction.

yonib05 avatar Oct 25 '26 23:10 yonib05