Skip to main content

Cohere

遗留功能

Cohere 已将其大型语言模型(LLMs)的 generate 接口标记为弃用。请参考其迁移指南,开始通过 ChatCohere 集成使用他们的聊天 API。

caution

您当前所在的页面记录的是将 Cohere 模型作为文本补全模型使用的相关内容。Cohere 上提供的许多流行模型实际上是聊天补全模型

您可能需要查看这个页面

这将帮助您开始使用 Cohere 补全模型(LLMs)配合 LangChain。有关 Cohere 功能和配置选项的详细文档,请参阅 API 参考

概览

集成详情

类别本地支持可序列化Python 支持包下载量最新版本
Cohere@langchain/cohereNPM - 下载量NPM - 版本

准备工作

要访问 Cohere 模型,您需要创建一个 Cohere 账户,获取 API 密钥,并安装 @langchain/cohere 集成包。

凭证

前往 cohere.com 注册 Cohere 账户并生成 API 密钥。完成此操作后,请设置 COHERE_API_KEY 环境变量:

export COHERE_API_KEY="your-api-key"

如果您希望自动追踪模型调用,也可以取消以下 LangSmith API 密钥设置的注释:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

安装

LangChain 的 Cohere 集成位于 @langchain/cohere 包中:

:::提示 请参阅安装集成包的一般说明部分。 :::

yarn add @langchain/cohere @langchain/core

实例化

现在我们可以实例化我们的模型对象并生成聊天补全:

import { Cohere } from "@langchain/cohere";

const llm = new Cohere({
model: "command",
temperature: 0,
maxTokens: undefined,
maxRetries: 2,
// other params...
});

自定义适用于 Azure 上的 Cohere、AWS Bedrock 上的 Cohere 以及独立 Cohere 实例的客户端。

我们可以实例化一个自定义的 CohereClient,并将其传递给 ChatCohere 构造函数。

注意: 如果提供了自定义客户端,则构造函数中的 COHERE_API_KEY 环境变量和 apiKey 参数都将被忽略。

import { Cohere } from "@langchain/cohere";
import { CohereClient } from "cohere-ai";

const client = new CohereClient({
token: "<your-api-key>",
environment: "<your-cohere-deployment-url>", //optional
// other params
});

const llmWithCustomClient = new Cohere({
client,
// other params...
});

调用

const inputText = "Cohere is an AI company that ";

const completion = await llm.invoke(inputText);
completion;
Cohere is a company that provides natural language processing models that help companies improve human-machine interactions. Cohere was founded in 2019 by Aidan Gomez, Ivan Zhang, and Nick Frosst.

链式调用

我们可以像这样将补全模型与提示模板进行链式调用

import { PromptTemplate } from "@langchain/core/prompts";

const prompt = new PromptTemplate({
template: "How to say {input} in {output_language}:\n",
inputVariables: ["input", "output_language"],
});

const chain = prompt.pipe(llm);
await chain.invoke({
output_language: "German",
input: "I love programming.",
});
 Ich liebe Programming.

But for day to day purposes Ich mag Programming. would be enough and perfectly understood.

I love programming is "Ich liebe Programming" and I like programming is "Ich mag Programming" respectively.

There are also other ways to express this feeling, such as "Ich habe Spaß mit Programming", which means "I enjoy programming". But "Ich mag" and "Ich liebe" are the most common expressions for this.

Let me know if I can be of further help with something else!

API 参考文档

有关所有 Cohere 功能和配置的详细文档,请访问 API 参考页面: https://api.js.langchain.com/classes/langchain_cohere.Cohere.html


Was this page helpful?


You can also leave detailed feedback on GitHub.