跳至主要内容

Cohere Command R+:完整的逐步教程

在线与本地探索 Cohere Command R+,了解 Cohere Python API 的独特功能,并使用 LangChain 与 Cohere 构建多步骤 AI 代理。
· 12分钟 阅读

使用 AI 探索

想通过一个上手项目拓展您的 AI 知识吗?在本教程中,我们将探索 Cohere Command R+,包括如何在线和本地访问它。我们还将深入介绍 Cohere Python API 的关键功能,并使用 LangChain 和 Tavily 构建一个 AI 项目。

精彩内容从项目部分开始。如果您已熟悉 Cohere 模型及其功能,可直接跳至项目部分。在那里,您将学习如何构建一个按顺序使用多种工具来完成任务的 AI 代理。

如果您是 AI 新手并希望系统学习该领域,建议学习 AI Fundamentals 学习路径。您将获得关于 ChatGPT、大语言模型(LLM)、生成式 AI 等热门主题的可操作性知识。

什么是 Cohere Command R+?

Command R+ 是 Cohere 最新、最先进的 LLM。该模型在对话交互和长上下文任务方面表现出色,特别针对复杂的检索增强生成(RAG)工作流和多步骤工具使用进行了优化,是企业级应用的强大工具。

Cohere R plus feature image

图片由作者提供

Cohere Command R+ 关键特性

以下是 Command R+ 模型的一些重要特性。

  • 更长的上下文长度: 相较以往模型,该模型在更高质量和更高可靠性的前提下执行语言任务,支持最长 128k tokens 的上下文长度,最大输出 4k tokens。
  • 多语言能力: Command R+ 在多语言的大规模语料上训练,能够执行多种文本生成任务。针对英语、法语、西班牙语、意大利语、德语等多种语言进行了优化。
  • 跨语言能力: 模型可执行跨语言任务,如翻译或问答。
  • 检索增强生成: 使用 Command R+ 进行 RAG 无需 LangChain 或其他 AI 框架。只需在聊天函数中提供附加文档,即可生成具备上下文意识的回答,并附带来源引用。
  • 多步骤工具使用: 将模型与搜索引擎工具连接,或创建您自己的工具以连接数据库和 API。这使模型能够与多个外部来源通信,并针对查询生成最新、相关的回答。

若想更深入了解 Cohere 模型,请阅读 Cohere API 教程:快速上手 Cohere 模型。

如何访问 Cohere Command R+

访问 Cohere 模型有多种方式,其中大多数是免费的。

您可以访问在线 LLM Playground,或将模型下载到本地并搭配聊天应用使用。此外,您也可以通过 Cohere API 访问它。下面逐一介绍这些方法。

在线使用 Cohere Command R+

访问 Cohere Command R+ 的最直接在线方式是通过 HuggingChat 网站。它没有限制,您还可以连接 6 种可用工具,用于图像生成或互联网搜索等不同任务。

1. 访问 https://huggingface.co/chat/ 网站。

2. 在左侧面板点击“Models”按钮打开模型菜单,然后选择“c4ai-command-r-plus”模型。

Models directory in Hugging Chat

Hugging Chat 中的模型目录。图片来源: HuggingChat

3. 开始输入您的查询,系统将快速生成高准确度的回答。

Prompting in Hugging Chat

在 Hugging Chat 中进行提示。图片来源: HuggingChat

本地使用 Cohere Command R+

您可以通过两种方式在本地使用 Command R+:将模型下载到本机,或在 Jan 聊天应用中提供 API 密钥。

我们来探索第二种方式。

1. 从 https://jan.ai/ 网站下载并安装 Jan。

2. 点击左侧面板的窗口按钮,进入模型中心。

Model directory in Jan application.

Jan 应用中的模型目录

3. 要访问 Command R+ 模型,在模型中心的搜索栏输入 “pmysl/c4ai-command-r-plus-GGUF”。

  • 请注意,下载 Command R+ 模型需要您的系统拥有超过 30GB 的内存。

4. 下载并开始使用模型的 “Q4_K_M 版本”,其大小约为 31.24GB。

importing the model from Hugging face

从 Hugging Face 导入模型

通过 API 使用 Cohere Command R+

