@hfyjq/crannia 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +45 -45
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON.md +162 -153
- package/THIRD-PARTY.md +316 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +671 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/skill_md.py +676 -676
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +881 -881
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +813 -813
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/auth.py +23 -5
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/config.yaml +2 -2
- package/core/activity.py +3 -0
- package/core/agent_loop.py +390 -55
- package/core/approval.py +17 -6
- package/core/artifacts.py +7 -0
- package/core/auto_review.py +23 -5
- package/core/channel_configs.py +34 -2
- package/core/channel_turns.py +759 -759
- package/core/child_approval.py +150 -0
- package/core/config_requirements.py +205 -0
- package/core/cron/runner.py +118 -6
- package/core/cron/store.py +14 -5
- package/core/cron/tools.py +17 -5
- package/core/endpoint.py +141 -0
- package/core/events.py +23 -0
- package/core/i18n.py +329 -329
- package/core/ice/store.py +191 -191
- package/core/inbound.py +193 -193
- package/core/jobs.py +19 -3
- package/core/last_good.py +150 -150
- package/core/llm_errors.py +227 -227
- package/core/llm_retry.py +230 -230
- package/core/memory/compressor.py +1214 -1214
- package/core/memory/manager.py +14 -0
- package/core/model_configs.py +80 -0
- package/core/pipeline/scheduler.py +2 -2
- package/core/pipeline/stages/agent_loop.py +24 -4
- package/core/pipeline/stages/pre_process.py +58 -7
- package/core/prompt_assembler.py +680 -680
- package/core/rg.py +255 -255
- package/core/security.py +1544 -1544
- package/core/settings_baseline.py +70 -1
- package/core/shell.py +5 -17
- package/core/skill_settings.py +7 -2
- package/core/state_registry.py +19 -0
- package/core/subagent.py +64 -3
- package/core/task_tool.py +1 -1
- package/core/tasks_notify.py +69 -4
- package/core/tiers.py +9 -3
- package/core/tool_outcome.py +108 -0
- package/core/update_tui.py +158 -0
- package/core/updater.py +229 -40
- package/core/version.py +2 -2
- package/core/web_cache.py +152 -0
- package/crannia_tray.py +278 -278
- package/creators/models.json +4 -4
- package/data/settings.example.json +67 -0
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +9 -4
- package/main.py +154 -154
- package/mcpx/manager.py +522 -522
- package/mcpx/servers/__init__.py +22 -22
- package/mcpx/servers/web_search.py +321 -33
- package/package.json +24 -10
- package/providers/anthropic/client.py +772 -772
- package/providers/cost_table.json +3779 -3779
- package/providers/deepseek/client.py +20 -20
- package/providers/deepseek/manifest.yaml +2 -2
- package/providers/factory.py +136 -136
- package/providers/lmstudio/client.py +2 -2
- package/providers/metadata.py +80 -80
- package/providers/model_capabilities.json +6665 -6665
- package/providers/moonshot/client.py +12 -12
- package/providers/ollama/client.py +2 -2
- package/providers/openai/client.py +13 -13
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +144 -144
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/window_table.json +8909 -8909
- package/sbom.json +4413 -4296
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +177 -4
- package/skills/file_parser/manifest.yaml +22 -1
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/github/manifest.yaml +5 -0
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +806 -806
- package/skills/mail_parser/manifest.yaml +5 -0
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +430 -430
- package/skills/media_gen/manifest.yaml +93 -88
- package/skills/office_parser/cell_validation.py +127 -127
- package/skills/office_parser/excel_transform.py +936 -936
- package/skills/office_parser/layout_spec.py +243 -243
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +2909 -2909
- package/tui/crannia.cmd +134 -0
- package/tui/crannia_tui/__init__.py +1 -0
- package/tui/crannia_tui/__main__.py +223 -0
- package/tui/crannia_tui/app.py +1318 -0
- package/tui/crannia_tui/app.tcss +153 -0
- package/tui/crannia_tui/approval.py +85 -0
- package/tui/crannia_tui/backend.py +279 -0
- package/tui/crannia_tui/channel.py +472 -0
- package/tui/crannia_tui/client.py +125 -0
- package/tui/crannia_tui/clipboard.py +62 -0
- package/tui/crannia_tui/commands.py +65 -0
- package/tui/crannia_tui/doctor.py +304 -0
- package/tui/crannia_tui/events.py +84 -0
- package/tui/crannia_tui/headless.py +152 -0
- package/tui/crannia_tui/i18n.py +164 -0
- package/tui/crannia_tui/locales/en.json +263 -0
- package/tui/crannia_tui/outcome.py +62 -0
- package/tui/crannia_tui/paths.py +181 -0
- package/tui/crannia_tui/probe.py +53 -0
- package/tui/crannia_tui/profile.py +169 -0
- package/tui/crannia_tui/render.py +209 -0
- package/tui/crannia_tui/settings.py +134 -0
- package/tui/crannia_tui/setup.py +380 -0
- package/tui/crannia_tui/term.py +116 -0
- package/tui/crannia_tui/ui.py +1236 -0
- package/tui/crannia_tui/update.py +389 -0
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +51 -51
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/package-source.json +19 -19
- package/web/__main__.py +15 -0
- package/web/server.py +178 -20
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
|
@@ -1,772 +1,772 @@
|
|
|
1
|
-
"""AnthropicProvider —— 原生 Anthropic Messages API provider。
|
|
2
|
-
|
|
3
|
-
使用 `anthropic` Python SDK,以完整使用 Claude 的原生能力:
|
|
4
|
-
扩展思考、tool_choice、提示缓存。
|
|
5
|
-
|
|
6
|
-
OpenAI ↔ Anthropic 的消息格式翻译在
|
|
7
|
-
:meth:`_to_anthropic_messages` 中完成。
|
|
8
|
-
"""
|
|
9
|
-
|
|
10
|
-
import json
|
|
11
|
-
from typing import AsyncIterator, Optional
|
|
12
|
-
|
|
13
|
-
from core import window_estimate
|
|
14
|
-
#: tiktoken 只许经这一处(见 `core/tokenizer.py`:随包词表 + 说得清的失败)。
|
|
15
|
-
from core.tokenizer import get_encoding as _get_tiktoken_encoding
|
|
16
|
-
from providers.base import (
|
|
17
|
-
BaseProvider,
|
|
18
|
-
ChatResponse,
|
|
19
|
-
StreamChunk,
|
|
20
|
-
classify_api_error,
|
|
21
|
-
classify_transport_error,
|
|
22
|
-
flatten_system,
|
|
23
|
-
read_cache_hit,
|
|
24
|
-
record_token_usage,
|
|
25
|
-
)
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def _session_key() -> str:
|
|
29
|
-
"""这一轮属于哪个会话(通道键)—— 重试横幅按它找会话。"""
|
|
30
|
-
try:
|
|
31
|
-
from core.request_snapshot import current_session_id
|
|
32
|
-
return str(current_session_id() or "")
|
|
33
|
-
except Exception: # noqa: BLE001
|
|
34
|
-
return ""
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
def _create_with_retry(client, kwargs):
|
|
38
|
-
"""把一次 `messages.create` 按统一节奏重试。
|
|
39
|
-
|
|
40
|
-
节奏与 OpenAI 兼容那条同源(`core/llm_retry.step`):连接 / 超时 / 5xx
|
|
41
|
-
走常规 10 次,再转静默每 120 秒一次;余额 / 参数 / 认证 / 限流 /
|
|
42
|
-
内容审核 / 请求过大一律不重试。
|
|
43
|
-
"""
|
|
44
|
-
from core import llm_retry
|
|
45
|
-
from core.llm_errors import headline
|
|
46
|
-
rstate: dict = {}
|
|
47
|
-
while True:
|
|
48
|
-
try:
|
|
49
|
-
resp = client.messages.create(**kwargs)
|
|
50
|
-
llm_retry.clear(_session_key())
|
|
51
|
-
return resp
|
|
52
|
-
except Exception as e: # noqa: BLE001
|
|
53
|
-
kind = classify_api_error(e) or classify_transport_error(e) or ""
|
|
54
|
-
action, delay = llm_retry.step(rstate, kind)
|
|
55
|
-
if action in ("retry", "silent"):
|
|
56
|
-
n = int(rstate.get("silent") or 0) if action == "silent" \
|
|
57
|
-
else int(rstate.get("retry") or 0)
|
|
58
|
-
llm_retry.note(_session_key(), n, kind=kind,
|
|
59
|
-
text=headline(e, kind=kind), phase=action)
|
|
60
|
-
print(f"[llm] {kind or 'unknown'} —— {delay}ms 后重试"
|
|
61
|
-
f"({action} {n})")
|
|
62
|
-
#: 可打断 —— 用户按了打断就立刻把原异常抛回。
|
|
63
|
-
if not llm_retry.wait(_session_key(), delay):
|
|
64
|
-
raise
|
|
65
|
-
continue
|
|
66
|
-
llm_retry.fail(_session_key(), kind=kind,
|
|
67
|
-
text=headline(e, kind=kind))
|
|
68
|
-
raise
|
|
69
|
-
from core.token_calibrator import TokenCalibrator
|
|
70
|
-
from core.image_input import content_text
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
# OpenAI 形状的 `content` -> Anthropic 形状
|
|
74
|
-
#
|
|
75
|
-
# 这是两条线唯一的翻译处(`_to_anthropic_messages` 是 Anthropic 唯一的
|
|
76
|
-
# 消息投影,正如 `_wire_messages` 是 OpenAI 那条路唯一的)。
|
|
77
|
-
#
|
|
78
|
-
# | | 文本块 | 图片块 |
|
|
79
|
-
# |---|---|---|
|
|
80
|
-
# | OpenAI | `{"type":"text","text":…}` | `{"type":"image_url","image_url":{"url":"data:…"}}` |
|
|
81
|
-
# | Anthropic | 同左(逐字一样) | `{"type":"image","source":{"type":"base64","media_type":…,"data":…}}` |
|
|
82
|
-
#
|
|
83
|
-
# 文本块形状不动 —— 两家逐字相同,所以只有图片需要翻译。
|
|
84
|
-
# 认不出的块不静默丢("不许静默改坏"):换成一个
|
|
85
|
-
# 可见的文本块,写清它是什么形状。丢掉它会让模型以为"这条消息就这些"。
|
|
86
|
-
|
|
87
|
-
def _to_anthropic_content(content):
|
|
88
|
-
"""消息 `content` -> Anthropic 接受的形式。
|
|
89
|
-
|
|
90
|
-
`str` / `None`,原样(`None` 变 `""`)。
|
|
91
|
-
块列表,逐块翻译;文本块原样、图片块换形状、其余变成一句实话。
|
|
92
|
-
"""
|
|
93
|
-
if content is None:
|
|
94
|
-
return ""
|
|
95
|
-
if isinstance(content, str):
|
|
96
|
-
return content
|
|
97
|
-
if not isinstance(content, (list, tuple)):
|
|
98
|
-
# 既不是串也不是块列表 —— 交给 `content_text` 取它能取的部分,
|
|
99
|
-
# 而不是把认不出的东西原样发上去(上游会 400,且报错看不出是我们的锅)
|
|
100
|
-
return content_text(content)
|
|
101
|
-
|
|
102
|
-
out: list[dict] = []
|
|
103
|
-
for part in content:
|
|
104
|
-
if not isinstance(part, dict):
|
|
105
|
-
if part:
|
|
106
|
-
out.append({"type": "text", "text": str(part)})
|
|
107
|
-
continue
|
|
108
|
-
kind = part.get("type")
|
|
109
|
-
if kind == "text":
|
|
110
|
-
out.append({"type": "text", "text": str(part.get("text") or "")})
|
|
111
|
-
elif kind == "image_url":
|
|
112
|
-
block = _image_block(part)
|
|
113
|
-
if block is not None:
|
|
114
|
-
out.append(block)
|
|
115
|
-
else:
|
|
116
|
-
print(f"[anthropic] 认不出的 content 块 type={kind!r} —— "
|
|
117
|
-
f"换成一个可见的说明(不静默丢)")
|
|
118
|
-
out.append({"type": "text",
|
|
119
|
-
"text": f"[这块内容({kind})Anthropic 这条线不支持]"})
|
|
120
|
-
# 空列表上游会 400(content 不能是空数组),补一个空文本块。
|
|
121
|
-
return out or [{"type": "text", "text": ""}]
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
def _image_block(part: dict) -> Optional[dict]:
|
|
125
|
-
"""`image_url` part -> Anthropic 的 `image` block;解不开就返回 `None` 并出声。
|
|
126
|
-
|
|
127
|
-
只认 `data:` URL:Anthropic 的 `source` 有 `base64` / `url` / `file`
|
|
128
|
-
三种,而 `url` 那种要求它自己去取(等于给上游开了一条我们看不见的出网路,
|
|
129
|
-
而那条出网闸是我们自己的)。远端图片不在这一层解决,
|
|
130
|
-
让它走不进来(`core/image_input.py::prepare_*` 只产 `data:`)。
|
|
131
|
-
"""
|
|
132
|
-
# 延迟 import:正常路径(`base64`)用不到它,而 `base64` 是标准库。
|
|
133
|
-
import base64 as _b64
|
|
134
|
-
|
|
135
|
-
url = (part.get("image_url") or {}).get("url") or ""
|
|
136
|
-
if not url.startswith("data:"):
|
|
137
|
-
print(f"[anthropic] 图片块不是一个 data: URL({url[:40]!r})—— "
|
|
138
|
-
f"Anthropic 那条路只收内嵌的字节,这一块被丢掉了")
|
|
139
|
-
return None
|
|
140
|
-
head, _, payload = url.partition(",")
|
|
141
|
-
media = head[5:].split(";")[0].strip().lower() or "image/png"
|
|
142
|
-
if not payload:
|
|
143
|
-
print("[anthropic] 图片块的 data: URL 里没有 payload —— 丢掉了")
|
|
144
|
-
return None
|
|
145
|
-
# 重编码成 base64 一次(`data:` 里本来就是 base64,但别假设 ——
|
|
146
|
-
# 一个 `;base64,` 都没有的 data URL 是百分号编码的)。
|
|
147
|
-
if "base64" in head[5:]:
|
|
148
|
-
data = payload
|
|
149
|
-
else:
|
|
150
|
-
from urllib.parse import unquote_to_bytes
|
|
151
|
-
data = _b64.b64encode(unquote_to_bytes(payload)).decode("ascii")
|
|
152
|
-
return {"type": "image",
|
|
153
|
-
"source": {"type": "base64", "media_type": media, "data": data}}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
#: Anthropic 对 `budget_tokens` 的硬下限(上游会拒,不是我们能选的):
|
|
157
|
-
#: 小于它 · 或者不小于 `max_tokens`,整个请求 400。`_thinking_kwargs`
|
|
158
|
-
#: 靠这两条把档位的预算夹进合法区间(并出声)。
|
|
159
|
-
_MIN_THINKING_BUDGET = 1024
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
def _image_block_media(block) -> list:
|
|
163
|
-
"""Anthropic 的 `image` 内容块 → `media` 列表。同步与流式共用这一处。
|
|
164
|
-
|
|
165
|
-
只收 `source.type == "base64"`;`url` 来源不下载(出网闸)。
|
|
166
|
-
"""
|
|
167
|
-
src = getattr(block, "source", None)
|
|
168
|
-
if getattr(src, "type", "") == "base64" and getattr(src, "data", ""):
|
|
169
|
-
return [{
|
|
170
|
-
"data_url": "data:%s;base64,%s" % (
|
|
171
|
-
getattr(src, "media_type", "image/png"), src.data),
|
|
172
|
-
"name": "image",
|
|
173
|
-
}]
|
|
174
|
-
print("[media] 忽略非 base64 的 image 块"
|
|
175
|
-
"(url 来源不下载,绕开出网闸)")
|
|
176
|
-
return []
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
def map_stream_event(event) -> list[StreamChunk]:
|
|
180
|
-
"""把一个 Anthropic 流事件映射成 0..1 个 `StreamChunk`(纯函数,可测)。
|
|
181
|
-
|
|
182
|
-
抽出来的理由不是"整洁",是要有机械读者:
|
|
183
|
-
本机没装 anthropic SDK(`AnthropicProvider.__init__` 会直接抛
|
|
184
|
-
"anthropic SDK required"),而"工具的**身份与名字只在 `content_block_start`
|
|
185
|
-
里"这条判据必须**有东西钉住 —— 否则它只能靠"读一遍代码觉得对"。
|
|
186
|
-
现在 `tests/test_stream_accumulator.py` 直接喂事件进来验它(不需要 SDK)。
|
|
187
|
-
|
|
188
|
-
必须处理 `content_block_start`:不接它,Anthropic 走流式时
|
|
189
|
-
`name` 永远是空,累积器得到 `unknown tool ''`。
|
|
190
|
-
"""
|
|
191
|
-
et = getattr(event, "type", None)
|
|
192
|
-
|
|
193
|
-
if et == "content_block_start":
|
|
194
|
-
block = getattr(event, "content_block", None)
|
|
195
|
-
btype = getattr(block, "type", None)
|
|
196
|
-
# 媒体块:与同步那条同一个收法(`_image_block_media`),
|
|
197
|
-
# 只在 `content_block_start` 里有 —— 图片不走增量分片。
|
|
198
|
-
if btype == "image":
|
|
199
|
-
media = _image_block_media(block)
|
|
200
|
-
return [StreamChunk(media=media)] if media else []
|
|
201
|
-
if btype != "tool_use":
|
|
202
|
-
return []
|
|
203
|
-
return [StreamChunk(
|
|
204
|
-
tool_call={
|
|
205
|
-
"id": getattr(block, "id", None),
|
|
206
|
-
"type": "function",
|
|
207
|
-
# 名字就在这里,且只有这里有(参数增量分片不带它)
|
|
208
|
-
"function": {"name": getattr(block, "name", None), "arguments": ""},
|
|
209
|
-
},
|
|
210
|
-
# 同一个槽位号贯穿 start 与后续的 json 增量
|
|
211
|
-
tool_call_index=getattr(event, "index", None),
|
|
212
|
-
)]
|
|
213
|
-
|
|
214
|
-
if et == "content_block_delta":
|
|
215
|
-
delta = getattr(event, "delta", None)
|
|
216
|
-
dt = getattr(delta, "type", None)
|
|
217
|
-
if dt == "text_delta":
|
|
218
|
-
return [StreamChunk(content=getattr(delta, "text", None))]
|
|
219
|
-
if dt == "input_json_delta":
|
|
220
|
-
# 只有参数增量:身份/名字一律给 `None`(累积器的"首个非空胜出"
|
|
221
|
-
# 不会让 None 把已知的值顶掉)
|
|
222
|
-
return [StreamChunk(
|
|
223
|
-
tool_call={
|
|
224
|
-
"id": None,
|
|
225
|
-
"type": "function",
|
|
226
|
-
"function": {"name": None,
|
|
227
|
-
"arguments": getattr(delta, "partial_json", None)},
|
|
228
|
-
},
|
|
229
|
-
tool_call_index=getattr(event, "index", None),
|
|
230
|
-
)]
|
|
231
|
-
return []
|
|
232
|
-
|
|
233
|
-
if et == "message_delta":
|
|
234
|
-
return [StreamChunk(
|
|
235
|
-
finish_reason=getattr(getattr(event, "delta", None), "stop_reason", None),
|
|
236
|
-
usage={"output_tokens": getattr(
|
|
237
|
-
getattr(event, "usage", None), "output_tokens", 0)},
|
|
238
|
-
)]
|
|
239
|
-
|
|
240
|
-
return []
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
class AnthropicProvider(BaseProvider):
|
|
244
|
-
"""Anthropic 原生 Messages API 的 provider。
|
|
245
|
-
|
|
246
|
-
直接使用 `anthropic` SDK(不是 OpenAI 兼容代理),
|
|
247
|
-
因此能使用 Claude 的原生能力:扩展思考与提示缓存。
|
|
248
|
-
"""
|
|
249
|
-
|
|
250
|
-
_api_key: str
|
|
251
|
-
_model: str
|
|
252
|
-
_temperature: float
|
|
253
|
-
_max_tokens: int
|
|
254
|
-
_context_window: int
|
|
255
|
-
_thinking_budget: int = 0 # 0 = 关闭
|
|
256
|
-
|
|
257
|
-
#: 与其他 provider 使用同一个编码(`cl100k_base`),
|
|
258
|
-
#: 让记忆层的测量在不同 provider 之间可比 —— 见下面的 count_tokens。
|
|
259
|
-
_tokenizer_encoding: str = "cl100k_base"
|
|
260
|
-
|
|
261
|
-
def __init__(
|
|
262
|
-
self,
|
|
263
|
-
api_key: str,
|
|
264
|
-
model: str = "claude-sonnet-4-20250514",
|
|
265
|
-
temperature: float = 0.3,
|
|
266
|
-
max_tokens: int = 8192,
|
|
267
|
-
context_window: int = 200000,
|
|
268
|
-
thinking_budget: int = 0,
|
|
269
|
-
base_url: str = "",
|
|
270
|
-
# 必须显式声明:落在 `**kwargs` 里会被静默吞掉,来源就丢了
|
|
271
|
-
window_source: str = "未知",
|
|
272
|
-
# 价格表按 `(provider, model)` 查 —— 见
|
|
273
|
-
# `providers/openai_compat.py` 的同名字段。必须显式声明:
|
|
274
|
-
# 落进 `**kwargs` 会被静默吞掉(同 `window_source` 那条)。
|
|
275
|
-
provider_name: str = "",
|
|
276
|
-
# 看不看得见图。必须显式声明 ——
|
|
277
|
-
# 落进 `**kwargs` 会被静默吞掉,那份声明就没了(同 `window_source`)。
|
|
278
|
-
# 默认 `False` 的理由在 `providers/base.py::accepts_images`。
|
|
279
|
-
supports_vision: bool = False,
|
|
280
|
-
# Anthropic 线没有音频部件 —— 这个形参收下但永远置 False,
|
|
281
|
-
# 并在显式声明 `true` 时出声(静默忽略一个写过的声明比拒绝更坏)。
|
|
282
|
-
supports_audio: bool = False,
|
|
283
|
-
**kwargs, # 接受统一装载器传来的 rpm/tpm/api_keys
|
|
284
|
-
) -> None:
|
|
285
|
-
self._api_key = api_key
|
|
286
|
-
self._model = model
|
|
287
|
-
self._provider_name = provider_name
|
|
288
|
-
self.supports_vision = bool(supports_vision)
|
|
289
|
-
# 这条路没有音频部件 —— 永远 False,声明了也要出声。
|
|
290
|
-
if supports_audio:
|
|
291
|
-
print("[anthropic] config 声明了 supports_audio,但这条线没有音频部件 "
|
|
292
|
-
"—— 仍按不支持处理(语音会以可见说明的形式交给模型)")
|
|
293
|
-
self.supports_audio = False
|
|
294
|
-
self._temperature = temperature
|
|
295
|
-
self._max_tokens = max_tokens
|
|
296
|
-
self._context_window = context_window
|
|
297
|
-
#: 这个窗口是谁给的(见 `providers/openai_compat.py` 的同名字段)
|
|
298
|
-
self._window_source = window_source
|
|
299
|
-
self._window_claim_warned = False
|
|
300
|
-
self._thinking_budget = thinking_budget
|
|
301
|
-
#: 档位取代配置那次只说一遍(每请求刷屏没有信息量)
|
|
302
|
-
self._tier_supersede_warned = False
|
|
303
|
-
#: 与 `openai_compat` 同一个入口(见 `core/tokenizer.py`):
|
|
304
|
-
#: 安装版用随包词表,断网也构造得出来。
|
|
305
|
-
self._tokenizer = _get_tiktoken_encoding(self._tokenizer_encoding)
|
|
306
|
-
|
|
307
|
-
try:
|
|
308
|
-
from anthropic import Anthropic
|
|
309
|
-
except ImportError:
|
|
310
|
-
raise ImportError(
|
|
311
|
-
"anthropic SDK required. Install: pip install anthropic"
|
|
312
|
-
)
|
|
313
|
-
|
|
314
|
-
# `http_client=` 必须给:不给的话 SDK 造的
|
|
315
|
-
# `httpx.Client` 是 `trust_env=True`,会静默采纳环境变量里的
|
|
316
|
-
# `ALL_PROXY` —— 一条没在听的本地代理能把整轮对话卡死。
|
|
317
|
-
from core import net_proxy
|
|
318
|
-
|
|
319
|
-
#: `url=` 让指向本机 / 内网中转站的自定义 `base_url` 直连
|
|
320
|
-
#: (判据在 `core/net_proxy.is_local_target`,与设置页探针共用)。
|
|
321
|
-
_http = net_proxy.httpx_client(url=base_url or None)
|
|
322
|
-
# Anthropic SDK doesn't support custom base_url in the same way,
|
|
323
|
-
# but we support it for proxies
|
|
324
|
-
if base_url:
|
|
325
|
-
self._client = Anthropic(
|
|
326
|
-
api_key=api_key,
|
|
327
|
-
base_url=base_url,
|
|
328
|
-
http_client=_http,
|
|
329
|
-
)
|
|
330
|
-
else:
|
|
331
|
-
self._client = Anthropic(api_key=api_key, http_client=_http)
|
|
332
|
-
|
|
333
|
-
# v1.1.0: Self-calibrating token estimator
|
|
334
|
-
cal_name = model or "claude"
|
|
335
|
-
self._calibrator = TokenCalibrator(cal_name)
|
|
336
|
-
if self._calibrator.load():
|
|
337
|
-
print(f"[calibrator] Loaded {cal_name}: "
|
|
338
|
-
f"factor={self._calibrator.factor:.4f}, "
|
|
339
|
-
f"samples={self._calibrator.samples}")
|
|
340
|
-
else:
|
|
341
|
-
print(f"[calibrator] Fresh start for {cal_name} "
|
|
342
|
-
f"— will auto-calibrate after ~3 turns")
|
|
343
|
-
|
|
344
|
-
# ------------------------------------------------------------------
|
|
345
|
-
# 窗口声明的矛盾检测
|
|
346
|
-
# ------------------------------------------------------------------
|
|
347
|
-
|
|
348
|
-
def _check_window_claim(self, prompt_tokens: int) -> None:
|
|
349
|
-
"""上游报的输入量超过声明的窗口,声明值一定是错的,吼一声。
|
|
350
|
-
|
|
351
|
-
与 `providers/openai_compat.py` 的同名方法同款(那边有完整注释:
|
|
352
|
-
没有别的探测手段,这是唯一的免费探针;每个实例只吼一次)。
|
|
353
|
-
|
|
354
|
-
这里同时是「演算」那一层的入口(`window_estimate.observe`)
|
|
355
|
-
—— 它必须在 early-return 之前(下界与"超没超过声明"无关)。
|
|
356
|
-
"""
|
|
357
|
-
window_estimate.observe(self._model, prompt_tokens)
|
|
358
|
-
if self._window_claim_warned or prompt_tokens <= self._context_window:
|
|
359
|
-
return
|
|
360
|
-
self._window_claim_warned = True
|
|
361
|
-
print(
|
|
362
|
-
f"[window] prompt={prompt_tokens:,} 已超过声明窗口 "
|
|
363
|
-
f"{self._context_window:,} —— 声明值错了"
|
|
364
|
-
f"(来源={self._window_source},model={self._model})。"
|
|
365
|
-
f"压缩闸门按声明值算({int(self._context_window * 0.85):,}),"
|
|
366
|
-
f"会永远够不着。"
|
|
367
|
-
)
|
|
368
|
-
|
|
369
|
-
# ------------------------------------------------------------------
|
|
370
|
-
# BaseProvider interface
|
|
371
|
-
# ------------------------------------------------------------------
|
|
372
|
-
|
|
373
|
-
@property
|
|
374
|
-
def context_window(self) -> int:
|
|
375
|
-
return self._context_window
|
|
376
|
-
|
|
377
|
-
@property
|
|
378
|
-
def window_source(self) -> str:
|
|
379
|
-
"""这个窗口是谁给的 —— 没有别的探测手段,所以来源必须跟着值走。"""
|
|
380
|
-
return getattr(self, "_window_source", "未知")
|
|
381
|
-
|
|
382
|
-
def count_tokens(self, text: str) -> int:
|
|
383
|
-
"""用 tiktoken(`cl100k_base`)计数,与其他 provider 同一把尺。
|
|
384
|
-
|
|
385
|
-
不要改用 SDK 的 token 计数:`client.count_tokens(text)`
|
|
386
|
-
这个接口并不存在(SDK 提供的是
|
|
387
|
-
`client.messages.count_tokens(messages=...)`),退回 len(text) // 3
|
|
388
|
-
会得到约 0.33 tokens/字符,而中文约 0.53(1.9 字符/token)——
|
|
389
|
-
低估约 37%。
|
|
390
|
-
|
|
391
|
-
方向很重要:记忆层的预检估算走这个方法(经 `estimate_request_tokens`),
|
|
392
|
-
再与非 tiktoken 计数的窗口比较。这个 provider 上出现第二种
|
|
393
|
-
静默不同的单位,两端就会对不上(判据:预算两端必须同源)。
|
|
394
|
-
|
|
395
|
-
共用 `cl100k_base` 编码,保证跨 provider 只有一把尺。
|
|
396
|
-
"""
|
|
397
|
-
return len(self._tokenizer.encode(text))
|
|
398
|
-
|
|
399
|
-
def _thinking_kwargs(self, thinking) -> dict:
|
|
400
|
-
"""这一次请求的 `thinking` 参数 —— 一处定义、两条路共用。
|
|
401
|
-
|
|
402
|
-
`chat` 与 `chat_stream` 必须走同一段逻辑 —— 只改一条是看不见的,
|
|
403
|
-
要等有人把流式打开才发现。
|
|
404
|
-
|
|
405
|
-
四条(每条都有理由或代价):
|
|
406
|
-
① `thinking is None`,这一格不参与,走构造函数那个
|
|
407
|
-
`thinking_budget`(= 既有行为,逐字不变);
|
|
408
|
-
② 档位说 开,发 `adaptive`(见下);
|
|
409
|
-
③ 档位说 关,不发;配置里设过值的话打一行
|
|
410
|
-
(静默忽略一个改过的键比不许改更坏);
|
|
411
|
-
④ Anthropic 的硬约束(上游会拒,不是我们能选的):
|
|
412
|
-
`budget_tokens >= 1024` 且 `budget_tokens < max_tokens`。
|
|
413
|
-
越界就夹到合法区间并出声 —— 不发是白丢这一档的能力,
|
|
414
|
-
硬发是整个请求 400(那一轮直接没了)。
|
|
415
|
-
"""
|
|
416
|
-
if thinking is None:
|
|
417
|
-
# 辅助调用(摘要 / 标题 / 压缩):逐字保留既有行为 ——
|
|
418
|
-
# 配置里没设预算就是什么都不发。
|
|
419
|
-
budget = self._thinking_budget
|
|
420
|
-
elif getattr(thinking, "enabled", False):
|
|
421
|
-
# 档位说开,发 `adaptive`,不再发预算。
|
|
422
|
-
#
|
|
423
|
-
# 理由有三条,都不是口味:
|
|
424
|
-
# ① `budget_tokens` 这一格已经删除 —— 可 Anthropic 的
|
|
425
|
-
# `enabled` 形状必须带一个预算,没有预算就只能二选一:
|
|
426
|
-
# 编一个,或者用 `adaptive`;
|
|
427
|
-
# ② `adaptive` = 模型自己决定想多久,档位只改一个字符串;
|
|
428
|
-
# ③ 编一个预算就是第二根随档的旋钮,而"手段随档增长"没有先例。
|
|
429
|
-
# 这一格未在真实 Anthropic 端点上验证过
|
|
430
|
-
# (本机没配 anthropic 的 key)。枚举本身经过探针验证
|
|
431
|
-
# (`bogus` 会报错,上游硬校验
|
|
432
|
-
# `{adaptive, enabled, disabled}`)。
|
|
433
|
-
return {"thinking": {"type": "adaptive"}}
|
|
434
|
-
else:
|
|
435
|
-
budget = 0
|
|
436
|
-
if self._thinking_budget > 0 and not self._tier_supersede_warned:
|
|
437
|
-
self._tier_supersede_warned = True
|
|
438
|
-
print(f"[thinking] 投入档这一档是「不思考」—— config.yaml 的 "
|
|
439
|
-
f"anthropic.thinking_budget={self._thinking_budget} 被它取代"
|
|
440
|
-
f"(档位是唯一来源)")
|
|
441
|
-
if budget <= 0:
|
|
442
|
-
return {}
|
|
443
|
-
if budget < _MIN_THINKING_BUDGET:
|
|
444
|
-
print(f"[thinking] 预算 {budget} 低于 Anthropic 的下限 "
|
|
445
|
-
f"{_MIN_THINKING_BUDGET} —— 按 {_MIN_THINKING_BUDGET} 发")
|
|
446
|
-
budget = _MIN_THINKING_BUDGET
|
|
447
|
-
if budget >= self._max_tokens:
|
|
448
|
-
if self._max_tokens <= _MIN_THINKING_BUDGET:
|
|
449
|
-
print(f"[thinking] max_tokens={self._max_tokens} 容不下思考预算 "
|
|
450
|
-
f"(要 >{_MIN_THINKING_BUDGET})—— 这一次**不带思考**"
|
|
451
|
-
f"(硬发会被上游 400,整轮都没了)")
|
|
452
|
-
return {}
|
|
453
|
-
print(f"[thinking] 预算 {budget} >= max_tokens {self._max_tokens} "
|
|
454
|
-
f"—— 夹到 {self._max_tokens - 1}(上游硬约束)")
|
|
455
|
-
budget = self._max_tokens - 1
|
|
456
|
-
return {"thinking": {"type": "enabled", "budget_tokens": budget}}
|
|
457
|
-
|
|
458
|
-
def chat(
|
|
459
|
-
self,
|
|
460
|
-
messages: list[dict],
|
|
461
|
-
tools: list[dict] | None = None,
|
|
462
|
-
system: "str | list[str] | None" = None,
|
|
463
|
-
thinking=None,
|
|
464
|
-
temperature: "float | None" = None,
|
|
465
|
-
) -> ChatResponse:
|
|
466
|
-
"""向 Claude 发一条同步消息。"""
|
|
467
|
-
system_prompt, api_messages = self._to_anthropic_messages(
|
|
468
|
-
messages, system=system
|
|
469
|
-
)
|
|
470
|
-
api_tools = self._to_anthropic_tools(tools)
|
|
471
|
-
|
|
472
|
-
# 给校准器做预检估算 —— 计入 `system` 与 `tools`,
|
|
473
|
-
# 与 API 的 usage.input_tokens 对齐(见
|
|
474
|
-
# BaseProvider.estimate_request_tokens)。
|
|
475
|
-
#
|
|
476
|
-
# `tools` 传的是 OpenAI 形状,不是投影后的 `api_tools`:
|
|
477
|
-
# 压缩闸门量的是注册表里的 schema,校准器必须与闸门用同一台仪器,
|
|
478
|
-
# 否则因子拟合的量与它要修正的量不是同一个。
|
|
479
|
-
# 这条 wire 上形状差异只是几个 key 名的 token。
|
|
480
|
-
estimated_input = self.estimate_message_tokens(
|
|
481
|
-
messages, system=system, tools=tools
|
|
482
|
-
)
|
|
483
|
-
|
|
484
|
-
kwargs: dict = {
|
|
485
|
-
"model": self._model,
|
|
486
|
-
"messages": api_messages,
|
|
487
|
-
"max_tokens": self._max_tokens,
|
|
488
|
-
}
|
|
489
|
-
if system_prompt:
|
|
490
|
-
kwargs["system"] = system_prompt
|
|
491
|
-
if api_tools:
|
|
492
|
-
kwargs["tools"] = api_tools
|
|
493
|
-
kwargs.update(self._thinking_kwargs(thinking))
|
|
494
|
-
# 按次覆盖:`None` 时一个字都不加 ——
|
|
495
|
-
# 本 client 默认不发 temperature。
|
|
496
|
-
# 判据同接 `thinking=` 那条:`None` = 逐字节等于现状。
|
|
497
|
-
#它只在调用点显式传的时候才改变 wire,
|
|
498
|
-
# 不顺手改掉所有 anthropic 调用的采样温度。
|
|
499
|
-
if temperature is not None:
|
|
500
|
-
kwargs["temperature"] = self.resolve_temperature(temperature)
|
|
501
|
-
|
|
502
|
-
response = _create_with_retry(self._client, kwargs)
|
|
503
|
-
|
|
504
|
-
# Extract text and tool calls
|
|
505
|
-
content = ""
|
|
506
|
-
tool_calls = []
|
|
507
|
-
#: assistant 内容里的 image 块(base64)。
|
|
508
|
-
#: 只收 `source.type == "base64"`;`url` 来源不下载(出网闸)。
|
|
509
|
-
media: list = []
|
|
510
|
-
|
|
511
|
-
for block in response.content:
|
|
512
|
-
if block.type == "text":
|
|
513
|
-
content += block.text
|
|
514
|
-
elif block.type == "tool_use":
|
|
515
|
-
tool_calls.append({
|
|
516
|
-
"id": block.id,
|
|
517
|
-
"type": "function",
|
|
518
|
-
"function": {
|
|
519
|
-
"name": block.name,
|
|
520
|
-
"arguments": json.dumps(block.input),
|
|
521
|
-
},
|
|
522
|
-
})
|
|
523
|
-
elif block.type == "image":
|
|
524
|
-
# 与流式那条同一个收法(`_image_block_media`):
|
|
525
|
-
# 两处各写一份,迟早一处改了、另一处漏(`A11`)。
|
|
526
|
-
media.extend(_image_block_media(block))
|
|
527
|
-
|
|
528
|
-
it = response.usage.input_tokens
|
|
529
|
-
ot = response.usage.output_tokens
|
|
530
|
-
# 缓存命中:Anthropic 走 `cache_read_input_tokens`,
|
|
531
|
-
# 同一个 reader 认三种字段名,这里不用特判。
|
|
532
|
-
cache_hit = read_cache_hit(response.usage)
|
|
533
|
-
record_token_usage(it, ot, cache_hit=cache_hit,
|
|
534
|
-
provider=self._provider_name, model=self._model)
|
|
535
|
-
|
|
536
|
-
# 声明窗口与实际请求的硬矛盾检测(与 openai_compat 同款)
|
|
537
|
-
self._check_window_claim(it)
|
|
538
|
-
|
|
539
|
-
# 把上游的真实 token 数喂给校准器
|
|
540
|
-
if self._calibrator is not None and it > 0:
|
|
541
|
-
prev_factor = self._calibrator.factor
|
|
542
|
-
ratio = self._calibrator.feed(estimated=estimated_input, actual=it)
|
|
543
|
-
self._calibrator.save()
|
|
544
|
-
if self._calibrator.factor != prev_factor:
|
|
545
|
-
print(
|
|
546
|
-
f"[calibrator] Updated: "
|
|
547
|
-
f"est={estimated_input} actual={it} "
|
|
548
|
-
f"ratio={ratio:.2f} "
|
|
549
|
-
f"factor={self._calibrator.factor:.4f} "
|
|
550
|
-
f"({self._calibrator.samples} samples)"
|
|
551
|
-
)
|
|
552
|
-
|
|
553
|
-
return ChatResponse(
|
|
554
|
-
content=content or None,
|
|
555
|
-
tool_calls=tool_calls if tool_calls else None,
|
|
556
|
-
prompt_tokens=it,
|
|
557
|
-
completion_tokens=ot,
|
|
558
|
-
cache_hit_tokens=cache_hit,
|
|
559
|
-
# 这一轮 assistant 直接产出的图(没有就是 `None`)。
|
|
560
|
-
media=media or None,
|
|
561
|
-
)
|
|
562
|
-
|
|
563
|
-
async def chat_stream(
|
|
564
|
-
self,
|
|
565
|
-
messages: list[dict],
|
|
566
|
-
tools: list[dict] | None = None,
|
|
567
|
-
system: "str | list[str] | None" = None,
|
|
568
|
-
thinking=None,
|
|
569
|
-
temperature: "float | None" = None,
|
|
570
|
-
) -> AsyncIterator[StreamChunk]:
|
|
571
|
-
"""流式接收 Claude 的回复。"""
|
|
572
|
-
system_prompt, api_messages = self._to_anthropic_messages(
|
|
573
|
-
messages, system=system
|
|
574
|
-
)
|
|
575
|
-
api_tools = self._to_anthropic_tools(tools)
|
|
576
|
-
|
|
577
|
-
kwargs: dict = {
|
|
578
|
-
"model": self._model,
|
|
579
|
-
"messages": api_messages,
|
|
580
|
-
"max_tokens": self._max_tokens,
|
|
581
|
-
}
|
|
582
|
-
if system_prompt:
|
|
583
|
-
kwargs["system"] = system_prompt
|
|
584
|
-
if api_tools:
|
|
585
|
-
kwargs["tools"] = api_tools
|
|
586
|
-
# 流式这条路也必须接思考参数 —— 只改 `chat` 一条是看不见的。
|
|
587
|
-
kwargs.update(self._thinking_kwargs(thinking))
|
|
588
|
-
# 按次覆盖:`None` 时一个字都不加 ——
|
|
589
|
-
# 本 client 默认不发 temperature。
|
|
590
|
-
# 判据同接 `thinking=` 那条:`None` = 逐字节等于现状。
|
|
591
|
-
#它只在调用点显式传的时候才改变 wire,
|
|
592
|
-
# 不顺手改掉所有 anthropic 调用的采样温度。
|
|
593
|
-
if temperature is not None:
|
|
594
|
-
kwargs["temperature"] = self.resolve_temperature(temperature)
|
|
595
|
-
|
|
596
|
-
#: 连接 / 超时按固定节奏重试
|
|
597
|
-
#: (与 OpenAI 兼容那条同一条判据)。已经交出去的内容不能重来
|
|
598
|
-
#: —— 那会让用户看到两遍(`emitted`)。
|
|
599
|
-
from core import llm_retry
|
|
600
|
-
from core.llm_errors import headline
|
|
601
|
-
rstate: dict = {}
|
|
602
|
-
while True:
|
|
603
|
-
emitted = False
|
|
604
|
-
try:
|
|
605
|
-
with self._client.messages.stream(**kwargs) as stream:
|
|
606
|
-
for event in stream:
|
|
607
|
-
for _chunk in map_stream_event(event):
|
|
608
|
-
emitted = True
|
|
609
|
-
yield _chunk
|
|
610
|
-
llm_retry.clear(_session_key())
|
|
611
|
-
return
|
|
612
|
-
except Exception as e:
|
|
613
|
-
transport = classify_transport_error(e)
|
|
614
|
-
kind = classify_api_error(e) or transport or ""
|
|
615
|
-
action, delay = (("no_retry", 0) if emitted
|
|
616
|
-
else llm_retry.step(rstate, kind))
|
|
617
|
-
if action in ("retry", "silent"):
|
|
618
|
-
n = int(rstate.get("silent") or 0) if action == "silent" \
|
|
619
|
-
else int(rstate.get("retry") or 0)
|
|
620
|
-
llm_retry.note(_session_key(), n, kind=kind,
|
|
621
|
-
text=headline(e, kind=kind), phase=action)
|
|
622
|
-
print(f"[llm] {kind or 'unknown'} —— {delay}ms 后重试"
|
|
623
|
-
f"({action} {n})")
|
|
624
|
-
#: 可打断(同 OpenAI 兼容那条)。
|
|
625
|
-
if not await llm_retry.wait_async(_session_key(), delay):
|
|
626
|
-
llm_retry.clear(_session_key())
|
|
627
|
-
yield StreamChunk(content="")
|
|
628
|
-
return
|
|
629
|
-
continue
|
|
630
|
-
#: 与 OpenAI 兼容那条同一条诊断口径 —— 错误类别跟着 chunk 走
|
|
631
|
-
#: (用户面 `core/llm_errors.explain` 要用),并且出声。
|
|
632
|
-
print(f"[llm] 流式失败({type(e).__name__}: {str(e)[:200]})"
|
|
633
|
-
f" —— model={self._model}")
|
|
634
|
-
llm_retry.fail(_session_key(), kind=kind,
|
|
635
|
-
text=headline(e, kind=kind))
|
|
636
|
-
yield StreamChunk(
|
|
637
|
-
error=str(e),
|
|
638
|
-
error_kind=kind)
|
|
639
|
-
return
|
|
640
|
-
|
|
641
|
-
async def test_connection(self) -> dict:
|
|
642
|
-
"""ping 一次 Claude,验证 API key。"""
|
|
643
|
-
try:
|
|
644
|
-
resp = self._client.messages.create(
|
|
645
|
-
model=self._model,
|
|
646
|
-
messages=[{"role": "user", "content": "ping"}],
|
|
647
|
-
max_tokens=1,
|
|
648
|
-
)
|
|
649
|
-
return {"ok": True, "message": f"Claude reachable (model={self._model})"}
|
|
650
|
-
except Exception as e:
|
|
651
|
-
return {"ok": False, "message": f"Connection failed: {e}"}
|
|
652
|
-
|
|
653
|
-
# ------------------------------------------------------------------
|
|
654
|
-
# Message format translation
|
|
655
|
-
# ------------------------------------------------------------------
|
|
656
|
-
|
|
657
|
-
# (helper `_to_anthropic_content` lives at module level — see below)
|
|
658
|
-
|
|
659
|
-
def _to_anthropic_messages(
|
|
660
|
-
self, messages: list[dict], system: "str | list[str] | None" = None
|
|
661
|
-
) -> tuple[str, list[dict]]:
|
|
662
|
-
"""把 OpenAI 格式的消息转成 Anthropic 格式。
|
|
663
|
-
|
|
664
|
-
Anthropic 有原生顶层 `system` 字段,所以这个类是系统提示词
|
|
665
|
-
唯一不必伪装成消息的地方。`system` 参数以 `kwargs["system"]`
|
|
666
|
-
发出,别的都不走那里。
|
|
667
|
-
|
|
668
|
-
**列表内的 `role="system"` 消息原地降级为 `user`,
|
|
669
|
-
不被提升到顶部。理由:
|
|
670
|
-
|
|
671
|
-
* 提升会把历史挪到指令之上。恢复历史的标记是位置相关的:
|
|
672
|
-
`<history_start>` … 轮次 … `<history_end>` 只有在原地才有意义。
|
|
673
|
-
拼成一个字符串放到顶部,模型会把一段旧对话当成当前指令 ——
|
|
674
|
-
"历史伪装成指令"那类故障只是换到了 provider 里。
|
|
675
|
-
* 降级为 `user` 是唯一遇到同样约束时的做法:只有一个 system 槽位,
|
|
676
|
-
没占上槽位的 system 消息折进 user 消息以保持顺序。
|
|
677
|
-
* Anthropic Messages API 会在服务端合并相邻的同角色轮次,
|
|
678
|
-
所以把标记折进相邻的 `user` 轮是安全的。
|
|
679
|
-
|
|
680
|
-
`system` 接受普通字符串或块列表;块用 :func:`flatten_system`
|
|
681
|
-
拍平(这里还没有 Anthropic 侧的缓存断点支持 —— 将来有时就在这里长,
|
|
682
|
-
这也是参数不标注成 `str` 的原因)。
|
|
683
|
-
|
|
684
|
-
返回:
|
|
685
|
-
(system_text: str, api_messages: list[dict])
|
|
686
|
-
"""
|
|
687
|
-
system_text = flatten_system(system)
|
|
688
|
-
api_messages = []
|
|
689
|
-
|
|
690
|
-
for msg in messages:
|
|
691
|
-
role = msg.get("role", "")
|
|
692
|
-
content = msg.get("content")
|
|
693
|
-
# 带图的 user 轮是块列表,而
|
|
694
|
-
# Anthropic 的块形状与 OpenAI 不同:
|
|
695
|
-
# OpenAI {"type": "image_url", "image_url": {"url": "data:…"}}
|
|
696
|
-
# Anthropic {"type": "image", "source": {"type": "base64",
|
|
697
|
-
# "media_type": …, "data": …}}
|
|
698
|
-
# 不翻译就直接透传,上游 400,而报错说的是
|
|
699
|
-
# "content.0.type: Input tag 'image_url' …",看不出是我们的锅。
|
|
700
|
-
# 翻译只在这一处(本函数是 Anthropic 唯一的消息投影),
|
|
701
|
-
# 与 `_wire_messages` 在 OpenAI 那条路上是同一条判据。
|
|
702
|
-
content = _to_anthropic_content(content)
|
|
703
|
-
|
|
704
|
-
if role == "system":
|
|
705
|
-
api_messages.append({"role": "user", "content": content})
|
|
706
|
-
continue
|
|
707
|
-
|
|
708
|
-
if role == "user":
|
|
709
|
-
api_messages.append({"role": "user", "content": content})
|
|
710
|
-
elif role == "assistant":
|
|
711
|
-
entry: dict = {"role": "assistant", "content": content}
|
|
712
|
-
# Handle tool_calls if present
|
|
713
|
-
tool_calls = msg.get("tool_calls")
|
|
714
|
-
if tool_calls:
|
|
715
|
-
tool_blocks = []
|
|
716
|
-
for tc in tool_calls:
|
|
717
|
-
name = tc["function"]["name"]
|
|
718
|
-
# 历史里那条 `tool_calls` 是模型的原样输出,
|
|
719
|
-
# 坏 JSON(以及流式无参调用的空串)会一路留在会话里。
|
|
720
|
-
# 直接 `json.loads`,一旦撞上,**整个请求崩在
|
|
721
|
-
# provider 内部**:上游看不到,我们只看到一句
|
|
722
|
-
# JSONDecodeError,从它反推"是历史坏了"要绕一大圈。
|
|
723
|
-
#判据是"历史必须始终可重发":坏的就按无参回填并出声。
|
|
724
|
-
# 不改历史 —— 修在消费端(一处),不在 N 个生产端。
|
|
725
|
-
raw_args = tc["function"]["arguments"]
|
|
726
|
-
try:
|
|
727
|
-
args = json.loads(raw_args)
|
|
728
|
-
except (json.JSONDecodeError, TypeError) as exc:
|
|
729
|
-
args = {}
|
|
730
|
-
print(f"[anthropic] 历史里 '{name}' 的 arguments 不是合法 "
|
|
731
|
-
f"JSON({type(exc).__name__}: {exc})—— 按无参回填"
|
|
732
|
-
f"(历史本身不动)")
|
|
733
|
-
tool_blocks.append({
|
|
734
|
-
"type": "tool_use",
|
|
735
|
-
"id": tc.get("id", ""),
|
|
736
|
-
"name": name,
|
|
737
|
-
"input": args,
|
|
738
|
-
})
|
|
739
|
-
entry["content"] = tool_blocks
|
|
740
|
-
api_messages.append(entry)
|
|
741
|
-
elif role == "tool":
|
|
742
|
-
# Anthropic: tool results go in a user message
|
|
743
|
-
tc_id = msg.get("tool_call_id", "")
|
|
744
|
-
api_messages.append({
|
|
745
|
-
"role": "user",
|
|
746
|
-
"content": [
|
|
747
|
-
{
|
|
748
|
-
"type": "tool_result",
|
|
749
|
-
"tool_use_id": tc_id,
|
|
750
|
-
"content": content,
|
|
751
|
-
}
|
|
752
|
-
],
|
|
753
|
-
})
|
|
754
|
-
|
|
755
|
-
return (system_text, api_messages)
|
|
756
|
-
|
|
757
|
-
def _to_anthropic_tools(
|
|
758
|
-
self, tools: list[dict] | None
|
|
759
|
-
) -> list[dict] | None:
|
|
760
|
-
"""把 OpenAI 格式的工具定义转成 Anthropic 格式。"""
|
|
761
|
-
if not tools:
|
|
762
|
-
return None
|
|
763
|
-
|
|
764
|
-
result = []
|
|
765
|
-
for tool in tools:
|
|
766
|
-
fn = tool.get("function", {})
|
|
767
|
-
result.append({
|
|
768
|
-
"name": fn.get("name", ""),
|
|
769
|
-
"description": fn.get("description", ""),
|
|
770
|
-
"input_schema": fn.get("parameters", {}),
|
|
771
|
-
})
|
|
772
|
-
return result
|
|
1
|
+
"""AnthropicProvider —— 原生 Anthropic Messages API provider。
|
|
2
|
+
|
|
3
|
+
使用 `anthropic` Python SDK,以完整使用 Claude 的原生能力:
|
|
4
|
+
扩展思考、tool_choice、提示缓存。
|
|
5
|
+
|
|
6
|
+
OpenAI ↔ Anthropic 的消息格式翻译在
|
|
7
|
+
:meth:`_to_anthropic_messages` 中完成。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import AsyncIterator, Optional
|
|
12
|
+
|
|
13
|
+
from core import window_estimate
|
|
14
|
+
#: tiktoken 只许经这一处(见 `core/tokenizer.py`:随包词表 + 说得清的失败)。
|
|
15
|
+
from core.tokenizer import get_encoding as _get_tiktoken_encoding
|
|
16
|
+
from providers.base import (
|
|
17
|
+
BaseProvider,
|
|
18
|
+
ChatResponse,
|
|
19
|
+
StreamChunk,
|
|
20
|
+
classify_api_error,
|
|
21
|
+
classify_transport_error,
|
|
22
|
+
flatten_system,
|
|
23
|
+
read_cache_hit,
|
|
24
|
+
record_token_usage,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _session_key() -> str:
|
|
29
|
+
"""这一轮属于哪个会话(通道键)—— 重试横幅按它找会话。"""
|
|
30
|
+
try:
|
|
31
|
+
from core.request_snapshot import current_session_id
|
|
32
|
+
return str(current_session_id() or "")
|
|
33
|
+
except Exception: # noqa: BLE001
|
|
34
|
+
return ""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _create_with_retry(client, kwargs):
|
|
38
|
+
"""把一次 `messages.create` 按统一节奏重试。
|
|
39
|
+
|
|
40
|
+
节奏与 OpenAI 兼容那条同源(`core/llm_retry.step`):连接 / 超时 / 5xx
|
|
41
|
+
走常规 10 次,再转静默每 120 秒一次;余额 / 参数 / 认证 / 限流 /
|
|
42
|
+
内容审核 / 请求过大一律不重试。
|
|
43
|
+
"""
|
|
44
|
+
from core import llm_retry
|
|
45
|
+
from core.llm_errors import headline
|
|
46
|
+
rstate: dict = {}
|
|
47
|
+
while True:
|
|
48
|
+
try:
|
|
49
|
+
resp = client.messages.create(**kwargs)
|
|
50
|
+
llm_retry.clear(_session_key())
|
|
51
|
+
return resp
|
|
52
|
+
except Exception as e: # noqa: BLE001
|
|
53
|
+
kind = classify_api_error(e) or classify_transport_error(e) or ""
|
|
54
|
+
action, delay = llm_retry.step(rstate, kind)
|
|
55
|
+
if action in ("retry", "silent"):
|
|
56
|
+
n = int(rstate.get("silent") or 0) if action == "silent" \
|
|
57
|
+
else int(rstate.get("retry") or 0)
|
|
58
|
+
llm_retry.note(_session_key(), n, kind=kind,
|
|
59
|
+
text=headline(e, kind=kind), phase=action)
|
|
60
|
+
print(f"[llm] {kind or 'unknown'} —— {delay}ms 后重试"
|
|
61
|
+
f"({action} {n})")
|
|
62
|
+
#: 可打断 —— 用户按了打断就立刻把原异常抛回。
|
|
63
|
+
if not llm_retry.wait(_session_key(), delay):
|
|
64
|
+
raise
|
|
65
|
+
continue
|
|
66
|
+
llm_retry.fail(_session_key(), kind=kind,
|
|
67
|
+
text=headline(e, kind=kind))
|
|
68
|
+
raise
|
|
69
|
+
from core.token_calibrator import TokenCalibrator
|
|
70
|
+
from core.image_input import content_text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# OpenAI 形状的 `content` -> Anthropic 形状
|
|
74
|
+
#
|
|
75
|
+
# 这是两条线唯一的翻译处(`_to_anthropic_messages` 是 Anthropic 唯一的
|
|
76
|
+
# 消息投影,正如 `_wire_messages` 是 OpenAI 那条路唯一的)。
|
|
77
|
+
#
|
|
78
|
+
# | | 文本块 | 图片块 |
|
|
79
|
+
# |---|---|---|
|
|
80
|
+
# | OpenAI | `{"type":"text","text":…}` | `{"type":"image_url","image_url":{"url":"data:…"}}` |
|
|
81
|
+
# | Anthropic | 同左(逐字一样) | `{"type":"image","source":{"type":"base64","media_type":…,"data":…}}` |
|
|
82
|
+
#
|
|
83
|
+
# 文本块形状不动 —— 两家逐字相同,所以只有图片需要翻译。
|
|
84
|
+
# 认不出的块不静默丢("不许静默改坏"):换成一个
|
|
85
|
+
# 可见的文本块,写清它是什么形状。丢掉它会让模型以为"这条消息就这些"。
|
|
86
|
+
|
|
87
|
+
def _to_anthropic_content(content):
|
|
88
|
+
"""消息 `content` -> Anthropic 接受的形式。
|
|
89
|
+
|
|
90
|
+
`str` / `None`,原样(`None` 变 `""`)。
|
|
91
|
+
块列表,逐块翻译;文本块原样、图片块换形状、其余变成一句实话。
|
|
92
|
+
"""
|
|
93
|
+
if content is None:
|
|
94
|
+
return ""
|
|
95
|
+
if isinstance(content, str):
|
|
96
|
+
return content
|
|
97
|
+
if not isinstance(content, (list, tuple)):
|
|
98
|
+
# 既不是串也不是块列表 —— 交给 `content_text` 取它能取的部分,
|
|
99
|
+
# 而不是把认不出的东西原样发上去(上游会 400,且报错看不出是我们的锅)
|
|
100
|
+
return content_text(content)
|
|
101
|
+
|
|
102
|
+
out: list[dict] = []
|
|
103
|
+
for part in content:
|
|
104
|
+
if not isinstance(part, dict):
|
|
105
|
+
if part:
|
|
106
|
+
out.append({"type": "text", "text": str(part)})
|
|
107
|
+
continue
|
|
108
|
+
kind = part.get("type")
|
|
109
|
+
if kind == "text":
|
|
110
|
+
out.append({"type": "text", "text": str(part.get("text") or "")})
|
|
111
|
+
elif kind == "image_url":
|
|
112
|
+
block = _image_block(part)
|
|
113
|
+
if block is not None:
|
|
114
|
+
out.append(block)
|
|
115
|
+
else:
|
|
116
|
+
print(f"[anthropic] 认不出的 content 块 type={kind!r} —— "
|
|
117
|
+
f"换成一个可见的说明(不静默丢)")
|
|
118
|
+
out.append({"type": "text",
|
|
119
|
+
"text": f"[这块内容({kind})Anthropic 这条线不支持]"})
|
|
120
|
+
# 空列表上游会 400(content 不能是空数组),补一个空文本块。
|
|
121
|
+
return out or [{"type": "text", "text": ""}]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _image_block(part: dict) -> Optional[dict]:
|
|
125
|
+
"""`image_url` part -> Anthropic 的 `image` block;解不开就返回 `None` 并出声。
|
|
126
|
+
|
|
127
|
+
只认 `data:` URL:Anthropic 的 `source` 有 `base64` / `url` / `file`
|
|
128
|
+
三种,而 `url` 那种要求它自己去取(等于给上游开了一条我们看不见的出网路,
|
|
129
|
+
而那条出网闸是我们自己的)。远端图片不在这一层解决,
|
|
130
|
+
让它走不进来(`core/image_input.py::prepare_*` 只产 `data:`)。
|
|
131
|
+
"""
|
|
132
|
+
# 延迟 import:正常路径(`base64`)用不到它,而 `base64` 是标准库。
|
|
133
|
+
import base64 as _b64
|
|
134
|
+
|
|
135
|
+
url = (part.get("image_url") or {}).get("url") or ""
|
|
136
|
+
if not url.startswith("data:"):
|
|
137
|
+
print(f"[anthropic] 图片块不是一个 data: URL({url[:40]!r})—— "
|
|
138
|
+
f"Anthropic 那条路只收内嵌的字节,这一块被丢掉了")
|
|
139
|
+
return None
|
|
140
|
+
head, _, payload = url.partition(",")
|
|
141
|
+
media = head[5:].split(";")[0].strip().lower() or "image/png"
|
|
142
|
+
if not payload:
|
|
143
|
+
print("[anthropic] 图片块的 data: URL 里没有 payload —— 丢掉了")
|
|
144
|
+
return None
|
|
145
|
+
# 重编码成 base64 一次(`data:` 里本来就是 base64,但别假设 ——
|
|
146
|
+
# 一个 `;base64,` 都没有的 data URL 是百分号编码的)。
|
|
147
|
+
if "base64" in head[5:]:
|
|
148
|
+
data = payload
|
|
149
|
+
else:
|
|
150
|
+
from urllib.parse import unquote_to_bytes
|
|
151
|
+
data = _b64.b64encode(unquote_to_bytes(payload)).decode("ascii")
|
|
152
|
+
return {"type": "image",
|
|
153
|
+
"source": {"type": "base64", "media_type": media, "data": data}}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
#: Anthropic 对 `budget_tokens` 的硬下限(上游会拒,不是我们能选的):
|
|
157
|
+
#: 小于它 · 或者不小于 `max_tokens`,整个请求 400。`_thinking_kwargs`
|
|
158
|
+
#: 靠这两条把档位的预算夹进合法区间(并出声)。
|
|
159
|
+
_MIN_THINKING_BUDGET = 1024
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _image_block_media(block) -> list:
|
|
163
|
+
"""Anthropic 的 `image` 内容块 → `media` 列表。同步与流式共用这一处。
|
|
164
|
+
|
|
165
|
+
只收 `source.type == "base64"`;`url` 来源不下载(出网闸)。
|
|
166
|
+
"""
|
|
167
|
+
src = getattr(block, "source", None)
|
|
168
|
+
if getattr(src, "type", "") == "base64" and getattr(src, "data", ""):
|
|
169
|
+
return [{
|
|
170
|
+
"data_url": "data:%s;base64,%s" % (
|
|
171
|
+
getattr(src, "media_type", "image/png"), src.data),
|
|
172
|
+
"name": "image",
|
|
173
|
+
}]
|
|
174
|
+
print("[media] 忽略非 base64 的 image 块"
|
|
175
|
+
"(url 来源不下载,绕开出网闸)")
|
|
176
|
+
return []
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def map_stream_event(event) -> list[StreamChunk]:
|
|
180
|
+
"""把一个 Anthropic 流事件映射成 0..1 个 `StreamChunk`(纯函数,可测)。
|
|
181
|
+
|
|
182
|
+
抽出来的理由不是"整洁",是要有机械读者:
|
|
183
|
+
本机没装 anthropic SDK(`AnthropicProvider.__init__` 会直接抛
|
|
184
|
+
"anthropic SDK required"),而"工具的**身份与名字只在 `content_block_start`
|
|
185
|
+
里"这条判据必须**有东西钉住 —— 否则它只能靠"读一遍代码觉得对"。
|
|
186
|
+
现在 `tests/test_stream_accumulator.py` 直接喂事件进来验它(不需要 SDK)。
|
|
187
|
+
|
|
188
|
+
必须处理 `content_block_start`:不接它,Anthropic 走流式时
|
|
189
|
+
`name` 永远是空,累积器得到 `unknown tool ''`。
|
|
190
|
+
"""
|
|
191
|
+
et = getattr(event, "type", None)
|
|
192
|
+
|
|
193
|
+
if et == "content_block_start":
|
|
194
|
+
block = getattr(event, "content_block", None)
|
|
195
|
+
btype = getattr(block, "type", None)
|
|
196
|
+
# 媒体块:与同步那条同一个收法(`_image_block_media`),
|
|
197
|
+
# 只在 `content_block_start` 里有 —— 图片不走增量分片。
|
|
198
|
+
if btype == "image":
|
|
199
|
+
media = _image_block_media(block)
|
|
200
|
+
return [StreamChunk(media=media)] if media else []
|
|
201
|
+
if btype != "tool_use":
|
|
202
|
+
return []
|
|
203
|
+
return [StreamChunk(
|
|
204
|
+
tool_call={
|
|
205
|
+
"id": getattr(block, "id", None),
|
|
206
|
+
"type": "function",
|
|
207
|
+
# 名字就在这里,且只有这里有(参数增量分片不带它)
|
|
208
|
+
"function": {"name": getattr(block, "name", None), "arguments": ""},
|
|
209
|
+
},
|
|
210
|
+
# 同一个槽位号贯穿 start 与后续的 json 增量
|
|
211
|
+
tool_call_index=getattr(event, "index", None),
|
|
212
|
+
)]
|
|
213
|
+
|
|
214
|
+
if et == "content_block_delta":
|
|
215
|
+
delta = getattr(event, "delta", None)
|
|
216
|
+
dt = getattr(delta, "type", None)
|
|
217
|
+
if dt == "text_delta":
|
|
218
|
+
return [StreamChunk(content=getattr(delta, "text", None))]
|
|
219
|
+
if dt == "input_json_delta":
|
|
220
|
+
# 只有参数增量:身份/名字一律给 `None`(累积器的"首个非空胜出"
|
|
221
|
+
# 不会让 None 把已知的值顶掉)
|
|
222
|
+
return [StreamChunk(
|
|
223
|
+
tool_call={
|
|
224
|
+
"id": None,
|
|
225
|
+
"type": "function",
|
|
226
|
+
"function": {"name": None,
|
|
227
|
+
"arguments": getattr(delta, "partial_json", None)},
|
|
228
|
+
},
|
|
229
|
+
tool_call_index=getattr(event, "index", None),
|
|
230
|
+
)]
|
|
231
|
+
return []
|
|
232
|
+
|
|
233
|
+
if et == "message_delta":
|
|
234
|
+
return [StreamChunk(
|
|
235
|
+
finish_reason=getattr(getattr(event, "delta", None), "stop_reason", None),
|
|
236
|
+
usage={"output_tokens": getattr(
|
|
237
|
+
getattr(event, "usage", None), "output_tokens", 0)},
|
|
238
|
+
)]
|
|
239
|
+
|
|
240
|
+
return []
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class AnthropicProvider(BaseProvider):
|
|
244
|
+
"""Anthropic 原生 Messages API 的 provider。
|
|
245
|
+
|
|
246
|
+
直接使用 `anthropic` SDK(不是 OpenAI 兼容代理),
|
|
247
|
+
因此能使用 Claude 的原生能力:扩展思考与提示缓存。
|
|
248
|
+
"""
|
|
249
|
+
|
|
250
|
+
_api_key: str
|
|
251
|
+
_model: str
|
|
252
|
+
_temperature: float
|
|
253
|
+
_max_tokens: int
|
|
254
|
+
_context_window: int
|
|
255
|
+
_thinking_budget: int = 0 # 0 = 关闭
|
|
256
|
+
|
|
257
|
+
#: 与其他 provider 使用同一个编码(`cl100k_base`),
|
|
258
|
+
#: 让记忆层的测量在不同 provider 之间可比 —— 见下面的 count_tokens。
|
|
259
|
+
_tokenizer_encoding: str = "cl100k_base"
|
|
260
|
+
|
|
261
|
+
def __init__(
|
|
262
|
+
self,
|
|
263
|
+
api_key: str,
|
|
264
|
+
model: str = "claude-sonnet-4-20250514",
|
|
265
|
+
temperature: float = 0.3,
|
|
266
|
+
max_tokens: int = 8192,
|
|
267
|
+
context_window: int = 200000,
|
|
268
|
+
thinking_budget: int = 0,
|
|
269
|
+
base_url: str = "",
|
|
270
|
+
# 必须显式声明:落在 `**kwargs` 里会被静默吞掉,来源就丢了
|
|
271
|
+
window_source: str = "未知",
|
|
272
|
+
# 价格表按 `(provider, model)` 查 —— 见
|
|
273
|
+
# `providers/openai_compat.py` 的同名字段。必须显式声明:
|
|
274
|
+
# 落进 `**kwargs` 会被静默吞掉(同 `window_source` 那条)。
|
|
275
|
+
provider_name: str = "",
|
|
276
|
+
# 看不看得见图。必须显式声明 ——
|
|
277
|
+
# 落进 `**kwargs` 会被静默吞掉,那份声明就没了(同 `window_source`)。
|
|
278
|
+
# 默认 `False` 的理由在 `providers/base.py::accepts_images`。
|
|
279
|
+
supports_vision: bool = False,
|
|
280
|
+
# Anthropic 线没有音频部件 —— 这个形参收下但永远置 False,
|
|
281
|
+
# 并在显式声明 `true` 时出声(静默忽略一个写过的声明比拒绝更坏)。
|
|
282
|
+
supports_audio: bool = False,
|
|
283
|
+
**kwargs, # 接受统一装载器传来的 rpm/tpm/api_keys
|
|
284
|
+
) -> None:
|
|
285
|
+
self._api_key = api_key
|
|
286
|
+
self._model = model
|
|
287
|
+
self._provider_name = provider_name
|
|
288
|
+
self.supports_vision = bool(supports_vision)
|
|
289
|
+
# 这条路没有音频部件 —— 永远 False,声明了也要出声。
|
|
290
|
+
if supports_audio:
|
|
291
|
+
print("[anthropic] config 声明了 supports_audio,但这条线没有音频部件 "
|
|
292
|
+
"—— 仍按不支持处理(语音会以可见说明的形式交给模型)")
|
|
293
|
+
self.supports_audio = False
|
|
294
|
+
self._temperature = temperature
|
|
295
|
+
self._max_tokens = max_tokens
|
|
296
|
+
self._context_window = context_window
|
|
297
|
+
#: 这个窗口是谁给的(见 `providers/openai_compat.py` 的同名字段)
|
|
298
|
+
self._window_source = window_source
|
|
299
|
+
self._window_claim_warned = False
|
|
300
|
+
self._thinking_budget = thinking_budget
|
|
301
|
+
#: 档位取代配置那次只说一遍(每请求刷屏没有信息量)
|
|
302
|
+
self._tier_supersede_warned = False
|
|
303
|
+
#: 与 `openai_compat` 同一个入口(见 `core/tokenizer.py`):
|
|
304
|
+
#: 安装版用随包词表,断网也构造得出来。
|
|
305
|
+
self._tokenizer = _get_tiktoken_encoding(self._tokenizer_encoding)
|
|
306
|
+
|
|
307
|
+
try:
|
|
308
|
+
from anthropic import Anthropic
|
|
309
|
+
except ImportError:
|
|
310
|
+
raise ImportError(
|
|
311
|
+
"anthropic SDK required. Install: pip install anthropic"
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
# `http_client=` 必须给:不给的话 SDK 造的
|
|
315
|
+
# `httpx.Client` 是 `trust_env=True`,会静默采纳环境变量里的
|
|
316
|
+
# `ALL_PROXY` —— 一条没在听的本地代理能把整轮对话卡死。
|
|
317
|
+
from core import net_proxy
|
|
318
|
+
|
|
319
|
+
#: `url=` 让指向本机 / 内网中转站的自定义 `base_url` 直连
|
|
320
|
+
#: (判据在 `core/net_proxy.is_local_target`,与设置页探针共用)。
|
|
321
|
+
_http = net_proxy.httpx_client(url=base_url or None)
|
|
322
|
+
# Anthropic SDK doesn't support custom base_url in the same way,
|
|
323
|
+
# but we support it for proxies
|
|
324
|
+
if base_url:
|
|
325
|
+
self._client = Anthropic(
|
|
326
|
+
api_key=api_key,
|
|
327
|
+
base_url=base_url,
|
|
328
|
+
http_client=_http,
|
|
329
|
+
)
|
|
330
|
+
else:
|
|
331
|
+
self._client = Anthropic(api_key=api_key, http_client=_http)
|
|
332
|
+
|
|
333
|
+
# v1.1.0: Self-calibrating token estimator
|
|
334
|
+
cal_name = model or "claude"
|
|
335
|
+
self._calibrator = TokenCalibrator(cal_name)
|
|
336
|
+
if self._calibrator.load():
|
|
337
|
+
print(f"[calibrator] Loaded {cal_name}: "
|
|
338
|
+
f"factor={self._calibrator.factor:.4f}, "
|
|
339
|
+
f"samples={self._calibrator.samples}")
|
|
340
|
+
else:
|
|
341
|
+
print(f"[calibrator] Fresh start for {cal_name} "
|
|
342
|
+
f"— will auto-calibrate after ~3 turns")
|
|
343
|
+
|
|
344
|
+
# ------------------------------------------------------------------
|
|
345
|
+
# 窗口声明的矛盾检测
|
|
346
|
+
# ------------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
def _check_window_claim(self, prompt_tokens: int) -> None:
|
|
349
|
+
"""上游报的输入量超过声明的窗口,声明值一定是错的,吼一声。
|
|
350
|
+
|
|
351
|
+
与 `providers/openai_compat.py` 的同名方法同款(那边有完整注释:
|
|
352
|
+
没有别的探测手段,这是唯一的免费探针;每个实例只吼一次)。
|
|
353
|
+
|
|
354
|
+
这里同时是「演算」那一层的入口(`window_estimate.observe`)
|
|
355
|
+
—— 它必须在 early-return 之前(下界与"超没超过声明"无关)。
|
|
356
|
+
"""
|
|
357
|
+
window_estimate.observe(self._model, prompt_tokens)
|
|
358
|
+
if self._window_claim_warned or prompt_tokens <= self._context_window:
|
|
359
|
+
return
|
|
360
|
+
self._window_claim_warned = True
|
|
361
|
+
print(
|
|
362
|
+
f"[window] prompt={prompt_tokens:,} 已超过声明窗口 "
|
|
363
|
+
f"{self._context_window:,} —— 声明值错了"
|
|
364
|
+
f"(来源={self._window_source},model={self._model})。"
|
|
365
|
+
f"压缩闸门按声明值算({int(self._context_window * 0.85):,}),"
|
|
366
|
+
f"会永远够不着。"
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
# ------------------------------------------------------------------
|
|
370
|
+
# BaseProvider interface
|
|
371
|
+
# ------------------------------------------------------------------
|
|
372
|
+
|
|
373
|
+
@property
|
|
374
|
+
def context_window(self) -> int:
|
|
375
|
+
return self._context_window
|
|
376
|
+
|
|
377
|
+
@property
|
|
378
|
+
def window_source(self) -> str:
|
|
379
|
+
"""这个窗口是谁给的 —— 没有别的探测手段,所以来源必须跟着值走。"""
|
|
380
|
+
return getattr(self, "_window_source", "未知")
|
|
381
|
+
|
|
382
|
+
def count_tokens(self, text: str) -> int:
|
|
383
|
+
"""用 tiktoken(`cl100k_base`)计数,与其他 provider 同一把尺。
|
|
384
|
+
|
|
385
|
+
不要改用 SDK 的 token 计数:`client.count_tokens(text)`
|
|
386
|
+
这个接口并不存在(SDK 提供的是
|
|
387
|
+
`client.messages.count_tokens(messages=...)`),退回 len(text) // 3
|
|
388
|
+
会得到约 0.33 tokens/字符,而中文约 0.53(1.9 字符/token)——
|
|
389
|
+
低估约 37%。
|
|
390
|
+
|
|
391
|
+
方向很重要:记忆层的预检估算走这个方法(经 `estimate_request_tokens`),
|
|
392
|
+
再与非 tiktoken 计数的窗口比较。这个 provider 上出现第二种
|
|
393
|
+
静默不同的单位,两端就会对不上(判据:预算两端必须同源)。
|
|
394
|
+
|
|
395
|
+
共用 `cl100k_base` 编码,保证跨 provider 只有一把尺。
|
|
396
|
+
"""
|
|
397
|
+
return len(self._tokenizer.encode(text))
|
|
398
|
+
|
|
399
|
+
def _thinking_kwargs(self, thinking) -> dict:
|
|
400
|
+
"""这一次请求的 `thinking` 参数 —— 一处定义、两条路共用。
|
|
401
|
+
|
|
402
|
+
`chat` 与 `chat_stream` 必须走同一段逻辑 —— 只改一条是看不见的,
|
|
403
|
+
要等有人把流式打开才发现。
|
|
404
|
+
|
|
405
|
+
四条(每条都有理由或代价):
|
|
406
|
+
① `thinking is None`,这一格不参与,走构造函数那个
|
|
407
|
+
`thinking_budget`(= 既有行为,逐字不变);
|
|
408
|
+
② 档位说 开,发 `adaptive`(见下);
|
|
409
|
+
③ 档位说 关,不发;配置里设过值的话打一行
|
|
410
|
+
(静默忽略一个改过的键比不许改更坏);
|
|
411
|
+
④ Anthropic 的硬约束(上游会拒,不是我们能选的):
|
|
412
|
+
`budget_tokens >= 1024` 且 `budget_tokens < max_tokens`。
|
|
413
|
+
越界就夹到合法区间并出声 —— 不发是白丢这一档的能力,
|
|
414
|
+
硬发是整个请求 400(那一轮直接没了)。
|
|
415
|
+
"""
|
|
416
|
+
if thinking is None:
|
|
417
|
+
# 辅助调用(摘要 / 标题 / 压缩):逐字保留既有行为 ——
|
|
418
|
+
# 配置里没设预算就是什么都不发。
|
|
419
|
+
budget = self._thinking_budget
|
|
420
|
+
elif getattr(thinking, "enabled", False):
|
|
421
|
+
# 档位说开,发 `adaptive`,不再发预算。
|
|
422
|
+
#
|
|
423
|
+
# 理由有三条,都不是口味:
|
|
424
|
+
# ① `budget_tokens` 这一格已经删除 —— 可 Anthropic 的
|
|
425
|
+
# `enabled` 形状必须带一个预算,没有预算就只能二选一:
|
|
426
|
+
# 编一个,或者用 `adaptive`;
|
|
427
|
+
# ② `adaptive` = 模型自己决定想多久,档位只改一个字符串;
|
|
428
|
+
# ③ 编一个预算就是第二根随档的旋钮,而"手段随档增长"没有先例。
|
|
429
|
+
# 这一格未在真实 Anthropic 端点上验证过
|
|
430
|
+
# (本机没配 anthropic 的 key)。枚举本身经过探针验证
|
|
431
|
+
# (`bogus` 会报错,上游硬校验
|
|
432
|
+
# `{adaptive, enabled, disabled}`)。
|
|
433
|
+
return {"thinking": {"type": "adaptive"}}
|
|
434
|
+
else:
|
|
435
|
+
budget = 0
|
|
436
|
+
if self._thinking_budget > 0 and not self._tier_supersede_warned:
|
|
437
|
+
self._tier_supersede_warned = True
|
|
438
|
+
print(f"[thinking] 投入档这一档是「不思考」—— config.yaml 的 "
|
|
439
|
+
f"anthropic.thinking_budget={self._thinking_budget} 被它取代"
|
|
440
|
+
f"(档位是唯一来源)")
|
|
441
|
+
if budget <= 0:
|
|
442
|
+
return {}
|
|
443
|
+
if budget < _MIN_THINKING_BUDGET:
|
|
444
|
+
print(f"[thinking] 预算 {budget} 低于 Anthropic 的下限 "
|
|
445
|
+
f"{_MIN_THINKING_BUDGET} —— 按 {_MIN_THINKING_BUDGET} 发")
|
|
446
|
+
budget = _MIN_THINKING_BUDGET
|
|
447
|
+
if budget >= self._max_tokens:
|
|
448
|
+
if self._max_tokens <= _MIN_THINKING_BUDGET:
|
|
449
|
+
print(f"[thinking] max_tokens={self._max_tokens} 容不下思考预算 "
|
|
450
|
+
f"(要 >{_MIN_THINKING_BUDGET})—— 这一次**不带思考**"
|
|
451
|
+
f"(硬发会被上游 400,整轮都没了)")
|
|
452
|
+
return {}
|
|
453
|
+
print(f"[thinking] 预算 {budget} >= max_tokens {self._max_tokens} "
|
|
454
|
+
f"—— 夹到 {self._max_tokens - 1}(上游硬约束)")
|
|
455
|
+
budget = self._max_tokens - 1
|
|
456
|
+
return {"thinking": {"type": "enabled", "budget_tokens": budget}}
|
|
457
|
+
|
|
458
|
+
def chat(
|
|
459
|
+
self,
|
|
460
|
+
messages: list[dict],
|
|
461
|
+
tools: list[dict] | None = None,
|
|
462
|
+
system: "str | list[str] | None" = None,
|
|
463
|
+
thinking=None,
|
|
464
|
+
temperature: "float | None" = None,
|
|
465
|
+
) -> ChatResponse:
|
|
466
|
+
"""向 Claude 发一条同步消息。"""
|
|
467
|
+
system_prompt, api_messages = self._to_anthropic_messages(
|
|
468
|
+
messages, system=system
|
|
469
|
+
)
|
|
470
|
+
api_tools = self._to_anthropic_tools(tools)
|
|
471
|
+
|
|
472
|
+
# 给校准器做预检估算 —— 计入 `system` 与 `tools`,
|
|
473
|
+
# 与 API 的 usage.input_tokens 对齐(见
|
|
474
|
+
# BaseProvider.estimate_request_tokens)。
|
|
475
|
+
#
|
|
476
|
+
# `tools` 传的是 OpenAI 形状,不是投影后的 `api_tools`:
|
|
477
|
+
# 压缩闸门量的是注册表里的 schema,校准器必须与闸门用同一台仪器,
|
|
478
|
+
# 否则因子拟合的量与它要修正的量不是同一个。
|
|
479
|
+
# 这条 wire 上形状差异只是几个 key 名的 token。
|
|
480
|
+
estimated_input = self.estimate_message_tokens(
|
|
481
|
+
messages, system=system, tools=tools
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
kwargs: dict = {
|
|
485
|
+
"model": self._model,
|
|
486
|
+
"messages": api_messages,
|
|
487
|
+
"max_tokens": self._max_tokens,
|
|
488
|
+
}
|
|
489
|
+
if system_prompt:
|
|
490
|
+
kwargs["system"] = system_prompt
|
|
491
|
+
if api_tools:
|
|
492
|
+
kwargs["tools"] = api_tools
|
|
493
|
+
kwargs.update(self._thinking_kwargs(thinking))
|
|
494
|
+
# 按次覆盖:`None` 时一个字都不加 ——
|
|
495
|
+
# 本 client 默认不发 temperature。
|
|
496
|
+
# 判据同接 `thinking=` 那条:`None` = 逐字节等于现状。
|
|
497
|
+
#它只在调用点显式传的时候才改变 wire,
|
|
498
|
+
# 不顺手改掉所有 anthropic 调用的采样温度。
|
|
499
|
+
if temperature is not None:
|
|
500
|
+
kwargs["temperature"] = self.resolve_temperature(temperature)
|
|
501
|
+
|
|
502
|
+
response = _create_with_retry(self._client, kwargs)
|
|
503
|
+
|
|
504
|
+
# Extract text and tool calls
|
|
505
|
+
content = ""
|
|
506
|
+
tool_calls = []
|
|
507
|
+
#: assistant 内容里的 image 块(base64)。
|
|
508
|
+
#: 只收 `source.type == "base64"`;`url` 来源不下载(出网闸)。
|
|
509
|
+
media: list = []
|
|
510
|
+
|
|
511
|
+
for block in response.content:
|
|
512
|
+
if block.type == "text":
|
|
513
|
+
content += block.text
|
|
514
|
+
elif block.type == "tool_use":
|
|
515
|
+
tool_calls.append({
|
|
516
|
+
"id": block.id,
|
|
517
|
+
"type": "function",
|
|
518
|
+
"function": {
|
|
519
|
+
"name": block.name,
|
|
520
|
+
"arguments": json.dumps(block.input),
|
|
521
|
+
},
|
|
522
|
+
})
|
|
523
|
+
elif block.type == "image":
|
|
524
|
+
# 与流式那条同一个收法(`_image_block_media`):
|
|
525
|
+
# 两处各写一份,迟早一处改了、另一处漏(`A11`)。
|
|
526
|
+
media.extend(_image_block_media(block))
|
|
527
|
+
|
|
528
|
+
it = response.usage.input_tokens
|
|
529
|
+
ot = response.usage.output_tokens
|
|
530
|
+
# 缓存命中:Anthropic 走 `cache_read_input_tokens`,
|
|
531
|
+
# 同一个 reader 认三种字段名,这里不用特判。
|
|
532
|
+
cache_hit = read_cache_hit(response.usage)
|
|
533
|
+
record_token_usage(it, ot, cache_hit=cache_hit,
|
|
534
|
+
provider=self._provider_name, model=self._model)
|
|
535
|
+
|
|
536
|
+
# 声明窗口与实际请求的硬矛盾检测(与 openai_compat 同款)
|
|
537
|
+
self._check_window_claim(it)
|
|
538
|
+
|
|
539
|
+
# 把上游的真实 token 数喂给校准器
|
|
540
|
+
if self._calibrator is not None and it > 0:
|
|
541
|
+
prev_factor = self._calibrator.factor
|
|
542
|
+
ratio = self._calibrator.feed(estimated=estimated_input, actual=it)
|
|
543
|
+
self._calibrator.save()
|
|
544
|
+
if self._calibrator.factor != prev_factor:
|
|
545
|
+
print(
|
|
546
|
+
f"[calibrator] Updated: "
|
|
547
|
+
f"est={estimated_input} actual={it} "
|
|
548
|
+
f"ratio={ratio:.2f} "
|
|
549
|
+
f"factor={self._calibrator.factor:.4f} "
|
|
550
|
+
f"({self._calibrator.samples} samples)"
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
return ChatResponse(
|
|
554
|
+
content=content or None,
|
|
555
|
+
tool_calls=tool_calls if tool_calls else None,
|
|
556
|
+
prompt_tokens=it,
|
|
557
|
+
completion_tokens=ot,
|
|
558
|
+
cache_hit_tokens=cache_hit,
|
|
559
|
+
# 这一轮 assistant 直接产出的图(没有就是 `None`)。
|
|
560
|
+
media=media or None,
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
async def chat_stream(
|
|
564
|
+
self,
|
|
565
|
+
messages: list[dict],
|
|
566
|
+
tools: list[dict] | None = None,
|
|
567
|
+
system: "str | list[str] | None" = None,
|
|
568
|
+
thinking=None,
|
|
569
|
+
temperature: "float | None" = None,
|
|
570
|
+
) -> AsyncIterator[StreamChunk]:
|
|
571
|
+
"""流式接收 Claude 的回复。"""
|
|
572
|
+
system_prompt, api_messages = self._to_anthropic_messages(
|
|
573
|
+
messages, system=system
|
|
574
|
+
)
|
|
575
|
+
api_tools = self._to_anthropic_tools(tools)
|
|
576
|
+
|
|
577
|
+
kwargs: dict = {
|
|
578
|
+
"model": self._model,
|
|
579
|
+
"messages": api_messages,
|
|
580
|
+
"max_tokens": self._max_tokens,
|
|
581
|
+
}
|
|
582
|
+
if system_prompt:
|
|
583
|
+
kwargs["system"] = system_prompt
|
|
584
|
+
if api_tools:
|
|
585
|
+
kwargs["tools"] = api_tools
|
|
586
|
+
# 流式这条路也必须接思考参数 —— 只改 `chat` 一条是看不见的。
|
|
587
|
+
kwargs.update(self._thinking_kwargs(thinking))
|
|
588
|
+
# 按次覆盖:`None` 时一个字都不加 ——
|
|
589
|
+
# 本 client 默认不发 temperature。
|
|
590
|
+
# 判据同接 `thinking=` 那条:`None` = 逐字节等于现状。
|
|
591
|
+
#它只在调用点显式传的时候才改变 wire,
|
|
592
|
+
# 不顺手改掉所有 anthropic 调用的采样温度。
|
|
593
|
+
if temperature is not None:
|
|
594
|
+
kwargs["temperature"] = self.resolve_temperature(temperature)
|
|
595
|
+
|
|
596
|
+
#: 连接 / 超时按固定节奏重试
|
|
597
|
+
#: (与 OpenAI 兼容那条同一条判据)。已经交出去的内容不能重来
|
|
598
|
+
#: —— 那会让用户看到两遍(`emitted`)。
|
|
599
|
+
from core import llm_retry
|
|
600
|
+
from core.llm_errors import headline
|
|
601
|
+
rstate: dict = {}
|
|
602
|
+
while True:
|
|
603
|
+
emitted = False
|
|
604
|
+
try:
|
|
605
|
+
with self._client.messages.stream(**kwargs) as stream:
|
|
606
|
+
for event in stream:
|
|
607
|
+
for _chunk in map_stream_event(event):
|
|
608
|
+
emitted = True
|
|
609
|
+
yield _chunk
|
|
610
|
+
llm_retry.clear(_session_key())
|
|
611
|
+
return
|
|
612
|
+
except Exception as e:
|
|
613
|
+
transport = classify_transport_error(e)
|
|
614
|
+
kind = classify_api_error(e) or transport or ""
|
|
615
|
+
action, delay = (("no_retry", 0) if emitted
|
|
616
|
+
else llm_retry.step(rstate, kind))
|
|
617
|
+
if action in ("retry", "silent"):
|
|
618
|
+
n = int(rstate.get("silent") or 0) if action == "silent" \
|
|
619
|
+
else int(rstate.get("retry") or 0)
|
|
620
|
+
llm_retry.note(_session_key(), n, kind=kind,
|
|
621
|
+
text=headline(e, kind=kind), phase=action)
|
|
622
|
+
print(f"[llm] {kind or 'unknown'} —— {delay}ms 后重试"
|
|
623
|
+
f"({action} {n})")
|
|
624
|
+
#: 可打断(同 OpenAI 兼容那条)。
|
|
625
|
+
if not await llm_retry.wait_async(_session_key(), delay):
|
|
626
|
+
llm_retry.clear(_session_key())
|
|
627
|
+
yield StreamChunk(content="")
|
|
628
|
+
return
|
|
629
|
+
continue
|
|
630
|
+
#: 与 OpenAI 兼容那条同一条诊断口径 —— 错误类别跟着 chunk 走
|
|
631
|
+
#: (用户面 `core/llm_errors.explain` 要用),并且出声。
|
|
632
|
+
print(f"[llm] 流式失败({type(e).__name__}: {str(e)[:200]})"
|
|
633
|
+
f" —— model={self._model}")
|
|
634
|
+
llm_retry.fail(_session_key(), kind=kind,
|
|
635
|
+
text=headline(e, kind=kind))
|
|
636
|
+
yield StreamChunk(
|
|
637
|
+
error=str(e),
|
|
638
|
+
error_kind=kind)
|
|
639
|
+
return
|
|
640
|
+
|
|
641
|
+
async def test_connection(self) -> dict:
|
|
642
|
+
"""ping 一次 Claude,验证 API key。"""
|
|
643
|
+
try:
|
|
644
|
+
resp = self._client.messages.create(
|
|
645
|
+
model=self._model,
|
|
646
|
+
messages=[{"role": "user", "content": "ping"}],
|
|
647
|
+
max_tokens=1,
|
|
648
|
+
)
|
|
649
|
+
return {"ok": True, "message": f"Claude reachable (model={self._model})"}
|
|
650
|
+
except Exception as e:
|
|
651
|
+
return {"ok": False, "message": f"Connection failed: {e}"}
|
|
652
|
+
|
|
653
|
+
# ------------------------------------------------------------------
|
|
654
|
+
# Message format translation
|
|
655
|
+
# ------------------------------------------------------------------
|
|
656
|
+
|
|
657
|
+
# (helper `_to_anthropic_content` lives at module level — see below)
|
|
658
|
+
|
|
659
|
+
def _to_anthropic_messages(
|
|
660
|
+
self, messages: list[dict], system: "str | list[str] | None" = None
|
|
661
|
+
) -> tuple[str, list[dict]]:
|
|
662
|
+
"""把 OpenAI 格式的消息转成 Anthropic 格式。
|
|
663
|
+
|
|
664
|
+
Anthropic 有原生顶层 `system` 字段,所以这个类是系统提示词
|
|
665
|
+
唯一不必伪装成消息的地方。`system` 参数以 `kwargs["system"]`
|
|
666
|
+
发出,别的都不走那里。
|
|
667
|
+
|
|
668
|
+
**列表内的 `role="system"` 消息原地降级为 `user`,
|
|
669
|
+
不被提升到顶部。理由:
|
|
670
|
+
|
|
671
|
+
* 提升会把历史挪到指令之上。恢复历史的标记是位置相关的:
|
|
672
|
+
`<history_start>` … 轮次 … `<history_end>` 只有在原地才有意义。
|
|
673
|
+
拼成一个字符串放到顶部,模型会把一段旧对话当成当前指令 ——
|
|
674
|
+
"历史伪装成指令"那类故障只是换到了 provider 里。
|
|
675
|
+
* 降级为 `user` 是唯一遇到同样约束时的做法:只有一个 system 槽位,
|
|
676
|
+
没占上槽位的 system 消息折进 user 消息以保持顺序。
|
|
677
|
+
* Anthropic Messages API 会在服务端合并相邻的同角色轮次,
|
|
678
|
+
所以把标记折进相邻的 `user` 轮是安全的。
|
|
679
|
+
|
|
680
|
+
`system` 接受普通字符串或块列表;块用 :func:`flatten_system`
|
|
681
|
+
拍平(这里还没有 Anthropic 侧的缓存断点支持 —— 将来有时就在这里长,
|
|
682
|
+
这也是参数不标注成 `str` 的原因)。
|
|
683
|
+
|
|
684
|
+
返回:
|
|
685
|
+
(system_text: str, api_messages: list[dict])
|
|
686
|
+
"""
|
|
687
|
+
system_text = flatten_system(system)
|
|
688
|
+
api_messages = []
|
|
689
|
+
|
|
690
|
+
for msg in messages:
|
|
691
|
+
role = msg.get("role", "")
|
|
692
|
+
content = msg.get("content")
|
|
693
|
+
# 带图的 user 轮是块列表,而
|
|
694
|
+
# Anthropic 的块形状与 OpenAI 不同:
|
|
695
|
+
# OpenAI {"type": "image_url", "image_url": {"url": "data:…"}}
|
|
696
|
+
# Anthropic {"type": "image", "source": {"type": "base64",
|
|
697
|
+
# "media_type": …, "data": …}}
|
|
698
|
+
# 不翻译就直接透传,上游 400,而报错说的是
|
|
699
|
+
# "content.0.type: Input tag 'image_url' …",看不出是我们的锅。
|
|
700
|
+
# 翻译只在这一处(本函数是 Anthropic 唯一的消息投影),
|
|
701
|
+
# 与 `_wire_messages` 在 OpenAI 那条路上是同一条判据。
|
|
702
|
+
content = _to_anthropic_content(content)
|
|
703
|
+
|
|
704
|
+
if role == "system":
|
|
705
|
+
api_messages.append({"role": "user", "content": content})
|
|
706
|
+
continue
|
|
707
|
+
|
|
708
|
+
if role == "user":
|
|
709
|
+
api_messages.append({"role": "user", "content": content})
|
|
710
|
+
elif role == "assistant":
|
|
711
|
+
entry: dict = {"role": "assistant", "content": content}
|
|
712
|
+
# Handle tool_calls if present
|
|
713
|
+
tool_calls = msg.get("tool_calls")
|
|
714
|
+
if tool_calls:
|
|
715
|
+
tool_blocks = []
|
|
716
|
+
for tc in tool_calls:
|
|
717
|
+
name = tc["function"]["name"]
|
|
718
|
+
# 历史里那条 `tool_calls` 是模型的原样输出,
|
|
719
|
+
# 坏 JSON(以及流式无参调用的空串)会一路留在会话里。
|
|
720
|
+
# 直接 `json.loads`,一旦撞上,**整个请求崩在
|
|
721
|
+
# provider 内部**:上游看不到,我们只看到一句
|
|
722
|
+
# JSONDecodeError,从它反推"是历史坏了"要绕一大圈。
|
|
723
|
+
#判据是"历史必须始终可重发":坏的就按无参回填并出声。
|
|
724
|
+
# 不改历史 —— 修在消费端(一处),不在 N 个生产端。
|
|
725
|
+
raw_args = tc["function"]["arguments"]
|
|
726
|
+
try:
|
|
727
|
+
args = json.loads(raw_args)
|
|
728
|
+
except (json.JSONDecodeError, TypeError) as exc:
|
|
729
|
+
args = {}
|
|
730
|
+
print(f"[anthropic] 历史里 '{name}' 的 arguments 不是合法 "
|
|
731
|
+
f"JSON({type(exc).__name__}: {exc})—— 按无参回填"
|
|
732
|
+
f"(历史本身不动)")
|
|
733
|
+
tool_blocks.append({
|
|
734
|
+
"type": "tool_use",
|
|
735
|
+
"id": tc.get("id", ""),
|
|
736
|
+
"name": name,
|
|
737
|
+
"input": args,
|
|
738
|
+
})
|
|
739
|
+
entry["content"] = tool_blocks
|
|
740
|
+
api_messages.append(entry)
|
|
741
|
+
elif role == "tool":
|
|
742
|
+
# Anthropic: tool results go in a user message
|
|
743
|
+
tc_id = msg.get("tool_call_id", "")
|
|
744
|
+
api_messages.append({
|
|
745
|
+
"role": "user",
|
|
746
|
+
"content": [
|
|
747
|
+
{
|
|
748
|
+
"type": "tool_result",
|
|
749
|
+
"tool_use_id": tc_id,
|
|
750
|
+
"content": content,
|
|
751
|
+
}
|
|
752
|
+
],
|
|
753
|
+
})
|
|
754
|
+
|
|
755
|
+
return (system_text, api_messages)
|
|
756
|
+
|
|
757
|
+
def _to_anthropic_tools(
|
|
758
|
+
self, tools: list[dict] | None
|
|
759
|
+
) -> list[dict] | None:
|
|
760
|
+
"""把 OpenAI 格式的工具定义转成 Anthropic 格式。"""
|
|
761
|
+
if not tools:
|
|
762
|
+
return None
|
|
763
|
+
|
|
764
|
+
result = []
|
|
765
|
+
for tool in tools:
|
|
766
|
+
fn = tool.get("function", {})
|
|
767
|
+
result.append({
|
|
768
|
+
"name": fn.get("name", ""),
|
|
769
|
+
"description": fn.get("description", ""),
|
|
770
|
+
"input_schema": fn.get("parameters", {}),
|
|
771
|
+
})
|
|
772
|
+
return result
|