{"record":{"id":"b1ae9241a6344fbf","repo":"FoundationAgents/MetaGPT","slug":"str-chunk","errorCode":null,"errorMessage":"{str(chunk)}","messagePattern":"\\{str\\(chunk\\)\\}","errorType":"exception","errorClass":"BlockedPromptException","httpStatus":null,"severity":"error","filePath":"metagpt/provider/google_gemini_api.py","lineNumber":149,"sourceCode":"        resp: AsyncGenerateContentResponse = await self.llm.generate_content_async(**self._const_kwargs(messages))\n        usage = await self.aget_usage(messages, resp.text)\n        self._update_costs(usage)\n        return resp\n\n    async def acompletion(self, messages: list[dict], timeout=USE_CONFIG_TIMEOUT) -> dict:\n        return await self._achat_completion(messages, timeout=self.get_timeout(timeout))\n\n    async def _achat_completion_stream(self, messages: list[dict], timeout: int = USE_CONFIG_TIMEOUT) -> str:\n        resp: AsyncGenerateContentResponse = await self.llm.generate_content_async(\n            **self._const_kwargs(messages, stream=True)\n        )\n        collected_content = []\n        async for chunk in resp:\n            try:\n                content = chunk.text\n            except Exception as e:\n                logger.warning(f\"messages: {messages}\\nerrors: {e}\\n{BlockedPromptException(str(chunk))}\")\n                raise BlockedPromptException(str(chunk))\n            log_llm_stream(content)\n            collected_content.append(content)\n        log_llm_stream(\"\\n\")\n\n        full_content = \"\".join(collected_content)\n        usage = await self.aget_usage(messages, full_content)\n        self._update_costs(usage)\n        return full_content\n\n    def list_models(self) -> List:\n        models = []\n        for model in genai.list_models(page_size=100):\n            models.append(asdict(model))\n        logger.info(json.dumps(models))\n        return models\n","sourceCodeStart":131,"sourceCodeEnd":165,"githubUrl":"https://github.com/FoundationAgents/MetaGPT/blob/11cdf466d042aece04fc6cfd13b28e1a70341b1f/metagpt/provider/google_gemini_api.py#L131-L165","documentation":"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.","triggerScenarios":"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)).","commonSituations":"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.","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."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"from metagpt.provider.google_gemini_api import BlockedPromptException\n\ntry:\n    text = await provider._achat_completion_stream(messages)\nexcept BlockedPromptException as e:\n    log.warning(f\"gemini safety block: {e}\")\n    text = await fallback_provider._achat_completion_stream(messages)","preventionTips":["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"],"tags":["gemini","safety","content-filter","streaming"],"backgroundTag":null,"analyzedSha":"11cdf466d042aece04fc6cfd13b28e1a70341b1f","analyzedAt":"2026-08-14T23:20:02.994Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}