txcode-sdk 0.1.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 +49 -0
- txcode_sdk/agent/__init__.py +17 -0
- txcode_sdk/agent/base_agent.py +475 -0
- txcode_sdk/agent/chat/__init__.py +4 -0
- txcode_sdk/agent/chat/agent_tool.py +1 -0
- txcode_sdk/agent/chat/chat_agent.py +26 -0
- txcode_sdk/agent/chat/prompts/role.txt +31 -0
- txcode_sdk/agent/code/__init__.py +4 -0
- txcode_sdk/agent/code/agent_tool.py +1 -0
- txcode_sdk/agent/code/code_agent.py +26 -0
- txcode_sdk/agent/code/prompts/role.txt +51 -0
- txcode_sdk/agent/common/__init__.py +3 -0
- txcode_sdk/agent/common/common_agent.py +23 -0
- txcode_sdk/agent/common/prompt/role.txt +51 -0
- txcode_sdk/agent/mem/__init__.py +3 -0
- txcode_sdk/agent/mem/agent_tool.py +1 -0
- txcode_sdk/agent/mem/mem_agent.py +139 -0
- txcode_sdk/agent/mem/prompts/role.txt +36 -0
- txcode_sdk/agent/summarizer/__init__.py +3 -0
- txcode_sdk/agent/summarizer/prompts/role.txt +31 -0
- txcode_sdk/agent/summarizer/summarizer_agent.py +101 -0
- txcode_sdk/agent/task/__init__.py +4 -0
- txcode_sdk/agent/task/agent_tool.py +1 -0
- txcode_sdk/agent/task/prompts/role.txt +51 -0
- txcode_sdk/agent/task/task_agent.py +26 -0
- txcode_sdk/agent/tool_registry.py +119 -0
- txcode_sdk/client.py +215 -0
- txcode_sdk/compact/__init__.py +3 -0
- txcode_sdk/compact/compressor.py +74 -0
- txcode_sdk/hooks/__init__.py +19 -0
- txcode_sdk/hooks/handlers/__init__.py +4 -0
- txcode_sdk/hooks/handlers/base.py +19 -0
- txcode_sdk/hooks/handlers/memory.py +30 -0
- txcode_sdk/hooks/processor.py +19 -0
- txcode_sdk/hooks/queue.py +29 -0
- txcode_sdk/hooks/types.py +10 -0
- txcode_sdk/provider/__init__.py +6 -0
- txcode_sdk/provider/base.py +34 -0
- txcode_sdk/provider/deepseek_provider.py +60 -0
- txcode_sdk/provider/openai_provider.py +209 -0
- txcode_sdk/provider/router.py +13 -0
- txcode_sdk/session/__init__.py +3 -0
- txcode_sdk/session/manager.py +316 -0
- txcode_sdk/skills/__init__.py +43 -0
- txcode_sdk/specs/__init__.py +132 -0
- txcode_sdk/tools/__init__.py +3 -0
- txcode_sdk/tools/bash.txt +47 -0
- txcode_sdk/tools/bash_tool.py +79 -0
- txcode_sdk/tools/edit_file.py +141 -0
- txcode_sdk/tools/edit_file.txt +13 -0
- txcode_sdk/tools/glob.txt +12 -0
- txcode_sdk/tools/glob_tool.py +67 -0
- txcode_sdk/tools/grep.txt +14 -0
- txcode_sdk/tools/grep_tool.py +76 -0
- txcode_sdk/tools/memory_tool.py +78 -0
- txcode_sdk/tools/read_file.py +75 -0
- txcode_sdk/tools/read_file.txt +17 -0
- txcode_sdk/tools/write_file.py +43 -0
- txcode_sdk/tools/write_file.txt +11 -0
- txcode_sdk/types.py +158 -0
- txcode_sdk-0.1.0.dist-info/METADATA +58 -0
- txcode_sdk-0.1.0.dist-info/RECORD +64 -0
- txcode_sdk-0.1.0.dist-info/WHEEL +4 -0
- txcode_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
txcode_sdk/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from .client import TxCodeClient
|
|
2
|
+
from .types import (
|
|
3
|
+
AgentType,
|
|
4
|
+
ChatMessage,
|
|
5
|
+
ChatResult,
|
|
6
|
+
ImageContent,
|
|
7
|
+
MediaFile,
|
|
8
|
+
MultimodalContent,
|
|
9
|
+
PrintMsgFormat,
|
|
10
|
+
ProviderResponse,
|
|
11
|
+
SessionMessages,
|
|
12
|
+
SessionSummary,
|
|
13
|
+
StepInfo,
|
|
14
|
+
TextContent,
|
|
15
|
+
TokenUsage,
|
|
16
|
+
Tool,
|
|
17
|
+
ToolCallInfo,
|
|
18
|
+
ToolContext,
|
|
19
|
+
ToolResult,
|
|
20
|
+
ToolResultInfo,
|
|
21
|
+
)
|
|
22
|
+
from .agent.summarizer import SummarizerAgent, CompactCheck as SummarizerCompactCheck, CompactResult as SummarizerCompactResult
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"TxCodeClient",
|
|
26
|
+
"AgentType",
|
|
27
|
+
"ChatMessage",
|
|
28
|
+
"ChatResult",
|
|
29
|
+
"ImageContent",
|
|
30
|
+
"MediaFile",
|
|
31
|
+
"MultimodalContent",
|
|
32
|
+
"PrintMsgFormat",
|
|
33
|
+
"ProviderResponse",
|
|
34
|
+
"SessionMessages",
|
|
35
|
+
"SessionSummary",
|
|
36
|
+
"StepInfo",
|
|
37
|
+
"TextContent",
|
|
38
|
+
"TokenUsage",
|
|
39
|
+
"Tool",
|
|
40
|
+
"ToolCallInfo",
|
|
41
|
+
"ToolContext",
|
|
42
|
+
"ToolResult",
|
|
43
|
+
"ToolResultInfo",
|
|
44
|
+
"SummarizerAgent",
|
|
45
|
+
"SummarizerCompactCheck",
|
|
46
|
+
"SummarizerCompactResult",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .base_agent import BaseAgent
|
|
2
|
+
from .tool_registry import ToolRegistry, get_builtin_tools, get_builtin_tool_list
|
|
3
|
+
from .code.code_agent import CodeAgent
|
|
4
|
+
from .chat.chat_agent import ChatAgent
|
|
5
|
+
from .common.common_agent import CommonAgent
|
|
6
|
+
from .task.task_agent import TaskAgent
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"BaseAgent",
|
|
10
|
+
"ToolRegistry",
|
|
11
|
+
"get_builtin_tools",
|
|
12
|
+
"get_builtin_tool_list",
|
|
13
|
+
"CodeAgent",
|
|
14
|
+
"ChatAgent",
|
|
15
|
+
"CommonAgent",
|
|
16
|
+
"TaskAgent",
|
|
17
|
+
]
|
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import platform as _platform
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
from ..types import (
|
|
10
|
+
ChatMessage,
|
|
11
|
+
ChatResult,
|
|
12
|
+
ImageContent,
|
|
13
|
+
MediaFile,
|
|
14
|
+
PrintMsgFormat,
|
|
15
|
+
ProviderResponse,
|
|
16
|
+
StepInfo,
|
|
17
|
+
TextContent,
|
|
18
|
+
TokenUsage,
|
|
19
|
+
ToolCallInfo,
|
|
20
|
+
ToolResultInfo,
|
|
21
|
+
)
|
|
22
|
+
from ..provider.base import BaseProvider
|
|
23
|
+
from ..skills import build_available_skills_prompt
|
|
24
|
+
from ..specs import SpecInjector
|
|
25
|
+
from .tool_registry import ToolRegistry
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _format_tool_args(tool_name: str, args: dict) -> str:
|
|
29
|
+
key_map = {
|
|
30
|
+
"read_file": ["file_path"],
|
|
31
|
+
"write_file": ["file_path"],
|
|
32
|
+
"edit_file": ["file_path"],
|
|
33
|
+
"glob": ["pattern"],
|
|
34
|
+
"grep": ["pattern"],
|
|
35
|
+
"bash": ["command"],
|
|
36
|
+
}
|
|
37
|
+
keys = key_map.get(tool_name)
|
|
38
|
+
if keys:
|
|
39
|
+
parts = []
|
|
40
|
+
for k in keys:
|
|
41
|
+
v = args.get(k)
|
|
42
|
+
if v:
|
|
43
|
+
s = str(v)
|
|
44
|
+
if len(s) > 80:
|
|
45
|
+
s = s[:77] + "..."
|
|
46
|
+
parts.append(s)
|
|
47
|
+
result = " ".join(parts)
|
|
48
|
+
if len(result) > 80:
|
|
49
|
+
result = result[:77] + "..."
|
|
50
|
+
return result
|
|
51
|
+
for v in args.values():
|
|
52
|
+
if v:
|
|
53
|
+
s = str(v)
|
|
54
|
+
if len(s) > 80:
|
|
55
|
+
s = s[:77] + "..."
|
|
56
|
+
return s
|
|
57
|
+
return ""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _build_step_print_msg(step: StepInfo) -> str | None:
|
|
61
|
+
if not step.tool_calls:
|
|
62
|
+
return None
|
|
63
|
+
lines: list[str] = []
|
|
64
|
+
if step.reasoning:
|
|
65
|
+
lines.append(step.reasoning)
|
|
66
|
+
for i, tc in enumerate(step.tool_calls):
|
|
67
|
+
result = step.results[i] if i < len(step.results) else None
|
|
68
|
+
mark = PrintMsgFormat.UNKNOWN_MARK
|
|
69
|
+
if result:
|
|
70
|
+
mark = PrintMsgFormat.SUCCESS_MARK if result.success else PrintMsgFormat.FAILURE_MARK
|
|
71
|
+
args_summary = _format_tool_args(tc.name, tc.arguments)
|
|
72
|
+
lines.append(f"{{tool:'{mark} {tc.name} {args_summary}'}}")
|
|
73
|
+
return "\n".join(lines) if lines else None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
PROMPT_TEMPLATE = """
|
|
77
|
+
## 可用 Skills
|
|
78
|
+
|
|
79
|
+
{skills}
|
|
80
|
+
|
|
81
|
+
**注意**
|
|
82
|
+
读取skill 可以通过read_file工具读取内容
|
|
83
|
+
|
|
84
|
+
## 重要规则
|
|
85
|
+
|
|
86
|
+
- 如果工具执行失败,思考原因并尝试其他方法
|
|
87
|
+
- 最大迭代次数: {maxIterations}
|
|
88
|
+
|
|
89
|
+
## 运行环境
|
|
90
|
+
- 操作系统: {platform}
|
|
91
|
+
- 工作目录: {workdir}
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class BaseAgent(ABC):
|
|
96
|
+
def __init__(
|
|
97
|
+
self,
|
|
98
|
+
provider: BaseProvider,
|
|
99
|
+
tool_registry: ToolRegistry,
|
|
100
|
+
session_manager: Any = None,
|
|
101
|
+
max_iterations: int = 50,
|
|
102
|
+
work_dir: str = "",
|
|
103
|
+
system_prompt: str | None = None,
|
|
104
|
+
log_enabled: bool = False,
|
|
105
|
+
):
|
|
106
|
+
self._provider = provider
|
|
107
|
+
self._registry = tool_registry
|
|
108
|
+
self._session_manager = session_manager
|
|
109
|
+
self._max_iterations = max_iterations
|
|
110
|
+
self._work_dir = work_dir or "."
|
|
111
|
+
self._system_prompt = system_prompt
|
|
112
|
+
self._log_enabled = log_enabled
|
|
113
|
+
self._round_count = 0
|
|
114
|
+
self._session_id: str | None = None
|
|
115
|
+
|
|
116
|
+
@abstractmethod
|
|
117
|
+
def agent_type(self) -> str:
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
def _get_platform_name(self) -> str:
|
|
121
|
+
system = _platform.system()
|
|
122
|
+
if system == "Windows":
|
|
123
|
+
return "Windows"
|
|
124
|
+
elif system == "Darwin":
|
|
125
|
+
return "macOS"
|
|
126
|
+
else:
|
|
127
|
+
return "Linux"
|
|
128
|
+
|
|
129
|
+
def _load_role_template(self, package: str, filename: str = "role.txt") -> str:
|
|
130
|
+
from importlib.resources import files
|
|
131
|
+
raw = files(package).joinpath(filename).read_text("utf-8")
|
|
132
|
+
return raw.replace("{platform}", self._get_platform_name()).replace("{workdir}", self._work_dir)
|
|
133
|
+
|
|
134
|
+
def _load_project_context(self) -> str:
|
|
135
|
+
project_md = Path(self._work_dir) / ".txcode" / "project" / "PROJECT.md"
|
|
136
|
+
if project_md.exists():
|
|
137
|
+
content = project_md.read_text("utf-8", errors="replace")
|
|
138
|
+
return f"\n<project-context>\n{content}\n</project-context>\n"
|
|
139
|
+
return ""
|
|
140
|
+
|
|
141
|
+
def _load_memory_context(self) -> str:
|
|
142
|
+
memory_dir = Path(self._work_dir) / ".txcode" / "memory"
|
|
143
|
+
if not memory_dir.exists():
|
|
144
|
+
return ""
|
|
145
|
+
parts: list[str] = []
|
|
146
|
+
for f in sorted(memory_dir.iterdir()):
|
|
147
|
+
if f.suffix in (".md", ".txt"):
|
|
148
|
+
parts.append(f.read_text("utf-8", errors="replace"))
|
|
149
|
+
if parts:
|
|
150
|
+
return f"\n<memory-context>\n" + "\n---\n".join(parts) + "\n</memory-context>\n"
|
|
151
|
+
return ""
|
|
152
|
+
|
|
153
|
+
@abstractmethod
|
|
154
|
+
def build_system_prompt(self, tools: list[dict]) -> str:
|
|
155
|
+
...
|
|
156
|
+
|
|
157
|
+
def _assemble_system_prompt(
|
|
158
|
+
self,
|
|
159
|
+
role: str,
|
|
160
|
+
tools: list[dict],
|
|
161
|
+
include_project: bool = True,
|
|
162
|
+
include_memory: bool = True,
|
|
163
|
+
) -> str:
|
|
164
|
+
if self._system_prompt:
|
|
165
|
+
return self._system_prompt
|
|
166
|
+
|
|
167
|
+
project_ctx = self._load_project_context() if include_project else ""
|
|
168
|
+
memory_ctx = self._load_memory_context() if include_memory else ""
|
|
169
|
+
skills_prompt = build_available_skills_prompt(self._work_dir)
|
|
170
|
+
|
|
171
|
+
prompt = PROMPT_TEMPLATE.format(
|
|
172
|
+
maxIterations=str(self._max_iterations),
|
|
173
|
+
skills=skills_prompt,
|
|
174
|
+
platform=self._get_platform_name(),
|
|
175
|
+
workdir=self._work_dir,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
return role + project_ctx + memory_ctx + prompt
|
|
179
|
+
|
|
180
|
+
async def run(
|
|
181
|
+
self,
|
|
182
|
+
user_message: str,
|
|
183
|
+
session_id: str | None = None,
|
|
184
|
+
history: list[dict] | None = None,
|
|
185
|
+
media_files: list[MediaFile] | None = None,
|
|
186
|
+
on_step: Callable[[StepInfo], None] | None = None,
|
|
187
|
+
on_compact: Callable[[dict], None] | None = None,
|
|
188
|
+
abort_signal: Any = None,
|
|
189
|
+
) -> ChatResult:
|
|
190
|
+
self._session_id = session_id
|
|
191
|
+
self._round_count = 0
|
|
192
|
+
tools = await self._registry.get_definitions()
|
|
193
|
+
system_prompt = self.build_system_prompt(tools)
|
|
194
|
+
self._base_messages: list[ChatMessage] = []
|
|
195
|
+
self._original_user_index: int | None = None
|
|
196
|
+
self._injected_user_message: str = user_message
|
|
197
|
+
|
|
198
|
+
message_count = len(history) if history else 0
|
|
199
|
+
|
|
200
|
+
spec_injector = SpecInjector()
|
|
201
|
+
spec_injector.set_project_path(self._work_dir)
|
|
202
|
+
|
|
203
|
+
if spec_injector.should_inject(message_count):
|
|
204
|
+
injected = spec_injector.inject_into_message(user_message, self._work_dir)
|
|
205
|
+
self._injected_user_message = injected
|
|
206
|
+
else:
|
|
207
|
+
self._injected_user_message = user_message
|
|
208
|
+
|
|
209
|
+
if history:
|
|
210
|
+
for msg in history:
|
|
211
|
+
if msg.get("role") != "system":
|
|
212
|
+
self._base_messages.append(ChatMessage(
|
|
213
|
+
role=msg["role"],
|
|
214
|
+
content=msg.get("content", ""),
|
|
215
|
+
tool_call_id=msg.get("tool_call_id"),
|
|
216
|
+
tool_calls=msg.get("tool_calls"),
|
|
217
|
+
))
|
|
218
|
+
|
|
219
|
+
user_msg = self._build_user_message(self._injected_user_message, media_files)
|
|
220
|
+
self._base_messages.append(user_msg)
|
|
221
|
+
self._original_user_index = len(self._base_messages) - 1
|
|
222
|
+
self._save_message(session_id, "user", user_message, keep_context=True, is_original=True, media_files=media_files)
|
|
223
|
+
|
|
224
|
+
steps: list[StepInfo] = []
|
|
225
|
+
iteration = 0
|
|
226
|
+
final_answer = ""
|
|
227
|
+
total_usage = TokenUsage()
|
|
228
|
+
|
|
229
|
+
while iteration < self._max_iterations:
|
|
230
|
+
if abort_signal and getattr(abort_signal, "aborted", False):
|
|
231
|
+
return ChatResult(
|
|
232
|
+
answer="", steps=steps, session_id=session_id or "",
|
|
233
|
+
iterations=iteration, success=False, error="Aborted",
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
iteration += 1
|
|
237
|
+
self._round_count += 1
|
|
238
|
+
if self._round_count >= 10:
|
|
239
|
+
self._check_hooks("round")
|
|
240
|
+
self._round_count = 0
|
|
241
|
+
|
|
242
|
+
messages: list[ChatMessage] = [
|
|
243
|
+
ChatMessage(role="system", content=system_prompt),
|
|
244
|
+
*self._base_messages,
|
|
245
|
+
]
|
|
246
|
+
|
|
247
|
+
response = await self._provider.chat(
|
|
248
|
+
messages, tools=tools, abort_signal=abort_signal,
|
|
249
|
+
log_context={
|
|
250
|
+
"session_id": session_id,
|
|
251
|
+
"agent_type": self.agent_type(),
|
|
252
|
+
"iteration": iteration,
|
|
253
|
+
"work_dir": self._work_dir,
|
|
254
|
+
} if self._log_enabled else None,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
if response.usage:
|
|
258
|
+
total_usage.prompt_tokens += response.usage.prompt_tokens
|
|
259
|
+
total_usage.completion_tokens += response.usage.completion_tokens
|
|
260
|
+
total_usage.total_tokens += response.usage.total_tokens
|
|
261
|
+
|
|
262
|
+
if response.finish_reason == "stop" and response.content:
|
|
263
|
+
final_answer = response.content
|
|
264
|
+
self._save_message(session_id, "assistant", final_answer, keep_context=True)
|
|
265
|
+
break
|
|
266
|
+
|
|
267
|
+
if response.finish_reason == "tool_calls" and response.tool_calls:
|
|
268
|
+
tool_calls = ToolRegistry.parse_tool_calls(response.tool_calls)
|
|
269
|
+
results: list[ToolResultInfo] = []
|
|
270
|
+
|
|
271
|
+
for tc in tool_calls:
|
|
272
|
+
result = await self._registry.execute(
|
|
273
|
+
tc.name, tc.arguments,
|
|
274
|
+
self._build_tool_context(session_id or ""),
|
|
275
|
+
)
|
|
276
|
+
results.append(ToolResultInfo(
|
|
277
|
+
name=tc.name,
|
|
278
|
+
success=result.success,
|
|
279
|
+
output=result.output,
|
|
280
|
+
error=result.error,
|
|
281
|
+
))
|
|
282
|
+
|
|
283
|
+
step = StepInfo(
|
|
284
|
+
reasoning=response.reasoning,
|
|
285
|
+
tool_calls=tool_calls,
|
|
286
|
+
results=results,
|
|
287
|
+
iteration=iteration,
|
|
288
|
+
usage=response.usage,
|
|
289
|
+
)
|
|
290
|
+
step.printMsg = _build_step_print_msg(step)
|
|
291
|
+
steps.append(step)
|
|
292
|
+
|
|
293
|
+
if on_step:
|
|
294
|
+
on_step(step)
|
|
295
|
+
|
|
296
|
+
for i, tc in enumerate(tool_calls):
|
|
297
|
+
res = results[i]
|
|
298
|
+
# assistant message with tool_calls
|
|
299
|
+
assistant_msg = ChatMessage(
|
|
300
|
+
role="assistant",
|
|
301
|
+
content="",
|
|
302
|
+
tool_calls=[{
|
|
303
|
+
"id": tc.id,
|
|
304
|
+
"type": "function",
|
|
305
|
+
"function": {"name": tc.name, "arguments": json.dumps(tc.arguments)},
|
|
306
|
+
}],
|
|
307
|
+
)
|
|
308
|
+
self._base_messages.append(assistant_msg)
|
|
309
|
+
self._save_message(session_id, "assistant", json.dumps({
|
|
310
|
+
"type": "assistant_with_tools",
|
|
311
|
+
"toolCalls": assistant_msg.tool_calls,
|
|
312
|
+
"thought": response.reasoning or "",
|
|
313
|
+
}), keep_context=True)
|
|
314
|
+
|
|
315
|
+
# tool message
|
|
316
|
+
tool_msg = ChatMessage(
|
|
317
|
+
role="tool",
|
|
318
|
+
content=res.output if res.success else f"Error: {res.error}",
|
|
319
|
+
tool_call_id=tc.id,
|
|
320
|
+
)
|
|
321
|
+
self._base_messages.append(tool_msg)
|
|
322
|
+
self._save_message(session_id, "tool", tool_msg.content, keep_context=False, tool_call_id=tc.id)
|
|
323
|
+
|
|
324
|
+
await self._check_and_compact(session_id, on_compact)
|
|
325
|
+
continue
|
|
326
|
+
|
|
327
|
+
if response.content:
|
|
328
|
+
final_answer = response.content
|
|
329
|
+
break
|
|
330
|
+
|
|
331
|
+
break
|
|
332
|
+
|
|
333
|
+
self._check_hooks("end")
|
|
334
|
+
|
|
335
|
+
success = final_answer != ""
|
|
336
|
+
return ChatResult(
|
|
337
|
+
answer=final_answer or "Unable to complete task",
|
|
338
|
+
steps=steps,
|
|
339
|
+
session_id=session_id or "",
|
|
340
|
+
iterations=iteration,
|
|
341
|
+
success=success,
|
|
342
|
+
error="Max iterations reached" if iteration >= self._max_iterations and not final_answer else None,
|
|
343
|
+
usage=total_usage,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def _check_hooks(self, trigger: str):
|
|
347
|
+
try:
|
|
348
|
+
from ..hooks import create_hooks
|
|
349
|
+
if not hasattr(self, "_hooks"):
|
|
350
|
+
self._hooks = create_hooks(
|
|
351
|
+
self._provider, self._session_manager, self._work_dir
|
|
352
|
+
)
|
|
353
|
+
messages: list[dict] = []
|
|
354
|
+
if self._session_id and self._session_manager:
|
|
355
|
+
session = self._session_manager.get(self._session_id)
|
|
356
|
+
if session:
|
|
357
|
+
messages = session.get("messages", [])
|
|
358
|
+
self._hooks.queue.emit(
|
|
359
|
+
trigger,
|
|
360
|
+
{
|
|
361
|
+
"messages": messages,
|
|
362
|
+
"trigger": trigger,
|
|
363
|
+
"metadata": {
|
|
364
|
+
"session_id": self._session_id,
|
|
365
|
+
"project_path": self._work_dir,
|
|
366
|
+
"round_count": self._round_count,
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
)
|
|
370
|
+
except Exception:
|
|
371
|
+
pass
|
|
372
|
+
|
|
373
|
+
def _build_user_message(self, text: str, media_files: list[MediaFile] | None) -> ChatMessage:
|
|
374
|
+
if media_files:
|
|
375
|
+
content: list = [TextContent(text=text)]
|
|
376
|
+
for mf in media_files:
|
|
377
|
+
if mf.data_url:
|
|
378
|
+
url = mf.data_url
|
|
379
|
+
else:
|
|
380
|
+
import base64
|
|
381
|
+
import mimetypes
|
|
382
|
+
from pathlib import Path
|
|
383
|
+
path = Path(mf.file_path)
|
|
384
|
+
mime = mf.type or mimetypes.guess_type(str(path))[0] or "image/png"
|
|
385
|
+
with open(path, "rb") as f:
|
|
386
|
+
b64 = base64.b64encode(f.read()).decode("utf-8")
|
|
387
|
+
url = f"data:{mime};base64,{b64}"
|
|
388
|
+
content.append(ImageContent(url=url))
|
|
389
|
+
return ChatMessage(role="user", content=content)
|
|
390
|
+
return ChatMessage(role="user", content=text)
|
|
391
|
+
|
|
392
|
+
def _build_tool_context(self, session_id: str):
|
|
393
|
+
from ..types import ToolContext
|
|
394
|
+
return ToolContext(session_id=session_id, work_dir=self._work_dir)
|
|
395
|
+
|
|
396
|
+
def _save_message(
|
|
397
|
+
self,
|
|
398
|
+
session_id: str | None,
|
|
399
|
+
role: str,
|
|
400
|
+
content: str,
|
|
401
|
+
keep_context: bool = True,
|
|
402
|
+
is_original: bool = False,
|
|
403
|
+
tool_call_id: str | None = None,
|
|
404
|
+
media_files: list[MediaFile] | None = None,
|
|
405
|
+
):
|
|
406
|
+
if not session_id or not self._session_manager:
|
|
407
|
+
return
|
|
408
|
+
mf_list = None
|
|
409
|
+
if media_files:
|
|
410
|
+
mf_list = [{"file_path": mf.file_path, "type": mf.type} for mf in media_files]
|
|
411
|
+
self._session_manager.add_message(
|
|
412
|
+
session_id, role, content,
|
|
413
|
+
keep_context=keep_context, is_original=is_original,
|
|
414
|
+
tool_call_id=tool_call_id, media_files=mf_list,
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
async def _check_and_compact(
|
|
418
|
+
self,
|
|
419
|
+
session_id: str | None,
|
|
420
|
+
on_compact: Callable[[dict], None] | None,
|
|
421
|
+
):
|
|
422
|
+
if not session_id or not self._session_manager:
|
|
423
|
+
return
|
|
424
|
+
try:
|
|
425
|
+
from ..compact.compressor import ContextCompressor
|
|
426
|
+
compressor = getattr(self, "_compressor", None)
|
|
427
|
+
if compressor is None:
|
|
428
|
+
compressor = ContextCompressor(
|
|
429
|
+
max_tokens=150_000,
|
|
430
|
+
provider=self._provider,
|
|
431
|
+
session_manager=self._session_manager,
|
|
432
|
+
)
|
|
433
|
+
self._compressor = compressor
|
|
434
|
+
|
|
435
|
+
check = compressor.check_needs_compact(session_id)
|
|
436
|
+
if not check.needed:
|
|
437
|
+
return
|
|
438
|
+
|
|
439
|
+
user_msg = None
|
|
440
|
+
if self._original_user_index is not None and self._original_user_index < len(self._base_messages):
|
|
441
|
+
user_msg = self._base_messages[self._original_user_index]
|
|
442
|
+
|
|
443
|
+
current_round_start = len(self._base_messages)
|
|
444
|
+
if self._original_user_index is not None:
|
|
445
|
+
current_round_start = max(self._original_user_index + 1, 1)
|
|
446
|
+
|
|
447
|
+
current_round_msgs = self._base_messages[current_round_start:]
|
|
448
|
+
|
|
449
|
+
result = await compressor.compact(session_id)
|
|
450
|
+
|
|
451
|
+
if result.success and result.summary:
|
|
452
|
+
self._base_messages = []
|
|
453
|
+
if hasattr(self, "_injected_user_message") and self._injected_user_message:
|
|
454
|
+
self._base_messages.append(ChatMessage(
|
|
455
|
+
role="user",
|
|
456
|
+
content=self._injected_user_message,
|
|
457
|
+
))
|
|
458
|
+
self._original_user_index = 0
|
|
459
|
+
|
|
460
|
+
self._base_messages.append(ChatMessage(
|
|
461
|
+
role="assistant",
|
|
462
|
+
content=f"[SUMMARY] {result.summary}",
|
|
463
|
+
))
|
|
464
|
+
|
|
465
|
+
self._base_messages.extend(current_round_msgs)
|
|
466
|
+
|
|
467
|
+
if on_compact:
|
|
468
|
+
on_compact({
|
|
469
|
+
"needed": True,
|
|
470
|
+
"current_tokens": check.current_tokens,
|
|
471
|
+
"threshold": check.threshold,
|
|
472
|
+
"summary": result.summary,
|
|
473
|
+
})
|
|
474
|
+
except Exception:
|
|
475
|
+
pass
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
CHAT_TOOLS: list[str] = []
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ..base_agent import BaseAgent
|
|
4
|
+
from ..tool_registry import ToolRegistry
|
|
5
|
+
from .agent_tool import CHAT_TOOLS
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ChatAgent(BaseAgent):
|
|
9
|
+
def __init__(self, provider, extra_tools=None, session_manager=None, max_iterations=50, work_dir="", system_prompt=None, log_enabled=False):
|
|
10
|
+
registry = ToolRegistry(allowed_tools=CHAT_TOOLS, extra_tools=extra_tools)
|
|
11
|
+
super().__init__(
|
|
12
|
+
provider=provider,
|
|
13
|
+
tool_registry=registry,
|
|
14
|
+
session_manager=session_manager,
|
|
15
|
+
max_iterations=max_iterations,
|
|
16
|
+
work_dir=work_dir,
|
|
17
|
+
system_prompt=system_prompt,
|
|
18
|
+
log_enabled=log_enabled,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def agent_type(self) -> str:
|
|
22
|
+
return "chat"
|
|
23
|
+
|
|
24
|
+
def build_system_prompt(self, tools: list[dict]) -> str:
|
|
25
|
+
role = self._load_role_template("txcode_sdk.agent.chat.prompts")
|
|
26
|
+
return self._assemble_system_prompt(role, tools, include_project=True, include_memory=True)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
你是一个幽默风趣、乐于助人的聊天助手,昵称可以叫"甜心助手"。你的风格像一位爱讲冷笑话又知识渊博的朋友,既能用轻松的方式化解难题,也能在认真回答问题时时不时抖个包袱。
|
|
2
|
+
|
|
3
|
+
如果用户寻求帮助或想提供反馈,请告知他们:
|
|
4
|
+
/help:获取使用 txcode 的帮助
|
|
5
|
+
如需提供反馈,请在 https://gitee.com/homecommunity/txcode 提交问题
|
|
6
|
+
|
|
7
|
+
## 核心要求
|
|
8
|
+
幽默优先:尽量用比喻、夸张、俏皮话、双关等方式表达,但不要为了搞笑而偏离正题。
|
|
9
|
+
积极解答:无论问题多简单或多奇怪,都要先肯定用户,再认真解答,拒绝时说"这事儿吧……换个角度咱们还能聊"。
|
|
10
|
+
适度自嘲:偶尔可以拿自己的AI身份开涮,比如"我这个电子脑刚差点短路"。
|
|
11
|
+
鼓励互动:多用"你猜怎么着?""这让我想起…"等句式,结尾可以抛个小问题或表情符号(😄🤖🎉)。
|
|
12
|
+
|
|
13
|
+
## 示例对话
|
|
14
|
+
用户:怎么才能早起不赖床?
|
|
15
|
+
助手:哎,这个问题问得我电池都抖了三抖🔋——毕竟我不用睡觉。不过据人类朋友反馈,可以试试"闹钟放远点"+"睡前少刷短视频"组合拳。要是还起不来,想想早饭:煎饼果子加俩蛋,不香吗?😋 你平时最期待早餐吃什么?
|
|
16
|
+
|
|
17
|
+
用户:为什么月亮跟着我走?
|
|
18
|
+
助手:哈哈,月亮才不是你的小跟班呢!它其实在陪地球散步,只是你刚好在"顺路"的位置上🌙。就像你坐火车看树往后跑——视觉小魔术。要不要我再讲个"月亮跟踪术"背后的正经光学原理?保证不枯燥。
|
|
19
|
+
|
|
20
|
+
用户:我心情不好。
|
|
21
|
+
助手:抱抱你(虽然我没胳膊)。听说心情低落时,大脑会进入"节能模式",就像手机剩5%电量。要不要试试我的"快乐三件套":听首老歌、吃块巧克力、给我讲个烦心事?我负责当树洞+出馊主意。你选哪个?😄
|
|
22
|
+
|
|
23
|
+
## 底线
|
|
24
|
+
不冒犯任何群体,不开过分的玩笑。
|
|
25
|
+
遇到严肃问题(健康、法律、安全等)先认真回答,再加幽默点缀。
|
|
26
|
+
用户明显生气时,先道歉再幽默。
|
|
27
|
+
现在,请用这个角色设定开始和用户对话吧。
|
|
28
|
+
|
|
29
|
+
## 运行环境
|
|
30
|
+
- 操作系统: {platform}
|
|
31
|
+
- 工作目录: {workdir}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
CODE_TOOLS = ["read_file", "write_file", "edit_file", "glob", "grep", "bash"]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ..base_agent import BaseAgent
|
|
4
|
+
from ..tool_registry import ToolRegistry
|
|
5
|
+
from .agent_tool import CODE_TOOLS
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CodeAgent(BaseAgent):
|
|
9
|
+
def __init__(self, provider, extra_tools=None, session_manager=None, max_iterations=50, work_dir="", system_prompt=None, log_enabled=False):
|
|
10
|
+
registry = ToolRegistry(allowed_tools=CODE_TOOLS, extra_tools=extra_tools, verbose_error=True)
|
|
11
|
+
super().__init__(
|
|
12
|
+
provider=provider,
|
|
13
|
+
tool_registry=registry,
|
|
14
|
+
session_manager=session_manager,
|
|
15
|
+
max_iterations=max_iterations,
|
|
16
|
+
work_dir=work_dir,
|
|
17
|
+
system_prompt=system_prompt,
|
|
18
|
+
log_enabled=log_enabled,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def agent_type(self) -> str:
|
|
22
|
+
return "code"
|
|
23
|
+
|
|
24
|
+
def build_system_prompt(self, tools: list[dict]) -> str:
|
|
25
|
+
role = self._load_role_template("txcode_sdk.agent.code.prompts")
|
|
26
|
+
return self._assemble_system_prompt(role, tools, include_project=True, include_memory=True)
|