docs: 将仓库代码注释统一为中文
CI / docs-check (push) Canceled after 0s
CI / backend-test (push) Canceled after 0s
CI / service-test (push) Canceled after 0s
CI / frontend-test (push) Canceled after 0s
CI / rust-core (push) Canceled after 0s
CI / docs-check (pull_request) Canceled after 0s
CI / backend-test (pull_request) Canceled after 0s
CI / service-test (pull_request) Canceled after 0s
CI / frontend-test (pull_request) Canceled after 0s
CI / rust-core (pull_request) Canceled after 0s

This commit is contained in:
2026-09-10 00:40:56 +08:00
parent 51c592841d
commit d703ab64e3
249 changed files with 707 additions and 900 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
"""Native Anthropic Messages protocol with incrementally decoded content blocks."""
"""原生 Anthropic Messages 协议,支持增量解码内容块。"""
import json
from contextlib import aclosing
@@ -135,7 +135,7 @@ class AnthropicMessagesProvider(OpenAICompatibleProvider):
fragment = string_value(delta.get("partial_json"))
block["arguments"] += fragment
yield ModelEventType.tool_call_delta, {"tool_call_id": block["id"], "arguments_delta": fragment}
# Signatures and future delta types have no representation in ModelEvent.
# 签名和未来​​的增量类型在 ModelEvent 中没有表示。
elif kind == "content_block_stop":
block = blocks.get(token_count(data.get("index")))
if block is None or block["closed"]:
+7 -7
View File
@@ -1,4 +1,4 @@
"""Opt-in, model-scoped text context checks. Estimates are not vendor token counts."""
"""按需启用、限定模型范围的文本上下文检查;估算值不等同于供应商的 token 计数。"""
import json
import math
@@ -7,8 +7,8 @@ from app.providers.base import ProviderError
def estimate(request):
# Include system, tool schemas and call arguments. A conservative UTF-8 heuristic
# still cannot replace the model's tokenizer or account for hidden reasoning.
# 统计系统提示、工具结构与调用参数。保守的 UTF-8 启发式无法取代模型分词器,
# 也无法计入隐藏推理。
body = {"system": request.system, "messages": [m.model_dump(mode="json") for m in request.messages],
"tools": [t.model_dump(mode="json") for t in request.tools], "format": request.response_format}
return math.ceil(len(json.dumps(body, ensure_ascii=False).encode("utf-8")) / 2) + 64
@@ -42,8 +42,8 @@ async def prepare_context(request, config, complete, *, stream=False):
message = f"上下文估算约 {before:,} Token,输入预算 {budget:,},已达到 {policy.threshold:.0%} 阈值。"
if policy.mode == "detect":
raise ProviderError("CONTEXT_COMPRESSION_REQUIRED", message + " 请在 Provider 表单启用历史摘要压缩,或新建对话。")
# Only compact completed plain-text turns. Tool chains have protocol-specific
# reasoning state; never split them or silently discard their signed content.
# 只压缩已经完成的纯文本轮次。工具调用链包含协议特定的推理状态,
# 不得拆分,也不能静默丢弃其签名内容。
if any(m.tool_calls or m.role == MessageRole.tool for m in request.messages):
raise ProviderError("CONTEXT_COMPRESSION_UNSUPPORTED", message + " 工具调用历史需完整保留,请新建对话。")
users = [i for i, m in enumerate(request.messages) if m.role == MessageRole.user]
@@ -59,7 +59,7 @@ async def prepare_context(request, config, complete, *, stream=False):
system=policy.prompt, messages=[Message(role=MessageRole.user,
content=json.dumps([m.model_dump(mode="json") for m in history], ensure_ascii=False))],
max_tokens=min(policy.output_reserve, 2048), metadata={**request.metadata, "purpose": "context_compression"})
# Detect oversize summarization itself before sending. No truncation or retry loop.
# 发送前检查摘要本身是否超限;不执行截断或循环重试。
if estimate(summary_request) + reserve >= policy.context_window:
raise ProviderError("CONTEXT_COMPRESSION_REQUIRED", message + " 历史过长,摘要请求也会超限,请新建对话或缩短历史。")
from app.services.usage_service import usage_context
@@ -76,7 +76,7 @@ async def prepare_context(request, config, complete, *, stream=False):
if not result.text or not result.text.strip() or result.tool_calls:
raise ProviderError("CONTEXT_COMPRESSION_FAILED", "模型未返回有效摘要,原对话未修改。")
prepared = request.model_copy(deep=True)
# Summary is conversation data, never promoted to system instructions.
# 摘要是对话数据,从未提升为系统指令。
prepared.messages = [*systems, Message(role=MessageRole.user, content="历史对话摘要(仅供参考):\n" + result.text),
Message(role=MessageRole.assistant, content="已记录历史摘要。"), *retained]
if estimate(prepared) >= budget or estimate(prepared) >= before:
+1 -1
View File
@@ -26,7 +26,7 @@ class CredentialResolver(Protocol):
class HostCredentialStore:
"""Desktop-only adapter. It cannot fall back to Fernet or environment keys."""
"""仅限桌面适配器。它不能回退到 Fernet 或环境密钥。"""
@staticmethod
def _call(method, **params):
from app.host_bridge import active
+1 -1
View File
@@ -106,7 +106,7 @@ class ProviderFactory:
requires_credential=False,
),
]
# General API endpoints. Coding-plan endpoints and keys are separate products.
# 通用 API 端点。编码计划端点和密钥是单独的产品。
domestic = [
("kimi", "Kimi / 月之暗面", "https://api.moonshot.cn/v1", [], "长上下文对话;模型以账号权限为准。"),
("qwen", "阿里云百炼", "https://dashscope.aliyuncs.com/compatible-mode/v1", [ModelCapability.embedding], "中国内地兼容接口;海外地域需修改地址。"),
+6 -6
View File
@@ -119,7 +119,7 @@ def token_count(value: object) -> int:
def remote_error(value: object) -> ProviderError:
# Never reflect upstream messages, URLs, request bodies or credentials.
# 绝不反映上游消息、URL、请求正文或凭据。
error = value if isinstance(value, dict) else {}
code = error.get("code") or error.get("type")
mapping = {
@@ -144,7 +144,7 @@ def check_error(data: dict) -> None:
class UsageTracker:
"""Merge cumulative snapshots, including partial usage updates."""
"""合并累积快照,包括部分使用情况更新。"""
def __init__(self, input_key: str = "input_tokens", output_key: str = "output_tokens",
*, cache_tokens: bool = False) -> None:
@@ -173,7 +173,7 @@ class EventStreamingMixin:
status = "completed"
try:
request, originals = prepare_tool_names(request)
# Closing the public iterator must synchronously close every nested iterator.
# 关闭公共迭代器必须同步关闭每个嵌套迭代器。
async with aclosing(self._events(request)) as events:
async for kind, data in events:
if kind == ModelEventType.tool_call_start and "name" in data:
@@ -196,14 +196,14 @@ class EventStreamingMixin:
data={"code": error.code, "message": error.message},
timestamp=datetime.now(timezone.utc))
sequence += 1
# CancelledError and GeneratorExit deliberately propagate without a Done event.
# CancelledError GeneratorExit 特意在没有 Done 事件的情况下传播。
yield ModelEvent(event=ModelEventType.done, sequence=sequence,
data={"status": status},
timestamp=datetime.now(timezone.utc))
async def sse_objects(response: httpx.Response) -> AsyncIterator[dict]:
"""Read SSE frames, accepting the adjacent data lines used by some gateways."""
"""读取SSE帧,接受某些网关使用的相邻数据线。"""
parts: list[str] = []
event_name = ""
@@ -235,7 +235,7 @@ async def sse_objects(response: httpx.Response) -> AsyncIterator[dict]:
event_name = line[6:].strip()
elif line.startswith("data:"):
if parts:
# Legacy compatible endpoints sometimes omit blank separators.
# 传统兼容端点有时会省略空白分隔符。
try:
json.loads("\n".join(parts))
except ValueError:
+3 -3
View File
@@ -115,7 +115,7 @@ class OpenAICompatibleProvider(EventStreamingMixin, HTTPProviderMixin):
if not call["name"]:
raise invalid_response()
decode_tool_arguments(call["arguments"] or "{}")
# A name can span multiple chunks; publish only the complete identity.
# 一个名称可以跨越多个块;仅公布完整身份。
call["id"] = call["id"] or f"call_{uuid4().hex}"
yield ModelEventType.tool_call_start, {"tool_call_id": call["id"], "name": call["name"]}
yield ModelEventType.tool_call_delta, {"tool_call_id": call["id"], "arguments_delta": call["arguments"] or "{}"}
@@ -130,8 +130,8 @@ class OpenAICompatibleProvider(EventStreamingMixin, HTTPProviderMixin):
@staticmethod
def _model_capabilities(model: str) -> list[ModelCapability]:
# /models does not advertise capabilities. Avoid known non-chat families;
# these are discovery hints, not a guarantee of support by a gateway.
# /models 不会声明能力,因此排除已知的非聊天模型系列;这些仅用于辅助发现,
# 不能保证网关实际支持。
name = model.lower()
if "embed" in name or name.startswith(("bge-", "bge/")):
return [ModelCapability.embedding]
+1 -1
View File
@@ -1,4 +1,4 @@
"""Native /responses adapter; stateless history uses function_call/output items."""
"""本机 /responses 适配器;无状态历史记录使用 function_call/输出项。"""
import json
from contextlib import aclosing
+4 -5
View File
@@ -1,7 +1,6 @@
"""Capability routing: validated remote results, then an explicit local backend.
"""能力路由:先验证远程结果,再显式回退到本地后端。
Production injects installed CPU/CUDA backends. Deterministic embeddings remain
available only for explicitly injected tests and protocol fixtures.
生产环境注入已安装的 CPU/CUDA 后端;确定性嵌入只供显式注入的测试与协议夹具使用。
"""
from __future__ import annotations
@@ -226,7 +225,7 @@ class ModelRoutingService:
try:
vectors = []
dimension = binding.dimensions
# Freeze the origin across batches, even if the user edits the provider.
# 跨批次冻结源,即使用户编辑提供程序也是如此。
remote = self._remote(binding)
provider_config = self.providers.get(binding.provider_id).config.model_copy(deep=True)
for start in range(0, len(texts), 32):
@@ -351,7 +350,7 @@ class ModelRoutingService:
reason = None
if binding:
try:
# Explicit application contract, not an OpenAI-standard endpoint.
# 这是应用自身定义的接口约定,并非 OpenAI 标准端点。
with self._media_file(source) as audio, self._media_file(reference) as sample:
data, _ = await self._request(binding, data={"model": binding.model}, files={
"file": (source.name, audio, "application/octet-stream"),
+1 -1
View File
@@ -1,4 +1,4 @@
"""Keep internal namespaced tools compatible with providers' 64-character names."""
"""保持内部命名空间工具与提供程序的 64 字符名称兼容。"""
import hashlib
import re
from functools import wraps