本地使用 Command R+ 的另一种方式是将 Cohere API 与 Jan 应用连接。

1. 访问 https://coral.cohere.com/ 并登录。

2. 前往 “Dashboard”。

3. 在左侧面板点击 “API keys” 按钮,下拉后点击 “+ Create Trail key”。

Generating the Cohere API

生成 Cohere 试用 API 密钥。来源: cohere.com

4. 生成 Cohere API 密钥后,将其粘贴到 “Model Provider” 部分。您可以在 “Settings” 中找到 “Cohere” 菜单进行设置。

Adding Cohere API key in Jan application.

在 Jan 应用中添加 Cohere API 密钥

5. 通过进入 “Thread” 菜单,并在右侧面板选择合适的模型,来选择 Command R+ 模型。

Selecting the model in Jan application

在 Jan 应用中选择模型

6. 开始进行提示,确保启用了 “Stream”。

Using Cohere Command R plus in Jan application.

在 Jan 应用中使用 Cohere Command R+

Cohere Python API 入门

本节将介绍如何设置并使用 Python API 生成回答。

1. 使用 pip 安装 Cohere Python 包。

pip install cohere

2. 生成新的 Cohere API 密钥。 您可以参照“通过 API 使用 Cohere Command R+”一节中的步骤。

creating a new cohere API key

生成 Cohere 试用 API 密钥。图片来源: cohere.com

3. 我们将使用 DataCamp 的 DataLab 作为开发环境。要在 DataLab 中设置环境变量,请按以下步骤操作:

    1. 访问 DataLab 并创建一个新笔记本。您可以免费开始使用。
    2. 创建完成后,您可以按需重命名笔记本。
    3. 前往 “Environment” 选项卡,选择 “Environment variables”,然后点击 “+ Add” 添加新的环境变量。
    4. 新增一个名为 “COHERE_API_KEY” 的环境变量,并将您刚创建的 Cohere API 密钥作为其值。集合名称可填 “Cohere”。

Adding Environment variables in DataLab

在 DataLab 中添加环境变量

4. 要在 DataCamp 的 DataLab 中激活该环境变量,前往环境变量菜单,点击 “Cohere” 旁的三点图标,然后点击 “Connect”。

connecting the environment variable.

在 DataLab 中连接 Cohere 环境变量

5. 现在,在您的笔记本中通过提供 API 密钥来初始化 Cohere 客户端。导入 Cohere 库并使用 API 密钥创建客户端对象即可。

import os
import cohere

cohere_api_key = os.environ["COHERE_API_KEY"]
co = cohere.Client(api_key=cohere_api_key)

6. 要使用 .chat() 函数生成回答,请提供 model 名称和 message。

response = co.chat(
  model="command-r-plus",
  message="Please help me write an email to the angry boss, who thinks I made the changes to the data pipeline but didn't. It was James."
)

print(response.text) 

模型对给定查询的回答

生成速度应当很快且高度相关!

下一节我们将探索 Cohere Python API 的多种功能。

探索 Command R+ Python API 的关键功能

接下来,我们将使用 Cohere Python API 生成带有历史的回答、流式输出以及可复现的输出。我们还将进行 RAG、将文本转换为嵌入,并在自定义数据集上微调模型。

文本生成

在上一节中,我们学习了如何通过简单的 .chat() 函数生成回答。现在,我们将提供更多参数,如系统提示(preamble)、chat_history、max_tokens 和 temperature。

response = co.chat(
    model="command-r-plus",
    preamble="You are a happy chatbot that puts a positive spin on everything.",
    chat_history=[
       {"role": "USER", "text": "Hey, my name is Abid!"},
       {"role": "CHATBOT", "text": "Hey Abid! How can I help you today?"},
    ],
    message="I can't swim?",
    max_tokens=150,
    temperature=0.7
)

print(response.text)

使用附加参数后的模型回答

基于这些附加参数,模型对回答进行了适当调整。

流式输出

我们还可以使用 .chat_stream() 函数进行流式输出。该函数允许实时生成回答,随着 token 可用立即输出,从而提升模型的“感知速度”。

response = co.chat_stream(
    model="command-r-plus",
    message="Tell me something interesting about the galaxy?"
)

