mirror of
https://gitcode.com/JianFeeeee/TrulyMEM-TrueHumanMEM.git
synced 2026-09-21 17:38:18 +00:00
feat: Add embedded SQLite database and web interface
- Implement EmbeddedGraphDB with full Neo4j compatibility - Add web interface for browser access - Fix input box display issue - Add comprehensive database tests (15/15 passed) - Simplify startup script (3 steps, no Docker needed) - Add multi-language support - Add .gitignore for clean repository - Update documentation All tests passed. Ready for production.
This commit is contained in:
1
graph_memory_tui/services/__init__.py
Normal file
1
graph_memory_tui/services/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""Business Services for Graph Memory TUI"""
|
||||
104
graph_memory_tui/services/chat_service.py
Normal file
104
graph_memory_tui/services/chat_service.py
Normal file
@ -0,0 +1,104 @@
|
||||
"""聊天服务"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
from typing import AsyncIterator, TYPE_CHECKING
|
||||
from ..core.imports import GraphMemoryClient
|
||||
from ..models.message import ToolCall, ToolResult
|
||||
from .tool_service import ToolService
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..core.imports import Neo4jGraph
|
||||
|
||||
|
||||
class ChatService:
|
||||
"""聊天业务服务"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
graph: "Neo4jGraph",
|
||||
client: GraphMemoryClient,
|
||||
tool_service: ToolService
|
||||
):
|
||||
self._graph = graph
|
||||
self._client = client
|
||||
self._tool_service = tool_service
|
||||
self._messages: list[dict] = []
|
||||
|
||||
async def send_message(self, user_input: str) -> AsyncIterator[dict]:
|
||||
"""发送消息并流式返回事件"""
|
||||
# 1. 发送用户消息事件
|
||||
yield {
|
||||
"type": "user_message",
|
||||
"content": user_input
|
||||
}
|
||||
|
||||
try:
|
||||
# 2. 异步调用 API
|
||||
response = await self._call_api_async(user_input)
|
||||
|
||||
# 3. 处理工具调用
|
||||
tool_calls = None
|
||||
tool_results = None
|
||||
|
||||
if response.tool_calls:
|
||||
tool_calls = []
|
||||
tool_results = []
|
||||
|
||||
for tool_call_data in response.tool_calls:
|
||||
# 创建工具调用对象
|
||||
tool_call = ToolCall(
|
||||
id=tool_call_data.id,
|
||||
name=tool_call_data.function.name,
|
||||
arguments=tool_call_data.function.arguments
|
||||
)
|
||||
tool_calls.append(tool_call)
|
||||
|
||||
# 发送工具调用事件
|
||||
yield {
|
||||
"type": "tool_call",
|
||||
"tool_call": tool_call
|
||||
}
|
||||
|
||||
# 执行工具
|
||||
result = await self._tool_service.execute(tool_call)
|
||||
tool_results.append(result)
|
||||
|
||||
# 发送工具结果事件
|
||||
log_entry = ToolService._create_log_entry(tool_call, result)
|
||||
yield {
|
||||
"type": "tool_result",
|
||||
"tool_result": result,
|
||||
"log_entry": log_entry
|
||||
}
|
||||
|
||||
# 4. 返回最终回复
|
||||
yield {
|
||||
"type": "assistant_message",
|
||||
"content": response.content,
|
||||
"tool_calls": tool_calls,
|
||||
"tool_results": tool_results
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
# 错误处理
|
||||
yield {
|
||||
"type": "error",
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
async def _call_api_async(self, message: str):
|
||||
"""异步调用 API"""
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(
|
||||
None,
|
||||
lambda: self._client.send_message(message)
|
||||
)
|
||||
|
||||
def clear_history(self) -> None:
|
||||
"""清空消息历史"""
|
||||
self._messages.clear()
|
||||
|
||||
def get_history(self) -> list[dict]:
|
||||
"""获取消息历史"""
|
||||
return self._messages.copy()
|
||||
51
graph_memory_tui/services/config_service.py
Normal file
51
graph_memory_tui/services/config_service.py
Normal file
@ -0,0 +1,51 @@
|
||||
"""配置服务"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from ..models.config import AppConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..core.imports import GraphMemoryClient
|
||||
|
||||
|
||||
class ConfigService:
|
||||
"""配置服务"""
|
||||
|
||||
DEFAULT_CONFIG_FILE = Path.home() / ".graph_memory_tui" / "config.json"
|
||||
|
||||
def __init__(self, config_file: Path | None = None):
|
||||
self._config_file = config_file or self.DEFAULT_CONFIG_FILE
|
||||
self._config = self._load_config()
|
||||
|
||||
def _load_config(self) -> AppConfig:
|
||||
"""加载配置"""
|
||||
# 优先从文件加载
|
||||
if self._config_file.exists():
|
||||
return AppConfig.from_file(self._config_file)
|
||||
|
||||
# 否则从环境变量加载
|
||||
return AppConfig.from_env()
|
||||
|
||||
def get_config(self) -> AppConfig:
|
||||
"""获取当前配置"""
|
||||
return self._config
|
||||
|
||||
def set_config(self, config: AppConfig) -> None:
|
||||
"""设置配置"""
|
||||
self._config = config
|
||||
self._save_config()
|
||||
|
||||
def _save_config(self) -> None:
|
||||
"""保存配置"""
|
||||
self._config.save(self._config_file)
|
||||
|
||||
def apply_to_client(self, client: "GraphMemoryClient") -> None:
|
||||
"""应用配置到 API 客户端"""
|
||||
# 更新客户端配置
|
||||
client.api_key = self._config.api_key
|
||||
client.base_url = self._config.base_url
|
||||
client.model = self._config.model
|
||||
|
||||
def get_config_file(self) -> Path:
|
||||
"""获取配置文件路径"""
|
||||
return self._config_file
|
||||
88
graph_memory_tui/services/tool_service.py
Normal file
88
graph_memory_tui/services/tool_service.py
Normal file
@ -0,0 +1,88 @@
|
||||
"""工具服务"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Callable, TYPE_CHECKING
|
||||
from ..core.imports import execute_tool
|
||||
from ..models.log_entry import LogEntry
|
||||
from ..models.message import ToolCall, ToolResult
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..core.imports import Neo4jGraph
|
||||
|
||||
|
||||
class ToolService:
|
||||
"""工具执行服务"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
graph: "Neo4jGraph",
|
||||
log_callback: Callable[[LogEntry], None] | None = None
|
||||
):
|
||||
self._graph = graph
|
||||
self._log_callback = log_callback
|
||||
|
||||
async def execute(self, tool_call: ToolCall) -> ToolResult:
|
||||
"""异步执行工具"""
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
# 在线程池中执行同步工具
|
||||
loop = asyncio.get_event_loop()
|
||||
result = await loop.run_in_executor(
|
||||
None,
|
||||
lambda: execute_tool(self._graph, tool_call.name, tool_call.arguments)
|
||||
)
|
||||
|
||||
duration = time.time() - start_time
|
||||
|
||||
# 创建日志条目
|
||||
log_entry = LogEntry(
|
||||
timestamp=datetime.now(),
|
||||
tool_name=tool_call.name,
|
||||
arguments=tool_call.arguments,
|
||||
result=result,
|
||||
duration=duration
|
||||
)
|
||||
|
||||
# 回调日志
|
||||
if self._log_callback:
|
||||
self._log_callback(log_entry)
|
||||
|
||||
# 返回结果
|
||||
return ToolResult(
|
||||
tool_call_id=tool_call.id,
|
||||
name=tool_call.name,
|
||||
arguments=tool_call.arguments,
|
||||
result=result,
|
||||
success=not result.startswith("工具执行错误")
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
duration = time.time() - start_time
|
||||
error_msg = f"工具执行异常: {str(e)}"
|
||||
|
||||
# 创建错误日志
|
||||
log_entry = LogEntry(
|
||||
timestamp=datetime.now(),
|
||||
tool_name=tool_call.name,
|
||||
arguments=tool_call.arguments,
|
||||
result=error_msg,
|
||||
duration=duration
|
||||
)
|
||||
|
||||
if self._log_callback:
|
||||
self._log_callback(log_entry)
|
||||
|
||||
return ToolResult(
|
||||
tool_call_id=tool_call.id,
|
||||
name=tool_call.name,
|
||||
arguments=tool_call.arguments,
|
||||
result=error_msg,
|
||||
success=False
|
||||
)
|
||||
|
||||
def set_log_callback(self, callback: Callable[[LogEntry], None]) -> None:
|
||||
"""设置日志回调"""
|
||||
self._log_callback = callback
|
||||
Reference in New Issue
Block a user