Skip to main content
Article·cohere.com
AIenterpriseNLPainlpcoherepythonembeddings

Cohere

Quickly integrate Cohere's enterprise-grade NLP models into your applications. This pack guides you from API key setup to performing your first text embedding, enabling search, generation, and classification capabilities.

beginner15 min5 steps
The play
  1. Get Your Cohere API Key
    Register on the Cohere platform and obtain your API key from the dashboard. This key authenticates your requests.
  2. Install the Cohere SDK
    Use pip to install the official Cohere Python SDK in your development environment.
  3. Initialize the Cohere Client
    Import the `cohere` library and initialize the client with your API key. For security, store your API key as an environment variable (e.g., `COHERE_API_KEY`).
  4. Generate Text Embeddings
    Use the `embed` endpoint to convert text into numerical vectors, essential for semantic search and retrieval. Specify an `input_type` for optimal results.
  5. Explore Other Capabilities
    Refer to the Cohere documentation for advanced usage, including text generation (`generate`), classification (`classify`), and summarization, leveraging different models.
Starter code
import cohere
import os

# Set your API key as an environment variable (e.g., COHERE_API_KEY='YOUR_API_KEY')
# For testing, you can uncomment and set it directly, but avoid in production:
# os.environ['COHERE_API_KEY'] = 'YOUR_API_KEY'

api_key = os.getenv('COHERE_API_KEY')

if not api_key:
    print("Error: COHERE_API_KEY environment variable not set.")
    print("Please set it or uncomment and replace 'YOUR_API_KEY' in the script.")
else:
    try:
        co = cohere.Client(api_key)

        # Example: Generate embeddings for a list of texts
        texts_to_embed = [
            "What is the capital of France?",
            "Paris is the capital of France.",
            "The Eiffel Tower is in Paris."
        ]

        print("\n--- Generating Embeddings ---")
        response = co.embed(
            texts=texts_to_embed,
            model='embed-english-v3.0', # Or another suitable model like 'embed-multilingual-v3.0'
            input_type='search_document' # Specify input type for better embeddings (e.g., 'search_document', 'search_query', 'classification', 'clustering')
        )

        for i, embedding in enumerate(response.embeddings):
            print(f"Embedding for '{texts_to_embed[i]}': {embedding[:5]}...") # Print first 5 dimensions

        # Example: Simple Text Generation (requires a generation model)
        print("\n--- Generating Text ---")
        generation_response = co.generate(
            prompt='Tell me a short story about a brave knight.',
            model='command', # Use a generation model like 'command' or 'command-light'
            max_tokens=50
        )
        print(f"Generated Text: {generation_response.generations[0].text}")

    except cohere.CohereError as e:
        print(f"Cohere API Error: {e}. Check your API key and model name.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
Source
Cohere — Action Pack