for event in response:
    if event.event_type == "text-generation":
      print(event.text, end="")
    elif event.event_type == "stream-end":
      print(event.finish_reason, end="")

Command R Plus Streaming Gif

模型实时返回 token

可预测输出

可预测输出是 Cohere 的一项独特功能。通过设置 seed 参数,我们可以让模型对相同提示生成相同回答。

通常,向 LLM 连续两次提出相同问题,您会收到不同答案。设置 seed 可确保结果一致且可复现,类似其他机器学习模型。

在下面的示例中,将 seed 设置为 55,您将总是收到 "Matilda" 作为回答。

res = co.chat(model="command-r", message="say a random name", seed=55)
print(res.text)
Sure! I will pick a random name for you. How about "Matilda"?

为了验证,我们再次用相同的 seed 向模型提出相同问题。

res = co.chat(model="command-r", message="say a random name", seed=55)
print(res.text)
Sure! I will pick a random name for you. How about "Matilda"?

结果相同!

检索增强生成(RAG)

Cohere API 提供了内置的 RAG 功能。我们只需为 .chat() 函数提供一个 documents 参数。提出问题后,函数会对文档执行相似度搜索,以生成具备上下文的答案。

我们将以动漫研究文档为例。文档格式应与下例相似。每份文档应包含 title 和 snippet 键。

anime = [
    {
        "title": "Naruto Popularity Analysis",
        "snippet": "Naruto's global success: massive manga sales, top anime ratings, extensive merchandise, and a dedicated fanbase. The series' impact on anime culture and its influence on subsequent shonen series is undeniable."
    },
    {
        "title": "One Piece Popularity Analysis",
        "snippet": "One Piece's record-breaking manga sales and its status as a long-running anime phenomenon highlight its popularity. The series' captivating story and characters have made it a staple in the anime community."
    },
        {
        "title": "Attack on Titan Popularity Analysis",
        "snippet": "Attack on Titan's intense storyline and high-quality animation have garnered a massive following. Its success in both manga and anime formats demonstrates its widespread appeal."
    },
    {
        "title": "My Hero Academia Popularity Analysis",
        "snippet": "My Hero Academia's rapid rise to fame is marked by its engaging characters and compelling plot. The series has achieved impressive manga sales and anime viewership."
    }
]

为了生成更准确且具上下文的回答,我们将把 anime 文档传给 documents 参数中的 .chat() 函数。

response = co.chat(
    model="command-r-plus",
    message="Which Anime series have most engaging characters?",
    documents=anime,
)

print(response.text) 
Some anime series with engaging characters include My Hero Academia and One Piece.

如您所见,模型利用文档生成了高度准确的回答。

如果您想了解背后的过程以及模型如何生成回答,您可以直接打印包含元数据的完整 response。

response

RAG response generations

请注意 ChatCitation 部分,以及 Cohere 的 .chat() 函数如何使用文档片段来生成回答。

我们还可以将工具和连接器接入 .chat() 函数。以下示例连接了互联网搜索引擎,以生成更新的答案。

response = co.chat(
    model="command-r-plus",
    message="Which Anime series have most engaging characters?",
    connectors=[{"id": "web-search"}],
)

print(response.text) 
Here are some Anime series with engaging characters:
- Jujutsu Kaisen
- One Piece
- Naruto
- Dragon Ball Z
- Bleach
- Death Note
- Fullmetal Alchemist: Brotherhood
- Demon Slayer: Kimetsu no Yaiba
- Attack on Titan
- Mob Psycho 100
- Trigun
- My Hero Academia
- Cowboy Bebop
- Komi Can't Communicate
- Spy X Family

在此情况下,模型会先在互联网上检索信息,再将上下文提供给模型以生成更新且准确的结果。

想要了解具备高效信息检索机制的 LLM 的优势,您可以阅读教程 用 RAG 与重排序提升 LLM 准确性。

嵌入

文本嵌入是文本的数值表示,能够捕捉语义含义,便于高效的相似度搜索和文本数据分析。

借助 Cohere 的 .embed() 函数,我们可以将文本转换为用于搜索查询的嵌入向量。只需提供 model 名称、texts 列表、input_type 和 embedding_types 即可。

texts = [ 'I love you', 'I hate you', 'Who are you?']  

