FoundationAgents/MetaGPT · error · BlockedPromptException
{str(chunk)}
Error message
{str(chunk)} What it means
During Gemini streaming, each chunk's .text property can raise (notably when safety settings block content or the chunk carries no parsable part). MetaGPT wraps this failure by re-raising BlockedPromptException with the raw chunk string, after logging the original exception. It effectively means the model or the input was blocked by Gemini safety filters mid-stream.
Source
Thrown at metagpt/provider/google_gemini_api.py:149
resp: AsyncGenerateContentResponse = await self.llm.generate_content_async(**self._const_kwargs(messages))
usage = await self.aget_usage(messages, resp.text)
self._update_costs(usage)
return resp
async def acompletion(self, messages: list[dict], timeout=USE_CONFIG_TIMEOUT) -> dict:
return await self._achat_completion(messages, timeout=self.get_timeout(timeout))
async def _achat_completion_stream(self, messages: list[dict], timeout: int = USE_CONFIG_TIMEOUT) -> str:
resp: AsyncGenerateContentResponse = await self.llm.generate_content_async(
**self._const_kwargs(messages, stream=True)
)
collected_content = []
async for chunk in resp:
try:
content = chunk.text
except Exception as e:
logger.warning(f"messages: {messages}\nerrors: {e}\n{BlockedPromptException(str(chunk))}")
raise BlockedPromptException(str(chunk))
log_llm_stream(content)
collected_content.append(content)
log_llm_stream("\n")
full_content = "".join(collected_content)
usage = await self.aget_usage(messages, full_content)
self._update_costs(usage)
return full_content
def list_models(self) -> List:
models = []
for model in genai.list_models(page_size=100):
models.append(asdict(model))
logger.info(json.dumps(models))
return models
View on GitHub (pinned to 11cdf466d0)
Solutions
- Reword or sanitize the prompt to avoid flagged content; split sensitive tasks into neutral sub-prompts.
- Adjust safety settings in generation config if your Google Cloud project allows it.
- Catch BlockedPromptException at the caller and fall back to a non-sensitive prompt or a different model.
- Inspect the logged chunk JSON (blockReason / finishReason = SAFETY) to confirm which filter fired.
Defensive patterns
Strategy: try-catch
Try / catch
from metagpt.provider.google_gemini_api import BlockedPromptException
try:
text = await provider._achat_completion_stream(messages)
except BlockedPromptException as e:
log.warning(f"gemini safety block: {e}")
text = await fallback_provider._achat_completion_stream(messages) Prevention
- Sanitize prompts that repeatedly trip safety filters
- Keep a fallback model/provider for blocked generations
- Log the raw chunk (blockReason) to identify which filter fired
When it happens
Trigger: Calling gemini completion with stream=True where Google's safety system blocks the prompt or a candidate: chunk.text raises, the except branch logs and raises BlockedPromptException(str(chunk)).
Common situations: Prompts touching violence/medical/policy-sensitive content, code-injection-looking payloads, strict org safety settings, or empty candidate chunks from the API; also transient malformed stream chunks.
Related errors
- Only support message type are: str, Message, dict, but got {
- Request failed, msg: {self._event_source.decode('utf-8')}, p
AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14).
Data as JSON: /api/errors/b1ae9241a6344fbf.
Report an issue: GitHub.