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
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import cast
|
|
4
|
+
|
|
5
|
+
from ..types import Tool, ToolContext, ToolResult
|
|
6
|
+
from ..tools.read_file import read_file_tool
|
|
7
|
+
from ..tools.write_file import write_file_tool
|
|
8
|
+
from ..tools.edit_file import edit_file_tool
|
|
9
|
+
from ..tools.glob_tool import glob_tool
|
|
10
|
+
from ..tools.grep_tool import grep_tool
|
|
11
|
+
from ..tools.bash_tool import bash_tool
|
|
12
|
+
from ..tools.memory_tool import memory_tool
|
|
13
|
+
|
|
14
|
+
_BUILTIN_TOOLS: dict[str, Tool] = {}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _ensure_builtin_tools():
|
|
18
|
+
global _BUILTIN_TOOLS
|
|
19
|
+
if _BUILTIN_TOOLS:
|
|
20
|
+
return
|
|
21
|
+
tools = [read_file_tool, write_file_tool, edit_file_tool, glob_tool, grep_tool, bash_tool, memory_tool]
|
|
22
|
+
for t in tools:
|
|
23
|
+
_BUILTIN_TOOLS[t.name] = t
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_builtin_tools() -> dict[str, Tool]:
|
|
27
|
+
_ensure_builtin_tools()
|
|
28
|
+
return dict(_BUILTIN_TOOLS)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_builtin_tool_list() -> list[Tool]:
|
|
32
|
+
_ensure_builtin_tools()
|
|
33
|
+
return list(_BUILTIN_TOOLS.values())
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ToolRegistry:
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
allowed_tools: list[str] | None = None,
|
|
40
|
+
extra_tools: list[Tool] | None = None,
|
|
41
|
+
verbose_error: bool = False,
|
|
42
|
+
):
|
|
43
|
+
self._allowed = allowed_tools
|
|
44
|
+
self._extra: dict[str, Tool] = {}
|
|
45
|
+
self._builtin: dict[str, Tool] = {}
|
|
46
|
+
self._verbose_error = verbose_error
|
|
47
|
+
self._loaded = False
|
|
48
|
+
|
|
49
|
+
if extra_tools:
|
|
50
|
+
for t in extra_tools:
|
|
51
|
+
self._extra[t.name] = t
|
|
52
|
+
|
|
53
|
+
async def _ensure_loaded(self):
|
|
54
|
+
if self._loaded:
|
|
55
|
+
return
|
|
56
|
+
_ensure_builtin_tools()
|
|
57
|
+
if self._allowed is None:
|
|
58
|
+
self._builtin = dict(_BUILTIN_TOOLS)
|
|
59
|
+
else:
|
|
60
|
+
for name in self._allowed:
|
|
61
|
+
if name in _BUILTIN_TOOLS:
|
|
62
|
+
self._builtin[name] = _BUILTIN_TOOLS[name]
|
|
63
|
+
self._loaded = True
|
|
64
|
+
|
|
65
|
+
async def get_definitions(self) -> list[dict]:
|
|
66
|
+
await self._ensure_loaded()
|
|
67
|
+
all_tools = {**self._builtin, **self._extra}
|
|
68
|
+
return [self._to_openai_tool(t) for t in all_tools.values()]
|
|
69
|
+
|
|
70
|
+
async def get_definitions_full(self) -> list[dict]:
|
|
71
|
+
_ensure_builtin_tools()
|
|
72
|
+
all_tools = {**_BUILTIN_TOOLS, **self._extra}
|
|
73
|
+
return [self._to_openai_tool(t) for t in all_tools.values()]
|
|
74
|
+
|
|
75
|
+
async def execute(self, name: str, args: dict, context: ToolContext) -> ToolResult:
|
|
76
|
+
await self._ensure_loaded()
|
|
77
|
+
try:
|
|
78
|
+
tool = self._extra.get(name) or self._builtin.get(name)
|
|
79
|
+
if not tool:
|
|
80
|
+
available = ", ".join({**self._builtin, **self._extra}.keys())
|
|
81
|
+
suffix = f". Available tools: {available}" if self._verbose_error else ""
|
|
82
|
+
return ToolResult(success=False, output="", error=f"Tool not found: {name}{suffix}")
|
|
83
|
+
|
|
84
|
+
import inspect
|
|
85
|
+
result = tool.execute(args, context)
|
|
86
|
+
if inspect.iscoroutine(result):
|
|
87
|
+
result = await result
|
|
88
|
+
return cast(ToolResult, result)
|
|
89
|
+
except Exception as e:
|
|
90
|
+
return ToolResult(success=False, output="", error=str(e))
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def parse_tool_calls(raw_tool_calls: list[dict]) -> list:
|
|
94
|
+
from ..types import ToolCallInfo
|
|
95
|
+
calls: list[ToolCallInfo] = []
|
|
96
|
+
for tc in raw_tool_calls or []:
|
|
97
|
+
func = tc.get("function", {})
|
|
98
|
+
args_str = func.get("arguments", "{}")
|
|
99
|
+
if isinstance(args_str, str):
|
|
100
|
+
import json
|
|
101
|
+
try:
|
|
102
|
+
args = json.loads(args_str)
|
|
103
|
+
except json.JSONDecodeError:
|
|
104
|
+
args = {}
|
|
105
|
+
else:
|
|
106
|
+
args = args_str or {}
|
|
107
|
+
calls.append(ToolCallInfo(id=tc.get("id", ""), name=func.get("name", ""), arguments=args))
|
|
108
|
+
return calls
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def _to_openai_tool(tool: Tool) -> dict:
|
|
112
|
+
return {
|
|
113
|
+
"type": "function",
|
|
114
|
+
"function": {
|
|
115
|
+
"name": tool.name,
|
|
116
|
+
"description": tool.description,
|
|
117
|
+
"parameters": tool.parameters,
|
|
118
|
+
},
|
|
119
|
+
}
|
txcode_sdk/client.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
from .types import (
|
|
9
|
+
AgentType,
|
|
10
|
+
ChatResult,
|
|
11
|
+
MediaFile,
|
|
12
|
+
StepInfo,
|
|
13
|
+
Tool,
|
|
14
|
+
)
|
|
15
|
+
from .provider.router import ProviderRouter
|
|
16
|
+
from .session.manager import SessionManager
|
|
17
|
+
from .compact.compressor import ContextCompressor
|
|
18
|
+
from .agent.tool_registry import ToolRegistry
|
|
19
|
+
from .agent.code import CodeAgent
|
|
20
|
+
from .agent.chat import ChatAgent
|
|
21
|
+
from .agent.common import CommonAgent
|
|
22
|
+
from .agent.task import TaskAgent
|
|
23
|
+
from .agent.base_agent import BaseAgent
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TxCodeClient:
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
api_key: str,
|
|
30
|
+
base_url: str = "https://api.openai.com/v1",
|
|
31
|
+
model: str = "gpt-4",
|
|
32
|
+
agent_type: AgentType = "code",
|
|
33
|
+
tools: list[Tool] | None = None,
|
|
34
|
+
max_context_tokens: int = 150_000,
|
|
35
|
+
max_iterations: int = 50,
|
|
36
|
+
system_prompt: str | None = None,
|
|
37
|
+
work_dir: str | None = None,
|
|
38
|
+
log_enabled: bool = False,
|
|
39
|
+
):
|
|
40
|
+
self._api_key = api_key
|
|
41
|
+
self._base_url = base_url
|
|
42
|
+
self._model = model
|
|
43
|
+
self._agent_type = agent_type
|
|
44
|
+
self._extra_tools = tools or []
|
|
45
|
+
self._max_context_tokens = max_context_tokens
|
|
46
|
+
self._max_iterations = max_iterations
|
|
47
|
+
self._system_prompt = system_prompt
|
|
48
|
+
self._work_dir = work_dir or str(Path.cwd())
|
|
49
|
+
self._log_enabled = log_enabled
|
|
50
|
+
|
|
51
|
+
self._provider = ProviderRouter.create(api_key, base_url, model)
|
|
52
|
+
self._session_manager = SessionManager(self._work_dir)
|
|
53
|
+
self._compressor = ContextCompressor(
|
|
54
|
+
max_tokens=max_context_tokens,
|
|
55
|
+
provider=self._provider,
|
|
56
|
+
session_manager=self._session_manager,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def work_dir(self) -> str:
|
|
61
|
+
return self._work_dir
|
|
62
|
+
|
|
63
|
+
async def chat(
|
|
64
|
+
self,
|
|
65
|
+
message: str,
|
|
66
|
+
session_id: str | None = None,
|
|
67
|
+
agent_type: AgentType | None = None,
|
|
68
|
+
history: list[dict] | None = None,
|
|
69
|
+
media_files: list[MediaFile] | None = None,
|
|
70
|
+
on_step: Callable[[StepInfo], None] | None = None,
|
|
71
|
+
on_compact: Callable[[dict], None] | None = None,
|
|
72
|
+
abort_signal: Any = None,
|
|
73
|
+
) -> ChatResult:
|
|
74
|
+
effective_agent_type = agent_type or self._agent_type
|
|
75
|
+
|
|
76
|
+
if session_id:
|
|
77
|
+
session = self._session_manager.get(session_id)
|
|
78
|
+
if not session:
|
|
79
|
+
session = self._create_session_with_id(session_id, message)
|
|
80
|
+
else:
|
|
81
|
+
session = self._session_manager.create(title=message[:50])
|
|
82
|
+
session_id = session["id"]
|
|
83
|
+
|
|
84
|
+
if session_id and history is None:
|
|
85
|
+
summary_idx = session.get("summary_message_index")
|
|
86
|
+
raw_messages = self._session_manager.get_messages_for_ai(
|
|
87
|
+
session_id, summary_index=summary_idx
|
|
88
|
+
)
|
|
89
|
+
if raw_messages:
|
|
90
|
+
history = self._parse_session_messages_to_history(raw_messages)
|
|
91
|
+
|
|
92
|
+
agent = self._create_agent(effective_agent_type)
|
|
93
|
+
|
|
94
|
+
result = await agent.run(
|
|
95
|
+
user_message=message,
|
|
96
|
+
session_id=session_id,
|
|
97
|
+
history=history,
|
|
98
|
+
media_files=media_files,
|
|
99
|
+
on_step=on_step,
|
|
100
|
+
on_compact=on_compact,
|
|
101
|
+
abort_signal=abort_signal,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
result.session_id = session_id
|
|
105
|
+
return result
|
|
106
|
+
|
|
107
|
+
def delete_session(self, session_id: str):
|
|
108
|
+
self._session_manager.delete(session_id)
|
|
109
|
+
|
|
110
|
+
def list_sessions(self) -> list[dict]:
|
|
111
|
+
return self._session_manager.list_sessions_summary()
|
|
112
|
+
|
|
113
|
+
def get_session(self, session_id: str) -> dict | None:
|
|
114
|
+
return self._session_manager.get(session_id)
|
|
115
|
+
|
|
116
|
+
def get_session_messages(self, session_id: str) -> dict | None:
|
|
117
|
+
return self._session_manager.get_session_messages(session_id)
|
|
118
|
+
|
|
119
|
+
def _create_agent(self, agent_type: str) -> BaseAgent:
|
|
120
|
+
extra_tools = self._extra_tools if self._extra_tools else None
|
|
121
|
+
|
|
122
|
+
if agent_type == "chat":
|
|
123
|
+
return ChatAgent(
|
|
124
|
+
provider=self._provider,
|
|
125
|
+
extra_tools=extra_tools,
|
|
126
|
+
session_manager=self._session_manager,
|
|
127
|
+
max_iterations=self._max_iterations,
|
|
128
|
+
work_dir=self._work_dir,
|
|
129
|
+
system_prompt=self._system_prompt,
|
|
130
|
+
log_enabled=self._log_enabled,
|
|
131
|
+
)
|
|
132
|
+
elif agent_type == "common":
|
|
133
|
+
return CommonAgent(
|
|
134
|
+
provider=self._provider,
|
|
135
|
+
extra_tools=extra_tools,
|
|
136
|
+
session_manager=self._session_manager,
|
|
137
|
+
max_iterations=self._max_iterations,
|
|
138
|
+
work_dir=self._work_dir,
|
|
139
|
+
system_prompt=self._system_prompt,
|
|
140
|
+
log_enabled=self._log_enabled,
|
|
141
|
+
)
|
|
142
|
+
elif agent_type == "task":
|
|
143
|
+
return TaskAgent(
|
|
144
|
+
provider=self._provider,
|
|
145
|
+
extra_tools=extra_tools,
|
|
146
|
+
session_manager=self._session_manager,
|
|
147
|
+
max_iterations=self._max_iterations,
|
|
148
|
+
work_dir=self._work_dir,
|
|
149
|
+
system_prompt=self._system_prompt,
|
|
150
|
+
log_enabled=self._log_enabled,
|
|
151
|
+
)
|
|
152
|
+
else:
|
|
153
|
+
return CodeAgent(
|
|
154
|
+
provider=self._provider,
|
|
155
|
+
extra_tools=extra_tools,
|
|
156
|
+
session_manager=self._session_manager,
|
|
157
|
+
max_iterations=self._max_iterations,
|
|
158
|
+
work_dir=self._work_dir,
|
|
159
|
+
system_prompt=self._system_prompt,
|
|
160
|
+
log_enabled=self._log_enabled,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def _parse_session_messages_to_history(self, messages: list[dict]) -> list[dict]:
|
|
164
|
+
result: list[dict] = []
|
|
165
|
+
for msg in messages:
|
|
166
|
+
role = msg.get("role", "")
|
|
167
|
+
content = msg.get("content", "")
|
|
168
|
+
|
|
169
|
+
if role == "assistant":
|
|
170
|
+
try:
|
|
171
|
+
parsed = json.loads(content)
|
|
172
|
+
if isinstance(parsed, dict) and parsed.get("type") == "assistant_with_tools":
|
|
173
|
+
result.append({
|
|
174
|
+
"role": "assistant",
|
|
175
|
+
"content": "",
|
|
176
|
+
"tool_calls": parsed.get("toolCalls", []),
|
|
177
|
+
})
|
|
178
|
+
continue
|
|
179
|
+
except (json.JSONDecodeError, TypeError):
|
|
180
|
+
pass
|
|
181
|
+
result.append({"role": "assistant", "content": content})
|
|
182
|
+
|
|
183
|
+
elif role == "tool":
|
|
184
|
+
result.append({
|
|
185
|
+
"role": "tool",
|
|
186
|
+
"content": content,
|
|
187
|
+
"tool_call_id": msg.get("tool_call_id"),
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
elif role == "user":
|
|
191
|
+
result.append({"role": "user", "content": content})
|
|
192
|
+
|
|
193
|
+
return result
|
|
194
|
+
|
|
195
|
+
def _create_session_with_id(self, session_id: str, title: str) -> dict:
|
|
196
|
+
import json
|
|
197
|
+
from datetime import datetime, timezone
|
|
198
|
+
|
|
199
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
200
|
+
session = {
|
|
201
|
+
"id": session_id,
|
|
202
|
+
"title": title[:50],
|
|
203
|
+
"created_at": now,
|
|
204
|
+
"updated_at": now,
|
|
205
|
+
"prompt_tokens": 0,
|
|
206
|
+
"completion_tokens": 0,
|
|
207
|
+
"summary_message_index": None,
|
|
208
|
+
"messages": [],
|
|
209
|
+
}
|
|
210
|
+
session_dir = Path(self._work_dir) / ".txcode" / "session"
|
|
211
|
+
session_dir.mkdir(parents=True, exist_ok=True)
|
|
212
|
+
session_path = session_dir / f"session_{session_id}.json"
|
|
213
|
+
with open(session_path, "w", encoding="utf-8") as f:
|
|
214
|
+
json.dump(session, f, ensure_ascii=False, indent=2)
|
|
215
|
+
return session
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from ..provider.base import BaseProvider
|
|
6
|
+
from ..session.manager import SessionManager
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class CompactCheck:
|
|
11
|
+
needed: bool
|
|
12
|
+
current_tokens: int
|
|
13
|
+
threshold: int
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class CompactResult:
|
|
18
|
+
success: bool
|
|
19
|
+
summary: str = ""
|
|
20
|
+
tokens_before: int = 0
|
|
21
|
+
tokens_after: int = 0
|
|
22
|
+
error: str | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ContextCompressor:
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
max_tokens: int = 150_000,
|
|
29
|
+
provider: BaseProvider | None = None,
|
|
30
|
+
session_manager: SessionManager | None = None,
|
|
31
|
+
):
|
|
32
|
+
self._max_tokens = max_tokens
|
|
33
|
+
self._provider = provider
|
|
34
|
+
self._session_manager = session_manager
|
|
35
|
+
|
|
36
|
+
def check_needs_compact(self, session_id: str) -> CompactCheck:
|
|
37
|
+
if not self._session_manager:
|
|
38
|
+
return CompactCheck(needed=False, current_tokens=0, threshold=self._max_tokens)
|
|
39
|
+
|
|
40
|
+
session = self._session_manager.get(session_id)
|
|
41
|
+
if not session:
|
|
42
|
+
return CompactCheck(needed=False, current_tokens=0, threshold=self._max_tokens)
|
|
43
|
+
|
|
44
|
+
total = session.get("prompt_tokens", 0) + session.get("completion_tokens", 0)
|
|
45
|
+
return CompactCheck(
|
|
46
|
+
needed=total >= self._max_tokens,
|
|
47
|
+
current_tokens=total,
|
|
48
|
+
threshold=self._max_tokens,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
async def compact(self, session_id: str) -> CompactResult:
|
|
52
|
+
if not self._session_manager or not self._provider:
|
|
53
|
+
return CompactResult(success=False, error="No session manager or provider")
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
session = self._session_manager.get(session_id)
|
|
57
|
+
if not session:
|
|
58
|
+
return CompactResult(success=False, error="Session not found")
|
|
59
|
+
|
|
60
|
+
tokens_before = session.get("prompt_tokens", 0) + session.get("completion_tokens", 0)
|
|
61
|
+
|
|
62
|
+
from ..agent.summarizer.summarizer_agent import SummarizerAgent
|
|
63
|
+
summarizer = SummarizerAgent(self._provider, self._max_tokens)
|
|
64
|
+
result = await summarizer.compact(self._session_manager, session_id)
|
|
65
|
+
|
|
66
|
+
return CompactResult(
|
|
67
|
+
success=result.success,
|
|
68
|
+
summary=result.summary,
|
|
69
|
+
tokens_before=tokens_before,
|
|
70
|
+
tokens_after=0,
|
|
71
|
+
error=result.error,
|
|
72
|
+
)
|
|
73
|
+
except Exception as e:
|
|
74
|
+
return CompactResult(success=False, error=str(e))
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .queue import HookQueue
|
|
4
|
+
from .processor import HookProcessor
|
|
5
|
+
from .types import HookMessage
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Hooks:
|
|
9
|
+
def __init__(self):
|
|
10
|
+
self.queue = HookQueue()
|
|
11
|
+
self.processor = HookProcessor(self.queue)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def create_hooks(provider, session_manager, work_dir: str) -> Hooks:
|
|
15
|
+
from .handlers.memory import MemoryHandler
|
|
16
|
+
|
|
17
|
+
hooks = Hooks()
|
|
18
|
+
hooks.queue.register(MemoryHandler(provider, session_manager, work_dir))
|
|
19
|
+
return hooks
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
from ..types import HookMessage
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BaseHookHandler(ABC):
|
|
9
|
+
trigger: str = ""
|
|
10
|
+
alternate_triggers: list[str] = []
|
|
11
|
+
|
|
12
|
+
def should_handle(self, message: HookMessage) -> bool:
|
|
13
|
+
if message.trigger == self.trigger:
|
|
14
|
+
return True
|
|
15
|
+
return message.trigger in self.alternate_triggers
|
|
16
|
+
|
|
17
|
+
@abstractmethod
|
|
18
|
+
async def handle(self, message: HookMessage):
|
|
19
|
+
...
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .base import BaseHookHandler
|
|
7
|
+
from ..types import HookMessage
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MemoryHandler(BaseHookHandler):
|
|
11
|
+
trigger = "round"
|
|
12
|
+
alternate_triggers = ["before_compact", "chat_end"]
|
|
13
|
+
|
|
14
|
+
def __init__(self, provider: Any, session_manager: Any, work_dir: str):
|
|
15
|
+
self._provider = provider
|
|
16
|
+
self._session_manager = session_manager
|
|
17
|
+
self._work_dir = work_dir
|
|
18
|
+
|
|
19
|
+
async def handle(self, message: HookMessage):
|
|
20
|
+
from ...agent.mem.mem_agent import MemAgent
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
mem_agent = MemAgent(
|
|
24
|
+
provider=self._provider,
|
|
25
|
+
work_dir=message.metadata.get("project_path", self._work_dir),
|
|
26
|
+
session_manager=self._session_manager,
|
|
27
|
+
)
|
|
28
|
+
await mem_agent.run(message.messages)
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from .queue import HookQueue
|
|
6
|
+
from .types import HookMessage
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class HookProcessor:
|
|
10
|
+
def __init__(self, queue: HookQueue):
|
|
11
|
+
self._queue = queue
|
|
12
|
+
self._tasks: list[asyncio.Task] = []
|
|
13
|
+
|
|
14
|
+
def dispatch(self, message: HookMessage):
|
|
15
|
+
task = asyncio.create_task(self._process(message))
|
|
16
|
+
self._tasks.append(task)
|
|
17
|
+
|
|
18
|
+
async def _process(self, message: HookMessage):
|
|
19
|
+
await asyncio.sleep(0)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .handlers.base import BaseHookHandler
|
|
7
|
+
from .types import HookMessage
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class HookQueue:
|
|
11
|
+
def __init__(self):
|
|
12
|
+
self._handlers: list[BaseHookHandler] = []
|
|
13
|
+
|
|
14
|
+
def register(self, handler: BaseHookHandler):
|
|
15
|
+
self._handlers.append(handler)
|
|
16
|
+
|
|
17
|
+
def emit(self, trigger: str, data: dict[str, Any]):
|
|
18
|
+
message = HookMessage(
|
|
19
|
+
messages=data.get("messages", []),
|
|
20
|
+
trigger=trigger,
|
|
21
|
+
metadata=data.get("metadata", {}),
|
|
22
|
+
)
|
|
23
|
+
for handler in self._handlers:
|
|
24
|
+
if handler.should_handle(message):
|
|
25
|
+
try:
|
|
26
|
+
loop = asyncio.get_running_loop()
|
|
27
|
+
loop.create_task(handler.handle(message))
|
|
28
|
+
except RuntimeError:
|
|
29
|
+
pass
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any, AsyncGenerator
|
|
5
|
+
|
|
6
|
+
from ..types import ChatMessage, ProviderResponse, TokenUsage
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BaseProvider(ABC):
|
|
10
|
+
@abstractmethod
|
|
11
|
+
async def chat(
|
|
12
|
+
self,
|
|
13
|
+
messages: list[ChatMessage],
|
|
14
|
+
tools: list[dict] | None = None,
|
|
15
|
+
abort_signal: Any = None,
|
|
16
|
+
log_context: dict | None = None,
|
|
17
|
+
) -> ProviderResponse:
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
@abstractmethod
|
|
21
|
+
async def chat_stream(
|
|
22
|
+
self,
|
|
23
|
+
messages: list[ChatMessage],
|
|
24
|
+
tools: list[dict] | None = None,
|
|
25
|
+
abort_signal: Any = None,
|
|
26
|
+
) -> AsyncGenerator[str, None]:
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
@abstractmethod
|
|
30
|
+
def get_model(self) -> str:
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
def get_base_url(self) -> str:
|
|
34
|
+
return ""
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from openai import AsyncOpenAI
|
|
6
|
+
|
|
7
|
+
from .openai_provider import OpenAIProvider
|
|
8
|
+
from ..types import ProviderResponse, TokenUsage
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DeepSeekProvider(OpenAIProvider):
|
|
12
|
+
def __init__(self, api_key: str, base_url: str = "https://api.deepseek.com/v1", model: str = "deepseek-chat"):
|
|
13
|
+
self._model = model
|
|
14
|
+
self._base_url = base_url
|
|
15
|
+
self._client = AsyncOpenAI(
|
|
16
|
+
api_key=api_key,
|
|
17
|
+
base_url=base_url,
|
|
18
|
+
default_headers={
|
|
19
|
+
"HTTP-Referer": "https://www.homecommunity.cn",
|
|
20
|
+
"X-Title": "txcode",
|
|
21
|
+
},
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
def _parse_response(self, response: Any) -> ProviderResponse:
|
|
25
|
+
if not response.choices:
|
|
26
|
+
raise RuntimeError("Invalid response: no choices")
|
|
27
|
+
choice = response.choices[0]
|
|
28
|
+
msg = choice.message
|
|
29
|
+
|
|
30
|
+
usage = None
|
|
31
|
+
if response.usage:
|
|
32
|
+
usage = TokenUsage(
|
|
33
|
+
prompt_tokens=response.usage.prompt_tokens,
|
|
34
|
+
completion_tokens=response.usage.completion_tokens,
|
|
35
|
+
total_tokens=response.usage.total_tokens,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
result = ProviderResponse(
|
|
39
|
+
content=msg.content or "",
|
|
40
|
+
finish_reason=choice.finish_reason or "stop",
|
|
41
|
+
usage=usage,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
reasoning = getattr(msg, "reasoning_content", None) or getattr(response, "reasoning", None)
|
|
45
|
+
result.reasoning = reasoning
|
|
46
|
+
|
|
47
|
+
if msg.tool_calls:
|
|
48
|
+
result.tool_calls = [
|
|
49
|
+
{
|
|
50
|
+
"id": tc.id,
|
|
51
|
+
"type": "function",
|
|
52
|
+
"function": {
|
|
53
|
+
"name": tc.function.name,
|
|
54
|
+
"arguments": tc.function.arguments,
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
for tc in msg.tool_calls
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
return result
|