Implementation:Cohere ai Cohere python API Key From Environment
| Metadata | |
|---|---|
| Source Repo | Cohere Python SDK |
| Domains | API_Authentication, SDK_Configuration |
| Last Updated | 2026-02-15 14:00 GMT |
Overview
Concrete utility function for retrieving Cohere API keys from environment variables.
Description
The _get_api_key_from_environment function reads the API key from environment variables using a priority chain. It checks CO_API_KEY first (the documented and preferred variable), then falls back to COHERE_API_KEY. Returns None if neither is set. This function is called automatically by Client.__init__ and ClientV2.__init__ when no explicit api_key parameter is provided.
Usage
This function is called automatically during client initialization when no explicit api_key is passed. You don't call it directly — just set the CO_API_KEY environment variable before creating a client.
Code Reference
- Source Location: Repository cohere-ai/cohere-python, File
src/cohere/client.py, Lines L514-519 - Signature:
def _get_api_key_from_environment() -> typing.Optional[str]:
return os.getenv("CO_API_KEY", os.getenv("COHERE_API_KEY"))
- Import:
from cohere.client import _get_api_key_from_environment(internal; typically not imported directly)
I/O Contract
| Name | Type | Required | Description |
|---|---|---|---|
| Inputs | |||
CO_API_KEY |
Environment variable (str) | No | Preferred API key source |
COHERE_API_KEY |
Environment variable (str) | No | Fallback API key source |
| Outputs | |||
| Return value | Optional[str] |
— | The API key string, or None if neither variable is set
|
Usage Examples
import os
# Set the API key in environment
os.environ["CO_API_KEY"] = "your-api-key-here"
# Client automatically picks up the key
from cohere import ClientV2
client = ClientV2() # Uses CO_API_KEY from environment