Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b9e99da01b | |||
| 34f02ad4d4 | |||
| 0c9bfca346 | |||
| 85dd206154 | |||
| 1b9bb1090c | |||
| 2373040b04 | |||
| f0789d6bbc | |||
| e05233fb4f | |||
| 7fa143b5b0 | |||
| b573638bf8 | |||
| af997aa5c5 | |||
| b1feaee976 | |||
| 87f9f4a7d8 | |||
| a1f1032000 | |||
| 7d6a345a7d | |||
| c6f157aa97 | |||
| 6e87f59fab | |||
| 066d2fe44d | |||
| 23935a1a28 | |||
| 08c4f79313 | |||
| 186f69c87a | |||
| 8c90fd5641 | |||
| 248ac4e471 | |||
| 51cc8161f1 | |||
| a62fe929c1 | |||
| 6adeb9b371 | |||
| 051fd5c1c8 | |||
| 90d31dba69 |
517
main_v2.py
517
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,
|
||||
LLMProvider, Agent, Channel, ChannelAgentMapping, MatrixRoomMapping, SearchToolConfig,
|
||||
init_default_data
|
||||
)
|
||||
from services.llm_service import llm_service
|
||||
from services.agent_service import AgentService, LLMProviderService, ChannelService
|
||||
from services.agent_service import AgentService, LLMProviderService, ChannelService, SearchToolService
|
||||
from services.conversation_service import ConversationService
|
||||
|
||||
# 配置日志
|
||||
@@ -60,8 +60,13 @@ class ConnectionManager:
|
||||
for connection in self.active_connections[user_id]:
|
||||
try:
|
||||
await connection.send_json(message)
|
||||
except:
|
||||
pass
|
||||
logger.info(f"发送消息到用户 {user_id}: {message.get('type', 'unknown')}")
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息失败: {e}")
|
||||
|
||||
async def ping(self, user_id: str):
|
||||
"""发送心跳ping"""
|
||||
await self.send_to_user(user_id, {"type": "ping"})
|
||||
|
||||
|
||||
manager = ConnectionManager()
|
||||
@@ -199,6 +204,7 @@ async def get_agents(db: Session = Depends(get_db)):
|
||||
"thinking_prompt": a.thinking_prompt,
|
||||
"thinking_prefix": a.thinking_prefix,
|
||||
"thinking_suffix": a.thinking_suffix,
|
||||
"tools": a.tools or [], # 工具列表
|
||||
"max_history": a.max_history,
|
||||
"temperature_override": a.temperature_override,
|
||||
"is_default": a.is_default,
|
||||
@@ -413,6 +419,128 @@ async def unbind_agent(mapping_id: int, db: Session = Depends(get_db)):
|
||||
return {"success": success}
|
||||
|
||||
|
||||
# ==================== 搜索工具 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()
|
||||
|
||||
return {
|
||||
"configs": [
|
||||
{
|
||||
"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
|
||||
}
|
||||
for c in configs
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@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.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)
|
||||
|
||||
if data.get('is_default'):
|
||||
service.set_default_config(config_id)
|
||||
|
||||
config = service.update_config(config_id, data)
|
||||
|
||||
if not config:
|
||||
return {"success": False, "message": "配置不存在"}
|
||||
|
||||
return {"success": True, "config": {"id": config.id, "name": config.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)
|
||||
|
||||
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)
|
||||
|
||||
return {"success": success}
|
||||
|
||||
|
||||
@app.post("/api/v2/search")
|
||||
async def perform_search(data: dict, db: Session = Depends(get_db)):
|
||||
"""执行搜索(供前端或Agent调用)"""
|
||||
import httpx
|
||||
|
||||
query = data.get('query')
|
||||
if not query:
|
||||
return {"success": False, "message": "缺少搜索关键词"}
|
||||
|
||||
# 获取搜索工具配置
|
||||
service = SearchToolService(db)
|
||||
config_id = data.get('config_id')
|
||||
|
||||
if config_id:
|
||||
config = service.get_config(config_id)
|
||||
else:
|
||||
config = service.get_default_config()
|
||||
|
||||
if not config or not config.api_key:
|
||||
return {"success": False, "message": "未配置搜索工具"}
|
||||
|
||||
# Tavily Search API
|
||||
if config.provider == 'tavily':
|
||||
try:
|
||||
tavily_url = "https://api.tavily.com/search"
|
||||
payload = {
|
||||
"api_key": config.api_key,
|
||||
"query": query,
|
||||
"max_results": config.max_results,
|
||||
"include_raw_content": config.include_raw_content,
|
||||
"search_depth": config.search_depth
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(tavily_url, json=payload)
|
||||
result = response.json()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"results": result.get("results", []),
|
||||
"query": query
|
||||
}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
return {"success": False, "message": "不支持的搜索提供商"}
|
||||
|
||||
|
||||
# ==================== 对话 API(保留原有) ====================
|
||||
|
||||
@app.get("/api/conversations")
|
||||
@@ -511,181 +639,260 @@ async def delete_conversation(conversation_id: str, db: Session = Depends(get_db
|
||||
# ==================== WebSocket路由 ====================
|
||||
|
||||
@app.websocket("/ws/{user_id}")
|
||||
async def websocket_endpoint(websocket: WebSocket, user_id: str, db: Session = Depends(get_db)):
|
||||
async def websocket_endpoint(websocket: WebSocket, user_id: str):
|
||||
"""WebSocket连接 - 实时对话"""
|
||||
actual_user_id = MAIN_USER_ID
|
||||
await manager.connect(websocket, actual_user_id)
|
||||
conv_service = ConversationService(db)
|
||||
user = conv_service.get_or_create_user(MAIN_USER_ID, display_name="主用户", user_type='web')
|
||||
|
||||
# 获取默认Agent配置
|
||||
agent_service = AgentService(db)
|
||||
default_agent = agent_service.get_default_agent()
|
||||
# 初始化时获取默认Agent ID
|
||||
db = SessionLocal()
|
||||
try:
|
||||
agent_service = AgentService(db)
|
||||
default_agent = agent_service.get_default_agent()
|
||||
default_agent_id = default_agent.id if default_agent else None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
current_conversation_id = None
|
||||
current_agent_id = default_agent.id if default_agent else None
|
||||
current_agent_id = default_agent_id
|
||||
|
||||
try:
|
||||
while True:
|
||||
data = await websocket.receive_json()
|
||||
action = data.get("action")
|
||||
|
||||
if action == "select_conversation":
|
||||
current_conversation_id = data.get("conversation_id")
|
||||
conversation = conv_service.get_conversation(current_conversation_id)
|
||||
|
||||
if conversation:
|
||||
messages = conv_service.get_messages(conversation.id)
|
||||
await websocket.send_json({
|
||||
"type": "history",
|
||||
"conversation_id": current_conversation_id,
|
||||
"messages": [
|
||||
{
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
"thinking_content": m.thinking_content,
|
||||
"source": m.source,
|
||||
"created_at": m.created_at.isoformat()
|
||||
}
|
||||
for m in messages
|
||||
]
|
||||
})
|
||||
|
||||
elif action == "switch_agent":
|
||||
# 切换Agent
|
||||
new_agent_id = data.get("agent_id")
|
||||
agent = agent_service.get_agent(new_agent_id)
|
||||
if agent and agent.is_active:
|
||||
current_agent_id = new_agent_id
|
||||
await websocket.send_json({
|
||||
"type": "agent_switched",
|
||||
"agent_id": current_agent_id,
|
||||
"agent_name": agent.display_name or agent.name
|
||||
})
|
||||
|
||||
elif action == "chat":
|
||||
message = data.get("message", "")
|
||||
conversation_id = data.get("conversation_id")
|
||||
enable_thinking = data.get("enable_thinking", True) # 可临时关闭思考
|
||||
agent_id_override = data.get("agent_id") # 前端可以指定agent
|
||||
|
||||
# 如果前端指定了agent,使用它
|
||||
if agent_id_override:
|
||||
agent = agent_service.get_agent(agent_id_override)
|
||||
if agent and agent.is_active:
|
||||
current_agent_id = agent_id_override
|
||||
|
||||
if not message.strip():
|
||||
continue
|
||||
|
||||
# 获取或创建会话
|
||||
if conversation_id:
|
||||
conversation = conv_service.get_conversation(conversation_id)
|
||||
else:
|
||||
conversation = conv_service.create_conversation(user.id)
|
||||
conversation_id = conversation.conversation_id
|
||||
await websocket.send_json({
|
||||
"type": "conversation_created",
|
||||
"conversation_id": conversation_id
|
||||
})
|
||||
|
||||
# 保存用户消息
|
||||
user_msg = conv_service.add_message(
|
||||
conversation_id=conversation.id,
|
||||
role='user',
|
||||
content=message,
|
||||
source='web'
|
||||
)
|
||||
|
||||
# 广播用户消息
|
||||
await manager.send_to_user(MAIN_USER_ID, {
|
||||
"type": "user_message",
|
||||
"conversation_id": conversation_id,
|
||||
"message": {
|
||||
"id": user_msg.id,
|
||||
"role": "user",
|
||||
"content": message,
|
||||
"source": "web",
|
||||
"created_at": user_msg.created_at.isoformat()
|
||||
}
|
||||
})
|
||||
|
||||
# 获取Agent配置
|
||||
agent_config = agent_service.get_agent_config(current_agent_id)
|
||||
|
||||
if not agent_config or not agent_config.get('provider'):
|
||||
await websocket.send_json({
|
||||
"type": "error",
|
||||
"message": "Agent配置不完整"
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取对话历史
|
||||
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
|
||||
|
||||
# 调用LLM
|
||||
try:
|
||||
data = await websocket.receive_json()
|
||||
except Exception as json_err:
|
||||
logger.error(f"JSON解析错误: {json_err}")
|
||||
# 如果连接已断开,退出循环
|
||||
if "disconnect" in str(json_err).lower() or "closed" in str(json_err).lower():
|
||||
logger.info("WebSocket已断开,退出循环")
|
||||
break
|
||||
try:
|
||||
# 发送"正在思考"状态
|
||||
if agent_config['agent'].get('enable_thinking') and enable_thinking:
|
||||
text_data = await websocket.receive_text()
|
||||
if text_data.strip():
|
||||
data = json.loads(text_data)
|
||||
else:
|
||||
continue
|
||||
except Exception as text_err:
|
||||
logger.error(f"文本消息解析错误: {text_err}")
|
||||
if "disconnect" in str(text_err).lower() or "closed" in str(text_err).lower():
|
||||
logger.info("WebSocket已断开,退出循环")
|
||||
break
|
||||
continue
|
||||
|
||||
action = data.get("action")
|
||||
logger.info(f"WebSocket收到消息: action={action}")
|
||||
|
||||
# 每次消息处理时创建新的数据库会话,处理完后关闭
|
||||
try:
|
||||
db = SessionLocal()
|
||||
conv_service = ConversationService(db)
|
||||
agent_service = AgentService(db)
|
||||
user = conv_service.get_or_create_user(MAIN_USER_ID, display_name="主用户", user_type='web')
|
||||
|
||||
if action == "select_conversation":
|
||||
current_conversation_id = data.get("conversation_id")
|
||||
conversation = conv_service.get_conversation(current_conversation_id)
|
||||
|
||||
if conversation:
|
||||
messages = conv_service.get_messages(conversation.id)
|
||||
|
||||
# 获取对话使用的Agent ID
|
||||
conv_agent_id = conversation.current_agent_id
|
||||
|
||||
await websocket.send_json({
|
||||
"type": "thinking_start",
|
||||
"type": "history",
|
||||
"conversation_id": current_conversation_id,
|
||||
"agent_id": conv_agent_id, # 返回对话的Agent ID
|
||||
"messages": [
|
||||
{
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
"thinking_content": m.thinking_content,
|
||||
"agent_id": m.agent_id, # 每条消息的Agent ID
|
||||
"source": m.source,
|
||||
"created_at": m.created_at.isoformat()
|
||||
}
|
||||
for m in messages
|
||||
]
|
||||
})
|
||||
|
||||
elif action == "switch_agent":
|
||||
# 切换Agent
|
||||
new_agent_id = data.get("agent_id")
|
||||
agent = agent_service.get_agent(new_agent_id)
|
||||
if agent and agent.is_active:
|
||||
current_agent_id = new_agent_id
|
||||
await websocket.send_json({
|
||||
"type": "agent_switched",
|
||||
"agent_id": current_agent_id,
|
||||
"agent_name": agent.display_name or agent.name
|
||||
})
|
||||
|
||||
elif action == "chat":
|
||||
message = data.get("message", "")
|
||||
conversation_id = data.get("conversation_id")
|
||||
enable_thinking = data.get("enable_thinking", True)
|
||||
agent_id_override = data.get("agent_id")
|
||||
disabled_tools = data.get("disabled_tools", []) # 禁用的工具列表
|
||||
|
||||
if agent_id_override:
|
||||
agent = agent_service.get_agent(agent_id_override)
|
||||
if agent and agent.is_active:
|
||||
current_agent_id = agent_id_override
|
||||
|
||||
if not message.strip():
|
||||
continue
|
||||
|
||||
# 获取Agent配置
|
||||
agent_config = agent_service.get_agent_config(current_agent_id)
|
||||
agent_tools = agent_config.get('agent', {}).get('tools', [])
|
||||
|
||||
# 检查是否需要执行搜索
|
||||
search_context = None
|
||||
if 'search' in agent_tools and 'search' not in disabled_tools:
|
||||
# 只要启用了搜索工具且未禁用,就执行搜索(不再依赖关键词检测)
|
||||
should_search = True
|
||||
|
||||
if should_search:
|
||||
# 执行搜索
|
||||
search_service = SearchToolService(db)
|
||||
search_config = search_service.get_default_config()
|
||||
|
||||
if search_config and search_config.api_key:
|
||||
import httpx
|
||||
try:
|
||||
logger.info(f"执行搜索: query={message}")
|
||||
tavily_url = "https://api.tavily.com/search"
|
||||
payload = {
|
||||
"api_key": search_config.api_key,
|
||||
"query": message,
|
||||
"max_results": search_config.max_results,
|
||||
"search_depth": search_config.search_depth
|
||||
}
|
||||
|
||||
# 同步调用(简化处理)
|
||||
with httpx.Client(timeout=30) as client:
|
||||
resp = client.post(tavily_url, json=payload)
|
||||
search_result = resp.json()
|
||||
|
||||
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'])} 条结果")
|
||||
except Exception as e:
|
||||
logger.error(f"搜索失败: {e}")
|
||||
|
||||
# 获取或创建会话
|
||||
if conversation_id:
|
||||
conversation = conv_service.get_conversation(conversation_id)
|
||||
else:
|
||||
conversation = conv_service.create_conversation(user.id)
|
||||
conversation_id = conversation.conversation_id
|
||||
await websocket.send_json({
|
||||
"type": "conversation_created",
|
||||
"conversation_id": conversation_id
|
||||
})
|
||||
|
||||
response, thinking_content = await llm_service.chat(
|
||||
messages=history,
|
||||
provider_config=agent_config['provider'],
|
||||
agent_config=agent_config['agent'],
|
||||
enable_thinking=enable_thinking
|
||||
)
|
||||
|
||||
# 发送思考内容
|
||||
if thinking_content:
|
||||
await websocket.send_json({
|
||||
"type": "thinking_content",
|
||||
"conversation_id": conversation_id,
|
||||
"content": thinking_content
|
||||
})
|
||||
|
||||
# 发送思考结束
|
||||
await websocket.send_json({
|
||||
"type": "thinking_end",
|
||||
"conversation_id": conversation_id
|
||||
})
|
||||
|
||||
# 保存AI回复
|
||||
assistant_msg = conv_service.add_message(
|
||||
# 保存用户消息
|
||||
user_msg = conv_service.add_message(
|
||||
conversation_id=conversation.id,
|
||||
role='assistant',
|
||||
content=response,
|
||||
source='web',
|
||||
thinking_content=thinking_content,
|
||||
agent_id=current_agent_id,
|
||||
model_used=agent_config['provider'].get('default_model')
|
||||
role='user',
|
||||
content=message,
|
||||
source='web'
|
||||
)
|
||||
|
||||
# 广播AI回复
|
||||
# 广播用户消息
|
||||
await manager.send_to_user(MAIN_USER_ID, {
|
||||
"type": "assistant_message",
|
||||
"type": "user_message",
|
||||
"conversation_id": conversation_id,
|
||||
"message": {
|
||||
"id": assistant_msg.id,
|
||||
"role": "assistant",
|
||||
"content": response,
|
||||
"thinking_content": thinking_content,
|
||||
"id": user_msg.id,
|
||||
"role": "user",
|
||||
"content": message,
|
||||
"source": "web",
|
||||
"agent_id": current_agent_id,
|
||||
"agent_name": agent_config['agent'].get('display_name'),
|
||||
"created_at": assistant_msg.created_at.isoformat()
|
||||
"created_at": user_msg.created_at.isoformat()
|
||||
}
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"LLM调用失败: {e}")
|
||||
await websocket.send_json({
|
||||
"type": "error",
|
||||
"message": f"AI服务暂时不可用: {str(e)}"
|
||||
})
|
||||
# 获取Agent配置
|
||||
agent_config = agent_service.get_agent_config(current_agent_id)
|
||||
|
||||
if not agent_config or not agent_config.get('provider'):
|
||||
await websocket.send_json({
|
||||
"type": "error",
|
||||
"message": "Agent配置不完整"
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取对话历史
|
||||
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
|
||||
|
||||
# 如果有搜索结果,添加到消息中
|
||||
if search_context:
|
||||
# 在系统提示中添加搜索结果说明
|
||||
modified_system_prompt = agent_config['agent'].get('system_prompt', '') + "\n\n如果提供了搜索结果,请基于搜索结果回答用户问题,并注明信息来源。"
|
||||
agent_config['agent']['system_prompt'] = modified_system_prompt
|
||||
# 将搜索结果作为系统消息添加到历史
|
||||
history.append({"role": "system", "content": f"以下是搜索到的相关信息,请参考这些内容回答用户问题:{search_context}"})
|
||||
|
||||
# 使用非流式调用LLM(简化版本,确保稳定)
|
||||
try:
|
||||
# 调用LLM(非流式)
|
||||
response, thinking_content = await llm_service.chat(
|
||||
messages=history,
|
||||
provider_config=agent_config['provider'],
|
||||
agent_config=agent_config['agent'],
|
||||
enable_thinking=enable_thinking
|
||||
)
|
||||
|
||||
logger.info(f"LLM响应: response长度={len(response)}, thinking长度={len(thinking_content) if thinking_content else 0}")
|
||||
|
||||
# 保存AI回复
|
||||
assistant_msg = conv_service.add_message(
|
||||
conversation_id=conversation.id,
|
||||
role='assistant',
|
||||
content=response,
|
||||
source='web',
|
||||
thinking_content=thinking_content if thinking_content else None,
|
||||
agent_id=current_agent_id,
|
||||
model_used=agent_config['provider'].get('default_model')
|
||||
)
|
||||
|
||||
# 发送完整回复(包含思考内容)
|
||||
await websocket.send_json({
|
||||
"type": "assistant_message",
|
||||
"conversation_id": conversation_id,
|
||||
"message": {
|
||||
"id": assistant_msg.id,
|
||||
"role": "assistant",
|
||||
"content": response,
|
||||
"thinking_content": thinking_content if thinking_content else None,
|
||||
"source": "web",
|
||||
"agent_id": current_agent_id,
|
||||
"agent_name": agent_config['agent'].get('display_name'),
|
||||
"created_at": assistant_msg.created_at.isoformat()
|
||||
}
|
||||
})
|
||||
|
||||
logger.info(f"AI回复已发送: conversation_id={conversation_id}")
|
||||
|
||||
# 启用发送按钮
|
||||
await websocket.send_json({
|
||||
"type": "stream_end",
|
||||
"conversation_id": conversation_id
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"LLM调用失败: {e}")
|
||||
await websocket.send_json({
|
||||
"type": "error",
|
||||
"message": f"AI服务暂时不可用: {str(e)}"
|
||||
})
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
except WebSocketDisconnect:
|
||||
manager.disconnect(websocket, user_id)
|
||||
|
||||
42
models_v2.py
42
models_v2.py
@@ -58,6 +58,9 @@ class Agent(Base):
|
||||
name = Column(String(100), unique=True, index=True) # Agent名称
|
||||
display_name = Column(String(100)) # 显示名称
|
||||
|
||||
# 工具配置
|
||||
tools = Column(JSON, default=list) # 可用工具列表 ["search", "calculator", ...]
|
||||
|
||||
# 大模型配置
|
||||
llm_provider_id = Column(Integer, ForeignKey('llm_providers.id'))
|
||||
model_override = Column(String(100), nullable=True) # 覆盖Provider默认模型
|
||||
@@ -224,6 +227,33 @@ class MatrixRoomMapping(Base):
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
|
||||
|
||||
# ==================== 搜索工具配置 ====================
|
||||
|
||||
class SearchToolConfig(Base):
|
||||
"""搜索工具配置(Tavily等)"""
|
||||
__tablename__ = 'search_tool_config'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100)) # 工具名称,如 "Tavily Search"
|
||||
provider = Column(String(50)) # 提供商:tavily, google, bing
|
||||
|
||||
# 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
|
||||
|
||||
# 状态
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_default = Column(Boolean, default=False) # 是否为默认搜索工具
|
||||
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
# ==================== 系统配置(保留) ====================
|
||||
|
||||
class SystemConfig(Base):
|
||||
@@ -335,6 +365,18 @@ def init_default_data():
|
||||
)
|
||||
db.add(matrix_mapping)
|
||||
|
||||
# 5. 创建默认搜索工具配置
|
||||
search_config = SearchToolConfig(
|
||||
name="Tavily Search",
|
||||
provider="tavily",
|
||||
api_key="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",
|
||||
max_results=5,
|
||||
search_depth="basic",
|
||||
is_active=True,
|
||||
is_default=True
|
||||
)
|
||||
db.add(search_config)
|
||||
|
||||
db.commit()
|
||||
print("默认数据初始化完成")
|
||||
|
||||
|
||||
@@ -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, init_default_data
|
||||
from models_v2 import Agent, LLMProvider, ChannelAgentMapping, Channel, SearchToolConfig, init_default_data
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -52,6 +52,7 @@ class AgentService:
|
||||
thinking_prompt=data.get('thinking_prompt'),
|
||||
thinking_prefix=data.get('thinking_prefix', ''),
|
||||
thinking_suffix=data.get('thinking_suffix', ''),
|
||||
tools=data.get('tools', []), # 工具列表
|
||||
max_history=data.get('max_history', 20),
|
||||
temperature_override=data.get('temperature_override'),
|
||||
is_active=data.get('is_active', True),
|
||||
@@ -405,4 +406,87 @@ class ChannelService:
|
||||
'is_active': channel.is_active,
|
||||
'is_primary': channel.is_primary,
|
||||
'agent_mappings': self.get_channel_agents(channel_id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class SearchToolService:
|
||||
"""搜索工具管理服务"""
|
||||
|
||||
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_active_configs(self) -> List[SearchToolConfig]:
|
||||
"""获取活跃的搜索工具配置"""
|
||||
return self.db.query(SearchToolConfig).filter(SearchToolConfig.is_active == True).all()
|
||||
|
||||
def get_config(self, config_id: int) -> Optional[SearchToolConfig]:
|
||||
"""获取单个配置"""
|
||||
return self.db.query(SearchToolConfig).filter(SearchToolConfig.id == config_id).first()
|
||||
|
||||
def get_default_config(self) -> Optional[SearchToolConfig]:
|
||||
"""获取默认配置"""
|
||||
config = self.db.query(SearchToolConfig).filter(
|
||||
SearchToolConfig.is_default == True,
|
||||
SearchToolConfig.is_active == True
|
||||
).first()
|
||||
if not config:
|
||||
config = self.db.query(SearchToolConfig).filter(SearchToolConfig.is_active == True).first()
|
||||
return config
|
||||
|
||||
def create_config(self, data: Dict) -> SearchToolConfig:
|
||||
"""创建搜索工具配置"""
|
||||
config = SearchToolConfig(
|
||||
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'),
|
||||
is_active=data.get('is_active', True),
|
||||
is_default=data.get('is_default', False)
|
||||
)
|
||||
self.db.add(config)
|
||||
self.db.commit()
|
||||
self.db.refresh(config)
|
||||
return config
|
||||
|
||||
def update_config(self, config_id: int, data: Dict) -> Optional[SearchToolConfig]:
|
||||
"""更新配置"""
|
||||
config = self.get_config(config_id)
|
||||
if not config:
|
||||
return None
|
||||
|
||||
for key, value in data.items():
|
||||
if hasattr(config, key) and value is not None:
|
||||
setattr(config, key, value)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(config)
|
||||
return config
|
||||
|
||||
def delete_config(self, config_id: int) -> bool:
|
||||
"""删除配置"""
|
||||
config = self.get_config(config_id)
|
||||
if not config:
|
||||
return False
|
||||
|
||||
self.db.delete(config)
|
||||
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:
|
||||
return False
|
||||
|
||||
config.is_default = True
|
||||
self.db.commit()
|
||||
return True
|
||||
@@ -128,6 +128,8 @@ class LLMService:
|
||||
# 处理思考功能
|
||||
if enable_thinking and agent_config.get('enable_thinking', True):
|
||||
thinking_prompt = agent_config.get('thinking_prompt')
|
||||
thinking_prefix = agent_config.get('thinking_prefix', '')
|
||||
thinking_suffix = agent_config.get('thinking_suffix', '')
|
||||
|
||||
if supports_thinking and thinking_model:
|
||||
# 使用专门的思考模型
|
||||
@@ -139,22 +141,15 @@ class LLMService:
|
||||
thinking_result = await self._call_api(
|
||||
api_base, api_key, thinking_model, thinking_messages,
|
||||
max_tokens=min(max_tokens, 1000),
|
||||
temperature=0.3 # 思考时降低温度
|
||||
temperature=0.3
|
||||
)
|
||||
thinking_content = thinking_result
|
||||
except Exception as e:
|
||||
logger.warning(f"思考模型调用失败: {e}")
|
||||
|
||||
elif supports_thinking:
|
||||
# Provider支持思考但无单独模型,尝试在回复中获取思考部分
|
||||
pass # 在回复解析时处理
|
||||
|
||||
elif thinking_prompt:
|
||||
# Provider不支持思考,但Agent配置了思考提示词
|
||||
# 将思考提示词添加到系统提示
|
||||
enhanced_system = f"{system_prompt}\n\n在回答之前,请先思考问题。思考过程请用{agent_config.get('thinking_prefix', '')}和{agent_config.get('thinking_suffix', '')}包裹,然后再给出正式回答。"
|
||||
if thinking_prompt:
|
||||
enhanced_system += f"\n思考指导:{thinking_prompt}"
|
||||
# Agent配置了思考提示词,添加到系统提示中
|
||||
enhanced_system = f"{system_prompt}\n\n{thinking_prompt}"
|
||||
final_messages[0] = {"role": "system", "content": enhanced_system}
|
||||
|
||||
# 调用主模型
|
||||
@@ -165,19 +160,37 @@ class LLMService:
|
||||
temperature=temperature
|
||||
)
|
||||
|
||||
# 尝试从回复中提取思考内容
|
||||
if enable_thinking and not supports_thinking:
|
||||
# 尝试从回复中提取思考内容(支持DeepSeek R1、GLM等模型的思考模式)
|
||||
if enable_thinking and agent_config.get('enable_thinking', True):
|
||||
thinking_prefix = agent_config.get('thinking_prefix', '')
|
||||
thinking_suffix = agent_config.get('thinking_suffix', '')
|
||||
|
||||
if thinking_prefix and thinking_suffix:
|
||||
# 提取思考部分
|
||||
pattern = f"{re.escape(thinking_prefix)}(.*?)?{re.escape(thinking_suffix)}"
|
||||
match = re.search(pattern, response, re.DOTALL)
|
||||
if match:
|
||||
thinking_content = match.group(1).strip()
|
||||
# 移除思考部分,只保留回复
|
||||
response = re.sub(pattern, '', response, flags=re.DOTALL).strip()
|
||||
# 如果没有配置前缀后缀,使用常见的思考标记
|
||||
if not thinking_prefix:
|
||||
# 尝试常见的思考标记
|
||||
common_thinking_markers = [
|
||||
('<think>', '</think>'),
|
||||
('【思考】', '【回答】'),
|
||||
('Thought:', 'Answer:'),
|
||||
('思考:', '回答:'),
|
||||
]
|
||||
for prefix, suffix in common_thinking_markers:
|
||||
if prefix in response and suffix in response:
|
||||
thinking_prefix = prefix
|
||||
thinking_suffix = suffix
|
||||
break
|
||||
|
||||
# 提取思考部分
|
||||
if thinking_prefix and thinking_suffix and thinking_prefix in response:
|
||||
try:
|
||||
start_idx = response.find(thinking_prefix)
|
||||
end_idx = response.find(thinking_suffix, start_idx)
|
||||
if end_idx > start_idx:
|
||||
thinking_content = response[start_idx + len(thinking_prefix):end_idx].strip()
|
||||
# 移除思考部分,只保留回复
|
||||
response = response[end_idx + len(thinking_suffix):].strip()
|
||||
except Exception as e:
|
||||
logger.warning(f"提取思考内容失败: {e}")
|
||||
|
||||
return response, thinking_content
|
||||
|
||||
@@ -268,8 +281,7 @@ class LLMService:
|
||||
|
||||
thinking_prefix = agent_config.get('thinking_prefix', '')
|
||||
thinking_suffix = agent_config.get('thinking_suffix', '')
|
||||
in_thinking = False
|
||||
thinking_buffer = ""
|
||||
buffer = "" # 用于累积和检测思考部分
|
||||
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
async with client.stream("POST", url, headers=headers, json=payload) as response:
|
||||
@@ -284,35 +296,46 @@ class LLMService:
|
||||
delta = data['choices'][0].get('delta', {})
|
||||
if 'content' in delta:
|
||||
text = delta['content']
|
||||
buffer += text
|
||||
|
||||
# 检测思考部分
|
||||
if thinking_prefix and thinking_suffix:
|
||||
for char in text:
|
||||
if in_thinking:
|
||||
thinking_buffer += char
|
||||
# 检查是否结束思考
|
||||
if thinking_buffer.endswith(thinking_suffix):
|
||||
thinking_content = thinking_buffer[:-len(thinking_suffix)]
|
||||
yield {"type": "thinking", "text": thinking_content}
|
||||
in_thinking = False
|
||||
thinking_buffer = ""
|
||||
# 检测思考部分(简化逻辑)
|
||||
if thinking_prefix and thinking_suffix and thinking_prefix in buffer:
|
||||
# 尝试解析思考部分
|
||||
try:
|
||||
start_idx = buffer.find(thinking_prefix)
|
||||
if start_idx >= 0:
|
||||
# 找到思考开始,继续找结束
|
||||
end_idx = buffer.find(thinking_suffix, start_idx)
|
||||
if end_idx > start_idx:
|
||||
# 思考部分完整,发送思考然后发送内容
|
||||
thinking = buffer[start_idx + len(thinking_prefix):end_idx]
|
||||
yield {"type": "thinking", "text": thinking}
|
||||
# 发送思考后的内容
|
||||
remaining = buffer[end_idx + len(thinking_suffix):]
|
||||
if remaining:
|
||||
yield {"type": "content", "text": remaining}
|
||||
buffer = ""
|
||||
else:
|
||||
# 检查是否接近结束
|
||||
suffix_len = len(thinking_suffix)
|
||||
if len(thinking_buffer) >= suffix_len:
|
||||
yield {"type": "thinking", "text": thinking_buffer[-suffix_len:]}
|
||||
# 思考部分还没结束,先发送之前的内容
|
||||
if start_idx > 0:
|
||||
yield {"type": "content", "text": buffer[:start_idx]}
|
||||
# 等待更多数据来完成思考部分
|
||||
buffer = buffer[start_idx:]
|
||||
else:
|
||||
if char == thinking_prefix[0]:
|
||||
# 可能开始思考
|
||||
thinking_buffer = char
|
||||
if len(thinking_prefix) == 1:
|
||||
in_thinking = True
|
||||
else:
|
||||
yield {"type": "content", "text": char}
|
||||
# 没有思考标记,直接发送内容
|
||||
yield {"type": "content", "text": text}
|
||||
buffer = ""
|
||||
except:
|
||||
yield {"type": "content", "text": text}
|
||||
else:
|
||||
# 没有思考标记配置,直接发送内容
|
||||
yield {"type": "content", "text": text}
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
# 处理剩余buffer
|
||||
if buffer:
|
||||
yield {"type": "content", "text": buffer}
|
||||
|
||||
|
||||
# 全局实例
|
||||
|
||||
@@ -42,6 +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="stats"><i class="ri-bar-chart-box-line"></i> 统计数据</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -109,6 +110,23 @@
|
||||
</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>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 统计 -->
|
||||
<div class="page-section" id="page-stats">
|
||||
<div class="page-header"><h2><i class="ri-bar-chart-box-line"></i> 统计数据</h2></div>
|
||||
@@ -152,6 +170,8 @@
|
||||
<div class="row mt-3"><div class="col-md-4 form-check"><input type="checkbox" class="form-check-input" id="agent-active" checked><label class="form-check-label">启用</label></div><div class="col-md-4 form-check"><input type="checkbox" class="form-check-input" id="agent-default"><label class="form-check-label">默认</label></div><div class="col-md-4"><label class="form-label">温度覆盖</label><input type="number" class="form-control" id="agent-temperature-override" step="0.1"></div></div>
|
||||
<hr><h6>思考功能</h6>
|
||||
<div class="thinking-config"><div class="form-check"><input type="checkbox" class="form-check-input" id="agent-enable-thinking" checked><label class="form-check-label">启用思考</label></div><div class="mt-2"><label class="form-label">思考提示词</label><textarea class="form-control" id="agent-thinking-prompt" rows="2"></textarea></div><div class="row mt-2"><div class="col-md-6"><label class="form-label">前缀</label><input type="text" class="form-control" id="agent-thinking-prefix"></div><div class="col-md-6"><label class="form-label">后缀</label><input type="text" class="form-control" id="agent-thinking-suffix"></div></div></div>
|
||||
<hr><h6>工具配置</h6>
|
||||
<div class="thinking-config"><div class="form-check"><input type="checkbox" class="form-check-input" id="agent-tool-search"><label class="form-check-label">启用搜索工具</label></div><small class="text-muted">启用后 Agent 可以使用搜索功能获取实时信息</small></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="saveAgent()">保存</button></div>
|
||||
</div></div></div>
|
||||
@@ -180,6 +200,22 @@
|
||||
<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>
|
||||
</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></div></div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
// 全局数据
|
||||
@@ -190,6 +226,7 @@
|
||||
if (page === 'llm-providers') loadProviders();
|
||||
if (page === 'agents') loadAgents();
|
||||
if (page === 'channels') loadChannels();
|
||||
if (page === 'search-tools') loadSearchTools();
|
||||
if (page === 'stats') loadStats();
|
||||
}
|
||||
|
||||
@@ -348,11 +385,18 @@
|
||||
document.getElementById('agent-thinking-prompt').value = a.thinking_prompt || '';
|
||||
document.getElementById('agent-thinking-prefix').value = a.thinking_prefix || '';
|
||||
document.getElementById('agent-thinking-suffix').value = a.thinking_suffix || '';
|
||||
// 工具配置
|
||||
const tools = a.tools || [];
|
||||
document.getElementById('agent-tool-search').checked = tools.includes('search');
|
||||
new bootstrap.Modal(document.getElementById('agentModal')).show();
|
||||
}
|
||||
|
||||
async function saveAgent() {
|
||||
const id = document.getElementById('agent-id').value;
|
||||
// 处理工具列表
|
||||
const tools = [];
|
||||
if (document.getElementById('agent-tool-search').checked) tools.push('search');
|
||||
|
||||
const data = {
|
||||
name: document.getElementById('agent-name').value,
|
||||
display_name: document.getElementById('agent-display-name').value,
|
||||
@@ -367,7 +411,8 @@
|
||||
enable_thinking: document.getElementById('agent-enable-thinking').checked,
|
||||
thinking_prompt: document.getElementById('agent-thinking-prompt').value,
|
||||
thinking_prefix: document.getElementById('agent-thinking-prefix').value,
|
||||
thinking_suffix: document.getElementById('agent-thinking-suffix').value
|
||||
thinking_suffix: document.getElementById('agent-thinking-suffix').value,
|
||||
tools: tools // 工具列表
|
||||
};
|
||||
const res = await fetch(id ? `/api/v2/agents/${id}` : '/api/v2/agents', { method: id ? 'PUT' : 'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(data) });
|
||||
const result = await res.json();
|
||||
@@ -482,6 +527,102 @@
|
||||
document.getElementById('stat-agents').textContent = (agentsData.agents || []).length;
|
||||
}
|
||||
|
||||
// ===== 搜索工具 =====
|
||||
async function loadSearchTools() {
|
||||
const res = await fetch('/api/v2/search-tools');
|
||||
const data = await res.json();
|
||||
const tools = data.configs || [];
|
||||
const tbody = document.getElementById('search-tools-list');
|
||||
if (tools.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无配置,点击添加按钮创建</td></tr>';
|
||||
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('');
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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
|
||||
};
|
||||
let res;
|
||||
if (id) {
|
||||
res = await fetch(`/api/v2/search-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) });
|
||||
}
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
bootstrap.Modal.getInstance(document.getElementById('searchToolModal')).hide();
|
||||
loadSearchTools();
|
||||
alert('保存成功');
|
||||
} else {
|
||||
alert('保存失败: ' + result.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSearchTool(id) {
|
||||
if (!confirm('确定删除此搜索工具配置?')) return;
|
||||
const res = await fetch(`/api/v2/search-tools/${id}`, { method: 'DELETE' });
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
loadSearchTools();
|
||||
alert('删除成功');
|
||||
} else {
|
||||
alert('删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 初始化 =====
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// 页面切换事件绑定
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user