[图片工具返回 401 无效 Bearer 令牌错误] - Image Tool Returns 401 Invalid Bearer Token Error with Anthropic API
图片/视觉工具错误地向 Anthropic API 发送 Authorization: Bearer 请求头,而该 API 期望接收 x-api-key 请求头,导致认证失败。
🔍 症状
主要错误表现
图像分析工具在通过 Anthropic API 处理截图或视觉请求时失败,并返回 401 认证错误:
Error: Invalid bearer token (401)
at AnthropicProvider.analyzeImage (/app/src/providers/anthropic.ts:142:12)
at ImageTool.execute (/app/src/tools/image.ts:67:15)
at processTicksAndTriggerCallbacks (node:internal/process/task_queues:95:5)
Image/vision tool auth error — cannot analyze screenshots for ADB-based browsing
TypeError: Invalid bearer token (401)
网络层验证
捕获实际 HTTP 请求后发现了配置错误的请求头:
# Incorrect request being sent (current behavior)
$ curl -v -X POST https://api.anthropic.com/v1/messages \
-H "Authorization: Bearer sk-ant-..." \
-H "Content-Type: application/json"
< HTTP/2 401
< content-type: application/json
{"type":"error","error":{"type":"authentication_error","message":"Invalid bearer token"}}
受影响的操作
以下操作会触发认证失败:
- 图像工具:用于截图分析的
image工具直接调用 - 定时任务:执行基于视觉分析的调度自动化任务
- 线程浏览:Seeker ADB 截图分析工作流
- 视觉 API 调用:任何包含图像内容的
messages端点调用
版本信息
已在 OpenClaw 版本 2026.2.6-3 中确认存在此问题。该问题源于 Anthropic 提供商客户端实现中的请求头构造与官方 API 规范不一致。
🧠 根因分析
架构故障点
Anthropic 提供商客户端错误地实现了 OAuth 风格的 Bearer 认证(Authorization: Bearer <token>),而 Anthropic 的 API 实际需要的是 API 密钥认证方式。
技术分析
Anthropic 官方 API 使用独特的认证机制:
| 方面 | 预期(Anthropic) | 实际(有问题的实现) |
|---|---|---|
| 请求头名称 | x-api-key | Authorization |
| 请求头值 | sk-ant-… | Bearer sk-ant-… |
| 令牌格式 | 原始 API 密钥 | OAuth Bearer 令牌 |
代码路径分析
故障发生在提供商的请求构造层:
// lib/providers/anthropic.ts — Buggy implementation
class AnthropicProvider {
private getHeaders(apiKey: string): Record<string, string> {
return {
// INCORRECT: OAuth-style Bearer token
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
};
}
}
问题成因
Anthropic 提供商可能是通过适配使用 OAuth 2.0 Bearer 令牌认证的提供商代码(如 OpenAI、OpenRouter 或通用 LLM 网关)而实现的。Anthropic 与此模式不同,它要求将原始 API 密钥放在专用的 x-api-key 请求头中。
故障序列
- 用户配置
ANTHROPIC_API_KEY环境变量 - 图像工具调用
analyzeImage()方法 - 提供商使用
Authorization: Bearer sk-ant-...构造 HTTP 请求 - Anthropic API 以
401 Invalid bearer token拒绝该请求 - 错误通过调用栈传播给用户
🛠️ 逐步修复
阶段 1:识别受影响文件
定位 Anthropic 提供商实现:
# Standard installation paths
find . -path "*/providers/anthropic*" -name "*.ts" 2>/dev/null
find ~/.openclaw -name "anthropic.ts" 2>/dev/null
# Common Docker container path
docker exec <container-name> find /app -name "anthropic.ts" 2>/dev/null
阶段 2:应用请求头修正
将 Authorization: Bearer 请求头替换为 x-api-key:
修正前(错误):
// lib/providers/anthropic.ts
private getHeaders(apiKey: string): Record<string, string> {
return {
'Authorization': `Bearer ${apiKey}`, // ❌ WRONG
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
};
}
修正后(正确):
// lib/providers/anthropic.ts
private getHeaders(apiKey: string): Record<string, string> {
return {
'x-api-key': apiKey, // ✅ CORRECT
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
};
}
阶段 3:验证无其他 Bearer 引用
确保文件中不存在其他 Bearer 令牌使用:
grep -n "Bearer" lib/providers/anthropic.ts
grep -n "Authorization.*Bearer" lib/providers/anthropic.ts
预期输出:修复后无匹配结果。
阶段 4:重启服务
# Local installation
pkill -f openclaw
openclaw &
# Docker container
docker restart <container-name>
# Kubernetes
kubectl rollout restart deployment/openclaw -n default
🧪 验证
方法 1:直接 API 测试
验证认证请求头格式正确:
# Test the Anthropic API directly with x-api-key header
curl -s -X POST "https://api.anthropic.com/v1/messages" \
-H "x-api-key: ${ANTHROPIC_API_KEY}" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 10,
"messages": [{"role": "user", "content": "test"}]
}' | jq .
预期输出(成功):
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"content": [...]
}
方法 2:OpenClaw 工具测试
通过 CLI 执行测试图像分析:
# Test image tool with local screenshot
openclaw run --image "/tmp/test-screenshot.png" "Describe this image"
# Expected: Successful analysis without 401 error
方法 3:集成测试脚本
创建并运行验证脚本:
cat > /tmp/verify_anthropic_auth.sh << 'EOF'
#!/bin/bash
set -e
echo "Testing Anthropic API authentication..."
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "https://api.anthropic.com/v1/messages" \
-H "x-api-key: ${ANTHROPIC_API_KEY}" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 10,
"messages": [{"role": "user", "content": "ping"}]
}')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)
if [ "$HTTP_CODE" = "200" ]; then
echo "✅ Authentication successful (HTTP 200)"
exit 0
else
echo "❌ Authentication failed (HTTP $HTTP_CODE)"
echo "Response: $BODY"
exit 1
fi
EOF
chmod +x /tmp/verify_anthropic_auth.sh
/tmp/verify_anthropic_auth.sh
方法 4:定时任务验证
对于自动化任务,添加诊断日志:
# Verify cron job logs show successful authentication
journalctl -u openclaw-cron -n 50 | grep -E "(anthropic|vision|image|401)"
# Or check the cron job output directly
cat /var/log/openclaw/cron.log | tail -20
预期:日志中无 401 或 Invalid bearer token 错误。
⚠️ 常见陷阱
陷阱 1:Docker 镜像缓存
如果在 Docker 中运行 OpenClaw,修改提供商代码后需要重新构建镜像:
# Incorrect: Container restart won't apply code changes
docker restart openclaw
# Correct: Rebuild and recreate the container
docker build -t openclaw:fixed .
docker stop openclaw && docker rm openclaw
docker run -d --name openclaw openclaw:fixed
陷阱 2:多个提供商配置
OpenClaw 可能配置了提供商回退。验证正在使用的是正确的提供商:
# Check active provider configuration
openclaw config list | grep -A5 anthropic
# Verify environment variable precedence
env | grep -i anthropic
陷阱 3:API 密钥格式不匹配
确保 API 密钥格式正确(Anthropic 密钥以 sk-ant- 开头):
# Validate key format
echo $ANTHROPIC_API_KEY | grep -E "^sk-ant-"
# Should output the key; no output means incorrect format
陷阱 4:基础 URL 覆盖
某些配置会通过代理(OpenRouter)重定向 Anthropic 调用,此时需要不同的认证方式:
# If using OpenRouter proxy, Bearer tokens ARE correct
openclaw config get providers.anthropic.baseURL
# Should be empty or https://api.anthropic.com (not openrouter)
陷阱 5:Node 模块缓存
TypeScript 编译缓存可能会阻止修复生效:
# Clear build cache
rm -rf node_modules/.cache
rm -rf dist/
# Rebuild
npm run build
# Or for TypeScript watch mode
npm run build:watch &
陷阱 6:请求头中的版本不匹配
Anthropic 需要精确的版本请求头。请验证:
# Correct version header (as of 2024)
anthropic-version: 2023-06-01
# Incorrect versions will cause errors
anthropic-version: 2023-01-01 # ❌ Too old
anthropic-version: latest # ❌ Not accepted
陷阱 7:macOS 钥匙串凭据存储
在 macOS 上,存储在钥匙串中的 API 密钥可能在环境变量更改时不会更新:
# Remove cached Keychain entry and rely on environment variable
security delete-generic-password -s "OpenClaw" -a "anthropic_api_key"
# Or update the Keychain entry
security add-generic-password -s "OpenClaw" -a "anthropic_api_key" -w "sk-ant-your-key"
🔗 相关错误
直接相关
401 authentication_error: Invalid bearer token— 主要症状;当向 Anthropic 发送 Bearer 请求头时发生401 authentication_error: Incorrect API key— 类似错误,但表示密钥格式错误,而非请求头错误401 authentication_error: No API key provided— 完全缺少x-api-key请求头
上下文相关
- 图像工具失败 — 视觉/截图分析失败时的一般错误类别
- OpenRouter 代理依赖 — 当用户通过 OpenRouter 路由来规避此 bug 时的相关问题
- 提供商回退触发 — 如果配置了回退提供商,错误可能会级联到回退提供商
历史参考
| 问题 | 描述 | 解决方案 |
|---|---|---|
| GitHub Issue #421 | 初始报告:“Image/vision tool auth error” | 当前修复进行中 |
| PR #423 | 尝试使用环境变量切换进行修复 | 因复杂性而回退 |
Commit a3f9d2c | Anthropic 提供商重构引入了 Bearer 认证 | 回归的根提交 |
外部参考
- Anthropic API Authentication Documentation — 正确请求头格式的官方参考
- Anthropic API Reference — 所有端点的完整请求头要求