Compare commits

..

15 Commits

Author SHA1 Message Date
fe65f23fa7 feat: 网页端添加文件上传功能
- 支持图片上传(预览显示)
- 支持文本文件上传(txt, md, json, csv等)
- 支持 PDF 和 Word 文档
- 文件内容自动添加到消息中供 AI 分析
- 多文件同时上传支持
2026-04-13 23:31:20 +08:00
d1431ac521 fix: WebSocket history 消息添加 extra_data 字段,搜索结果可正确显示 2026-04-13 23:10:13 +08:00
49e15130f1 fix: 使用 insertAdjacentHTML 在设置 innerHTML 后添加搜索结果 2026-04-13 19:00:26 +08:00
9aaff7ee87 fix: appendMessage 接收 extraData 参数,在创建消息时直接处理搜索结果显示 2026-04-13 17:52:59 +08:00
b5284ce18e fix: 搜索结果持久化保存,刷新页面后历史对话也显示搜索结果
- 用户消息 extra_data 存储搜索结果
- API 返回消息时包含 extra_data
- 前端 displayHistory 处理历史搜索结果显示
2026-04-13 17:36:19 +08:00
8aa1f5fd88 fix: 搜索结果数量根据工具配置读取,不再固定5条 2026-04-13 17:16:37 +08:00
813b4887ed fix: 调整对话流程顺序
1. 用户发送消息 → 前端立即显示
2. 后端收到 → 广播用户消息 → 执行搜索 → 发送搜索结果
3. AI生成回复 → 显示

- sendMessage 立即显示用户消息
- user_message 事件避免重复显示
- 后端处理顺序:广播 → 搜索 → 保存 → LLM
2026-04-13 17:11:11 +08:00
3cbdddf773 fix: 搜索结果放到用户消息下面,折叠显示
- 搜索结果追加到最后一条用户消息的 message-body 中
- 默认折叠,点击展开/收起
- 显示搜索关键词和结果数量
2026-04-13 17:01:08 +08:00
c0ed6cd505 fix: get_agent_config 添加 tools 字段返回 2026-04-13 16:46:00 +08:00
25e92b1fb1 fix: 搜索功能修复
- 添加详细日志帮助调试
- 搜索结果发送到前端展示
- 前端增加搜索结果展示组件
- 修复 datetime 导入错误
2026-04-13 16:34:00 +08:00
142904dff4 feat: 重构工具配置为通用模型,增加使用统计
- ToolConfig 模型:支持多种工具类型(搜索、计算器、代码执行等)
- ToolUsageLog 模型:记录工具调用日志
- 工具使用统计:调用次数、成功率、错误记录
- 后台管理界面:工具列表+统计展示
- API 重构:/api/v2/tools(替代 search-tools)
2026-04-13 16:15:26 +08:00
b9e99da01b fix: 搜索改为勾选即执行,不再依赖关键词检测 2026-04-13 16:00:32 +08:00
34f02ad4d4 fix: 修复数据库缺少tools字段,移动搜索复选框到输入框区域 2026-04-13 13:31:14 +08:00
0c9bfca346 feat: 添加搜索工具功能(Tavily Search)
- 新增 SearchToolConfig 模型:支持搜索工具配置
- Agent 增加 tools 字段:可配置可用工具列表
- 后台管理增加搜索工具配置页面
- Agent 管理增加工具启用开关
- 网页端增加搜索工具禁用复选框
- WebSocket chat 处理增加搜索调用逻辑
- 默认配置 Tavily Search API
2026-04-13 13:26:43 +08:00
85dd206154 fix: 简化新建对话判断条件,只检查无对话ID且无消息 2026-04-13 12:20:56 +08:00
5 changed files with 1052 additions and 36 deletions

View File