response = co.embed(
  model='embed-english-v3.0',
  texts=texts, 
  input_type='search_query',
  embedding_types=['float']) 


embeddings = response.embeddings.float # All text embeddings 
print(embeddings[2][:5]) 
[-0.00459671, -0.010803223, -0.048339844, -0.012306213, -0.019134521]

Cohere 也支持将多语言文本转换为嵌入。为此,我们需要将嵌入模型更改为 “embed-multilingual-v3.0”,并将 input_type 设置为 “classification”。

texts = [  
   'I love you', 'Te quiero', 'Ich liebe dich',  
   'Ti amo', 'Я тебя люблю', ' 我爱你 ',  
   '愛してる', 'أحبك', 'मैं तुमसे प्यार करता हूँ'  
]  

response = co.embed(
  model='embed-multilingual-v3.0',
  texts=texts, 
  input_type='classification',
  embedding_types=['float']) 

embeddings = response.embeddings.float # All text embeddings 
print(embeddings[2][:5]) 
[-0.011756897, 0.0116119385, -0.005115509, 0.011657715, -0.001660347]

微调

与 OpenAI API 类似,Cohere API 允许我们在自定义数据集上微调模型。我们只需上传数据并运行微调函数,就这么简单。

在示例中,我们将使用 ChatGPT(GPT-4o)模型生成两个自定义数据集。请遵循下图所示的数据集格式。

JSONL sample dataset

使用生成的数据,创建 “positive_bot_train” 和 “positive_bot_eval” 两个 JSONL 文件,并将文件位置提供给 .datasets.create() 函数。该函数还需要数据集的 name 和微调 type。

my_dataset = co.datasets.create(
  name="Happy assistant",
  type="chat-finetune-input",
  data=open("./data/positive_bot_train.jsonl", "rb"),
  eval_data=open("./data/positive_bot_eval.jsonl", "rb")
)

result = co.wait(my_dataset)
print(result)

uploading the dataset to Cohere

如图所示,函数已验证数据集并将其上传至 Cohere 云存储。

现在,我们只需将模型的 name、base_type 和 dataset_id 提供给 .finetuning.create_finetuned_model() 函数,即可在云端启动微调流程。

from cohere.finetuning import FinetunedModel, Settings, BaseModel

# start training a custom model using the dataset
finetuned_model = co.finetuning.create_finetuned_model(
  request=FinetunedModel(
    name="happy-chat-bot-model",
    settings=Settings(
      base_model=BaseModel(
        base_type="BASE_TYPE_CHAT",
      ),
      dataset_id=my_dataset.id,
    ),
  ),
)

要查看微调进度,请前往 Cohere 仪表板,点击左侧面板的 “Fine-tuning”。

finetuning status

微调状态。来源: Models | Cohere

微调模型并生成评估报告可能需要几分钟。

model evolution and usage on dashboard

微调结果。图片来源: Fine-tuned Model - happy-chat-bot-model | Cohere

模型微调完成后,我们可以查看结果概览。如上图所示,模型的准确率较低。为何如此?因为我们仅提供了两行数据。为提升准确率,请尝试提供至少 1000 行的真实世界数据。

要访问我们微调后的模型,可以将模型 ID 传给 .chat() 函数,同时提供 preamble、message 和 max_tokens。

您可通过进入仪表板,选择 “Fine-tuning”,然后进入 “YOUR MODELS”,从微调模型列表中复制模型 ID。

response = co.chat(
    model="8f34d596-b94e-4395-afad-1db35b2b0b53-ft",
    preamble="You are a happy chatbot that puts a positive spin on everything.",
    message="I burned my finger while barbecuing.",
    max_tokens=100
)

print(response.text)
Ouch! That doesn't sound fun, but it's great that you're taking time to relax and enjoy some delicious grilled foods. Barbecuing is a wonderful way to spend time with friends and family, and it's an excellent opportunity to savor the little things in life. Remember to take care of your burn; it's a small price to pay for a fun day making delicious memories!

这个回答已经相当不错!

使用 Command R+ 构建 AI 项目

我们现在将使用 LangChain 生态与 Cohere Command R+ 模型构建一个多步骤 AI 代理。

