Skip to main content
Open In Colab在 GitHub 上打开

Cohere

谨慎

您当前正在访问一个页面,其中记录了如何将 Cohere 模型用作文本完成模型。许多流行的 Cohere 模型都是聊天完成模型

您可能正在寻找此页面

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

前往 API 参考 获取所有属性和方法的详细文档。

概述

集成详细信息

本地化序列 化JS 支持软件包下载最新包装
Coherelangchain_communitybetaPyPI - DownloadsPyPI - Version

设置

集成位于langchain-community包。我们还需要安装coherepackage 本身。我们可以使用以下方式安装这些设备:

凭据

我们需要获取一个 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()

调用

Cohere 支持所有 LLM 功能:

from langchain_cohere import Cohere
from langchain_core.messages import HumanMessage
API 参考:HumanMessage
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 参考:PromptTemplate
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 参考

有关所有Coherellm 功能和配置可参考 API 参考:https://python.langchain.com/api_reference/community/llms/langchain_community.llms.cohere.Cohere.html