@@ -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, ToolConfig, ToolUsageLog,
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, ToolService
from services.conversation_service import ConversationService
# 配置日志
@@ -204,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,
@@ -418,6 +419,162 @@ async def unbind_agent(mapping_id: int, db: Session = Depends(get_db)):
return {"success": success}
# ==================== 工具配置 API ====================
@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 {
"tools": [
{
"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 t in tools
]
}
@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/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_tool(tool_id)
tool = service.update_tool(tool_id, data)
if not tool:
return {"success": False, "message": "工具不存在"}
return {"success": True, "tool": {"id": tool.id, "name": tool.name}}
@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/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.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 = ToolService(db)
tool_id = data.get('tool_id')
if tool_id:
tool = service.get_tool(tool_id)
else:
tool = service.get_default_tool('search')
if not tool or not tool.config.get('api_key'):
return {"success": False, "message": "未配置搜索工具"}
# Tavily Search API
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.get('api_key'),
"query": query,
"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": "不支持的搜索提供商"}
# ==================== 对话 API保留原有 ====================
@app.get("/api/conversations")
@@ -491,6 +648,7 @@ async def get_messages(conversation_id: str, db: Session = Depends(get_db)):
"role": m.role,
"content": m.content,
"thinking_content": m.thinking_content, # v2新增
"extra_data": m.extra_data, # 包含搜索结果等
"source": m.source,
"agent_id": m.agent_id, # v2新增
"model_used": m.model_used, # v2新增
@@ -585,6 +743,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
"role": m.role,
"content": m.content,
"thinking_content": m.thinking_content,
"extra_data": m.extra_data, # 包含搜索结果等
"agent_id": m.agent_id, # 每条消息的Agent ID
"source": m.source,
"created_at": m.created_at.isoformat()
@@ -607,19 +766,38 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
elif action == "chat":
message = data.get("message", "")
files = data.get("files", []) # 上传的文件
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():
# 如果没有消息但有文件,构造消息
if not message.strip() and files:
message = "[上传文件]"
if not message.strip() and not files:
continue
# 获取或创建会话
# 处理文件内容,添加到消息
if files:
for f in files:
if f.get('type') and f['type'].startswith('image/'):
message += f"\n[图片: {f['name']}]"
elif f.get('content'):
# 文本文件内容
message += f"\n\n文件 {f['name']} 内容:\n{f['content'][:3000]}"
# 1. 获取Agent配置
agent_config = agent_service.get_agent_config(current_agent_id)
agent_tools = agent_config.get('agent', {}).get('tools', [])
# 2. 获取或创建会话(先有 conversation_id
if conversation_id:
conversation = conv_service.get_conversation(conversation_id)
else:
@@ -630,30 +808,122 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
"conversation_id": conversation_id
})
# 保存用户消息
user_msg = conv_service.add_message(
conversation_id=conversation.id,
role='user',
content=message,
source='web'
)
# 广播用户消息
# 3. 广播用户消息(前端立即看到)
await manager.send_to_user(MAIN_USER_ID, {
"type": "user_message",
"conversation_id": conversation_id,
"message": {
"id": user_msg.id,
"id": None, # 临时,后面会保存
"role": "user",
"content": message,
"source": "web",
"created_at": user_msg.created_at.isoformat()
"created_at": datetime.utcnow().isoformat()
}
})
# 获取Agent配置
agent_config = agent_service.get_agent_config(current_agent_id)
# 4. 执行搜索并发送搜索结果
search_context = None
search_results_for_client = None # 用于发送给前端和保存
logger.info(f"检查搜索条件: agent_tools={agent_tools}, disabled_tools={disabled_tools}")
if 'search' in agent_tools and 'search' not in disabled_tools:
logger.info("搜索条件满足,开始执行搜索")
tool_service = ToolService(db)
search_tool = tool_service.get_default_tool('search')
logger.info(f"获取到搜索工具: {search_tool.name if search_tool else 'None'}")
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": config.get('api_key'),
"query": message,
"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"):
# 构建搜索上下文给LLM
max_for_llm = config.get('max_results', 5)
search_context = "\n\n【搜索结果】\n"
for i, r in enumerate(search_result["results"][:max_for_llm], 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'])} 条结果,使用 {min(len(search_result['results']), max_for_llm)}")
# 发送搜索结果给前端(按配置的数量)
max_display = config.get('max_results', 5)
search_results_for_client = [
{
"title": r.get('title', 'N/A'),
"snippet": r.get('content', r.get('snippet', ''))[:150],
"url": r.get('url', 'N/A')
}
for r in search_result["results"][:max_display]
]
await websocket.send_json({
"type": "search_results",
"conversation_id": conversation_id,
"results": search_results_for_client,
"query": message
})
# 更新统计和日志
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
})
# 5. 保存用户消息到数据库(包含搜索结果)
user_msg = conv_service.add_message(
conversation_id=conversation.id,
role='user',
content=message,
source='web',
extra_data={'search_results': search_results_for_client, 'search_query': message} if search_results_for_client else None
)
# 6. 获取对话历史(包含刚保存的用户消息)
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
# 7. 如果有搜索结果,添加到消息中
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}"})
# 8. 调用LLM返回回复
if not agent_config or not agent_config.get('provider'):
await websocket.send_json({
"type": "error",
@@ -661,12 +931,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
})
continue
# 获取对话历史
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
# 使用非流式调用LLM简化版本确保稳定
try:
# 调用LLM非流式
response, thinking_content = await llm_service.chat(
messages=history,
provider_config=agent_config['provider'],
@@ -687,7 +952,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
model_used=agent_config['provider'].get('default_model')
)
# 发送完整回复(包含思考内容)
# 发送AI回复
await websocket.send_json({
"type": "assistant_message",
"conversation_id": conversation_id,
@@ -705,7 +970,6 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
logger.info(f"AI回复已发送: conversation_id={conversation_id}")
# 启用发送按钮
await websocket.send_json({
"type": "stream_end",
"conversation_id": conversation_id

View File

@@ -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,60 @@ class MatrixRoomMapping(Base):
created_at = Column(DateTime, default=datetime.utcnow)
# ==================== 搜索工具配置 ====================
class ToolConfig(Base):
"""工具配置(通用,支持搜索、计算器、代码执行等)"""
__tablename__ = 'tool_configs'
id = Column(Integer, primary_key=True, index=True)
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配置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) # 是否为该类型的默认工具
# 统计
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):
@@ -335,6 +392,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("默认数据初始化完成")

View File

@@ -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, ToolConfig, ToolUsageLog, 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),
@@ -125,6 +126,7 @@ class AgentService:
'model_override': agent.model_override,
'max_history': agent.max_history,
'temperature_override': agent.temperature_override,
'tools': agent.tools or [], # 工具列表
'is_default': agent.is_default,
'is_active': agent.is_active
},
@@ -405,4 +407,172 @@ class ChannelService:
'is_active': channel.is_active,
'is_primary': channel.is_primary,
'agent_mappings': self.get_channel_agents(channel_id)
}
}
class ToolService:
"""工具管理服务"""
def __init__(self, db: Session):
self.db = db
def get_all_tools(self) -> List[ToolConfig]:
"""获取所有工具配置"""
return self.db.query(ToolConfig).order_by(ToolConfig.tool_type, ToolConfig.is_default.desc()).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_active_tools(self) -> List[ToolConfig]:
"""获取活跃的工具"""
return self.db.query(ToolConfig).filter(ToolConfig.is_active == True).all()
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 tool:
tool = self.db.query(ToolConfig).filter(
ToolConfig.tool_type == tool_type,
ToolConfig.is_active == True
).first()
return tool
def create_tool(self, data: Dict) -> ToolConfig:
"""创建工具配置"""
tool = ToolConfig(
name=data.get('name'),
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(tool)
self.db.commit()
self.db.refresh(tool)
return tool
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(tool, key) and value is not None:
setattr(tool, key, value)
self.db.commit()
self.db.refresh(tool)
return tool
def delete_tool(self, tool_id: int) -> bool:
"""删除工具配置"""
tool = self.get_tool(tool_id)
if not tool:
return False
self.db.delete(tool)
self.db.commit()
return True
def set_default_tool(self, tool_id: int) -> bool:
"""设置默认工具"""
tool = self.get_tool(tool_id)
if not tool:
return False
# 清除同类型的其他默认
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
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 datetime, 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

View File

@@ -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="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>
@@ -109,6 +110,33 @@
</div>
</div>
<!-- 工具管理 -->
<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="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>
<!-- 统计 -->
<div class="page-section" id="page-stats">
<div class="page-header"><h2><i class="ri-bar-chart-box-line"></i> 统计数据</h2></div>
@@ -152,6 +180,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 +210,43 @@
<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>
<!-- 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="saveTool()">保存</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 +257,7 @@
if (page === 'llm-providers') loadProviders();
if (page === 'agents') loadAgents();
if (page === 'channels') loadChannels();
if (page === 'tools') loadTools();
if (page === 'stats') loadStats();
}
@@ -348,11 +416,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 +442,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 +558,178 @@
document.getElementById('stat-agents').textContent = (agentsData.agents || []).length;
}
// ===== 工具管理 =====
async function loadTools() {
const res = await fetch('/api/v2/tools');
const data = await res.json();
const tools = data.tools || [];
const tbody = document.getElementById('tools-list');
if (tools.length === 0) {
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;
}
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 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();
}
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/tools/${id}`, { method: 'PUT', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) });
} else {
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('toolModal')).hide();
loadTools();
alert('保存成功');
} else {
alert('保存失败: ' + result.message);
}
}
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) {
loadTools();
alert('删除成功');
} else {
alert('删除失败');
}
}
// ===== 初始化 =====
document.addEventListener('DOMContentLoaded', function() {
// 页面切换事件绑定

View File

@@ -32,6 +32,9 @@
.agent-selector select { padding: 8px 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; cursor: pointer; min-width: 150px; }
.ws-status { font-size: 12px; color: #666; background: #f0f0f0; padding: 4px 8px; border-radius: 4px; }
.ws-status.connected { color: #10a37f; }
.tool-toggle { display: flex; align-items: center; gap: 6px; font-size: 12px; }
.tool-toggle input { width: 14px; height: 14px; }
.tool-toggle label { cursor: pointer; }
.messages-container { flex: 1; overflow-y: auto; padding: 24px; }
.message { max-width: 800px; margin: 0 auto 24px; display: flex; gap: 16px; }
@@ -83,6 +86,17 @@
.thinking-toggle { font-size: 12px; color: #667eea; }
.thinking-content { margin-top: 12px; display: none; }
.thinking-content.expanded { display: block; }
.search-results-box { margin: 12px 0; padding: 10px 12px; background: linear-gradient(135deg, #f0f7ff 0%, #e8f4f8 100%); border-radius: 8px; border: 1px solid #d0e8f0; }
.search-results-header { display: flex; align-items: center; justify-content: space-between; cursor: pointer; }
.search-results-header h5 { margin: 0; font-size: 13px; color: #10a37f; display: flex; align-items: center; gap: 6px; }
.search-results-toggle { font-size: 12px; color: #666; }
.search-results-content { margin-top: 10px; display: none; }
.search-results-content.expanded { display: block; }
.search-result-item { margin-bottom: 8px; padding: 8px 10px; background: white; border-radius: 6px; border: 1px solid #eee; }
.search-result-item:last-child { margin-bottom: 0; }
.search-result-title { font-size: 13px; color: #10a37f; font-weight: 500; margin-bottom: 4px; }
.search-result-snippet { font-size: 12px; color: #666; line-height: 1.4; }
.search-result-url { font-size: 11px; color: #999; margin-top: 4px; overflow: hidden; text-overflow: ellipsis; }
/* Agent信息 */
.agent-info { font-size: 12px; color: #999; margin-top: 8px; }
@@ -93,10 +107,23 @@
.input-row { display: flex; gap: 12px; align-items: center; }
.input-row textarea { flex: 1; padding: 12px 16px; border: 1px solid #ddd; border-radius: 12px; font-size: 16px; resize: none; outline: none; max-height: 200px; min-height: 48px; line-height: 1.5; }
.input-row textarea:focus { border-color: #10a37f; }
.upload-btn { width: 48px; height: 48px; border-radius: 12px; background: #f5f5f5; border: 1px solid #ddd; cursor: pointer; font-size: 20px; display: flex; align-items: center; justify-content: center; transition: all 0.2s; color: #666; }
.upload-btn:hover { background: #e8e8e8; border-color: #10a37f; color: #10a37f; }
.send-btn { width: 48px; height: 48px; border-radius: 12px; background: #10a37f; border: none; color: #fff; cursor: pointer; font-size: 20px; display: flex; align-items: center; justify-content: center; transition: background 0.2s; }
.send-btn:hover { background: #0d8c6d; }
.send-btn:disabled { background: #ccc; cursor: not-allowed; }
/* 文件预览 */
.file-preview-area { margin-top: 12px; display: flex; gap: 8px; flex-wrap: wrap; }
.file-preview-item { position: relative; border: 1px solid #e0e0e0; border-radius: 8px; padding: 8px; background: #f8f9fa; max-width: 200px; }
.file-preview-item.image-preview { padding: 4px; }
.file-preview-item img { max-width: 180px; max-height: 120px; border-radius: 6px; }
.file-preview-item .file-icon { display: flex; align-items: center; gap: 8px; }
.file-preview-item .file-icon i { font-size: 24px; color: #10a37f; }
.file-preview-item .file-name { font-size: 12px; color: #666; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-preview-item .file-remove { position: absolute; top: 4px; right: 4px; width: 20px; height: 20px; border-radius: 50%; background: #ff4757; color: white; border: none; cursor: pointer; font-size: 12px; display: flex; align-items: center; justify-content: center; }
.file-preview-item .file-remove:hover { background: #ff6b7a; }
/* 快捷语句 - 横向扁平 */
.quick-phrases-bar { display: flex; align-items: center; gap: 8px; margin-top: 12px; position: relative; }
.add-phrase-btn { padding: 6px 10px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 6px; cursor: pointer; font-size: 12px; color: #666; white-space: nowrap; flex-shrink: 0; }
@@ -152,10 +179,17 @@
<div class="input-container">
<div class="input-area">
<div class="input-row">
<input type="file" id="fileInput" multiple accept="image/*,.pdf,.txt,.md,.json,.csv,.doc,.docx" style="display:none" onchange="handleFileUpload(event)">
<button class="upload-btn" onclick="document.getElementById('fileInput').click()" title="上传文件"><i class="ri-attachment-2"></i></button>
<textarea id="messageInput" placeholder="输入消息..." rows="1"></textarea>
<button class="send-btn" id="sendBtn" onclick="sendMessage()"><i class="ri-send-plane-fill"></i></button>
</div>
<div class="file-preview-area" id="filePreviewArea"></div>
<div class="quick-phrases-bar">
<div class="tool-toggle">
<input type="checkbox" id="enableSearch" checked>
<label for="enableSearch"><i class="ri-search-line"></i> 搜索</label>
</div>
<button class="add-phrase-btn" onclick="showAddPhraseModal()"><i class="ri-add-line"></i> 添加</button>
<div class="phrase-list-wrapper" id="phraseListWrapper" onwheel="scrollPhrases(event)">
<div class="phrase-list" id="quickPhrasesList"></div>
@@ -262,9 +296,11 @@
case 'stream_end': document.getElementById('sendBtn').disabled = false; break;
case 'user_message':
lastUserMessage = data.message.content; // 存储最后一条用户消息
if (!isRegenerating) {
// 如果是刚发送的消息,已经显示了,不再重复显示
if (!isRegenerating && data.message.content !== lastSentMessage) {
appendMessage('user', data.message.content);
}
lastSentMessage = null; // 清除标记
// 注意:不要在这里重置 isRegenerating要等 assistant_message 处理后再重置
break;
case 'assistant_message':
@@ -279,11 +315,12 @@
document.getElementById('sendBtn').disabled = false;
break;
case 'error': showError(data.message); document.getElementById('sendBtn').disabled = false; break;
case 'search_results': displaySearchResults(data.results, data.query); break;
}
}
// 消息渲染
function appendMessage(role, content, thinking = null, agentName = null) {
function appendMessage(role, content, thinking = null, agentName = null, extraData = null) {
const container = document.getElementById('messagesContainer');
container.querySelector('.welcome')?.remove();
@@ -350,6 +387,23 @@
html += '</div>';
div.innerHTML = html;
// 如果是用户消息且有搜索结果在设置innerHTML后追加
if (role === 'user' && extraData) {
console.log('Processing extraData for user message:', extraData);
console.log('search_results exists:', extraData.search_results);
if (extraData.search_results && extraData.search_results.length > 0) {
console.log('Building search results HTML for', extraData.search_results.length, 'results');
const searchHtml = buildSearchResultsHtml(extraData.search_results, extraData.search_query || content);
const bodyDiv = div.querySelector('.message-body');
console.log('bodyDiv found:', bodyDiv != null);
if (bodyDiv) {
bodyDiv.insertAdjacentHTML('beforeend', searchHtml);
console.log('Search results HTML inserted');
}
}
}
container.appendChild(div);
container.scrollTop = container.scrollHeight;
}
@@ -601,7 +655,10 @@
function displayHistory(messages) {
const container = document.getElementById('messagesContainer');
container.innerHTML = '';
messages.forEach(m => appendMessage(m.role, m.content, m.thinking_content));
messages.forEach(m => {
console.log('displayHistory message:', m.role, 'extra_data:', m.extra_data);
appendMessage(m.role, m.content, m.thinking_content, null, m.extra_data);
});
}
function clearMessages() {
@@ -616,6 +673,66 @@
container.appendChild(div);
}
function displaySearchResults(results, query) {
if (!results || results.length === 0) return;
const container = document.getElementById('messagesContainer');
// 找到最后一条用户消息
const userMessages = container.querySelectorAll('.message.user');
const lastUserMsg = userMessages[userMessages.length - 1];
if (!lastUserMsg) {
// 没有用户消息,作为独立消息显示
const div = document.createElement('div');
div.className = 'message assistant';
div.innerHTML = `<div class="message-avatar">🔍</div><div class="message-body">${buildSearchResultsHtml(results, query)}</div>`;
container.appendChild(div);
} else {
// 在用户消息的 message-body 中追加搜索结果
const msgBody = lastUserMsg.querySelector('.message-body');
if (msgBody) {
msgBody.innerHTML += buildSearchResultsHtml(results, query);
}
}
// 滚动到底部
container.scrollTop = container.scrollHeight;
}
function buildSearchResultsHtml(results, query) {
const resultId = 'sr-' + Date.now();
let html = `<div class="search-results-box">
<div class="search-results-header" onclick="toggleSearchResults('${resultId}')">
<h5><i class="ri-search-line"></i> 搜索: ${escapeHtml(query.substring(0, 30))}${query.length > 30 ? '...' : ''} (${results.length}条结果)</h5>
<span class="search-results-toggle" id="${resultId}-toggle">展开 <i class="ri-arrow-down-s-line"></i></span>
</div>
<div class="search-results-content" id="${resultId}">`;
for (const r of results) {
html += `<div class="search-result-item">
<div class="search-result-title">${escapeHtml(r.title)}</div>
<div class="search-result-snippet">${escapeHtml(r.snippet)}</div>
<div class="search-result-url">${escapeHtml(r.url)}</div>
</div>`;
}
html += '</div></div>';
return html;
}
function toggleSearchResults(id) {
const content = document.getElementById(id);
const toggle = document.getElementById(id + '-toggle');
if (content.classList.contains('expanded')) {
content.classList.remove('expanded');
toggle.innerHTML = '展开 <i class="ri-arrow-down-s-line"></i>';
} else {
content.classList.add('expanded');
toggle.innerHTML = '收起 <i class="ri-arrow-up-s-line"></i>';
}
}
// 会话管理
async function loadConversations() {
const res = await fetch('/api/conversations');
@@ -644,13 +761,12 @@
}
async function createNewConversation() {
// 检查是否已经是新建对话状态
// 检查是否已经是新建对话状态无对话ID且无消息
const container = document.getElementById('messagesContainer');
const welcomeDiv = container.querySelector('.welcome');
const hasMessages = container.querySelectorAll('.message').length > 0;
// 如果当前没有对话ID,且显示欢迎界面,且没有消息,则不创建新对话
if (!currentConversationId && welcomeDiv && !hasMessages) {
// 如果当前没有对话ID且没有消息则不创建新对话
if (!currentConversationId && !hasMessages) {
return; // 已经是新建对话状态,无需创建
}
@@ -673,15 +789,164 @@
function sendMessage() {
const input = document.getElementById('messageInput');
const msg = input.value.trim();
if (!msg) return;
// 如果没有消息且没有文件,不发送
if (!msg && pendingFiles.length === 0) return;
document.getElementById('sendBtn').disabled = true;
input.value = '';
input.style.height = 'auto';
// 立即显示用户消息(包含文件)
lastSentMessage = msg;
appendMessageWithFiles('user', msg, pendingFiles);
// 清空文件预览
pendingFiles = [];
document.getElementById('filePreviewArea').innerHTML = '';
// 获取工具禁用状态
const enableSearch = document.getElementById('enableSearch').checked;
const disabledTools = [];
if (!enableSearch) disabledTools.push('search');
// 发送消息(包含文件)
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ action: 'chat', message: msg, conversation_id: currentConversationId, agent_id: currentAgentId }));
ws.send(JSON.stringify({
action: 'chat',
message: msg,
conversation_id: currentConversationId,
agent_id: currentAgentId,
disabled_tools: disabledTools,
files: lastSentFiles || [] // 发送的文件列表
}));
}
lastSentFiles = null; // 清空
}
let lastSentFiles = null; // 记录发送的文件
// 显示带文件的用户消息
function appendMessageWithFiles(role, content, files) {
const container = document.getElementById('messagesContainer');
container.querySelector('.welcome')?.remove();
const div = document.createElement('div');
div.className = `message ${role}`;
// 构建消息内容
let msgContent = content;
if (files && files.length > 0) {
lastSentFiles = files.map(f => ({
name: f.name,
type: f.type,
content: f.content
}));
// 添加文件信息到消息
let filesText = '\n\n[附件]';
for (const f of files) {
if (f.type.startsWith('image/')) {
filesText += `\n图片: ${f.name}`;
} else {
filesText += `\n文件: ${f.name}`;
// 文本文件显示内容摘要
if (!f.type.startsWith('image/') && f.content && f.content.length < 2000) {
filesText += `\n内容: ${f.content.substring(0, 500)}${f.content.length > 500 ? '...' : ''}`;
}
}
}
msgContent += filesText;
}
const avatar = role === 'user' ? '👤' : '🤖';
let html = `<div class="message-avatar">${avatar}</div><div class="message-body">`;
html += `<div class="message-content"><div class="user-message-text">${escapeHtml(msgContent)}</div></div>`;
html += `<input type="hidden" class="copy-source" value="${msgContent.replace(/"/g, '&quot;')}">`;
html += `<div class="message-actions"><button class="action-btn" onclick="copyMessage(this)"><i class="ri-file-copy-line"></i> 复制</button></div>`;
html += '</div>';
div.innerHTML = html;
container.appendChild(div);
container.scrollTop = container.scrollHeight;
}
let pendingFiles = []; // 待发送的文件
// 文件上传处理
function handleFileUpload(event) {
const files = event.target.files;
const previewArea = document.getElementById('filePreviewArea');
for (const file of files) {
const fileId = 'file-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
// 读取文件内容
const reader = new FileReader();
reader.onload = (e) => {
const fileData = {
id: fileId,
name: file.name,
type: file.type,
size: file.size,
content: e.target.result
};
pendingFiles.push(fileData);
// 显示预览
const previewItem = document.createElement('div');
previewItem.className = 'file-preview-item';
previewItem.id = fileId + '-preview';
if (file.type.startsWith('image/')) {
previewItem.classList.add('image-preview');
previewItem.innerHTML = `
<img src="${e.target.result}" alt="${file.name}">
<button class="file-remove" onclick="removeFile('${fileId}')"><i class="ri-close-line"></i></button>
`;
} else {
// 文件图标
let iconClass = 'ri-file-text-line';
if (file.name.endsWith('.pdf')) iconClass = 'ri-file-pdf-line';
else if (file.name.endsWith('.json')) iconClass = 'ri-code-line';
else if (file.name.endsWith('.csv')) iconClass = 'ri-table-line';
else if (file.type.includes('word') || file.name.endsWith('.doc') || file.name.endsWith('.docx')) iconClass = 'ri-file-word-line';
previewItem.innerHTML = `
<div class="file-icon">
<i class="${iconClass}"></i>
<span class="file-name">${file.name}</span>
</div>
<button class="file-remove" onclick="removeFile('${fileId}')"><i class="ri-close-line"></i></button>
`;
}
previewArea.appendChild(previewItem);
};
// 根据文件类型选择读取方式
if (file.type.startsWith('image/')) {
reader.readAsDataURL(file);
} else if (file.type === 'application/pdf') {
reader.readAsDataURL(file);
} else {
// 文本类文件直接读取内容
reader.readAsText(file);
}
}
// 清空 input 以便再次选择
event.target.value = '';
}
function removeFile(fileId) {
pendingFiles = pendingFiles.filter(f => f.id !== fileId);
const preview = document.getElementById(fileId + '-preview');
if (preview) preview.remove();
}
// 发送消息
function setupTextarea() {
const textarea = document.getElementById('messageInput');
textarea.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });