跳至主要内容

Claude 3 与 Claude 3 API 入门

了解 Claude 3 模型、详细的性能基准,以及访问方式。此外,探索全新的 Claude 3 Python API,用于文本生成、视觉能力调用与流式输出。

使用 AI 探索

AI 之战仍在持续。谷歌的 Gemini 与 Gemma 近期声势浩大,而今 Anthropic 的 Claude 3 强势登场,在各项基准测试中全面超越 GPT-4 与 Gemini Ultra。

在本教程中,我们将探索 Claude 3 模型、性能基准以及如何访问这些模型。我们还会将 Claude 3 与其前代 Claude 2.1 以及 ChatGPT 进行比较。最后,我们将学习使用 Claude 3 的 Python API 来生成文本、调用视觉能力、流式返回响应,并以异步方式使用它。

什么是 Claude 3?

Anthropic 近期发布了名为 Claude 3 的新一代 AI 模型家族。这些模型在多种认知任务中树立了行业基准。Claude 3 系列包含三款先进模型:Haiku、Sonnet 与 Opus。它们可用于实时客服对话、自动补全以及数据抽取等任务。

目前,Opus 与 Sonnet 已可在 claude.ai 与 Claude API 上使用,体量更小的 Haiku 将很快发布。Claude 3 模型在遵循复杂的多步指令、贴合品牌语气与响应规范、以及以 JSON 等格式生成结构化输出方面表现更佳。

与以往的 Claude 模型相比,新模型的上下文理解力进一步提升,从而减少了不必要的拒答。

它们提供 200K 的上下文窗口,但可处理超过 100 万 token 的输入。具体而言,Claude 3 Opus 在召回方面几乎达到完美,准确率超过 99%。

为确保模型的可靠性,Anthropic 设有专门团队来追踪并缓解各类风险。

模型详情

Claude 3 提供三款模型,在智能、速度与成本之间为不同应用场景实现平衡。

Claude 3 Opus

Opus 面向复杂、高智能的任务,在开放式问题求解与战略分析上表现突出,具备更大的上下文窗口;其更高的成本反映了更强的能力。

价格:输入 token 每百万 $15,输出 token 每百万 $75。

Claude 3 Sonnet

Sonnet 在性能与成本之间提供最佳平衡,适用于涉及数据处理、销售优化与可扩展 AI 部署的企业级工作负载。其价格亲民,并配备大上下文窗口。

价格:输入 token 每百万 $3,输出 token 每百万 $15。

Claude 3 Haiku

Haiku 以速度与效率见长,适配客户服务、内容审核与成本敏感任务中的实时响应需求,是该系列中最经济、响应最快的模型。

价格:输入 token 每百万 $0.25,输出 token 每百万 $1.25。

如何访问 Claude 3

访问 Claude 3 模型有三种方式。

Claude Chat

如果您想用简单且免费的方式体验 Claude AI 模型,可以注册 claude.ai/chats,其使用体验类似 ChatGPT。该聊天界面交互性强且易于上手。

目前可免费使用 Claude 3 Sonnet;如需访问 Claude 3 Opus,则需要购买 Claude Pro 月度订阅。

Claude Chat

Claude Chat

Workbench

若想免费使用 Claude 3 Opus,您需要注册 Anthropic API:console.anthropic.com。

按照简单步骤免费注册,然后点击 Workbench 选项卡并选择“claude-3-opus-20240229”模型即可开始使用 Opus。

Anthropic Workbench

Anthropic Workbench

API 和 SDK

第三种方式是通过 API。Anthropic 提供 Python 与 Typescript 的客户端 SDK。您也可以在终端中使用 curl 命令通过 REST API 访问模型。

curl https://api.anthropic.com/v1/messages \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "anthropic-version: 2023-06-01" \
     --header "content-type: application/json" \
     --data \
'{
    "model": "claude-3-opus-20240229",
    "max_tokens": 1024,
    "messages": [
        {"role": "user", "content": "How many moons does Jupiter have?"}
    ]
}'

