{"record":{"id":"3136b9f7a98472c7","repo":"FoundationAgents/MetaGPT","slug":"get-embedding-failed","errorCode":null,"errorMessage":"get_embedding failed","messagePattern":"get_embedding failed","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"metagpt/ext/stanford_town/utils/utils.py","lineNumber":64,"sourceCode":"                analysis_list += [row]\n        return analysis_list[0], analysis_list[1:]\n\n\ndef get_embedding(text, model: str = \"text-embedding-ada-002\"):\n    text = text.replace(\"\\n\", \" \")\n    embedding = None\n    if not text:\n        text = \"this is blank\"\n    for idx in range(3):\n        try:\n            embedding = (\n                OpenAI(api_key=config.llm.api_key).embeddings.create(input=[text], model=model).data[0].embedding\n            )\n        except Exception as exp:\n            logger.info(f\"get_embedding failed, exp: {exp}, will retry.\")\n            time.sleep(5)\n    if not embedding:\n        raise ValueError(\"get_embedding failed\")\n    return embedding\n\n\ndef extract_first_json_dict(data_str: str) -> Union[None, dict]:\n    # Find the first occurrence of a JSON object within the string\n    start_idx = data_str.find(\"{\")\n    end_idx = data_str.find(\"}\", start_idx) + 1\n\n    # Check if both start and end indices were found\n    if start_idx == -1 or end_idx == 0:\n        return None\n\n    # Extract the first JSON dictionary\n    json_str = data_str[start_idx:end_idx]\n\n    try:\n        # Attempt to parse the JSON data\n        json_dict = json.loads(json_str)","sourceCodeStart":46,"sourceCodeEnd":82,"githubUrl":"https://github.com/FoundationAgents/MetaGPT/blob/11cdf466d042aece04fc6cfd13b28e1a70341b1f/metagpt/ext/stanford_town/utils/utils.py#L46-L82","documentation":"In the Stanford Town module, get_embedding calls OpenAI embeddings and retries 3 times (5s apart) on any exception; if all retries fail and no embedding was ever produced, it raises ValueError('get_embedding failed'). The per-attempt exceptions are only logged at info level, so the raise itself hides the root cause (bad API key, wrong model, network).","triggerScenarios":"Invalid/missing OpenAI API key in config.llm.api_key; embedding model not available to the account; network/proxy blocking api.openai.com; rate limits persisting across all 3 retries.","commonSituations":"Running stanford_town examples without OPENAI_API_KEY configured; using a key without access to the requested embedding model; corporate proxies or offline environments; exceeding rate limits during large simulations.","solutions":["Enable info logs (or add logging of exp) to see the actual per-attempt exception before the final raise.","Verify config.llm.api_key is set and valid, and that the embedding model name is one your key can access.","Check network/proxy connectivity to the OpenAI embeddings endpoint.","For rate limits, slow down simulation or increase retry backoff."],"exampleFix":"// before\nembedding = OpenAI(api_key=config.llm.api_key).embeddings.create(input=[text], model=model).data[0].embedding\n\n// after (surface root cause)\nclient = OpenAI(api_key=config.llm.api_key)\ntry:\n    embedding = client.embeddings.create(input=[text], model=model).data[0].embedding\nexcept Exception as exp:\n    logger.error(f\"get_embedding failed permanently: {exp}\")\n    raise","handlingStrategy":"retry","validationCode":"from metagpt.config2 import config\n\ndef embedding_ready(model: str) -> bool:\n    return bool(config.llm.api_key)  # cheap precondition; full check needs a live call","typeGuard":null,"tryCatchPattern":"from metagpt.ext.stanford_town.utils.utils import get_embedding\n\nasync def safe_embedding(text: str, model: str, attempts: int = 3):\n    last = None\n    for _ in range(attempts):\n        try:\n            return get_embedding(text, model=model)\n        except ValueError as e:\n            if \"get_embedding failed\" in str(e):\n                last = e\n                continue\n            raise\n    raise RuntimeError(\"embeddings unavailable; check api key/model/network\") from last","preventionTips":["Fail fast at startup on missing api_key instead of after 3 silent retries.","Turn logger level to INFO during bring-up to capture the per-attempt exception."],"tags":["embedding","openai","network","retry-exhausted","stanford-town"],"backgroundTag":null,"analyzedSha":"11cdf466d042aece04fc6cfd13b28e1a70341b1f","analyzedAt":"2026-08-14T23:20:02.994Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}