{"record":{"id":"b700b04a3c072417","repo":"run-llama/llama_index","slug":"cannot-import-cohere-package-please-pip-install","errorCode":null,"errorMessage":"Cannot import cohere package, please `pip install cohere`.","messagePattern":"Cannot import cohere package, please `pip install cohere`\\.","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"llama-index-core/llama_index/core/evaluation/retrieval/metrics.py","lineNumber":453,"sourceCode":"\n    _client: Any = PrivateAttr()\n\n    def __init__(\n        self,\n        model: str = \"rerank-english-v2.0\",\n        api_key: Optional[str] = None,\n    ):\n        try:\n            api_key = api_key or os.environ[\"COHERE_API_KEY\"]\n        except IndexError:\n            raise ValueError(\n                \"Must pass in cohere api key or \"\n                \"specify via COHERE_API_KEY environment variable \"\n            )\n        try:\n            from cohere import Client  # pants: no-infer-dep\n        except ImportError:\n            raise ImportError(\n                \"Cannot import cohere package, please `pip install cohere`.\"\n            )\n\n        super().__init__(model=model)\n        self._client = Client(api_key=api_key)\n\n    def _get_agg_func(self, agg: Literal[\"max\", \"median\", \"mean\"]) -> Callable:\n        \"\"\"Get agg func.\"\"\"\n        return _AGG_FUNC[agg]\n\n    def compute(\n        self,\n        query: Optional[str] = None,\n        expected_ids: Optional[List[str]] = None,\n        retrieved_ids: Optional[List[str]] = None,\n        expected_texts: Optional[List[str]] = None,\n        retrieved_texts: Optional[List[str]] = None,\n        agg: Literal[\"max\", \"median\", \"mean\"] = \"max\",","sourceCodeStart":435,"sourceCodeEnd":471,"githubUrl":"https://github.com/run-llama/llama_index/blob/afd0fef371831f9bda13e5af7167cf4e981278ab/llama-index-core/llama_index/core/evaluation/retrieval/metrics.py#L435-L471","documentation":"Raised by CohereRerankRelevancyMetric.__init__ when it tries `from cohere import Client` and the optional cohere package is not installed. llama-index-core declares cohere as an optional dependency (note the `# pants: no-infer-dep` marker), so the rerank relevancy metric fails at construction time on any environment without it.","triggerScenarios":"Constructing CohereRerankRelevancyMetric (directly or through RetrieverEvaluator with the 'cohere_rerank_relevancy' metric) on an environment where `pip install cohere` was never run — typically a slim Docker image or a fresh venv holding only llama-index-core.","commonSituations":"Adding cohere-rerank evaluation to an existing project without updating requirements.txt; CI images that cache old dependency locks; upgrading llama-index and losing a transitive cohere install that used to come from another integration package.","solutions":["Install the SDK: pip install cohere (and pin it in your dependency file).","If you do not need Cohere reranking, drop 'cohere_rerank_relevancy' from the metrics list and use the built-in hits/mrr/precision/recall metrics instead.","Gate the metric behind an availability check (importlib.util.find_spec('cohere')) so evaluation configs degrade gracefully on environments without the package."],"exampleFix":"# before\nmetric = CohereRerankRelevancyMetric()  # ModuleNotFoundError -> wrapped ImportError\n\n# after\npip install cohere\nmetric = CohereRerankRelevancyMetric()","handlingStrategy":"validation","validationCode":"import importlib.util\n\nif importlib.util.find_spec(\"cohere\") is None:\n    raise RuntimeError(\"cohere package required for rerank relevancy: pip install cohere\")","typeGuard":null,"tryCatchPattern":"try:\n    metric = CohereRerankRelevancyMetric(api_key=key)\nexcept ImportError as e:\n    if \"pip install cohere\" in str(e):\n        log.warning(\"cohere not installed; skipping rerank relevancy metric\")\n        metric = None\n    else:\n        raise","preventionTips":["Add cohere to your lockfile whenever the cohere_rerank_relevancy metric is registered.","Gate optional-dependency features behind find_spec checks in eval harnesses.","Run dependency smoke tests in CI that construct every configured metric."],"tags":["missing-dependency","cohere","installation","optional-extra"],"backgroundTag":null,"analyzedSha":"afd0fef371831f9bda13e5af7167cf4e981278ab","analyzedAt":"2026-08-15T05:42:58.429Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}