深入基准测试

Claude 3 模型与当前表现最强的各大语言模型(LLM)进行了基准对比,并在多项测试中取得显著提升。

尤其是 Claude 3 Opus,在多项常见评估基准(如 MMLU、GPQA、GSM8K)上超过了 GPT-4 与 Gemini Ultra。在复杂任务上,它展现出近似人类的理解力与流畅度,迈出通用智能的重要一步。

想了解 OpenAI 的前沿 LLM,请阅读 DataCamp 的文章 What is GPT-4 and Why Does it Matter?。此外,关于谷歌的 ChatGPT 竞品 Google Gemini,请查阅 What is Google Gemini? Everything You Need To Know About It。

从下方基准数据可见,Claude 3 模型在分析与预测、代码生成、以及非英语语言的响应生成方面均有提升:

Claude 3 Benchmarks

图片来源

Claude 3 的视觉能力显著增强,能够理解复杂的照片、图表与图示。这项进步有利于具备多种格式知识库的企业,如 PDF、流程图与演示文稿。

Claude 3 Vision Benchmarks

图片来源

与前代模型相比,Claude 3 在减少不必要拒答与提升准确性方面也有大幅改进。

Claude 3 incorrect refusals comparison

图片来源

最后,我们可以看到,与 Claude 2.1 相比,Claude 3 在开放式问题上的准确性提升近两倍。同时,新模型的错误回答率也有所降低。

Claude 3 Opus vs Claude 2.1

本节将比较 Claude 3 Opus 与 Claude 2.1 在三类常见任务上的表现,以便了解二者的差异。

问答

提示: I speak without a mouth and hear without ears. I have no body, but I come alive with wind. What am I?

Claude 3 Q&A

Claude 2.1 以缺乏内容为由拒绝作答。但实际上用户提出的是一个谜语,而 Claude Opus 给出了正确答案。

生成代码

提示: Create a FastAPI web application for a simple Scikit-learn classification model.

Claude 3 vs Claude 2.1 generating code

Claude 2.1 生成的代码最初看似可用,但在输入样例值后报错。进一步检查发现,代码未优化,推理函数存在错误。

相较之下,Claude 3 Opus 生成的代码运行顺畅,并给出准确预测,如下所示。

Claude 3 vs Claude 2.1 generating code answers

复杂问题

提示:How does a neural network with one layer and one input and output compare to a logistic regression?

Claude 3 vs Claude 2.1 Complex Problems

两款模型的回答大体相近,但 Claude 3 Opus 的表述更详尽,也更易读。

Claude 3 Opus vs ChatGPT 4

我们将以类似任务对比 Claude 3 Opus 与 ChatGPT 4,以展示 Claude 3 在某些方面对 GPT-4 的小幅领先。

问答

提示:How many moons does Jupiter have?

Claude 3 Opus vs ChatGPT 4  Q&A

两者的说法都不正确。截止 2024 年 2 月 5 日,木星有 95 颗卫星。这个提示有助于理解数据集的截断期。看起来 Claude 3 Opus 训练于更早(约 2021 年)的数据集,而 ChatGPT 的最新更新时间为 2023 年 4 月。

生成代码

提示:Creating a Gradio web application for a simple Scikit-learn classification model.

Claude 3 Opus vs ChatGPT 4  Generating Code

Claude 3 生成的代码运行顺利;而 GPT-4 生成的代码因多处错误与幻觉而无法运行。

复杂问题

提示:There are four people in an elevator and four floors in a building. What’s the probability that each person gets off on a different floor?

Claude 3 Opus vs ChatGPT 4  Complex Problem

两款模型都正确解答了这道著名的概率题。一个给出了数学推导,另一个生成并运行了 Python 代码得到相同答案。在此场景中,两者均表现出色。

Claude 3 Python SDK

本部分我们将了解 Claude 3 Python SDK,以及如何用它生成定制化响应。

快速开始

1. 使用 PIP 安装 anthropic Python 包。

pip install anthropic