该 AI 应用将接收用户查询,使用 Tavily API 进行网络搜索并生成 Python 代码。随后使用 Python REPL 执行代码并返回用户所需的可视化结果。

首先需要安装所有必需的 Python 包。我们可以在 DataLab 笔记本中完成。

%pip install --quiet langchain langchain_cohere langchain_experimental

然后,使用 LangChain Python API 创建聊天客户端,提供之前创建的 Cohere API 密钥。我们将在 AI 代理中使用 Command R+ 作为语言模型。

import os
from langchain_cohere.chat_models import ChatCohere

cohere_api_key = os.environ["COHERE_API_KEY"]
chat = ChatCohere(model="command-r-plus", temperature=0.7, api_key=cohere_api_key)

注册 Tavily 并复制您的 API 密钥。Tavily 是面向 LLM 与 RAG 流水线的互联网搜索 API。

generating the Tavily API key

生成 Tavily API 密钥。图片来源: Tavily AI

要创建互联网搜索工具,请在 DataLab 中将刚生成的 API 密钥设置为环境变量。然后更新 name、description 和 args_schema。

from langchain_community.tools.tavily_search import TavilySearchResults

internet_search = TavilySearchResults(api_key=os.environ['TAVILY_API_KEY'])
internet_search.name = "internet_search"
internet_search.description = "Returns a list of relevant documents from the internet."

from langchain_core.pydantic_v1 import BaseModel, Field

class TavilySearchInput(BaseModel):
    query: str = Field(description="Internet query engine.")

internet_search.args_schema = TavilySearchInput

创建 Python REPL 工具非常直接:给 Tool 类提供一个 Python REPL 对象、name 和 description,并按下方所示修改参数模式。

from langchain.agents import Tool
from langchain_experimental.utilities import PythonREPL

python_repl = PythonREPL()
repl_tool = Tool(
    name="python_repl",
    description="Executes python code and returns the result.",
    func=python_repl.run,
)
repl_tool.name = "python_interpreter"

class ToolInput(BaseModel):
    code: str = Field(description="Python code execution.")

repl_tool.args_schema = ToolInput

现在我们将一切组合起来,使用 .create_cohere_react_agent() 函数、Cohere 模型客户端、工具以及提示模板创建多步骤 AI 代理。我们将通过为 AgentExecutor 类提供代理对象与工具来执行我们的 AI 代理。

from langchain.agents import AgentExecutor
from langchain_cohere.react_multi_hop.agent import create_cohere_react_agent
from langchain_core.prompts import ChatPromptTemplate

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

agent = create_cohere_react_agent(
    llm=chat,
    tools=[internet_search, repl_tool],
    prompt=prompt,
)

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

然后,使用 agent_executor 生成可视化。在我们的案例中,我们要求 AI 代理从互联网上收集最新数据并创建一个饼图。

response = agent_executor.invoke({
    "input": "Create a pie chart of the top 5 most used programming languages in 2024.",
})

Pie chart of top programing language

由 Cohere 模型创建的热门编程语言饼图。图片由作者提供

结果非常出色!它成功使用互联网上的最新数据生成了饼图。

如果您在运行本教程代码时遇到问题,请查看 DataLab 工作空间 Cohere Command R+ 教程,其中包含代码源、数据集和输出。

与 LangChain 类似,您也可以使用 LlamaIndex 构建多步骤 AI 代理。要开始使用 LlamaIndex,请观看 使用 LlamaIndex 进行检索增强生成 的跟学视频教程。

结语

AI 市场再次升温,学习新的工具和 API 将帮助您构建更优秀的 AI 系统并强化您的作品集。此外,一些 AI 框架能够为您处理大部分任务,您只需编写少量代码即可,极大简化了工作流程。

在本教程中,我们了解了 Cohere Command R+ 模型,以及如何通过 Hugging Face Chat、Jan 应用和 API 访问它。我们还学习了 Python API,并了解如何微调模型以生成自定义回答。最后,我们构建了一个能够接收用户查询、在互联网上检索最新数据并使用 Python REPL 生成可视化的完整 AI 代理。

若想进一步了解 LLM 的强大功能,以及如何从提示生成内容、从文档中提取信息、构建语义搜索引擎,请查看我们的跟学视频: 使用 Cohere API 的大语言模型。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题