用 Haiku 读取网页

使用快速的 Haiku 模型读取网页内容

🌐 查看英文原文 | 源码 Notebook


使用 Claude 3 Haiku 总结网页内容

在本教程中,我们将学习如何根据给定的 URL 获取网页内容,然后使用 Anthropic 的 Claude API 生成网页内容的摘要。

让我们先安装 Anthropic 库。

环境配置

首先,让我们安装必要的库,并使用 API key 设置 Anthropic 客户端。

# Install the necessary libraries
%pip install anthropic
# Import the required libraries
from anthropic import Anthropic

# Set up the Claude API client
client = Anthropic()
MODEL_NAME = "claude-haiku-4-5"

第一步:获取网页内容

首先,我们需要使用提供的 URL 获取网页内容。为此,我们将使用 requests 库。

import requests

url = "https://en.wikipedia.org/wiki/96th_Academy_Awards"
response = requests.get(url, timeout=30)

if response.status_code == 200:
    page_content = response.text
else:
    print(f"Failed to fetch the web page. Status code: {response.status_code}")
    exit(1)

第二步:为 Claude 准备输入

接下来,我们将为 Claude API 准备输入。我们会创建一条消息,其中包含网页内容和一个要求 Claude 进行总结的 prompt。

prompt = (
    f"<content>{page_content}</content>Please produce a concise summary of the web page content."
)

messages = [{"role": "user", "content": prompt}]

第三步:生成摘要

现在,我们将调用 Haiku 来生成网页内容的摘要。

response = client.messages.create(model="claude-haiku-4-5", max_tokens=1024, messages=messages)

summary = response.content[0].text
print(summary)
The 96th Academy Awards ceremony took place on March 10, 2024 at the Dolby Theatre in Los Angeles. The ceremony, hosted by Jimmy Kimmel, presented Academy Awards (Oscars) in 23 categories honoring films released in 2023. 

The big winner of the night was the film "Oppenheimer," which won a leading 7 awards including Best Picture, Best Director for Christopher Nolan, and several technical awards. Other major winners were "Poor Things" with 4 awards and "The Zone of Interest" with 2 awards. Several notable records and milestones were set, including Steven Spielberg receiving his 13th Best Picture nomination, and Billie Eilish and Finneas O'Connell becoming the youngest two-time Oscar winners.

The ceremony featured musical performances, tributes to past winners, and a touching "In Memoriam" segment. However, it also faced some criticism, such as the distracting and hard-to-follow "In Memoriam" presentation and political controversy around a director's comments about the Israel-Gaza conflict.

Tip

中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。