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、将文本转换为嵌入,并在自定义数据集上微调模型。
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)技术支持
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="")技术支持
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."}]技术支持
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技术支持
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])技术支持
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,),),)技术支持
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 执行代码并返回用户所需的可视化结果。
要创建互联网搜索工具,请在 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
classTavilySearchInput(BaseModel):
query:str= Field(description="Internet query engine.")
internet_search.args_schema = TavilySearchInput技术支持
想通过一个上手项目拓展您的 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 Command R+ 关键特性
以下是 Command R+ 模型的一些重要特性。
若想更深入了解 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”模型。
Hugging Chat 中的模型目录。图片来源: HuggingChat
3. 开始输入您的查询,系统将快速生成高准确度的回答。
在 Hugging Chat 中进行提示。图片来源: HuggingChat
本地使用 Cohere Command R+
您可以通过两种方式在本地使用 Command R+:将模型下载到本机,或在 Jan 聊天应用中提供 API 密钥。
我们来探索第二种方式。
1. 从 https://jan.ai/ 网站下载并安装 Jan。
2. 点击左侧面板的窗口按钮,进入模型中心。
Jan 应用中的模型目录
3. 要访问 Command R+ 模型,在模型中心的搜索栏输入 “pmysl/c4ai-command-r-plus-GGUF”。
4. 下载并开始使用模型的 “Q4_K_M 版本”,其大小约为 31.24GB。
从 Hugging Face 导入模型
通过 API 使用 Cohere Command R+
本地使用 Command R+ 的另一种方式是将 Cohere API 与 Jan 应用连接。
1. 访问 https://coral.cohere.com/ 并登录。
2. 前往 “Dashboard”。
3. 在左侧面板点击 “API keys” 按钮,下拉后点击 “+ Create Trail key”。
生成 Cohere 试用 API 密钥。来源: cohere.com
4. 生成 Cohere API 密钥后,将其粘贴到 “Model Provider” 部分。您可以在 “Settings” 中找到 “Cohere” 菜单进行设置。
在 Jan 应用中添加 Cohere API 密钥
5. 通过进入 “Thread” 菜单,并在右侧面板选择合适的模型,来选择 Command R+ 模型。
在 Jan 应用中选择模型
6. 开始进行提示,确保启用了 “Stream”。
在 Jan 应用中使用 Cohere Command R+
Cohere Python API 入门
本节将介绍如何设置并使用 Python API 生成回答。
1. 使用 pip 安装 Cohere Python 包。
2. 生成新的 Cohere API 密钥。 您可以参照“通过 API 使用 Cohere Command R+”一节中的步骤。
生成 Cohere 试用 API 密钥。图片来源: cohere.com
3. 我们将使用 DataCamp 的 DataLab 作为开发环境。要在 DataLab 中设置环境变量,请按以下步骤操作:
在 DataLab 中添加环境变量
4. 要在 DataCamp 的 DataLab 中激活该环境变量,前往环境变量菜单,点击 “Cohere” 旁的三点图标,然后点击 “Connect”。
在 DataLab 中连接 Cohere 环境变量
5. 现在,在您的笔记本中通过提供 API 密钥来初始化 Cohere 客户端。导入 Cohere 库并使用 API 密钥创建客户端对象即可。
6. 要使用
.chat()函数生成回答,请提供model名称和message。模型对给定查询的回答
生成速度应当很快且高度相关!
下一节我们将探索 Cohere Python API 的多种功能。
探索 Command R+ Python API 的关键功能
接下来,我们将使用 Cohere Python API 生成带有历史的回答、流式输出以及可复现的输出。我们还将进行 RAG、将文本转换为嵌入,并在自定义数据集上微调模型。
文本生成
在上一节中,我们学习了如何通过简单的
.chat()函数生成回答。现在,我们将提供更多参数,如系统提示(preamble)、chat_history、max_tokens和temperature。使用附加参数后的模型回答
基于这些附加参数,模型对回答进行了适当调整。
流式输出
我们还可以使用
.chat_stream()函数进行流式输出。该函数允许实时生成回答,随着 token 可用立即输出,从而提升模型的“感知速度”。模型实时返回 token
可预测输出
可预测输出是 Cohere 的一项独特功能。通过设置
seed参数,我们可以让模型对相同提示生成相同回答。通常,向 LLM 连续两次提出相同问题,您会收到不同答案。设置
seed可确保结果一致且可复现,类似其他机器学习模型。在下面的示例中,将
seed设置为 55,您将总是收到 "Matilda" 作为回答。为了验证,我们再次用相同的
seed向模型提出相同问题。结果相同!
检索增强生成(RAG)
Cohere API 提供了内置的 RAG 功能。我们只需为
.chat()函数提供一个documents参数。提出问题后,函数会对文档执行相似度搜索,以生成具备上下文的答案。我们将以动漫研究文档为例。文档格式应与下例相似。每份文档应包含
title和snippet键。为了生成更准确且具上下文的回答,我们将把
anime文档传给documents参数中的.chat()函数。如您所见,模型利用文档生成了高度准确的回答。
如果您想了解背后的过程以及模型如何生成回答,您可以直接打印包含元数据的完整
response。请注意
ChatCitation部分,以及 Cohere 的.chat()函数如何使用文档片段来生成回答。我们还可以将工具和连接器接入
.chat()函数。以下示例连接了互联网搜索引擎,以生成更新的答案。在此情况下,模型会先在互联网上检索信息,再将上下文提供给模型以生成更新且准确的结果。
想要了解具备高效信息检索机制的 LLM 的优势,您可以阅读教程 用 RAG 与重排序提升 LLM 准确性。
嵌入
文本嵌入是文本的数值表示,能够捕捉语义含义,便于高效的相似度搜索和文本数据分析。
借助 Cohere 的
.embed()函数,我们可以将文本转换为用于搜索查询的嵌入向量。只需提供model名称、texts列表、input_type和embedding_types即可。Cohere 也支持将多语言文本转换为嵌入。为此,我们需要将嵌入模型更改为 “embed-multilingual-v3.0”,并将
input_type设置为 “classification”。微调
与 OpenAI API 类似,Cohere API 允许我们在自定义数据集上微调模型。我们只需上传数据并运行微调函数,就这么简单。
在示例中,我们将使用 ChatGPT(GPT-4o)模型生成两个自定义数据集。请遵循下图所示的数据集格式。
使用生成的数据,创建 “positive_bot_train” 和 “positive_bot_eval” 两个 JSONL 文件,并将文件位置提供给
.datasets.create()函数。该函数还需要数据集的 name 和微调type。如图所示,函数已验证数据集并将其上传至 Cohere 云存储。
现在,我们只需将模型的
name、base_type和dataset_id提供给.finetuning.create_finetuned_model()函数,即可在云端启动微调流程。要查看微调进度,请前往 Cohere 仪表板,点击左侧面板的 “Fine-tuning”。
微调状态。来源: Models | Cohere
微调模型并生成评估报告可能需要几分钟。
微调结果。图片来源: Fine-tuned Model - happy-chat-bot-model | Cohere
模型微调完成后,我们可以查看结果概览。如上图所示,模型的准确率较低。为何如此?因为我们仅提供了两行数据。为提升准确率,请尝试提供至少 1000 行的真实世界数据。
要访问我们微调后的模型,可以将模型 ID 传给
.chat()函数,同时提供preamble、message和max_tokens。您可通过进入仪表板,选择 “Fine-tuning”,然后进入 “YOUR MODELS”,从微调模型列表中复制模型 ID。
这个回答已经相当不错!
使用 Command R+ 构建 AI 项目
我们现在将使用 LangChain 生态与 Cohere Command R+ 模型构建一个多步骤 AI 代理。
该 AI 应用将接收用户查询,使用 Tavily API 进行网络搜索并生成 Python 代码。随后使用 Python REPL 执行代码并返回用户所需的可视化结果。
1. 安装 Python 包
首先需要安装所有必需的 Python 包。我们可以在 DataLab 笔记本中完成。
2. 设置 Cohere 聊天模型
然后,使用 LangChain Python API 创建聊天客户端,提供之前创建的 Cohere API 密钥。我们将在 AI 代理中使用 Command R+ 作为语言模型。
3. 设置 Tavily 进行互联网搜索
注册 Tavily 并复制您的 API 密钥。Tavily 是面向 LLM 与 RAG 流水线的互联网搜索 API。
生成 Tavily API 密钥。图片来源: Tavily AI
要创建互联网搜索工具,请在 DataLab 中将刚生成的 API 密钥设置为环境变量。然后更新
name、description和args_schema。4. 设置 Python REPL
创建 Python REPL 工具非常直接:给
Tool类提供一个 Python REPL 对象、name和description,并按下方所示修改参数模式。5. 创建并执行 AI 代理
现在我们将一切组合起来,使用
.create_cohere_react_agent()函数、Cohere 模型客户端、工具以及提示模板创建多步骤 AI 代理。我们将通过为AgentExecutor类提供代理对象与工具来执行我们的 AI 代理。6. 测试代理
然后,使用
agent_executor生成可视化。在我们的案例中,我们要求 AI 代理从互联网上收集最新数据并创建一个饼图。由 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 的大语言模型。