agentscope-ai/agentscope · error · ValueError

hint_template must contain exactly one '{context}' placehold

Error message

hint_template must contain exactly one '{context}' placeholder; found {count}.

What it means

RAG middleware substitutes retrieved content into hint_template at its single '{context}' placeholder; a pydantic validator enforces exactly one occurrence because zero drops the content and multiple duplicates it.

Source

Thrown at src/agentscope/middleware/_rag.py:564

            ),
        )

        # ``hint_template`` is intentionally hidden from the JSON Schema
        # exposed to the dock UI: the wrapper text is part of the
        # middleware's prompt contract and exposing it through the dock
        # invites session-by-session prompt drift.  It is still accepted
        # for programmatic use.

        @field_validator("hint_template")
        @classmethod
        def _validate_hint_template(cls, value: str) -> str:
            """Reject templates with anything other than exactly one
            ``{context}`` placeholder — :func:`_wrap_hint` substitutes on
            the first occurrence, so zero placeholders silently drop the
            matched content and multiple placeholders duplicate it."""
            count = value.count("{context}")
            if count != 1:
                raise ValueError(
                    "hint_template must contain exactly one '{context}' "
                    f"placeholder; found {count}.",
                )
            return value

    def __init__(
        self,
        knowledge_bases: list["KnowledgeBase"],
        parameters: "RAGMiddleware.Parameters | None" = None,
    ) -> None:
        """Initialize the RAG middleware.

        Args:
            knowledge_bases (`list[KnowledgeBase]`):
                The knowledge bases this agent searches.
            parameters (`RAGMiddleware.Parameters | None`, optional):
                Search-time knobs (mode, top_k, score threshold, hint
                behaviour).  ``None`` uses the defaults of

View on GitHub (pinned to e90f1c7592)

Solutions

  1. Include exactly one '{context}' in hint_template
  2. Escape literal braces as '{{' and '}}' while keeping one '{context}'
  3. Omit hint_template entirely to use the built-in default

Example fix

# before
KnowledgeRetrieval(hint_template='Context:\n{{context}}')
# after
KnowledgeRetrieval(hint_template='Context:\n{context}')
Defensive patterns

Strategy: validation

Validate before calling

count = hint_template.count('{context}')
assert count == 1, f'hint_template needs exactly one {{context}}; found {count}'

Try / catch

try:
    kr = KnowledgeRetrieval(hint_template=t)
except ValueError:
    t = t if t.count('{context}') == 1 else DEFAULT_HINT
    kr = KnowledgeRetrieval(hint_template=t)

Prevention

When it happens

Trigger: KnowledgeRetrieval(hint_template='Answer using:') (no placeholder), or '...{context}...{context}...' (two); literal braces like '{{context}}' also count as zero.

Common situations: Customizing the retrieval prompt and forgetting or doubling the placeholder; escaping braces incorrectly; template edited from f-string habits.

Related errors


AI-assisted analysis of agentscope-ai/agentscope@e90f1c7592 (2026-08-28). Data as JSON: /api/errors/405dc05e8758bbe9. Report an issue: GitHub.