AuthenticationError
cohere.error.AuthenticationError
Stack trace
cohere.error.AuthenticationError: Invalid API key provided. Please check your COHERE_API_KEY environment variable and try again.
Why it happens
This error occurs when the Cohere client receives a 401 Unauthorized response due to an invalid or missing API key. The rerank endpoint requires a valid API key set in the environment or client configuration. If the key is expired, revoked, or mistyped, authentication fails.
Detection
Check for AuthenticationError exceptions when calling the rerank method and verify the COHERE_API_KEY environment variable is set and correct before making requests.
Causes & fixes
API key environment variable COHERE_API_KEY is not set or is empty
Set the COHERE_API_KEY environment variable with your valid Cohere API key before running your application.
API key provided is expired or revoked in the Cohere dashboard
Generate a new API key from the Cohere dashboard and update your environment variable accordingly.
Typo or incorrect API key string used in environment or client initialization
Double-check the API key string for typos and ensure it matches exactly the key from your Cohere account.
Using an API key with insufficient permissions for reranking endpoint
Verify your API key has reranking access enabled in your Cohere account settings.
Code: broken vs fixed
import os
from cohere import Client
client = Client(api_key=None) # Missing API key
response = client.rerank(
model='rerank-english-v2.0',
query='What is AI?',
documents=['AI is artificial intelligence.', 'AI stands for artificial intelligence.']
) # This line raises AuthenticationError
print(response) import os
from cohere import Client
client = Client(api_key=os.environ['COHERE_API_KEY']) # Pass API key correctly
response = client.rerank(
model='rerank-english-v2.0',
query='What is AI?',
documents=['AI is artificial intelligence.', 'AI stands for artificial intelligence.']
) # Fixed: valid API key used
print(response) Workaround
Catch AuthenticationError exceptions and prompt the user or system to reload or reset the API key environment variable dynamically before retrying.
Prevention
Use environment management tools to securely store and inject valid API keys, and implement startup checks that verify API key validity before making rerank requests.