2. 在安装 Python 包前,需前往 https://console.anthropic.com/dashboard 获取 API 密钥。

Claude 3 API Key

3. 设置 ANTHROPIC_API_KEY 环境变量,并将其值设为 API 密钥。在 DataLab(DataCamp 的 AI 加持数据笔记本)中配置与访问环境变量非常方便。

Claude 3 Add Environment Variables

4. 使用 API 密钥创建客户端对象。我们将用它进行文本生成、调用视觉能力与流式输出。

import os
import anthropic

client = anthropic.Anthropic(
    api_key=os.environ["ANTHROPIC_API_KEY"],
)

Claude 2 Completions API

需要注意的是,更新的 Claude 3 模型不再使用 Completion API。如果您尝试用该 API 调用 Claude 3,将会报错,并提示改用 Messages API。

from IPython.display import Markdown, display
from anthropic import HUMAN_PROMPT, AI_PROMPT

completion = client.completions.create(
    model="claude-2.1",
    max_tokens_to_sample=300,
    prompt=f"{HUMAN_PROMPT} What is Matthew effect? {AI_PROMPT}",
)
Markdown(completion.completion)

Claude 3 Example

如欲了解更低成本的 Claude Python API,请阅读 Getting Started with the Claude 2 and Anthropic API。

Claude 3 Messages API

为进一步说明,我们将测试 Claude 3 Opus 的 Anthropic Messages API。该 API 与 Completion API 类似,但需要以字典列表的形式传入 messages 参数,其中包含角色与内容。

Prompt = "Write the Go code for the simple data analysis."
message = client.messages.create(
    model="claude-3-opus-20240229",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": Prompt}
    ]
)
Markdown(message.content[0].text)

借助 IPython Markdown,可将响应以 Markdown 格式显示,即以更清晰的方式呈现项目符号、代码块、标题与链接。

Creating code in markdown with Claude 3

代码运行良好,解释也足够清晰,便于理解其工作原理。

添加系统提示

我们可以通过提供系统提示来自定义响应。此处我们要求它将所有回答转换为瑞典语。

Prompt = "Write a report on climate change."

message = client.messages.create(
    model="claude-3-opus-20240229",
    max_tokens=1024,
    system="Respond only in Svenska.",
    messages=[
        {"role": "user", "content": Prompt} 
    ]
)

Markdown(message.content[0].text)

它已准确地用瑞典语生成了一篇气候变化报告。

Claude 3 Output (Swedish)

Claude 3 视觉块

Messages API 支持视觉能力。本节我们将使用来自 Pexels.com 的两张照片来生成响应。

Claude 3 Vision Block

我们将使用 httpx 包加载图像,并将其转换为 base64 编码。

import base64
import httpx

media_type = "image/jpeg"

url_1 = "https://images.pexels.com/photos/20433278/pexels-photo-20433278/free-photo-of-indian-blue-jay.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"

image_encode_1 = base64.b64encode(httpx.get(url_1).content).decode("utf-8")

url_2 = "https://images.pexels.com/photos/772429/pexels-photo-772429.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"

image_encode_2 = base64.b64encode(httpx.get(url_2).content).decode("utf-8")

单图视觉

要就图像发问,需要向 Claude 3 API 提供图像数据、编码类型与媒体类型。图像与提示共同构成 message 参数中 content 字典的一部分。

message = client.messages.create(
    model="claude-3-opus-20240229",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": media_type,
                        "data": image_encode_1,
                    },
                },
                {
                    "type": "text",
                    "text": "Describe the image."
                }
            ],
        }
    ],
)
Markdown(message.content[0].text)

Claude 3 Vision Block Results

多图视觉

添加多张图像略显复杂,但只要遵循示例中的代码模式,即可理解其工作方式。

我们只需编写文本指明图像 1 与图像 2,然后就这两张图像提出问题即可。

