txcode-sdk 1.3.0__py3-none-any.whl → 1.5.0__py3-none-any.whl
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.
- txcode_sdk/__init__.py +1 -1
- txcode_sdk/client.py +44 -3
- txcode_sdk/config/__init__.py +25 -2
- txcode_sdk/config/ai_settings.py +42 -0
- txcode_sdk/provider/base.py +16 -1
- txcode_sdk/provider/deepseek_provider.py +41 -35
- txcode_sdk/provider/openai_provider.py +41 -34
- txcode_sdk/provider/router.py +10 -3
- txcode_sdk/server/__main__.py +49 -0
- txcode_sdk/server/config_store.py +36 -4
- txcode_sdk/server/handler.py +21 -0
- txcode_sdk/server/http/__init__.py +14 -3
- txcode_sdk/server/http/http_base.py +50 -11
- txcode_sdk/server/http/sys_config_routes.py +355 -288
- txcode_sdk/server/provider_config.py +101 -1
- txcode_sdk/server/services/config_import_export.py +148 -0
- txcode_sdk/server/services/provider_service.py +14 -0
- txcode_sdk/server/yaml_lite.py +734 -0
- {txcode_sdk-1.3.0.dist-info → txcode_sdk-1.5.0.dist-info}/METADATA +63 -1
- {txcode_sdk-1.3.0.dist-info → txcode_sdk-1.5.0.dist-info}/RECORD +24 -21
- {txcode_sdk-1.3.0.dist-info → txcode_sdk-1.5.0.dist-info}/WHEEL +0 -0
- {txcode_sdk-1.3.0.dist-info → txcode_sdk-1.5.0.dist-info}/entry_points.txt +0 -0
- {txcode_sdk-1.3.0.dist-info → txcode_sdk-1.5.0.dist-info}/licenses/LICENSE +0 -0
- {txcode_sdk-1.3.0.dist-info → txcode_sdk-1.5.0.dist-info}/top_level.txt +0 -0
txcode_sdk/__init__.py
CHANGED
txcode_sdk/client.py
CHANGED
|
@@ -15,6 +15,11 @@ from .types import (
|
|
|
15
15
|
from .provider.router import ProviderRouter
|
|
16
16
|
from .session.manager import SessionManager
|
|
17
17
|
from .compact.compressor import ContextCompressor
|
|
18
|
+
from .config.ai_settings import (
|
|
19
|
+
DEFAULT_REASONING_EFFORT,
|
|
20
|
+
normalize_positive_int,
|
|
21
|
+
normalize_reasoning_effort,
|
|
22
|
+
)
|
|
18
23
|
from .config.context_config import merge_context_config
|
|
19
24
|
from .agent.factory import create_agent
|
|
20
25
|
from .agent.tool_registry import ToolRegistry
|
|
@@ -38,6 +43,7 @@ class TxCodeClient:
|
|
|
38
43
|
log_enabled: bool = False,
|
|
39
44
|
context_config: Optional[Dict[str, Any]] = None,
|
|
40
45
|
model_context_window: Optional[int] = None,
|
|
46
|
+
reasoning_effort: str = DEFAULT_REASONING_EFFORT,
|
|
41
47
|
):
|
|
42
48
|
self._api_key = api_key
|
|
43
49
|
self._base_url = base_url
|
|
@@ -51,8 +57,11 @@ class TxCodeClient:
|
|
|
51
57
|
self._log_enabled = log_enabled
|
|
52
58
|
self._context_config = merge_context_config(context_config)
|
|
53
59
|
self._model_context_window = model_context_window
|
|
60
|
+
self._reasoning_effort = normalize_reasoning_effort(reasoning_effort)
|
|
54
61
|
|
|
55
|
-
self._provider = ProviderRouter.create(
|
|
62
|
+
self._provider = ProviderRouter.create(
|
|
63
|
+
api_key, base_url, model, reasoning_effort=self._reasoning_effort
|
|
64
|
+
)
|
|
56
65
|
self._session_manager = SessionManager(self._work_dir)
|
|
57
66
|
self._compressor = ContextCompressor(
|
|
58
67
|
max_tokens=max_context_tokens,
|
|
@@ -82,7 +91,9 @@ class TxCodeClient:
|
|
|
82
91
|
|
|
83
92
|
def set_model(self, model: str):
|
|
84
93
|
"""当前供应商内切模型:同类型原地切换,跨类型(deepseek 判定翻转)重建并同步压缩器。"""
|
|
85
|
-
new_provider = ProviderRouter.create(
|
|
94
|
+
new_provider = ProviderRouter.create(
|
|
95
|
+
self._api_key, self._base_url, model, reasoning_effort=self._reasoning_effort
|
|
96
|
+
)
|
|
86
97
|
if type(new_provider) is type(self._provider) and \
|
|
87
98
|
new_provider.get_base_url() == self._provider.get_base_url():
|
|
88
99
|
self._provider.set_model(model)
|
|
@@ -94,9 +105,39 @@ class TxCodeClient:
|
|
|
94
105
|
def set_provider(self, api_key: str, base_url: str, model: str):
|
|
95
106
|
"""切供应商:api_key/base_url/model 均可变,重建 Provider 并同步压缩器。"""
|
|
96
107
|
self._api_key, self._base_url, self._model = api_key, base_url, model
|
|
97
|
-
self._provider = ProviderRouter.create(
|
|
108
|
+
self._provider = ProviderRouter.create(
|
|
109
|
+
api_key, base_url, model, reasoning_effort=self._reasoning_effort
|
|
110
|
+
)
|
|
98
111
|
self._compressor._provider = self._provider
|
|
99
112
|
|
|
113
|
+
def get_max_context_tokens(self) -> int:
|
|
114
|
+
return self._max_context_tokens
|
|
115
|
+
|
|
116
|
+
def set_max_context_tokens(self, max_context_tokens: int):
|
|
117
|
+
"""热更新上下文大小:双写压缩阈值与展示配置(mode 保持 fixed)。"""
|
|
118
|
+
value = normalize_positive_int(max_context_tokens, self._max_context_tokens)
|
|
119
|
+
self._max_context_tokens = value
|
|
120
|
+
self._compressor._max_tokens = value
|
|
121
|
+
self._context_config["mode"] = "fixed"
|
|
122
|
+
self._context_config["max_tokens"] = value
|
|
123
|
+
self._compressor._context_config = self._context_config
|
|
124
|
+
|
|
125
|
+
def get_max_iterations(self) -> int:
|
|
126
|
+
return self._max_iterations
|
|
127
|
+
|
|
128
|
+
def set_max_iterations(self, max_iterations: int):
|
|
129
|
+
"""热更新循环次数:下次 chat 的 create_agent 生效(含 prompt 占位符)。"""
|
|
130
|
+
self._max_iterations = normalize_positive_int(max_iterations, self._max_iterations)
|
|
131
|
+
|
|
132
|
+
def get_reasoning_effort(self) -> str:
|
|
133
|
+
return self._reasoning_effort
|
|
134
|
+
|
|
135
|
+
def set_reasoning_effort(self, reasoning_effort: str):
|
|
136
|
+
"""热更新思考强度:同步当前 Provider 请求体构造。"""
|
|
137
|
+
self._reasoning_effort = normalize_reasoning_effort(reasoning_effort)
|
|
138
|
+
if self._provider is not None:
|
|
139
|
+
self._provider.set_reasoning_effort(self._reasoning_effort)
|
|
140
|
+
|
|
100
141
|
def set_work_dir(self, work_dir: str):
|
|
101
142
|
"""切项目(工作目录):重建会话存储并同步压缩器。"""
|
|
102
143
|
self._work_dir = work_dir
|
txcode_sdk/config/__init__.py
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
|
-
"""txcode_sdk.config
|
|
1
|
+
"""txcode_sdk.config:上下文压缩配置 + AI 运行参数(上下文大小/迭代次数/思考强度)。"""
|
|
2
2
|
|
|
3
|
+
from .ai_settings import (
|
|
4
|
+
DEFAULT_CONTEXT_MAX_TOKENS,
|
|
5
|
+
DEFAULT_MAX_ITERATIONS,
|
|
6
|
+
DEFAULT_REASONING_EFFORT,
|
|
7
|
+
KEY_CONTEXT_MAX_TOKENS,
|
|
8
|
+
KEY_MAX_ITERATIONS,
|
|
9
|
+
KEY_REASONING_EFFORT,
|
|
10
|
+
REASONING_EFFORTS,
|
|
11
|
+
normalize_positive_int,
|
|
12
|
+
normalize_reasoning_effort,
|
|
13
|
+
)
|
|
3
14
|
from .context_config import DEFAULT_CONTEXT_CONFIG, merge_context_config
|
|
4
15
|
|
|
5
|
-
__all__ = [
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DEFAULT_CONTEXT_CONFIG",
|
|
18
|
+
"merge_context_config",
|
|
19
|
+
"REASONING_EFFORTS",
|
|
20
|
+
"KEY_CONTEXT_MAX_TOKENS",
|
|
21
|
+
"KEY_MAX_ITERATIONS",
|
|
22
|
+
"KEY_REASONING_EFFORT",
|
|
23
|
+
"DEFAULT_CONTEXT_MAX_TOKENS",
|
|
24
|
+
"DEFAULT_MAX_ITERATIONS",
|
|
25
|
+
"DEFAULT_REASONING_EFFORT",
|
|
26
|
+
"normalize_reasoning_effort",
|
|
27
|
+
"normalize_positive_int",
|
|
28
|
+
]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""ai_settings:对齐 txcode(TS 版)ConfigService 的三项 AI 运行参数。
|
|
2
|
+
|
|
3
|
+
集中承载「配置键名 + 默认值 + 规范化」,避免 key 字符串散落各模块:
|
|
4
|
+
|
|
5
|
+
- 上下文大小 ``ai.context.maxTokens`` 默认 150000(对应压缩阈值)
|
|
6
|
+
- 循环次数 ``ai.maxIterations`` 默认 1000
|
|
7
|
+
- 思考强度 ``ai.reasoningEffort`` 默认 max(白名单 none/minimal/low/medium/high/xhigh/max)
|
|
8
|
+
|
|
9
|
+
Python 3.6 兼容,零第三方依赖。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
REASONING_EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
|
|
15
|
+
|
|
16
|
+
KEY_CONTEXT_MAX_TOKENS = "ai.context.maxTokens"
|
|
17
|
+
KEY_MAX_ITERATIONS = "ai.maxIterations"
|
|
18
|
+
KEY_REASONING_EFFORT = "ai.reasoningEffort"
|
|
19
|
+
|
|
20
|
+
DEFAULT_CONTEXT_MAX_TOKENS = 150_000
|
|
21
|
+
DEFAULT_MAX_ITERATIONS = 1000
|
|
22
|
+
DEFAULT_REASONING_EFFORT = "max"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize_reasoning_effort(value: Any) -> str:
|
|
26
|
+
"""白名单精确命中则原样返回,非法/None → ``max``(对齐 TS getReasoningEffort)。"""
|
|
27
|
+
if isinstance(value, str) and value in REASONING_EFFORTS:
|
|
28
|
+
return value
|
|
29
|
+
return DEFAULT_REASONING_EFFORT
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def normalize_positive_int(value: Any, default: int) -> int:
|
|
33
|
+
"""可转为正整数则返回该值,非法/None/非正 → ``default``(对齐 TS getMaxContextTokens)。"""
|
|
34
|
+
if isinstance(value, bool):
|
|
35
|
+
return default
|
|
36
|
+
try:
|
|
37
|
+
number = int(value)
|
|
38
|
+
except (TypeError, ValueError):
|
|
39
|
+
return default
|
|
40
|
+
if number <= 0:
|
|
41
|
+
return default
|
|
42
|
+
return number
|
txcode_sdk/provider/base.py
CHANGED
|
@@ -12,6 +12,7 @@ from datetime import datetime, timezone
|
|
|
12
12
|
from pathlib import Path
|
|
13
13
|
from typing import Any, AsyncGenerator, Dict, List, Optional, Union
|
|
14
14
|
|
|
15
|
+
from ..config.ai_settings import DEFAULT_REASONING_EFFORT, normalize_reasoning_effort
|
|
15
16
|
from ..types import ChatMessage, ImageContent, ProviderResponse, TokenUsage
|
|
16
17
|
|
|
17
18
|
|
|
@@ -29,9 +30,15 @@ def _resolve_image_url(url: str) -> str:
|
|
|
29
30
|
|
|
30
31
|
|
|
31
32
|
class BaseProvider(ABC):
|
|
32
|
-
def __init__(
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
base_url: str = "",
|
|
36
|
+
model: str = "",
|
|
37
|
+
reasoning_effort: Optional[str] = None,
|
|
38
|
+
):
|
|
33
39
|
self._base_url = base_url
|
|
34
40
|
self._model = model
|
|
41
|
+
self._reasoning_effort = normalize_reasoning_effort(reasoning_effort)
|
|
35
42
|
|
|
36
43
|
@abstractmethod
|
|
37
44
|
async def chat(
|
|
@@ -62,6 +69,14 @@ class BaseProvider(ABC):
|
|
|
62
69
|
"""运行期切换模型(base_url/api_key 不变,子类公共实现)。"""
|
|
63
70
|
self._model = model
|
|
64
71
|
|
|
72
|
+
def get_reasoning_effort(self) -> str:
|
|
73
|
+
"""当前思考强度(none/minimal/low/medium/high/xhigh/max),默认 max。"""
|
|
74
|
+
return getattr(self, "_reasoning_effort", DEFAULT_REASONING_EFFORT)
|
|
75
|
+
|
|
76
|
+
def set_reasoning_effort(self, value: Optional[str]):
|
|
77
|
+
"""运行期切换思考强度(非法值回退 max)。"""
|
|
78
|
+
self._reasoning_effort = normalize_reasoning_effort(value)
|
|
79
|
+
|
|
65
80
|
def _write_log(self, log_context: dict, event: str, extra: dict):
|
|
66
81
|
work_dir = log_context.get("work_dir", ".")
|
|
67
82
|
log_dir = Path(work_dir) / ".txcode" / "log"
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""DeepSeek Provider:对齐 TS 端 deepseek.provider.ts 行为,直接继承 BaseProvider。
|
|
2
2
|
|
|
3
|
-
- chat
|
|
4
|
-
|
|
3
|
+
- chat:思考强度 none → thinking.disabled 且不带 reasoning_effort;其余 → thinking.enabled + reasoning_effort=<值>
|
|
4
|
+
(默认 max),max_tokens 由 Provider 内部硬编码 65536
|
|
5
|
+
- chat_stream:关闭思考模式(thinking.disabled)且不带 reasoning_effort,max_tokens 由 Provider 内部硬编码 65536
|
|
5
6
|
- max_tokens 不接受外部覆盖:DeepSeek 思考模式要求 max_tokens ≥ 思考 + 回复预算,
|
|
6
7
|
由 Provider 全权决策;如需调整,直接修改本文件常量即可
|
|
7
8
|
- assistant 消息无 reasoning_content 时补 "null" 占位,规避 DeepSeek API 校验错误
|
|
@@ -19,31 +20,32 @@ from .txcode_ai import TxCodeAI
|
|
|
19
20
|
_DEEPSEEK_MAX_TOKENS = 65536
|
|
20
21
|
|
|
21
22
|
|
|
22
|
-
class DeepSeekProvider(BaseProvider):
|
|
23
|
-
def __init__(
|
|
24
|
-
self,
|
|
25
|
-
api_key: str,
|
|
26
|
-
base_url: str = "https://api.deepseek.com/v1",
|
|
27
|
-
model: str = "deepseek-chat",
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
23
|
+
class DeepSeekProvider(BaseProvider):
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
api_key: str,
|
|
27
|
+
base_url: str = "https://api.deepseek.com/v1",
|
|
28
|
+
model: str = "deepseek-chat",
|
|
29
|
+
reasoning_effort: Optional[str] = None,
|
|
30
|
+
connect_timeout: Optional[float] = None,
|
|
31
|
+
read_timeout: Optional[float] = None,
|
|
32
|
+
stream_interval_timeout: Optional[float] = None,
|
|
33
|
+
):
|
|
34
|
+
super().__init__(base_url=base_url, model=model, reasoning_effort=reasoning_effort)
|
|
35
|
+
client_kwargs: Dict[str, Any] = {
|
|
36
|
+
"api_key": api_key,
|
|
37
|
+
"base_url": base_url,
|
|
38
|
+
"default_headers": {
|
|
39
|
+
"HTTP-Referer": "https://www.homecommunity.cn",
|
|
40
|
+
"X-Title": "txcode",
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
if connect_timeout is not None:
|
|
44
|
+
client_kwargs["connect_timeout"] = connect_timeout
|
|
45
|
+
if read_timeout is not None:
|
|
46
|
+
client_kwargs["read_timeout"] = read_timeout
|
|
47
|
+
if stream_interval_timeout is not None:
|
|
48
|
+
client_kwargs["stream_interval_timeout"] = stream_interval_timeout
|
|
47
49
|
self._client = TxCodeAI(**client_kwargs)
|
|
48
50
|
|
|
49
51
|
async def chat(
|
|
@@ -53,14 +55,18 @@ class DeepSeekProvider(BaseProvider):
|
|
|
53
55
|
abort_signal: Any = None,
|
|
54
56
|
log_context: Optional[dict] = None,
|
|
55
57
|
) -> ProviderResponse:
|
|
56
|
-
resolved = await self._resolve_messages(messages)
|
|
57
|
-
kwargs: Dict[str, Any] = {
|
|
58
|
-
"model": self._model,
|
|
59
|
-
"messages": resolved,
|
|
60
|
-
"max_tokens": _DEEPSEEK_MAX_TOKENS,
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
58
|
+
resolved = await self._resolve_messages(messages)
|
|
59
|
+
kwargs: Dict[str, Any] = {
|
|
60
|
+
"model": self._model,
|
|
61
|
+
"messages": resolved,
|
|
62
|
+
"max_tokens": _DEEPSEEK_MAX_TOKENS,
|
|
63
|
+
}
|
|
64
|
+
effort = self.get_reasoning_effort()
|
|
65
|
+
if effort == "none":
|
|
66
|
+
kwargs["thinking"] = {"type": "disabled"}
|
|
67
|
+
else:
|
|
68
|
+
kwargs["thinking"] = {"type": "enabled"}
|
|
69
|
+
kwargs["reasoning_effort"] = effort
|
|
64
70
|
if tools:
|
|
65
71
|
kwargs["tools"] = tools
|
|
66
72
|
kwargs["tool_choice"] = "auto"
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
"""OpenAI Provider:基于自研 TxCodeAI(urllib)实现,零 openai SDK 依赖。
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
- chat:思考强度非 none → 附 reasoning_effort=<值>(默认 max);none → 不发送
|
|
4
|
+
(对齐 TS 行为并兼容不识别该字段的第三方 OpenAI 兼容端点)
|
|
5
|
+
- chat_stream:不发送 reasoning_effort
|
|
6
|
+
- max_tokens 由 Provider 内部硬编码 65536,不接受外部覆盖
|
|
4
7
|
"""
|
|
5
8
|
|
|
6
9
|
from typing import Any, AsyncGenerator, Dict, List, Optional
|
|
@@ -12,31 +15,32 @@ from .txcode_ai import TxCodeAI
|
|
|
12
15
|
_OPENAI_MAX_TOKENS = 65536
|
|
13
16
|
|
|
14
17
|
|
|
15
|
-
class OpenAIProvider(BaseProvider):
|
|
16
|
-
def __init__(
|
|
17
|
-
self,
|
|
18
|
-
api_key: str,
|
|
19
|
-
base_url: str = "https://api.openai.com/v1",
|
|
20
|
-
model: str = "gpt-4",
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
|
|
31
|
-
"
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
18
|
+
class OpenAIProvider(BaseProvider):
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
api_key: str,
|
|
22
|
+
base_url: str = "https://api.openai.com/v1",
|
|
23
|
+
model: str = "gpt-4",
|
|
24
|
+
reasoning_effort: Optional[str] = None,
|
|
25
|
+
connect_timeout: Optional[float] = None,
|
|
26
|
+
read_timeout: Optional[float] = None,
|
|
27
|
+
stream_interval_timeout: Optional[float] = None,
|
|
28
|
+
):
|
|
29
|
+
super().__init__(base_url=base_url, model=model, reasoning_effort=reasoning_effort)
|
|
30
|
+
client_kwargs: Dict[str, Any] = {
|
|
31
|
+
"api_key": api_key,
|
|
32
|
+
"base_url": base_url,
|
|
33
|
+
"default_headers": {
|
|
34
|
+
"HTTP-Referer": "https://www.homecommunity.cn",
|
|
35
|
+
"X-Title": "txcode",
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
if connect_timeout is not None:
|
|
39
|
+
client_kwargs["connect_timeout"] = connect_timeout
|
|
40
|
+
if read_timeout is not None:
|
|
41
|
+
client_kwargs["read_timeout"] = read_timeout
|
|
42
|
+
if stream_interval_timeout is not None:
|
|
43
|
+
client_kwargs["stream_interval_timeout"] = stream_interval_timeout
|
|
40
44
|
self._client = TxCodeAI(**client_kwargs)
|
|
41
45
|
|
|
42
46
|
async def chat(
|
|
@@ -47,14 +51,17 @@ class OpenAIProvider(BaseProvider):
|
|
|
47
51
|
log_context: Optional[dict] = None,
|
|
48
52
|
) -> ProviderResponse:
|
|
49
53
|
resolved = await self._resolve_messages(messages)
|
|
50
|
-
kwargs: Dict[str, Any] = {
|
|
51
|
-
"model": self._model,
|
|
52
|
-
"messages": resolved,
|
|
53
|
-
"temperature": 0.7,
|
|
54
|
-
"max_tokens": _OPENAI_MAX_TOKENS,
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
kwargs: Dict[str, Any] = {
|
|
55
|
+
"model": self._model,
|
|
56
|
+
"messages": resolved,
|
|
57
|
+
"temperature": 0.7,
|
|
58
|
+
"max_tokens": _OPENAI_MAX_TOKENS,
|
|
59
|
+
}
|
|
60
|
+
effort = self.get_reasoning_effort()
|
|
61
|
+
if effort != "none":
|
|
62
|
+
kwargs["reasoning_effort"] = effort
|
|
63
|
+
if tools:
|
|
64
|
+
kwargs["tools"] = tools
|
|
58
65
|
kwargs["tool_choice"] = "auto"
|
|
59
66
|
|
|
60
67
|
if log_context:
|
txcode_sdk/provider/router.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"""ProviderRouter:按 base_url / model 自动选择 Provider 实现。"""
|
|
2
2
|
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
3
5
|
from .base import BaseProvider
|
|
4
6
|
from .openai_provider import OpenAIProvider
|
|
5
7
|
from .deepseek_provider import DeepSeekProvider
|
|
@@ -7,7 +9,12 @@ from .deepseek_provider import DeepSeekProvider
|
|
|
7
9
|
|
|
8
10
|
class ProviderRouter:
|
|
9
11
|
@staticmethod
|
|
10
|
-
def create(
|
|
12
|
+
def create(
|
|
13
|
+
api_key: str,
|
|
14
|
+
base_url: str,
|
|
15
|
+
model: str,
|
|
16
|
+
reasoning_effort: Optional[str] = None,
|
|
17
|
+
) -> BaseProvider:
|
|
11
18
|
if "deepseek" in base_url.lower() or model.lower().startswith("deepseek"):
|
|
12
|
-
return DeepSeekProvider(api_key, base_url, model)
|
|
13
|
-
return OpenAIProvider(api_key, base_url, model)
|
|
19
|
+
return DeepSeekProvider(api_key, base_url, model, reasoning_effort=reasoning_effort)
|
|
20
|
+
return OpenAIProvider(api_key, base_url, model, reasoning_effort=reasoning_effort)
|
txcode_sdk/server/__main__.py
CHANGED
|
@@ -21,6 +21,13 @@ import logging
|
|
|
21
21
|
import os
|
|
22
22
|
import sys
|
|
23
23
|
|
|
24
|
+
from ..config.ai_settings import (
|
|
25
|
+
DEFAULT_CONTEXT_MAX_TOKENS,
|
|
26
|
+
DEFAULT_MAX_ITERATIONS,
|
|
27
|
+
REASONING_EFFORTS,
|
|
28
|
+
normalize_positive_int,
|
|
29
|
+
normalize_reasoning_effort,
|
|
30
|
+
)
|
|
24
31
|
from ..utils.path_util import _get_event_loop
|
|
25
32
|
|
|
26
33
|
DEFAULT_HOST = "0.0.0.0"
|
|
@@ -90,6 +97,24 @@ def _add_serve_args(parser: argparse.ArgumentParser):
|
|
|
90
97
|
default=argparse.SUPPRESS,
|
|
91
98
|
help="初始模型列表 `[显示名=]模型名` 逗号分隔(仅显式传参时解析;不再读取 TXCODE_MODELS)",
|
|
92
99
|
)
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--context-tokens",
|
|
102
|
+
type=int,
|
|
103
|
+
default=argparse.SUPPRESS,
|
|
104
|
+
help="上下文大小(tokens,默认 150000;显式传参优先于 ~/.txcode/config.json)",
|
|
105
|
+
)
|
|
106
|
+
parser.add_argument(
|
|
107
|
+
"--max-iterations",
|
|
108
|
+
type=int,
|
|
109
|
+
default=argparse.SUPPRESS,
|
|
110
|
+
help="Agent 最大循环次数(默认 1000;显式传参优先于 ~/.txcode/config.json)",
|
|
111
|
+
)
|
|
112
|
+
parser.add_argument(
|
|
113
|
+
"--reasoning-effort",
|
|
114
|
+
choices=list(REASONING_EFFORTS),
|
|
115
|
+
default=argparse.SUPPRESS,
|
|
116
|
+
help="思考强度(默认 max;可选 %s)" % "/".join(REASONING_EFFORTS),
|
|
117
|
+
)
|
|
93
118
|
|
|
94
119
|
|
|
95
120
|
def build_parser() -> argparse.ArgumentParser:
|
|
@@ -124,8 +149,10 @@ async def build_components(args, user_dir: str = None, log_enabled: bool = False
|
|
|
124
149
|
0.4.1 起无激活供应商时不再抛 MissingApiKeyError,以占位 client(api_key 为空)
|
|
125
150
|
空配置启动,等待桌面端 WS 添加供应商;环境变量不再参与装配。
|
|
126
151
|
log_enabled 透传 TxCodeClient:info/debug 级别时开启 Agent 循环日志。
|
|
152
|
+
AI 运行参数(上下文大小/循环次数/思考强度)优先级:显式 CLI 参数 > config.json > 内置默认值。
|
|
127
153
|
"""
|
|
128
154
|
from txcode_sdk import TxCodeClient
|
|
155
|
+
from .config_store import ConfigStore
|
|
129
156
|
from .provider_config import ProviderConfigManager
|
|
130
157
|
from .project_manager import ProjectManager
|
|
131
158
|
|
|
@@ -133,6 +160,22 @@ async def build_components(args, user_dir: str = None, log_enabled: bool = False
|
|
|
133
160
|
provider_config = ProviderConfigManager(os.path.join(user_dir, "providers.json"))
|
|
134
161
|
project_manager = ProjectManager(os.path.join(user_dir, "projects.json"))
|
|
135
162
|
|
|
163
|
+
# AI 运行参数:config.json(桌面端写入)为默认来源,显式 CLI 参数覆盖
|
|
164
|
+
ai_settings = ConfigStore(os.path.join(user_dir, "config.json")).get_ai_settings()
|
|
165
|
+
context_tokens = ai_settings["context_tokens"]
|
|
166
|
+
max_iterations = ai_settings["max_iterations"]
|
|
167
|
+
reasoning_effort = ai_settings["reasoning_effort"]
|
|
168
|
+
if getattr(args, "context_tokens", None) is not None:
|
|
169
|
+
context_tokens = normalize_positive_int(
|
|
170
|
+
args.context_tokens, DEFAULT_CONTEXT_MAX_TOKENS
|
|
171
|
+
)
|
|
172
|
+
if getattr(args, "max_iterations", None) is not None:
|
|
173
|
+
max_iterations = normalize_positive_int(
|
|
174
|
+
args.max_iterations, DEFAULT_MAX_ITERATIONS
|
|
175
|
+
)
|
|
176
|
+
if getattr(args, "reasoning_effort", None):
|
|
177
|
+
reasoning_effort = normalize_reasoning_effort(args.reasoning_effort)
|
|
178
|
+
|
|
136
179
|
# 项目装配:target_dir(默认 cwd)绝对路径 → 存在即选中 / 不存在即创建,work_dir 统一
|
|
137
180
|
target_dir = os.path.abspath(getattr(args, "target_dir", None) or os.getcwd())
|
|
138
181
|
if not os.path.isdir(target_dir):
|
|
@@ -157,6 +200,9 @@ async def build_components(args, user_dir: str = None, log_enabled: bool = False
|
|
|
157
200
|
work_dir=work_dir,
|
|
158
201
|
agent_type=getattr(args, "agent_type", None) or "code",
|
|
159
202
|
log_enabled=log_enabled,
|
|
203
|
+
max_context_tokens=context_tokens,
|
|
204
|
+
max_iterations=max_iterations,
|
|
205
|
+
reasoning_effort=reasoning_effort,
|
|
160
206
|
)
|
|
161
207
|
sys.stderr.write(
|
|
162
208
|
"[txcode-sdk] WARN: No active provider configured, "
|
|
@@ -174,6 +220,9 @@ async def build_components(args, user_dir: str = None, log_enabled: bool = False
|
|
|
174
220
|
work_dir=work_dir,
|
|
175
221
|
agent_type=getattr(args, "agent_type", None) or "code",
|
|
176
222
|
log_enabled=log_enabled,
|
|
223
|
+
max_context_tokens=context_tokens,
|
|
224
|
+
max_iterations=max_iterations,
|
|
225
|
+
reasoning_effort=reasoning_effort,
|
|
177
226
|
)
|
|
178
227
|
return client, provider_config, project_manager, work_dir
|
|
179
228
|
|
|
@@ -7,6 +7,15 @@
|
|
|
7
7
|
import json
|
|
8
8
|
import os
|
|
9
9
|
|
|
10
|
+
from ..config.ai_settings import (
|
|
11
|
+
DEFAULT_CONTEXT_MAX_TOKENS,
|
|
12
|
+
DEFAULT_MAX_ITERATIONS,
|
|
13
|
+
KEY_CONTEXT_MAX_TOKENS,
|
|
14
|
+
KEY_MAX_ITERATIONS,
|
|
15
|
+
KEY_REASONING_EFFORT,
|
|
16
|
+
normalize_positive_int,
|
|
17
|
+
normalize_reasoning_effort,
|
|
18
|
+
)
|
|
10
19
|
from .json_store import JsonStore
|
|
11
20
|
|
|
12
21
|
|
|
@@ -16,10 +25,8 @@ class ConfigStore:
|
|
|
16
25
|
def __init__(self, path: str = "~/.txcode/config.json"):
|
|
17
26
|
self._store = JsonStore(os.path.expanduser(path))
|
|
18
27
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
data = self._store.load({})
|
|
22
|
-
value = data.get(key)
|
|
28
|
+
@staticmethod
|
|
29
|
+
def _decode(value):
|
|
23
30
|
if value is None:
|
|
24
31
|
return None
|
|
25
32
|
if isinstance(value, str):
|
|
@@ -29,6 +36,31 @@ class ConfigStore:
|
|
|
29
36
|
except (TypeError, ValueError):
|
|
30
37
|
return value
|
|
31
38
|
|
|
39
|
+
def get(self, key: str):
|
|
40
|
+
"""不存在返回 None;值为字符串原样返回,否则返回 JSON 对象。"""
|
|
41
|
+
data = self._store.load({})
|
|
42
|
+
return self._decode(data.get(key))
|
|
43
|
+
|
|
44
|
+
def get_ai_settings(self) -> dict:
|
|
45
|
+
"""读取三项 AI 运行参数(缺失/非法回退默认值,对齐 txcode)。
|
|
46
|
+
|
|
47
|
+
返回 ``{"context_tokens": int, "max_iterations": int, "reasoning_effort": str}``。
|
|
48
|
+
"""
|
|
49
|
+
data = self._store.load({})
|
|
50
|
+
return {
|
|
51
|
+
"context_tokens": normalize_positive_int(
|
|
52
|
+
self._decode(data.get(KEY_CONTEXT_MAX_TOKENS)),
|
|
53
|
+
DEFAULT_CONTEXT_MAX_TOKENS,
|
|
54
|
+
),
|
|
55
|
+
"max_iterations": normalize_positive_int(
|
|
56
|
+
self._decode(data.get(KEY_MAX_ITERATIONS)),
|
|
57
|
+
DEFAULT_MAX_ITERATIONS,
|
|
58
|
+
),
|
|
59
|
+
"reasoning_effort": normalize_reasoning_effort(
|
|
60
|
+
self._decode(data.get(KEY_REASONING_EFFORT))
|
|
61
|
+
),
|
|
62
|
+
}
|
|
63
|
+
|
|
32
64
|
async def set(self, key: str, value):
|
|
33
65
|
"""value 为字符串原样存,否则 json.dumps;原子写。"""
|
|
34
66
|
data = self._store.load({})
|
txcode_sdk/server/handler.py
CHANGED
|
@@ -230,7 +230,28 @@ class CodeWebSocketHandler:
|
|
|
230
230
|
)
|
|
231
231
|
self._send(writer, {"type": "error", "error": "Unknown message type"})
|
|
232
232
|
|
|
233
|
+
def _apply_runtime_settings(self):
|
|
234
|
+
"""兜底刷新:chat 前比对 config.json 与 client 当前值,有差异才应用(下次 Agent 运行生效)。
|
|
235
|
+
|
|
236
|
+
覆盖外部直接编辑 `~/.txcode/config.json` 的场景;读文件开销极小(JsonStore.load)。
|
|
237
|
+
"""
|
|
238
|
+
if self._client is None:
|
|
239
|
+
return
|
|
240
|
+
try:
|
|
241
|
+
settings = self._config_store.get_ai_settings()
|
|
242
|
+
except Exception:
|
|
243
|
+
logger.warning("runtime settings load failed", exc_info=True)
|
|
244
|
+
return
|
|
245
|
+
if settings["context_tokens"] != self._client.get_max_context_tokens():
|
|
246
|
+
self._client.set_max_context_tokens(settings["context_tokens"])
|
|
247
|
+
if settings["max_iterations"] != self._client.get_max_iterations():
|
|
248
|
+
self._client.set_max_iterations(settings["max_iterations"])
|
|
249
|
+
if settings["reasoning_effort"] != self._client.get_reasoning_effort():
|
|
250
|
+
self._client.set_reasoning_effort(settings["reasoning_effort"])
|
|
251
|
+
|
|
233
252
|
async def _handle_chat(self, data: dict):
|
|
253
|
+
self._apply_runtime_settings()
|
|
254
|
+
|
|
234
255
|
session_id = data.get("sessionId")
|
|
235
256
|
if not session_id:
|
|
236
257
|
logger.warning("chat request rejected | reason=missing_session_id")
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
拆分自原 http.py:HttpApiHandler 只保留入口 handle() / _route() 分发;
|
|
4
4
|
协议解析在 http_base.py,各 API 组路由在 *_routes.py 子 Handler,业务逻辑走 services/。
|
|
5
|
-
路由路径与响应 JSON
|
|
5
|
+
路由路径与响应 JSON 结构与重构前完全一致;路由返回 RawResponse 时按自定义
|
|
6
|
+
Content-Type 输出(导出配置文件用 `application/x-yaml`),其余仍为 JSON 响应。
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
import inspect
|
|
@@ -13,6 +14,7 @@ from .git_routes import GitRoutes
|
|
|
13
14
|
from .http_base import (
|
|
14
15
|
HttpContext,
|
|
15
16
|
HttpRequest,
|
|
17
|
+
RawResponse,
|
|
16
18
|
build_json_response,
|
|
17
19
|
read_http_request,
|
|
18
20
|
)
|
|
@@ -27,6 +29,7 @@ __all__ = [
|
|
|
27
29
|
"HttpApiHandler",
|
|
28
30
|
"HttpContext",
|
|
29
31
|
"HttpRequest",
|
|
32
|
+
"RawResponse",
|
|
30
33
|
"build_json_response",
|
|
31
34
|
"read_http_request",
|
|
32
35
|
]
|
|
@@ -87,14 +90,22 @@ class HttpApiHandler:
|
|
|
87
90
|
# ---------- 入口 ----------
|
|
88
91
|
|
|
89
92
|
async def handle(self, request: HttpRequest, writer):
|
|
93
|
+
raw = None
|
|
90
94
|
try:
|
|
91
|
-
|
|
95
|
+
result = await self._route(request)
|
|
96
|
+
if isinstance(result, RawResponse):
|
|
97
|
+
raw = result
|
|
98
|
+
else:
|
|
99
|
+
status, payload = result
|
|
92
100
|
except ValueError as exc:
|
|
93
101
|
status, payload = 400, {"success": False, "error": str(exc)}
|
|
94
102
|
except Exception as exc:
|
|
95
103
|
status, payload = 500, {"success": False, "error": str(exc)}
|
|
96
104
|
try:
|
|
97
|
-
writer.write(
|
|
105
|
+
writer.write(
|
|
106
|
+
raw.to_http_bytes() if raw is not None
|
|
107
|
+
else build_json_response(status, payload)
|
|
108
|
+
)
|
|
98
109
|
await writer.drain()
|
|
99
110
|
except Exception:
|
|
100
111
|
pass
|