Skip to main content
Open In ColabOpen on GitHub

Cohere

注意

您当前所在的页面记录了Cohere模型作为文本补全模型的使用方法。许多流行的Cohere模型是聊天补全模型

您可能正在寻找这个页面

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

前往详细的文档以查看所有属性和方法的API参考

概览

集成细节

Class本地序列化JS支持Package downloadsPackage 最新版本
Coherelangchain_communitybetaPyPI - DownloadsPyPI - Version

设置

The integration lives in the langchain-community package. We also need to install the cohere package itself. We can install these with:

Credentials

我们将需要获取一个 Cohere API 密钥 并设置 COHERE_API_KEY 环境变量:

import getpass
import os

if "COHERE_API_KEY" not in os.environ:
os.environ["COHERE_API_KEY"] = getpass.getpass()

安装

pip install -U langchain-community langchain-cohere

这也是可选但有益的步骤,可以通过设置LangSmith来实现最佳级别的可观测性

# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()

Invocation

Cohere 支持所有 LLM 功能:

from langchain_cohere import Cohere
from langchain_core.messages import HumanMessage
API 参考:人类消息
model = Cohere(max_tokens=256, temperature=0.75)
message = "Knock knock"
model.invoke(message)
" Who's there?"
await model.ainvoke(message)
" Who's there?"
for chunk in model.stream(message):
print(chunk, end="", flush=True)
 Who's there?
model.batch([message])
[" Who's there?"]

链式调用

您也可以轻松结合提示模板,以便更方便地组织用户输入。我们可以通过使用LCEL来实现这一点。

from langchain_core.prompts import PromptTemplate

prompt = PromptTemplate.from_template("Tell me a joke about {topic}")
chain = prompt | model
API 参考:提示模板
chain.invoke({"topic": "bears"})
' Why did the teddy bear cross the road?\nBecause he had bear crossings.\n\nWould you like to hear another joke? '

API 参考

提供所有 Cohere llm 功能和配置的详细文档,请访问 API 参考: https://python.langchain.com/api_reference/community/llms/langchain_community.llms.cohere.Cohere.html