message = client.messages.create(
    model="claude-3-opus-20240229",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Image 1:"
                },
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": media_type,
                        "data": image_encode_1,
                    },
                },
                {
                    "type": "text",
                    "text": "Image 2:"
                },
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": media_type,
                        "data": image_encode_2,
                    },
                },
                {
                    "type": "text",
                    "text": "What do these images have in common?"
                }
            ],
        }
    ],
)
Markdown(message.content[0].text)

很好。两张图像都包含鸟类。

Claude 3 Vision Block Results 2

Claude 3 流式 API

流式生成指的是连续产出文本,而非等待整段文本生成完成后再返回结果。采用该技术时,输出会以 token 为粒度逐步生成,从而降低感知延迟。

我们将使用流式函数替代 create 来生成流式响应。

为显示结果,我们将使用 with 语法与 for 循环,在 token 可用时立即打印。

Prompt = "Write a Python code for typical data engineering workflow."


completion = client.messages.stream(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": Prompt,
        }
    ],
    model="claude-3-opus-20240229",
)

with completion as stream:
    for text in stream.text_stream:
            print(text, end="", flush=True)

Claude 3 Streaming Response

Claude 3 异步 API

同步 API 会顺序执行请求,并在收到响应前阻塞,随后再发起下一次调用。相对地,异步 API 允许并发处理多个请求而不被阻塞,因此更高效、更易扩展。

我们将使用 AsyncAnthropic 初始化异步客户端。然后使用 async 关键字创建 main 函数,并通过 asyncio.run 运行该函数。

注意:如果在 Jupyter Notebook 中使用异步,请尝试使用 await main(),而非 asyncio.run(main())。

import asyncio
from anthropic import AsyncAnthropic

async_client = AsyncAnthropic(
    api_key=os.environ["ANTHROPIC_API_KEY"],
)

Prompt = "Could you explain what MLOps is and suggest some of the best tools to use for it?"

async def main() -> None:

    message = await async_client.messages.create(
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": Prompt,
            }
        ],
        model="claude-3-opus-20240229",
    )
    display(Markdown(message.content[0].text))


asyncio.run(main())

Claude 3 Async API

将流式与异步 API 相结合

我们可以通过异步客户端的流式方法轻松将流式与异步结合。这样即可同时接收多个请求并流式返回响应,使 AI 应用更具可扩展性与健壮性。

async def main() -> None:
    
    completion = async_client.messages.stream(
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": Prompt,
            }
        ],
        model="claude-3-opus-20240229",
    )
    async with completion as stream:
        async for text in stream.text_stream:
            print(text, end="", flush=True)

asyncio.run(main())

Claude 3 Combining Streaming with Async API

如果您在运行代码时遇到困难,可以访问此 DataLab 工作簿,您可以在其中查看并自行执行代码(需先复制)。

想了解如何访问 OpenAI 的大语言模型,请参考教程 Using GPT-3.5 and GPT-4 via the OpenAI API in Python。

结语

Anthropic 现已与 OpenAI 类似,面向公众与企业提供服务。其模型对所有人开放,在部分情况下可免费使用。您可以通过 Pro 订阅或 API 访问性能最佳的 LLM——Claude 3 Opus。然而,Anthropic 目前尚未拥有 OpenAI 的生态系统,缺少嵌入模型、图像与视频生成、文本转语音以及语音识别等能力,也不具备 OpenAI API 所提供的核心功能。

您可以通过阅读 What is Open AI's Sora? How it Works, Use Cases, Alternatives & More 了解 OpenAI 全新文本转视频模型,该模型已在社交媒体上引发热潮。

在本教程中,我们了解了在 AI 领域备受关注的 Claude 3 模型,并在多项任务上将其与 Claude 2.1 与 GPT-4 进行了对比。最后,我们使用 Anthropic Python SDK 来生成文本、调用视觉能力、以 token 为粒度流式输出响应,并以异步方式使用 API。

如果您是 AI 新手,想深入理解前沿 LLM 的工作原理,建议学习 AI Fundamentals 技能路径。课程将为您提供关于 ChatGPT、大语言模型、生成式 AI 等热门主题的实践知识。

Abid Ali Awan

作者

Abid Ali Awan

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

主题