Skip to main content
Cohere 是一家加拿大初创公司,提供自然语言处理模型,帮助企业改善人机交互。

安装与设置

  • 安装 Python SDK:
pip install langchain-cohere
获取 Cohere API 密钥并将其设置为环境变量(COHERE_API_KEY

Cohere LangChain 集成

API说明端点文档导入使用示例
Chat构建聊天机器人chatfrom langchain_cohere import ChatCoherecohere.ipynb
LLM生成文本generatefrom langchain_cohere.llms import Coherecohere.ipynb
RAG 检索器连接外部数据源chat + ragfrom langchain_classic.retrievers import CohereRagRetrievercohere.ipynb
文本嵌入将字符串嵌入为向量embedfrom langchain_cohere import CohereEmbeddingscohere.ipynb
重排检索器根据相关性对字符串排序rerankfrom langchain_classic.retrievers.document_compressors import CohereRerankcohere.ipynb

快速复制示例

聊天

from langchain_cohere import ChatCohere
from langchain.messages import HumanMessage
chat = ChatCohere()
messages = [HumanMessage(content="knock knock")]
print(chat.invoke(messages))
Cohere 聊天模型的使用方法

LLM

from langchain_cohere.llms import Cohere

llm = Cohere()
print(llm.invoke("Come up with a pet name"))
Cohere(旧版)LLM 模型的使用方法

工具调用

from langchain_cohere import ChatCohere
from langchain.messages import (
    HumanMessage,
    ToolMessage,
)
from langchain.tools import tool

@tool
def magic_function(number: int) -> int:
    """Applies a magic operation to an integer

    Args:
        number: Number to have magic operation performed on
    """
    return number + 10

def invoke_tools(tool_calls, messages):
    for tool_call in tool_calls:
        selected_tool = {"magic_function":magic_function}[
            tool_call["name"].lower()
        ]
        tool_output = selected_tool.invoke(tool_call["args"])
        messages.append(ToolMessage(tool_output, tool_call_id=tool_call["id"]))
    return messages

tools = [magic_function]

llm = ChatCohere()
llm_with_tools = llm.bind_tools(tools=tools)
messages = [
    HumanMessage(
        content="What is the value of magic_function(2)?"
    )
]

res = llm_with_tools.invoke(messages)
while res.tool_calls:
    messages.append(res)
    messages = invoke_tools(res.tool_calls, messages)
    res = llm_with_tools.invoke(messages)

print(res.content)
如上所示,可以通过将必要的工具绑定到 LLM 来实现 Cohere LLM 的工具调用。 另一种方式是使用下面的 ReAct 智能体支持多跳工具调用。

ReAct 智能体

该智能体基于论文 ReAct: Synergizing Reasoning and Acting in Language Models
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_cohere import ChatCohere, create_cohere_react_agent
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents import AgentExecutor

llm = ChatCohere()

internet_search = TavilySearchResults(max_results=4)
internet_search.name = "internet_search"
internet_search.description = "Route a user query to the internet"

prompt = ChatPromptTemplate.from_template("{input}")

agent = create_cohere_react_agent(
    llm,
    [internet_search],
    prompt
)

agent_executor = AgentExecutor(agent=agent, tools=[internet_search], verbose=True)

agent_executor.invoke({
    "input": "In what year was the company that was founded as Sound of Music added to the S&P 500?",
})
ReAct 智能体可用于按顺序调用多个工具。

RAG 检索器

from langchain_cohere import ChatCohere
from langchain_classic.retrievers import CohereRagRetriever
from langchain_core.documents import Document

rag = CohereRagRetriever(llm=ChatCohere())
print(rag.invoke("What is cohere ai?"))
Cohere RAG 检索器的使用方法

文本嵌入

from langchain_cohere import CohereEmbeddings

embeddings = CohereEmbeddings(model="embed-english-light-v3.0")
print(embeddings.embed_documents(["This is a test document."]))
Cohere 文本嵌入模型的使用方法

重排器

Cohere 重排器的使用方法