llm-anthropic 0.31 版本更新
llm-anthropic 0.31
AI 实践llm-anthropic
PyPI 更新日志 测试 许可证:Apache License, Version 2.0
通过 LLM 访问 Anthropic 的模型,包括 Claude 系列
安装
在与 LLM 相同的环境中安装此插件。
llm install llm-anthropic
用法
首先,为 Anthropic 设置API 密钥:
llm keys set anthropic
# Paste key here
你也可以在环境变量中设置密钥:ANTHROPIC_API_KEY
运行 llm models 列出模型,运行 llm models --options 可以同时列出它们的选项。
要直接从 Anthropic 模型 API 查看当前 API 密钥可用的模型,请运行:
llm anthropic models
输出示例:
claude-fable-5-2: Claude Fable 5.2 (created 2026-11-09)
claude-sonnet-5-5: Claude Sonnet 5.5 (created 2026-09-28)
claude-opus-5-5: Claude Opus 5.5 (created 2026-09-21)
添加 --json 可查看 API 返回的完整 JSON,包括每个模型的能力详情。使用 --key 可以传入另一个 API 密钥。
像这样运行提示:
llm -m claude-fable-5.2 'Fun facts about otters'
llm -m claude-opus-5.5 'Fun facts about walruses'
llm -m claude-sonnet-5.5 'Fun facts about pelicans'
llm -m claude-haiku-4.5 'Fun facts about cormorants'
claude-mythos-5.2 也已注册,但只适用于属于 Anthropic 验证计划中组织的 API 密钥。
也支持图片附件:
llm -m claude-sonnet-5.5 'describe this image' -a https://static.simonwillison.net/static/2024/pelicans.jpg
llm -m claude-haiku-4.5 'extract text' -a page.png
Claude 3.5 及后续模型可以处理 PDF 文件:
llm -m claude-sonnet-5.5 'extract text' -a page.pdf
Anthropic 的模型支持模式(schema)。下面展示如何使用 Claude Sonnet 5.5 虚构一只狗:
llm -m claude-sonnet-5.5 --schema 'name,age int,bio: one sentence' 'invent a surprising dog'
输出示例:
{
"name": "Whiskers the Mathematical Mastiff",
"age": 7,
"bio": "Whiskers is a mastiff who can solve complex calculus problems by barking in binary code and has won three international mathematics competitions against human competitors."
}
新模型
此插件为它支持的每个 Claude 模型提供内置设置。你也可以使用在已安装插件版本之后发布的模型:
- anthropic Python 库列出的模型 ID 会自动注册。运行
llm install -U anthropic升级该库并获取新发布的模型。 - 运行
llm anthropic refresh,从 Anthropic 模型 API 获取当前 API 密钥可用的模型。插件不认识的模型将按照 API 报告的能力注册:图片和 PDF 输入、思考、推理强度、结构化输出和最大输出 token 数。
llm anthropic refresh
输出示例:
Saved 12 models to /Users/you/Library/Application Support/io.datasette.llm/anthropic_models.json
Added models: claude-opus-6
列表缓存在 LLM 用户目录中的 anthropic_models.json。再次运行命令即可更新。
没有内置设置的模型在其他方面会被视为最新的 Claude 模型,因此默认使用自适应思考。如果模型 API 未报告某个模型的输出上限,max_tokens 默认为 64,000。
网页搜索
较新的模型支持 Anthropic 的网页搜索工具以获取实时信息,使用 -T WebSearch 服务器端工具:
llm -m claude-sonnet-5.5 -T WebSearch 'What is the current weather in San Francisco?'
该工具接受可选配置:
llm -m claude-sonnet-5.5 \
-T 'WebSearch(max_uses=2, user_location={"city": "London", "country": "GB"})' \
'Recent headlines'
可用参数:
max_uses:每次请求最多搜索次数allowed_domains/blocked_domains:允许或屏蔽的域名列表(不能组合使用)user_location:包含可选键city、region、country和timezone的字典,用于本地化结果
请注意,user_location 会影响网页搜索工具的搜索结果,但位置信息不会直接提供给模型。
在 Claude 4.6 及后续模型上,这会使用具有动态过滤功能的 web_search_20260318 工具版本;较旧的模型使用基础的 web_search_20250305 版本。
网页抓取
支持网页搜索的模型也可以使用 Anthropic 的网页抓取工具 获取某个 URL 的完整内容,使用 -T WebFetch 服务器端工具:
llm -m claude-sonnet-5.5 -T WebFetch 'Fetch https://www.example.com/ and quote its first heading'
出于安全原因,Claude 只能抓取已出现在对话中的 URL:这些 URL 由你提供,或由之前的网页搜索或抓取返回。
该工具接受可选配置:
llm -m claude-sonnet-5.5 \
-T 'WebFetch(max_uses=2, max_content_tokens=20000)' \
'Summarize https://www.example.com/'
可用参数:
max_uses:每次请求最多抓取次数allowed_domains/blocked_domains:允许或屏蔽的域名列表(不能组合使用)citations:设为True可为抓取的内容启用引用max_content_tokens:上下文中所含抓取内容的大致 token 上限use_cache:设为False可绕过 Anthropic 的抓取缓存(仅限 Claude 4.6 及后续模型)
在 Claude 4.6 及后续模型上,这会使用 web_fetch_20260318 工具版本并支持动态过滤;较旧的模型使用基础的 web_fetch_20250910 版本。
在 Python 中,将 WebFetch 类的实例传入 tools=:
import llm
from llm_anthropic import WebFetch
model = llm.get_model("claude-sonnet-5.5")
response = model.prompt(
"Fetch https://www.example.com/ and quote its first heading",
tools=[WebFetch(max_uses=1)],
)
print(response.text())
MCP 连接器
支持网页搜索的模型也可以使用 远程 MCP 服务器上的工具,通过 AnthropicMCP 服务器端工具调用。Anthropic 从其自身基础设施连接服务器,因此服务器必须能够通过 HTTPS 访问:
llm -m claude-sonnet-5.5 \
-T 'AnthropicMCP(url="https://mcp.deepwiki.com/mcp", name="deepwiki")' \
'Use the deepwiki tools to say what simonw/llm does, one sentence'
可用参数:
url:远程 MCP 服务器的 HTTPS URL(必填)name:服务器标识符,默认为 URL 的主机名authorization_token:需要身份验证的服务器使用的 OAuth bearer tokenallowed_tools:可选工具名称列表;如提供,则仅启用这些工具
llm -m claude-sonnet-5.5 \
-T 'AnthropicMCP(url="https://mcp.deepwiki.com/mcp", name="deepwiki", allowed_tools=["ask_question"])' \
'What does simonw/llm do?'
你可以传入多个 MCP 工具,在同一请求中连接多个服务器。仅支持 MCP 工具调用,不支持 MCP 资源或提示。
在 Python 中,将 AnthropicMCP 类的实例传入 tools=:
import llm
from llm_anthropic import AnthropicMCP
model = llm.get_model("claude-sonnet-5.5")
response = model.prompt(
"Use the deepwiki tools to say what simonw/llm does, one sentence",
tools=[AnthropicMCP(url="https://mcp.deepwiki.com/mcp", name="deepwiki")],
)
print(response.text())
此功能使用 Anthropic 的 mcp-client-2025-11-20 测试版。
代码执行
Claude 4.5 及后续模型支持 Anthropic 的代码执行工具,该工具在沙箱化的服务器端容器中运行 Python 和 bash。使用 -T CodeExecution 服务器端工具:
llm -m claude-sonnet-4.6 -T CodeExecution \
'Compute the sha256 hex digest of the string "pelican"'
每个运行代码的响应都会在其 response_json 中报告容器 ID,可通过 llm logs --json 查看。将该 ID 传回,可以在之后的提示中复用容器文件和状态(容器在一段时间不活动后会过期):
llm -m claude-sonnet-4.6 -T 'CodeExecution(container="container_011CPd...")' \
'Read /tmp/results.csv and summarize it'
快速模式
部分模型支持快速模式以降低响应延迟。使用 -o fast 1 选项启用:
llm -m claude-opus-5 -o fast 1 'Fun facts about walruses'
计算 token 数
llm anthropic count 命令使用 Anthropic token 计数 API,在不运行提示的情况下计算其输入 token 数:
llm anthropic count 'Fun facts about walruses' -m claude-opus-5
它输出 token 数量:
15
该命令接受与 llm prompt 相同的选项,因此计数反映实际将要发送的完整请求,包括系统提示、附件、片段、模板、工具、模式、模型选项和对话中的先前消息:
cat code.py | llm anthropic count -m claude-sonnet-5.5 -s 'Review this code'
llm anthropic count -m claude-opus-5 'Describe this' -a pelican.jpg
llm anthropic count -m claude-opus-5 --schema 'name, age int' 'Invent a dog'
llm anthropic count -m claude-opus-5 -T llm_time -o thinking_effort high 'What time is it?'
llm anthropic count -c 'Tell me more'
计算 token 时不会向数据库记录任何内容。
在 Python 中使用
Python 代码可以像这样访问模型:
import llm
model = llm.get_model("claude-haiku-4.5")
print(model.prompt("Fun facts about chipmunks"))
更多详情请参阅LLM 的 Python API 文档。
要在不运行提示的情况下计算其输入 token 数,请调用 model.count_tokens()。它接受与 model.prompt() 相同的参数,并返回一个整数:
model = llm.get_model("claude-opus-5")
count = model.count_tokens(
"Describe this image",
system="Be concise",
attachments=[
llm.Attachment(url="https://static.simonwillison.net/static/2024/pelicans.jpg")
],
thinking_effort="high",
)
传入 conversation= 可以包含对话中的先前消息:
conversation = model.conversation()
conversation.prompt("Fun facts about pelicans").text()
count = model.count_tokens("Tell me more", conversation=conversation)
对于异步模型,使用 await model.count_tokens(...)。
你也可以直接导入模型类;如果希望将 base_url 指向另一个兼容 Anthropic 的端点,这会很有用:
from llm_anthropic import ClaudeMessages
model = ClaudeMessages(
"MiniMax-M2",
base_url="https://api.minimax.io/anthropic"
)
print(model.prompt("Fun facts about pangolins", key="eyJh..."))
对话中的系统消息
Claude Opus 4.8 和 Claude 5 系列模型接受在对话过程中更新系统指令,这会保留先前轮次的提示缓存命中。传入 system 消息到显式的 messages= 链中:
import llm
from llm import system, user, assistant
model = llm.get_model("claude-opus-5")
response = model.prompt(messages=[
system("You are a helpful assistant."),
user("Say hi to me, briefly"),
assistant("Hi there!"),
system("New instruction: reply only in French from now on"),
user("Say goodbye to me, briefly"),
])
print(response.text()) # Au revoir !
第一条系统消息作为顶层系统提示发送;后续消息内联在消息数组中,并自动定位以满足 API 的位置规则。早于 Opus 4.8 的模型如果在消息链开头之外的任何位置出现系统消息,将引发 ValueError。
扩展思考
Anthropic 模型可以消耗思考 token,在生成响应之前对提示进行推理。LLM 在推理产生时将其流式输出到标准错误;传入 -R/--hide-reasoning 可将其隐藏。推理也会被记录,可作为 reasoning 中的 llm logs --json 字段获取。
Claude 5 模型默认会进行思考。使用 thinking_effort 选项调整其思考强度,可选值为 low、medium、high、xhigh 或 max:
llm -m claude-opus-5 -o thinking_effort max 'Design a fair algorithm for splitting rent between roommates with different sized rooms'
Sonnet 5 和 Opus 5 可以使用 -o thinking 0 完全关闭思考。Fable 模型和 5.5 系列模型始终进行思考,禁用思考会引发错误。
Claude 4.6 和更早的模型不会主动思考,除非被要求。使用 -o thinking 1 启用思考:
llm -m claude-sonnet-4.6 -o thinking 1 'Write a convincing speech to congress about the need to protect the California Brown Pelican'
Claude 4.6 模型(以及 Opus 4.5)也支持 thinking_effort,这会隐含启用 thinking 1。更早的模型使用固定的 1,024 token 思考预算。
Claude 4.7 及后续模型默认不会在响应中包含思考轨迹,因此开启思考时,该插件会请求 API 使用 display: summarized。设置 -R/--hide-reasoning 时,插件改为传入 display: omitted,从响应中完全省略思考轨迹:它不会出现在日志中,但思考 token 仍会计费。
thinking_budget、thinking_display 和 thinking_adaptive 选项已在 llm-anthropic 0.26 中移除;如果旧模型需要这些选项,请安装 llm-anthropic==0.25。
拒绝
Claude Opus 5 和 Fable 模型运行安全分类器,可能拒绝请求。API 将其报告为带有 stop_reason: "refusal" 和空内容的成功响应,因此该插件会抛出 llm_anthropic.ClaudeRefusal 异常(llm.ModelError 的子类),而不是返回空字符串。异常消息包含 API 返回的类别和解释,异常对象通过 .category 和 .explanation 公开它们:
import llm
from llm_anthropic import ClaudeRefusal
model = llm.get_model("claude-fable-5.2")
try:
print(model.prompt("...").text())
except ClaudeRefusal as ex:
print(ex.category, ex.explanation)
模型选项
以下选项可以在 CLI 中通过 -o name value 传入,或作为 keyword=value 参数传给 Python 的 model.prompt() 方法:
max_tokens:
int停止前最多生成的 token 数
temperature:
float注入响应的随机程度。默认为 1.0,取值范围为 0.0 到 1.0。分析或多项选择任务使用更接近 0.0 的 temperature,创意和生成任务使用更接近 1.0 的值。注意,即使 temperature 为 0.0,结果也不会完全具有确定性。
top_p:
float使用核采样。在核采样中,我们按概率递减顺序计算后续每个 token 所有候选项的累积分布,并在达到 top_p 所设的特定概率后截断。应调整 temperature 或 top_p,而非两者同时调整。建议仅用于高级场景。通常只需使用 temperature。
top_k:
int只从每个后续 token 的前 K 个候选项中采样,用于移除概率较低的“长尾”响应。建议仅用于高级场景。通常只需使用 temperature。
user_id:
str与请求关联的用户的外部标识符
prefill:
str用于响应的预填充内容
hide_prefill:
boolean不要在响应开头重复预填充值
stop_sequences:
array, str导致模型停止生成的自定义文本序列;传入字符串列表或单个字符串
cache:
boolean对任何附件或片段使用 Anthropic 提示缓存
fast:
boolean使用快速模式以降低响应延迟:https://platform.claude.com/docs/en/build-with-claude/fast-mode
thinking:
boolean启用思考模式。Claude 5 模型默认思考;对于允许关闭的模型,设为 false 可禁用思考
Claude 5 模型不再接受采样参数;在这些模型上设置 temperature、top_p 或 top_k 会导致 Anthropic API 返回错误。
prefill 选项可用于设置响应的第一部分。为了提高返回 JSON 的概率,请将其设为 {:
llm -m claude-haiku-4.5 'Fun data about pelicans as JSON' \
-o prefill '{'
如果不希望在响应中回显预填充 token,请将 hide_prefill 设为 true:
llm -m claude-haiku-4.5 'Short python function describing a pelican' \
-o prefill '```python' \
-o hide_prefill true \
-o stop_sequences '```'
此示例将 ``` 设置为停止序列,因此响应将是不带外层 Markdown 代码块的 Python 函数。
要传入单个停止序列,请发送一个字符串:
llm -m claude-sonnet-5.5 'Fun facts about pelicans' \
-o stop_sequences "pouch"
对于多个停止序列,请传入一个 JSON 数组:
llm -m claude-sonnet-5.5 'Fun facts about pelicans' \
-o stop_sequences '["beak", "feathers"]'
开发
要在本地设置此插件,请先检出代码。然后使用 uv 运行测试:
uv run pytest
uv run pytest -k test_tools
要执行 llm 命令,请通过 uv:
uv run llm 'your prompt here'
要在运行时启用调试日志(像这样),请设置以下环境变量:
export ANTHROPIC_LOG=debug
此项目使用 pytest-recording 为测试记录 Anthropic API 响应,并使用 inline-snapshot 进行测试断言。
如果添加了调用 API 的新测试,可以像这样捕获 API 响应:
PYTEST_ANTHROPIC_API_KEY="$(llm keys get anthropic)" uv run pytest --record-mode once
你需要先使用此命令存储有效的 Anthropic API 密钥:
llm keys set anthropic
# Paste key here
要使用一个命令重新录制所有 cassette 并更新所有 inline snapshot 断言:
rm tests/cassettes/test_anthropic/*.yaml
PYTEST_ANTHROPIC_API_KEY="$(llm keys get anthropic)" uv run pytest --record-mode all --inline-snapshot=fix
要重新录制单个测试:
rm tests/cassettes/test_anthropic/test_thinking_prompt.yaml
PYTEST_ANTHROPIC_API_KEY="$(llm keys get anthropic)" uv run pytest -k test_thinking_prompt --record-mode once --inline-snapshot=fix
来源:Simon Willison 官方项目 · github.com