Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 142904dff4 | |||
| b9e99da01b |
208
main_v2.py
208
main_v2.py
@@ -18,11 +18,11 @@ import os
|
||||
from models_v2 import (
|
||||
init_db, get_db, SessionLocal,
|
||||
User, Conversation, Message, SystemConfig,
|
||||
LLMProvider, Agent, Channel, ChannelAgentMapping, MatrixRoomMapping, SearchToolConfig,
|
||||
LLMProvider, Agent, Channel, ChannelAgentMapping, MatrixRoomMapping, ToolConfig, ToolUsageLog,
|
||||
init_default_data
|
||||
)
|
||||
from services.llm_service import llm_service
|
||||
from services.agent_service import AgentService, LLMProviderService, ChannelService, SearchToolService
|
||||
from services.agent_service import AgentService, LLMProviderService, ChannelService, ToolService
|
||||
from services.conversation_service import ConversationService
|
||||
|
||||
# 配置日志
|
||||
@@ -419,123 +419,157 @@ async def unbind_agent(mapping_id: int, db: Session = Depends(get_db)):
|
||||
return {"success": success}
|
||||
|
||||
|
||||
# ==================== 搜索工具 API ====================
|
||||
# ==================== 工具配置 API ====================
|
||||
|
||||
@app.get("/api/v2/search-tools")
|
||||
async def get_search_tools(db: Session = Depends(get_db)):
|
||||
"""获取所有搜索工具配置"""
|
||||
service = SearchToolService(db)
|
||||
configs = service.get_all_configs()
|
||||
@app.get("/api/v2/tools")
|
||||
async def get_tools(tool_type: str = None, db: Session = Depends(get_db)):
|
||||
"""获取所有工具配置"""
|
||||
service = ToolService(db)
|
||||
if tool_type:
|
||||
tools = service.get_tools_by_type(tool_type)
|
||||
else:
|
||||
tools = service.get_all_tools()
|
||||
|
||||
return {
|
||||
"configs": [
|
||||
"tools": [
|
||||
{
|
||||
"id": c.id,
|
||||
"name": c.name,
|
||||
"provider": c.provider,
|
||||
"api_key": c.api_key,
|
||||
"api_base": c.api_base,
|
||||
"max_results": c.max_results,
|
||||
"include_raw_content": c.include_raw_content,
|
||||
"search_depth": c.search_depth,
|
||||
"is_active": c.is_active,
|
||||
"is_default": c.is_default
|
||||
"id": t.id,
|
||||
"name": t.name,
|
||||
"tool_type": t.tool_type,
|
||||
"provider": t.provider,
|
||||
"config": t.config,
|
||||
"is_active": t.is_active,
|
||||
"is_default": t.is_default,
|
||||
"total_calls": t.total_calls,
|
||||
"success_calls": t.success_calls,
|
||||
"failed_calls": t.failed_calls
|
||||
}
|
||||
for c in configs
|
||||
for t in tools
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/v2/search-tools")
|
||||
async def create_search_tool(data: dict, db: Session = Depends(get_db)):
|
||||
"""创建搜索工具配置"""
|
||||
service = SearchToolService(db)
|
||||
|
||||
# 如果设为默认,更新其他
|
||||
if data.get('is_default'):
|
||||
service.set_default_config(0) # 先清除所有默认
|
||||
|
||||
config = service.create_config(data)
|
||||
return {"success": True, "config": {"id": config.id, "name": config.name}}
|
||||
@app.post("/api/v2/tools")
|
||||
async def create_tool(data: dict, db: Session = Depends(get_db)):
|
||||
"""创建工具配置"""
|
||||
service = ToolService(db)
|
||||
tool = service.create_tool(data)
|
||||
return {"success": True, "tool": {"id": tool.id, "name": tool.name, "tool_type": tool.tool_type}}
|
||||
|
||||
|
||||
@app.put("/api/v2/search-tools/{config_id}")
|
||||
async def update_search_tool(config_id: int, data: dict, db: Session = Depends(get_db)):
|
||||
"""更新搜索工具配置"""
|
||||
service = SearchToolService(db)
|
||||
@app.put("/api/v2/tools/{tool_id}")
|
||||
async def update_tool(tool_id: int, data: dict, db: Session = Depends(get_db)):
|
||||
"""更新工具配置"""
|
||||
service = ToolService(db)
|
||||
|
||||
if data.get('is_default'):
|
||||
service.set_default_config(config_id)
|
||||
service.set_default_tool(tool_id)
|
||||
|
||||
config = service.update_config(config_id, data)
|
||||
tool = service.update_tool(tool_id, data)
|
||||
|
||||
if not config:
|
||||
return {"success": False, "message": "配置不存在"}
|
||||
if not tool:
|
||||
return {"success": False, "message": "工具不存在"}
|
||||
|
||||
return {"success": True, "config": {"id": config.id, "name": config.name}}
|
||||
return {"success": True, "tool": {"id": tool.id, "name": tool.name}}
|
||||
|
||||
|
||||
@app.delete("/api/v2/search-tools/{config_id}")
|
||||
async def delete_search_tool(config_id: int, db: Session = Depends(get_db)):
|
||||
"""删除搜索工具配置"""
|
||||
service = SearchToolService(db)
|
||||
success = service.delete_config(config_id)
|
||||
@app.delete("/api/v2/tools/{tool_id}")
|
||||
async def delete_tool(tool_id: int, db: Session = Depends(get_db)):
|
||||
"""删除工具配置"""
|
||||
service = ToolService(db)
|
||||
success = service.delete_tool(tool_id)
|
||||
|
||||
return {"success": success}
|
||||
|
||||
|
||||
@app.post("/api/v2/search-tools/{config_id}/default")
|
||||
async def set_search_tool_default(config_id: int, db: Session = Depends(get_db)):
|
||||
"""设置默认搜索工具"""
|
||||
service = SearchToolService(db)
|
||||
success = service.set_default_config(config_id)
|
||||
@app.post("/api/v2/tools/{tool_id}/default")
|
||||
async def set_tool_default(tool_id: int, db: Session = Depends(get_db)):
|
||||
"""设置默认工具"""
|
||||
service = ToolService(db)
|
||||
success = service.set_default_tool(tool_id)
|
||||
|
||||
return {"success": success}
|
||||
|
||||
|
||||
@app.post("/api/v2/search")
|
||||
@app.get("/api/v2/tools/stats")
|
||||
async def get_tool_stats(days: int = 7, db: Session = Depends(get_db)):
|
||||
"""获取工具使用统计"""
|
||||
service = ToolService(db)
|
||||
stats = service.get_usage_stats(days=days)
|
||||
return stats
|
||||
|
||||
|
||||
@app.post("/api/v2/tools/search")
|
||||
async def perform_search(data: dict, db: Session = Depends(get_db)):
|
||||
"""执行搜索(供前端或Agent调用)"""
|
||||
import httpx
|
||||
import time
|
||||
|
||||
query = data.get('query')
|
||||
if not query:
|
||||
return {"success": False, "message": "缺少搜索关键词"}
|
||||
|
||||
# 获取搜索工具配置
|
||||
service = SearchToolService(db)
|
||||
config_id = data.get('config_id')
|
||||
service = ToolService(db)
|
||||
tool_id = data.get('tool_id')
|
||||
|
||||
if config_id:
|
||||
config = service.get_config(config_id)
|
||||
if tool_id:
|
||||
tool = service.get_tool(tool_id)
|
||||
else:
|
||||
config = service.get_default_config()
|
||||
tool = service.get_default_tool('search')
|
||||
|
||||
if not config or not config.api_key:
|
||||
if not tool or not tool.config.get('api_key'):
|
||||
return {"success": False, "message": "未配置搜索工具"}
|
||||
|
||||
# Tavily Search API
|
||||
if config.provider == 'tavily':
|
||||
if tool.provider == 'tavily' or tool.tool_type == 'search':
|
||||
start_time = time.time()
|
||||
try:
|
||||
tavily_url = "https://api.tavily.com/search"
|
||||
config = tool.config
|
||||
payload = {
|
||||
"api_key": config.api_key,
|
||||
"api_key": config.get('api_key'),
|
||||
"query": query,
|
||||
"max_results": config.max_results,
|
||||
"include_raw_content": config.include_raw_content,
|
||||
"search_depth": config.search_depth
|
||||
"max_results": config.get('max_results', 5),
|
||||
"include_raw_content": config.get('include_raw_content', False),
|
||||
"search_depth": config.get('search_depth', 'basic')
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(tavily_url, json=payload)
|
||||
result = response.json()
|
||||
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
# 更新统计和日志
|
||||
service.increment_stats(tool.id, True)
|
||||
service.log_usage({
|
||||
'tool_id': tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': query,
|
||||
'success': True,
|
||||
'result_summary': f'{len(result.get("results", []))} results',
|
||||
'conversation_id': data.get('conversation_id'),
|
||||
'agent_id': data.get('agent_id'),
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"results": result.get("results", []),
|
||||
"query": query
|
||||
}
|
||||
except Exception as e:
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
service.increment_stats(tool.id, False)
|
||||
service.log_usage({
|
||||
'tool_id': tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': query,
|
||||
'success': False,
|
||||
'error_message': str(e),
|
||||
'conversation_id': data.get('conversation_id'),
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
return {"success": False, "message": "不支持的搜索提供商"}
|
||||
@@ -750,40 +784,68 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
# 检查是否需要执行搜索
|
||||
search_context = None
|
||||
if 'search' in agent_tools and 'search' not in disabled_tools:
|
||||
# 使用关键词检测:如果消息包含搜索相关关键词,执行搜索
|
||||
search_keywords = ['搜索', '查找', '查询', '最新', '新闻', '新闻', 'weather', '天气', '股价', '股票', '汇率', 'what is', 'what are', 'find', 'search', 'look up']
|
||||
should_search = any(kw in message.lower() for kw in search_keywords)
|
||||
# 只要启用了搜索工具且未禁用,就执行搜索(不再依赖关键词检测)
|
||||
should_search = True
|
||||
|
||||
if should_search:
|
||||
# 执行搜索
|
||||
search_service = SearchToolService(db)
|
||||
search_config = search_service.get_default_config()
|
||||
tool_service = ToolService(db)
|
||||
search_tool = tool_service.get_default_tool('search')
|
||||
|
||||
if search_config and search_config.api_key:
|
||||
if search_tool and search_tool.config.get('api_key'):
|
||||
import httpx
|
||||
import time
|
||||
start_time = time.time()
|
||||
try:
|
||||
logger.info(f"执行搜索: query={message}")
|
||||
tavily_url = "https://api.tavily.com/search"
|
||||
config = search_tool.config
|
||||
payload = {
|
||||
"api_key": search_config.api_key,
|
||||
"api_key": config.get('api_key'),
|
||||
"query": message,
|
||||
"max_results": search_config.max_results,
|
||||
"search_depth": search_config.search_depth
|
||||
"max_results": config.get('max_results', 5),
|
||||
"search_depth": config.get('search_depth', 'basic')
|
||||
}
|
||||
|
||||
# 同步调用(简化处理)
|
||||
# 同步调用
|
||||
with httpx.Client(timeout=30) as client:
|
||||
resp = client.post(tavily_url, json=payload)
|
||||
search_result = resp.json()
|
||||
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
|
||||
if search_result.get("results"):
|
||||
# 构建搜索上下文
|
||||
search_context = "\n\n【搜索结果】\n"
|
||||
for i, r in enumerate(search_result["results"][:5], 1):
|
||||
search_context += f"{i}. {r.get('title', 'N/A')}\n {r.get('content', r.get('snippet', 'N/A'))[:200]}\n 来源: {r.get('url', 'N/A')}\n"
|
||||
logger.info(f"搜索完成: {len(search_result['results'])} 条结果")
|
||||
|
||||
# 更新统计和日志
|
||||
tool_service.increment_stats(search_tool.id, True)
|
||||
tool_service.log_usage({
|
||||
'tool_id': search_tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': message,
|
||||
'success': True,
|
||||
'result_summary': f'{len(search_result["results"])} results',
|
||||
'conversation_id': conversation_id,
|
||||
'agent_id': current_agent_id,
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
except Exception as e:
|
||||
duration_ms = int((time.time() - start_time) * 1000)
|
||||
logger.error(f"搜索失败: {e}")
|
||||
tool_service.increment_stats(search_tool.id, False)
|
||||
tool_service.log_usage({
|
||||
'tool_id': search_tool.id,
|
||||
'tool_type': 'search',
|
||||
'query': message,
|
||||
'success': False,
|
||||
'error_message': str(e),
|
||||
'conversation_id': conversation_id,
|
||||
'duration_ms': duration_ms
|
||||
})
|
||||
|
||||
# 获取或创建会话
|
||||
if conversation_id:
|
||||
|
||||
55
models_v2.py
55
models_v2.py
@@ -229,31 +229,58 @@ class MatrixRoomMapping(Base):
|
||||
|
||||
# ==================== 搜索工具配置 ====================
|
||||
|
||||
class SearchToolConfig(Base):
|
||||
"""搜索工具配置(Tavily等)"""
|
||||
__tablename__ = 'search_tool_config'
|
||||
class ToolConfig(Base):
|
||||
"""工具配置(通用,支持搜索、计算器、代码执行等)"""
|
||||
__tablename__ = 'tool_configs'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100)) # 工具名称,如 "Tavily Search"
|
||||
provider = Column(String(50)) # 提供商:tavily, google, bing
|
||||
name = Column(String(100)) # 工具名称,如 "Tavily Search"、"Calculator"
|
||||
tool_type = Column(String(50), index=True) # 工具类型:search, calculator, code_runner, image_gen, etc.
|
||||
provider = Column(String(50), nullable=True) # 提供商(可选):tavily, google, wolfram, etc.
|
||||
|
||||
# API配置
|
||||
api_key = Column(String(200)) # API密钥
|
||||
api_base = Column(String(200), nullable=True) # API地址(可选)
|
||||
|
||||
# 搜索参数
|
||||
max_results = Column(Integer, default=5) # 最大返回结果数
|
||||
include_raw_content = Column(Boolean, default=False) # 是否包含原始内容
|
||||
search_depth = Column(String(20), default='basic') # basic 或 advanced
|
||||
# API配置(JSON,不同工具可能有不同配置)
|
||||
config = Column(JSON, default=dict)
|
||||
# search示例: {"api_key": "xxx", "max_results": 5, "search_depth": "basic"}
|
||||
# calculator示例: {"api_base": "xxx"}
|
||||
|
||||
# 状态
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_default = Column(Boolean, default=False) # 是否为默认搜索工具
|
||||
is_default = Column(Boolean, default=False) # 是否为该类型的默认工具
|
||||
|
||||
# 统计
|
||||
total_calls = Column(Integer, default=0) # 总调用次数
|
||||
success_calls = Column(Integer, default=0) # 成功次数
|
||||
failed_calls = Column(Integer, default=0) # 失败次数
|
||||
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class ToolUsageLog(Base):
|
||||
"""工具使用日志"""
|
||||
__tablename__ = 'tool_usage_logs'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
tool_id = Column(Integer, ForeignKey('tool_configs.id'))
|
||||
tool_type = Column(String(50), index=True)
|
||||
|
||||
# 调用信息
|
||||
query = Column(Text) # 调用参数/查询内容
|
||||
success = Column(Boolean, default=True)
|
||||
error_message = Column(Text, nullable=True)
|
||||
result_summary = Column(Text, nullable=True) # 结果摘要
|
||||
|
||||
# 关联信息
|
||||
conversation_id = Column(String(100), nullable=True)
|
||||
agent_id = Column(Integer, nullable=True)
|
||||
user_id = Column(String(100), nullable=True)
|
||||
|
||||
# 性能
|
||||
duration_ms = Column(Integer, nullable=True) # 调用耗时(毫秒)
|
||||
|
||||
called_at = Column(DateTime, default=datetime.utcnow)
|
||||
|
||||
|
||||
# ==================== 系统配置(保留) ====================
|
||||
|
||||
class SystemConfig(Base):
|
||||
|
||||
@@ -5,7 +5,7 @@ from sqlalchemy.orm import Session
|
||||
from typing import List, Optional, Dict
|
||||
import logging
|
||||
|
||||
from models_v2 import Agent, LLMProvider, ChannelAgentMapping, Channel, SearchToolConfig, init_default_data
|
||||
from models_v2 import Agent, LLMProvider, ChannelAgentMapping, Channel, ToolConfig, ToolUsageLog, init_default_data
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -409,84 +409,169 @@ class ChannelService:
|
||||
}
|
||||
|
||||
|
||||
class SearchToolService:
|
||||
"""搜索工具管理服务"""
|
||||
class ToolService:
|
||||
"""工具管理服务"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_all_configs(self) -> List[SearchToolConfig]:
|
||||
"""获取所有搜索工具配置"""
|
||||
return self.db.query(SearchToolConfig).order_by(SearchToolConfig.is_default.desc(), SearchToolConfig.name).all()
|
||||
def get_all_tools(self) -> List[ToolConfig]:
|
||||
"""获取所有工具配置"""
|
||||
return self.db.query(ToolConfig).order_by(ToolConfig.tool_type, ToolConfig.is_default.desc()).all()
|
||||
|
||||
def get_active_configs(self) -> List[SearchToolConfig]:
|
||||
"""获取活跃的搜索工具配置"""
|
||||
return self.db.query(SearchToolConfig).filter(SearchToolConfig.is_active == True).all()
|
||||
def get_tools_by_type(self, tool_type: str) -> List[ToolConfig]:
|
||||
"""获取指定类型的工具"""
|
||||
return self.db.query(ToolConfig).filter(ToolConfig.tool_type == tool_type).all()
|
||||
|
||||
def get_config(self, config_id: int) -> Optional[SearchToolConfig]:
|
||||
"""获取单个配置"""
|
||||
return self.db.query(SearchToolConfig).filter(SearchToolConfig.id == config_id).first()
|
||||
def get_active_tools(self) -> List[ToolConfig]:
|
||||
"""获取活跃的工具"""
|
||||
return self.db.query(ToolConfig).filter(ToolConfig.is_active == True).all()
|
||||
|
||||
def get_default_config(self) -> Optional[SearchToolConfig]:
|
||||
"""获取默认配置"""
|
||||
config = self.db.query(SearchToolConfig).filter(
|
||||
SearchToolConfig.is_default == True,
|
||||
SearchToolConfig.is_active == True
|
||||
def get_tool(self, tool_id: int) -> Optional[ToolConfig]:
|
||||
"""获取单个工具"""
|
||||
return self.db.query(ToolConfig).filter(ToolConfig.id == tool_id).first()
|
||||
|
||||
def get_default_tool(self, tool_type: str) -> Optional[ToolConfig]:
|
||||
"""获取指定类型的默认工具"""
|
||||
tool = self.db.query(ToolConfig).filter(
|
||||
ToolConfig.tool_type == tool_type,
|
||||
ToolConfig.is_default == True,
|
||||
ToolConfig.is_active == True
|
||||
).first()
|
||||
if not config:
|
||||
config = self.db.query(SearchToolConfig).filter(SearchToolConfig.is_active == True).first()
|
||||
return config
|
||||
if not tool:
|
||||
tool = self.db.query(ToolConfig).filter(
|
||||
ToolConfig.tool_type == tool_type,
|
||||
ToolConfig.is_active == True
|
||||
).first()
|
||||
return tool
|
||||
|
||||
def create_config(self, data: Dict) -> SearchToolConfig:
|
||||
"""创建搜索工具配置"""
|
||||
config = SearchToolConfig(
|
||||
def create_tool(self, data: Dict) -> ToolConfig:
|
||||
"""创建工具配置"""
|
||||
tool = ToolConfig(
|
||||
name=data.get('name'),
|
||||
provider=data.get('provider', 'tavily'),
|
||||
api_key=data.get('api_key'),
|
||||
api_base=data.get('api_base'),
|
||||
max_results=data.get('max_results', 5),
|
||||
include_raw_content=data.get('include_raw_content', False),
|
||||
search_depth=data.get('search_depth', 'basic'),
|
||||
tool_type=data.get('tool_type', 'search'),
|
||||
provider=data.get('provider'),
|
||||
config=data.get('config', {}),
|
||||
is_active=data.get('is_active', True),
|
||||
is_default=data.get('is_default', False)
|
||||
)
|
||||
self.db.add(config)
|
||||
self.db.add(tool)
|
||||
self.db.commit()
|
||||
self.db.refresh(config)
|
||||
return config
|
||||
self.db.refresh(tool)
|
||||
return tool
|
||||
|
||||
def update_config(self, config_id: int, data: Dict) -> Optional[SearchToolConfig]:
|
||||
"""更新配置"""
|
||||
config = self.get_config(config_id)
|
||||
if not config:
|
||||
def update_tool(self, tool_id: int, data: Dict) -> Optional[ToolConfig]:
|
||||
"""更新工具配置"""
|
||||
tool = self.get_tool(tool_id)
|
||||
if not tool:
|
||||
return None
|
||||
|
||||
for key, value in data.items():
|
||||
if hasattr(config, key) and value is not None:
|
||||
setattr(config, key, value)
|
||||
if hasattr(tool, key) and value is not None:
|
||||
setattr(tool, key, value)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(config)
|
||||
return config
|
||||
self.db.refresh(tool)
|
||||
return tool
|
||||
|
||||
def delete_config(self, config_id: int) -> bool:
|
||||
"""删除配置"""
|
||||
config = self.get_config(config_id)
|
||||
if not config:
|
||||
def delete_tool(self, tool_id: int) -> bool:
|
||||
"""删除工具配置"""
|
||||
tool = self.get_tool(tool_id)
|
||||
if not tool:
|
||||
return False
|
||||
|
||||
self.db.delete(config)
|
||||
self.db.delete(tool)
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
def set_default_config(self, config_id: int) -> bool:
|
||||
"""设置默认配置"""
|
||||
self.db.query(SearchToolConfig).update({SearchToolConfig.is_default: False})
|
||||
|
||||
config = self.get_config(config_id)
|
||||
if not config:
|
||||
def set_default_tool(self, tool_id: int) -> bool:
|
||||
"""设置默认工具"""
|
||||
tool = self.get_tool(tool_id)
|
||||
if not tool:
|
||||
return False
|
||||
|
||||
config.is_default = True
|
||||
# 清除同类型的其他默认
|
||||
self.db.query(ToolConfig).filter(
|
||||
ToolConfig.tool_type == tool.tool_type
|
||||
).update({ToolConfig.is_default: False})
|
||||
|
||||
tool.is_default = True
|
||||
self.db.commit()
|
||||
return True
|
||||
return True
|
||||
|
||||
def increment_stats(self, tool_id: int, success: bool):
|
||||
"""更新工具调用统计"""
|
||||
tool = self.get_tool(tool_id)
|
||||
if tool:
|
||||
tool.total_calls += 1
|
||||
if success:
|
||||
tool.success_calls += 1
|
||||
else:
|
||||
tool.failed_calls += 1
|
||||
self.db.commit()
|
||||
|
||||
def log_usage(self, data: Dict) -> ToolUsageLog:
|
||||
"""记录工具使用日志"""
|
||||
log = ToolUsageLog(
|
||||
tool_id=data.get('tool_id'),
|
||||
tool_type=data.get('tool_type'),
|
||||
query=data.get('query'),
|
||||
success=data.get('success', True),
|
||||
error_message=data.get('error_message'),
|
||||
result_summary=data.get('result_summary'),
|
||||
conversation_id=data.get('conversation_id'),
|
||||
agent_id=data.get('agent_id'),
|
||||
user_id=data.get('user_id'),
|
||||
duration_ms=data.get('duration_ms')
|
||||
)
|
||||
self.db.add(log)
|
||||
self.db.commit()
|
||||
self.db.refresh(log)
|
||||
return log
|
||||
|
||||
def get_usage_stats(self, days: int = 7) -> Dict:
|
||||
"""获取工具使用统计"""
|
||||
from datetime import timedelta
|
||||
start_date = datetime.utcnow() - timedelta(days=days)
|
||||
|
||||
# 按工具类型统计
|
||||
logs = self.db.query(ToolUsageLog).filter(
|
||||
ToolUsageLog.called_at >= start_date
|
||||
).all()
|
||||
|
||||
stats = {
|
||||
'total_calls': len(logs),
|
||||
'success_rate': sum(1 for l in logs if l.success) / len(logs) * 100 if logs else 0,
|
||||
'by_type': {},
|
||||
'by_tool': {},
|
||||
'recent_errors': []
|
||||
}
|
||||
|
||||
for log in logs:
|
||||
# 按类型
|
||||
if log.tool_type not in stats['by_type']:
|
||||
stats['by_type'][log.tool_type] = {'total': 0, 'success': 0, 'failed': 0}
|
||||
stats['by_type'][log.tool_type]['total'] += 1
|
||||
if log.success:
|
||||
stats['by_type'][log.tool_type]['success'] += 1
|
||||
else:
|
||||
stats['by_type'][log.tool_type]['failed'] += 1
|
||||
|
||||
# 按工具
|
||||
tool = self.get_tool(log.tool_id) if log.tool_id else None
|
||||
tool_name = tool.name if tool else f'Tool#{log.tool_id}'
|
||||
if tool_name not in stats['by_tool']:
|
||||
stats['by_tool'][tool_name] = {'total': 0, 'success': 0}
|
||||
stats['by_tool'][tool_name]['total'] += 1
|
||||
if log.success:
|
||||
stats['by_tool'][tool_name]['success'] += 1
|
||||
|
||||
# 最近错误
|
||||
if not log.success and log.error_message:
|
||||
stats['recent_errors'].append({
|
||||
'tool': tool_name,
|
||||
'error': log.error_message[:100],
|
||||
'time': log.called_at.isoformat()
|
||||
})
|
||||
|
||||
return stats
|
||||
@@ -42,7 +42,7 @@
|
||||
<div class="nav-item active" data-page="llm-providers"><i class="ri-cloud-line"></i> 大模型池</div>
|
||||
<div class="nav-item" data-page="agents"><i class="ri-robot-2-line"></i> Agent管理</div>
|
||||
<div class="nav-item" data-page="channels"><i class="ri-chat-3-line"></i> 渠道管理</div>
|
||||
<div class="nav-item" data-page="search-tools"><i class="ri-search-line"></i> 搜索工具</div>
|
||||
<div class="nav-item" data-page="tools"><i class="ri-tools-line"></i> 工具管理</div>
|
||||
<div class="nav-item" data-page="stats"><i class="ri-bar-chart-box-line"></i> 统计数据</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -110,19 +110,29 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 搜索工具 -->
|
||||
<div class="page-section" id="page-search-tools">
|
||||
<div class="page-header"><h2><i class="ri-search-line"></i> 搜索工具配置</h2></div>
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between">
|
||||
<span>搜索工具列表(Tavily、Google等)</span>
|
||||
<button class="btn btn-primary btn-sm" onclick="showAddSearchToolModal()"><i class="ri-add-line"></i> 添加</button>
|
||||
<!-- 工具管理 -->
|
||||
<div class="page-section" id="page-tools">
|
||||
<div class="page-header"><h2><i class="ri-tools-line"></i> 工具管理</h2></div>
|
||||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between">
|
||||
<span>工具列表(搜索、计算器、代码执行等)</span>
|
||||
<button class="btn btn-primary btn-sm" onclick="showAddToolModal()"><i class="ri-add-line"></i> 添加工具</button>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<table class="table">
|
||||
<thead><tr><th>名称</th><th>类型</th><th>提供商</th><th>调用次数</th><th>成功率</th><th>默认</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody id="tools-list"><tr><td colspan="8" class="text-center">加载中...</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<table class="table">
|
||||
<thead><tr><th>名称</th><th>提供商</th><th>API Key</th><th>最大结果</th><th>默认</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody id="search-tools-list"><tr><td colspan="7" class="text-center">加载中...</td></tr></tbody>
|
||||
</table>
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-header"><i class="ri-bar-chart-line"></i> 工具使用统计(近7天)</div>
|
||||
<div class="card-body" id="tool-stats">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -200,20 +210,41 @@
|
||||
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button><button type="button" class="btn btn-primary" onclick="saveMatrixConfig()">保存</button></div>
|
||||
</div></div></div>
|
||||
|
||||
<!-- Search Tool Modal -->
|
||||
<div class="modal fade" id="searchToolModal"><div class="modal-dialog"><div class="modal-content">
|
||||
<div class="modal-header"><h5 class="modal-title">添加/编辑搜索工具</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
||||
<div class="modal-body"><form id="search-tool-form">
|
||||
<input type="hidden" id="search-tool-id">
|
||||
<div class="mb-3"><label class="form-label">名称</label><input type="text" class="form-control" id="search-tool-name" value="Tavily Search"></div>
|
||||
<div class="mb-3"><label class="form-label">提供商</label><select class="form-select" id="search-tool-provider"><option value="tavily">Tavily</option><option value="google">Google</option><option value="bing">Bing</option></select></div>
|
||||
<div class="mb-3"><label class="form-label">API Key *</label><input type="text" class="form-control" id="search-tool-api-key" required></div>
|
||||
<div class="mb-3"><label class="form-label">API地址(可选)</label><input type="text" class="form-control" id="search-tool-api-base"></div>
|
||||
<div class="row"><div class="col-md-6"><label class="form-label">最大结果数</label><input type="number" class="form-control" id="search-tool-max-results" value="5"></div><div class="col-md-6"><label class="form-label">搜索深度</label><select class="form-select" id="search-tool-depth"><option value="basic">Basic</option><option value="advanced">Advanced</option></select></div></div>
|
||||
<div class="mt-3 form-check"><input type="checkbox" class="form-check-input" id="search-tool-active" checked><label class="form-check-label">启用</label></div>
|
||||
<div class="mt-2 form-check"><input type="checkbox" class="form-check-input" id="search-tool-default"><label class="form-check-label">设为默认</label></div>
|
||||
<!-- Tool Modal -->
|
||||
<div class="modal fade" id="toolModal"><div class="modal-dialog modal-lg"><div class="modal-content">
|
||||
<div class="modal-header"><h5 class="modal-title">添加/编辑工具</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
||||
<div class="modal-body"><form id="tool-form">
|
||||
<input type="hidden" id="tool-id">
|
||||
<div class="row">
|
||||
<div class="col-md-6"><label class="form-label">名称 *</label><input type="text" class="form-control" id="tool-name" required></div>
|
||||
<div class="col-md-6"><label class="form-label">类型 *</label><select class="form-select" id="tool-type" onchange="updateToolForm()">
|
||||
<option value="search">搜索工具</option>
|
||||
<option value="calculator">计算器</option>
|
||||
<option value="code_runner">代码执行</option>
|
||||
<option value="image_gen">图像生成</option>
|
||||
<option value="translator">翻译</option>
|
||||
<option value="weather">天气查询</option>
|
||||
<option value="custom">自定义</option>
|
||||
</select></div>
|
||||
</div>
|
||||
<div class="row mt-3">
|
||||
<div class="col-md-6"><label class="form-label">提供商</label><select class="form-select" id="tool-provider">
|
||||
<option value="">无</option>
|
||||
<option value="tavily">Tavily</option>
|
||||
<option value="google">Google</option>
|
||||
<option value="bing">Bing</option>
|
||||
<option value="wolfram">Wolfram</option>
|
||||
<option value="openai">OpenAI</option>
|
||||
<option value="anthropic">Anthropic</option>
|
||||
<option value="custom">自定义</option>
|
||||
</select></div>
|
||||
<div class="col-md-6"><label class="form-label">API Key</label><input type="text" class="form-control" id="tool-api-key"></div>
|
||||
</div>
|
||||
<div class="mt-3"><label class="form-label">配置参数(JSON格式)</label><textarea class="form-control" id="tool-config" rows="3">{"max_results": 5, "search_depth": "basic"}</textarea></div>
|
||||
<div class="mt-3 form-check"><input type="checkbox" class="form-check-input" id="tool-active" checked><label class="form-check-label">启用</label></div>
|
||||
<div class="mt-2 form-check"><input type="checkbox" class="form-check-input" id="tool-default"><label class="form-check-label">设为该类型默认</label></div>
|
||||
</form></div>
|
||||
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button><button type="button" class="btn btn-primary" onclick="saveSearchTool()">保存</button></div>
|
||||
<div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button><button type="button" class="btn btn-primary" onclick="saveTool()">保存</button></div>
|
||||
</div></div></div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
@@ -226,7 +257,7 @@
|
||||
if (page === 'llm-providers') loadProviders();
|
||||
if (page === 'agents') loadAgents();
|
||||
if (page === 'channels') loadChannels();
|
||||
if (page === 'search-tools') loadSearchTools();
|
||||
if (page === 'tools') loadTools();
|
||||
if (page === 'stats') loadStats();
|
||||
}
|
||||
|
||||
@@ -527,96 +558,172 @@
|
||||
document.getElementById('stat-agents').textContent = (agentsData.agents || []).length;
|
||||
}
|
||||
|
||||
// ===== 搜索工具 =====
|
||||
async function loadSearchTools() {
|
||||
const res = await fetch('/api/v2/search-tools');
|
||||
// ===== 工具管理 =====
|
||||
async function loadTools() {
|
||||
const res = await fetch('/api/v2/tools');
|
||||
const data = await res.json();
|
||||
const tools = data.configs || [];
|
||||
const tbody = document.getElementById('search-tools-list');
|
||||
const tools = data.tools || [];
|
||||
const tbody = document.getElementById('tools-list');
|
||||
if (tools.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无配置,点击添加按钮创建</td></tr>';
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">暂无工具,点击添加按钮创建</td></tr>';
|
||||
} else {
|
||||
tbody.innerHTML = tools.map(t => {
|
||||
const successRate = t.total_calls > 0 ? Math.round(t.success_calls / t.total_calls * 100) : 0;
|
||||
return `
|
||||
<tr>
|
||||
<td>${t.name}</td>
|
||||
<td><span class="badge bg-info">${t.tool_type}</span></td>
|
||||
<td>${t.provider || '-'}</td>
|
||||
<td>${t.total_calls}</td>
|
||||
<td><span class="badge ${successRate >= 90 ? 'bg-success' : successRate >= 70 ? 'bg-warning' : 'bg-danger'}">${successRate}%</span></td>
|
||||
<td>${t.is_default ? '<i class="ri-check-line text-success"></i>' : ''}</td>
|
||||
<td>${t.is_active ? '<span class="badge bg-success">启用</span>' : '<span class="badge bg-secondary">禁用</span>'}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-outline-primary" onclick="editTool(${t.id})"><i class="ri-edit-line"></i></button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteTool(${t.id})"><i class="ri-delete-bin-line"></i></button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// 加载统计
|
||||
loadToolStats();
|
||||
}
|
||||
|
||||
async function loadToolStats() {
|
||||
const res = await fetch('/api/v2/tools/stats?days=7');
|
||||
const stats = await res.json();
|
||||
const container = document.getElementById('tool-stats');
|
||||
|
||||
if (stats.total_calls === 0) {
|
||||
container.innerHTML = '<p class="text-muted">暂无使用记录</p>';
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = tools.map(t => `
|
||||
<tr>
|
||||
<td>${t.name}</td>
|
||||
<td>${t.provider}</td>
|
||||
<td><small class="text-muted">${t.api_key ? t.api_key.substring(0, 10) + '...' : '-'}</small></td>
|
||||
<td>${t.max_results}</td>
|
||||
<td>${t.is_default ? '<i class="ri-check-line text-success"></i>' : ''}</td>
|
||||
<td>${t.is_active ? '<span class="badge bg-success">启用</span>' : '<span class="badge bg-secondary">禁用</span>'}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-outline-primary" onclick="editSearchTool(${t.id})"><i class="ri-edit-line"></i></button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteSearchTool(${t.id})"><i class="ri-delete-bin-line"></i></button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
|
||||
let html = `<p><strong>总调用:</strong> ${stats.total_calls} 次</p>`;
|
||||
html += `<p><strong>成功率:</strong> ${Math.round(stats.success_rate)}%</p>`;
|
||||
|
||||
if (stats.by_type) {
|
||||
html += '<hr><h6>按类型:</h6>';
|
||||
for (const [type, data] of Object.entries(stats.by_type)) {
|
||||
html += `<p><span class="badge bg-info">${type}</span> ${data.total}次 (成功${data.success})</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
if (stats.recent_errors && stats.recent_errors.length > 0) {
|
||||
html += '<hr><h6>最近错误:</h6>';
|
||||
stats.recent_errors.slice(0, 3).forEach(e => {
|
||||
html += `<p class="text-danger small">${e.tool}: ${e.error}</p>`;
|
||||
});
|
||||
}
|
||||
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
function showAddSearchToolModal() {
|
||||
document.getElementById('search-tool-id').value = '';
|
||||
document.getElementById('search-tool-name').value = 'Tavily Search';
|
||||
document.getElementById('search-tool-provider').value = 'tavily';
|
||||
document.getElementById('search-tool-api-key').value = '';
|
||||
document.getElementById('search-tool-api-base').value = '';
|
||||
document.getElementById('search-tool-max-results').value = 5;
|
||||
document.getElementById('search-tool-depth').value = 'basic';
|
||||
document.getElementById('search-tool-active').checked = true;
|
||||
document.getElementById('search-tool-default').checked = false;
|
||||
new bootstrap.Modal(document.getElementById('searchToolModal')).show();
|
||||
function showAddToolModal() {
|
||||
document.getElementById('tool-id').value = '';
|
||||
document.getElementById('tool-name').value = '';
|
||||
document.getElementById('tool-type').value = 'search';
|
||||
document.getElementById('tool-provider').value = 'tavily';
|
||||
document.getElementById('tool-api-key').value = '';
|
||||
document.getElementById('tool-config').value = '{"max_results": 5, "search_depth": "basic"}';
|
||||
document.getElementById('tool-active').checked = true;
|
||||
document.getElementById('tool-default').checked = false;
|
||||
updateToolForm();
|
||||
new bootstrap.Modal(document.getElementById('toolModal')).show();
|
||||
}
|
||||
|
||||
async function editSearchTool(id) {
|
||||
const res = await fetch('/api/v2/search-tools');
|
||||
const data = await res.json();
|
||||
const tool = (data.configs || []).find(t => t.id === id);
|
||||
if (!tool) return;
|
||||
document.getElementById('search-tool-id').value = tool.id;
|
||||
document.getElementById('search-tool-name').value = tool.name;
|
||||
document.getElementById('search-tool-provider').value = tool.provider;
|
||||
document.getElementById('search-tool-api-key').value = tool.api_key || '';
|
||||
document.getElementById('search-tool-api-base').value = tool.api_base || '';
|
||||
document.getElementById('search-tool-max-results').value = tool.max_results;
|
||||
document.getElementById('search-tool-depth').value = tool.search_depth;
|
||||
document.getElementById('search-tool-active').checked = tool.is_active;
|
||||
document.getElementById('search-tool-default').checked = tool.is_default;
|
||||
new bootstrap.Modal(document.getElementById('searchToolModal')).show();
|
||||
}
|
||||
|
||||
async function saveSearchTool() {
|
||||
const id = document.getElementById('search-tool-id').value;
|
||||
const data = {
|
||||
name: document.getElementById('search-tool-name').value,
|
||||
provider: document.getElementById('search-tool-provider').value,
|
||||
api_key: document.getElementById('search-tool-api-key').value,
|
||||
api_base: document.getElementById('search-tool-api-base').value,
|
||||
max_results: parseInt(document.getElementById('search-tool-max-results').value),
|
||||
search_depth: document.getElementById('search-tool-depth').value,
|
||||
is_active: document.getElementById('search-tool-active').checked,
|
||||
is_default: document.getElementById('search-tool-default').checked
|
||||
function updateToolForm() {
|
||||
const type = document.getElementById('tool-type').value;
|
||||
const providerSelect = document.getElementById('tool-provider');
|
||||
const configTextarea = document.getElementById('tool-config');
|
||||
|
||||
// 根据类型设置默认配置
|
||||
const defaults = {
|
||||
'search': { provider: 'tavily', config: '{"api_key": "", "max_results": 5, "search_depth": "basic"}' },
|
||||
'calculator': { provider: 'wolfram', config: '{"api_key": ""}' },
|
||||
'code_runner': { provider: '', config: '{"timeout": 30, "language": "python"}' },
|
||||
'image_gen': { provider: 'openai', config: '{"api_key": "", "model": "dall-e-3"}' },
|
||||
'translator': { provider: '', config: '{"source": "auto", "target": "zh"}' },
|
||||
'weather': { provider: '', config: '{"api_key": ""}' },
|
||||
'custom': { provider: '', config: '{}' }
|
||||
};
|
||||
|
||||
const def = defaults[type] || defaults['custom'];
|
||||
providerSelect.value = def.provider;
|
||||
configTextarea.value = def.config;
|
||||
}
|
||||
|
||||
async function editTool(id) {
|
||||
const res = await fetch('/api/v2/tools');
|
||||
const data = await res.json();
|
||||
const tool = (data.tools || []).find(t => t.id === id);
|
||||
if (!tool) return;
|
||||
|
||||
document.getElementById('tool-id').value = tool.id;
|
||||
document.getElementById('tool-name').value = tool.name;
|
||||
document.getElementById('tool-type').value = tool.tool_type;
|
||||
document.getElementById('tool-provider').value = tool.provider || '';
|
||||
document.getElementById('tool-config').value = JSON.stringify(tool.config || {});
|
||||
document.getElementById('tool-active').checked = tool.is_active;
|
||||
document.getElementById('tool-default').checked = tool.is_default;
|
||||
|
||||
// 提取 API Key
|
||||
const apiKey = tool.config?.api_key || '';
|
||||
document.getElementById('tool-api-key').value = apiKey;
|
||||
|
||||
new bootstrap.Modal(document.getElementById('toolModal')).show();
|
||||
}
|
||||
|
||||
async function saveTool() {
|
||||
const id = document.getElementById('tool-id').value;
|
||||
|
||||
// 解析配置 JSON
|
||||
let config = {};
|
||||
try {
|
||||
config = JSON.parse(document.getElementById('tool-config').value);
|
||||
} catch (e) {
|
||||
alert('配置 JSON 格式错误');
|
||||
return;
|
||||
}
|
||||
|
||||
// 添加 API Key 到配置
|
||||
const apiKey = document.getElementById('tool-api-key').value;
|
||||
if (apiKey) config.api_key = apiKey;
|
||||
|
||||
const data = {
|
||||
name: document.getElementById('tool-name').value,
|
||||
tool_type: document.getElementById('tool-type').value,
|
||||
provider: document.getElementById('tool-provider').value,
|
||||
config: config,
|
||||
is_active: document.getElementById('tool-active').checked,
|
||||
is_default: document.getElementById('tool-default').checked
|
||||
};
|
||||
|
||||
let res;
|
||||
if (id) {
|
||||
res = await fetch(`/api/v2/search-tools/${id}`, { method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
|
||||
res = await fetch(`/api/v2/tools/${id}`, { method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
|
||||
} else {
|
||||
res = await fetch('/api/v2/search-tools', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
|
||||
res = await fetch('/api/v2/tools', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
|
||||
}
|
||||
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
bootstrap.Modal.getInstance(document.getElementById('searchToolModal')).hide();
|
||||
loadSearchTools();
|
||||
bootstrap.Modal.getInstance(document.getElementById('toolModal')).hide();
|
||||
loadTools();
|
||||
alert('保存成功');
|
||||
} else {
|
||||
alert('保存失败: ' + result.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSearchTool(id) {
|
||||
if (!confirm('确定删除此搜索工具配置?')) return;
|
||||
const res = await fetch(`/api/v2/search-tools/${id}`, { method: 'DELETE' });
|
||||
async function deleteTool(id) {
|
||||
if (!confirm('确定删除此工具配置?')) return;
|
||||
const res = await fetch(`/api/v2/tools/${id}`, { method: 'DELETE' });
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
loadSearchTools();
|
||||
loadTools();
|
||||
alert('删除成功');
|
||||
} else {
|
||||
alert('删除失败');
|
||||
|
||||
Reference in New Issue
Block a user