Cohere
Cohere 是一家加拿大初创公司,提供自然语言处理模型,帮助公司改善人机交互。
前往 API 参考 获取所有属性和方法的详细文档。
设置
集成位于 langchain-community
包中。我们还需要安装 cohere
包。我们可以通过以下命令安装这些包:
pip install -U langchain-community langchain-cohere
我们还需要获取一个 Cohere API 密钥 并设置 COHERE_API_KEY
环境变量:
import getpass
import os
os.environ["COHERE_API_KEY"] = getpass.getpass()
········
设置 LangSmith 以获得最佳的可观察性也是有帮助的(但不是必需的)
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
用法
Cohere 支持所有 LLM 功能:
from langchain_cohere import Cohere
from langchain_core.messages import 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
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? '