Cohere LangChain Integration

0.5.0 · active · verified Sun Apr 12

langchain-cohere is an integration package that connects Cohere's powerful language AI models (Chat, Embeddings, Rerank) with the LangChain framework. It simplifies the process of building LLM-powered applications using Cohere's capabilities. The library is actively developed, with frequent releases often occurring on a weekly or bi-weekly cadence, and the current version is 0.5.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `ChatCohere` model and perform a simple chat completion. It uses the `COHERE_API_KEY` environment variable for authentication and `command-r-plus` as the model, which can be changed to other supported Cohere models.

import os
from langchain_cohere import ChatCohere
from langchain_core.messages import HumanMessage

# Ensure your COHERE_API_KEY is set as an environment variable
# or pass it directly to the ChatCohere constructor.
# For example: cohere_api_key="your_api_key"

llm = ChatCohere(
    model="command-r-plus", # or another supported Cohere chat model
    temperature=0, 
    cohere_api_key=os.environ.get('COHERE_API_KEY', '')
)

messages = [HumanMessage(content="What is the capital of Canada?")]

try:
    response = llm.invoke(messages)
    print(response.content)
except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure COHERE_API_KEY is set and the model name is correct.")

view raw JSON →