fix(chatbot): 修复智能体工具获取和权限问题
- 修改工具获取逻辑,使用智能体实例的工具列表 - 将工具获取接口的权限从管理员改为普通用户 - 更新日志格式,添加行号信息 - 修复前端工具获取时未传递智能体ID的问题
This commit is contained in:
parent
13b0c7b4c8
commit
221f4af213
@ -13,6 +13,8 @@
|
||||
- [ ] 当出现不支持的文件类型的时候,前端没有限制
|
||||
- [ ] 默认智能体设置后,在一些情况下依然仅加载第一个智能体
|
||||
- [ ] 目前只能获取默认的 tools,单个智能体的tools没法展示
|
||||
- [ ] 生成的过程中切换对话,会出现消息渲染混乱的问题,消息完全记载完成之后不会出现混乱
|
||||
- [ ] 当消息生成的时候有报错的时候,前端无显示
|
||||
|
||||
💯 **More**:
|
||||
|
||||
|
||||
@ -179,10 +179,17 @@ async def update_chat_models(model_provider: str, model_names: list[str], curren
|
||||
return {"models": config.model_names[model_provider]["models"]}
|
||||
|
||||
@chat.get("/tools")
|
||||
async def get_tools(agent_id: str, current_user: User = Depends(get_admin_user)):
|
||||
async def get_tools(agent_id: str, current_user: User = Depends(get_required_user)):
|
||||
"""获取所有可用工具(需要登录)"""
|
||||
logger.info(f"agent_id: {agent_id}")
|
||||
tools = get_buildin_tools()
|
||||
# 获取Agent实例和配置类
|
||||
if not (agent := agent_manager.get_agent(agent_id)):
|
||||
raise HTTPException(status_code=404, detail=f"智能体 {agent_id} 不存在")
|
||||
|
||||
if hasattr(agent, "agent_tools"):
|
||||
tools = agent.agent_tools
|
||||
else:
|
||||
tools = get_buildin_tools()
|
||||
|
||||
tools_info = gen_tool_info(tools)
|
||||
return {"tools": {tool["id"]: tool for tool in tools_info}}
|
||||
|
||||
@ -190,9 +197,9 @@ async def get_tools(agent_id: str, current_user: User = Depends(get_admin_user))
|
||||
async def save_agent_config(
|
||||
agent_id: str,
|
||||
config: dict = Body(...),
|
||||
current_user: User = Depends(get_admin_user)
|
||||
current_user: User = Depends(get_required_user)
|
||||
):
|
||||
"""保存智能体配置到YAML文件(需要管理员权限)"""
|
||||
"""保存智能体配置到YAML文件(需要登录)"""
|
||||
try:
|
||||
# 获取Agent实例和配置类
|
||||
if not (agent := agent_manager.get_agent(agent_id)):
|
||||
|
||||
@ -2,7 +2,9 @@ from typing import Annotated
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from src.agents.common.context import BaseContext
|
||||
from src.agents.common.tools import get_buildin_tools
|
||||
from src.agents.common.tools import gen_tool_info
|
||||
|
||||
from .tools import get_tools
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class Context(BaseContext):
|
||||
@ -16,11 +18,11 @@ class Context(BaseContext):
|
||||
},
|
||||
)
|
||||
|
||||
tools: Annotated[list[str], {"__template_metadata__": {"kind": "tools"}}] = field(
|
||||
tools: Annotated[list[dict], {"__template_metadata__": {"kind": "tools"}}] = field(
|
||||
default_factory=list,
|
||||
metadata={
|
||||
"name": "工具",
|
||||
"options": [t.name for t in get_buildin_tools()], # 这里的选择是所有的工具
|
||||
"options": gen_tool_info(get_tools()), # 这里的选择是所有的工具
|
||||
"description": "工具列表"
|
||||
},
|
||||
)
|
||||
|
||||
@ -34,20 +34,21 @@ class ChatbotAgent(BaseAgent):
|
||||
self.context_schema = Context
|
||||
self.workdir = Path(sys_config.save_dir) / "agents" / self.module_name
|
||||
self.workdir.mkdir(parents=True, exist_ok=True)
|
||||
self.agent_tools = get_tools()
|
||||
|
||||
def _get_tools(self, tools: list[str]):
|
||||
"""根据配置获取工具。
|
||||
默认不使用任何工具。
|
||||
如果配置为列表,则使用列表中的工具。
|
||||
"""
|
||||
platform_tools = get_tools()
|
||||
self.agent_tools = get_tools()
|
||||
if tools is None or not isinstance(tools, list) or len(tools) == 0:
|
||||
# 默认不使用任何工具
|
||||
logger.info("未配置工具或配置为空,不使用任何工具")
|
||||
return []
|
||||
else:
|
||||
# 使用配置中指定的工具
|
||||
tools = [tool for tool in platform_tools if tool.name in tools]
|
||||
tools = [tool for tool in self.agent_tools if tool.name in tools]
|
||||
logger.info(f"使用工具: {[tool.name for tool in tools]}")
|
||||
return tools
|
||||
|
||||
|
||||
@ -20,7 +20,7 @@ def setup_logger(name, level="DEBUG", console=True):
|
||||
loguru_logger.add(
|
||||
LOG_FILE,
|
||||
level=level,
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} - {level} - {name} - {message}",
|
||||
format="{time:YYYY-MM-DD HH:mm:ss} - {level} - {name}:{line} - {message}",
|
||||
encoding="utf-8",
|
||||
rotation="10 MB", # 文件大小达到 10MB 时轮转
|
||||
retention="30 days", # 保留30天的日志
|
||||
@ -32,7 +32,7 @@ def setup_logger(name, level="DEBUG", console=True):
|
||||
loguru_logger.add(
|
||||
lambda msg: print(msg, end=""),
|
||||
level=level,
|
||||
format="<green>{time:MM-DD HH:mm:ss}</green> <level>{level}</level> <cyan>{name}</cyan>: <level>{message}</level>",
|
||||
format="<green>{time:MM-DD HH:mm:ss}</green> <level>{level}</level> <cyan>{name}:{line}</cyan>: <level>{message}</level>",
|
||||
colorize=True
|
||||
)
|
||||
|
||||
|
||||
@ -50,7 +50,7 @@ export const useAgentStore = defineStore('agent', {
|
||||
configurableItems: (state) => {
|
||||
const agent = state.selectedAgentId ? state.agents[state.selectedAgentId] : null;
|
||||
if (!agent || !agent.configurable_items) return {};
|
||||
|
||||
|
||||
const agentConfigurableItems = agent.configurable_items;
|
||||
const items = { ...agentConfigurableItems };
|
||||
Object.keys(items).forEach(key => {
|
||||
@ -108,13 +108,13 @@ export const useAgentStore = defineStore('agent', {
|
||||
try {
|
||||
// 首先加载智能体列表
|
||||
await this.fetchAgents();
|
||||
|
||||
|
||||
// 然后设置默认智能体
|
||||
await this.fetchDefaultAgent();
|
||||
|
||||
|
||||
// 最后加载工具
|
||||
await this.fetchTools();
|
||||
|
||||
|
||||
this.isInitialized = true;
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize agent store:', error);
|
||||
@ -244,7 +244,7 @@ export const useAgentStore = defineStore('agent', {
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await agentApi.getTools();
|
||||
const response = await agentApi.getTools(this.selectedAgentId);
|
||||
this.availableTools = response.tools;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch tools:', error);
|
||||
@ -444,7 +444,7 @@ export const useAgentStore = defineStore('agent', {
|
||||
|
||||
this.isStreaming = true;
|
||||
this.resetOnGoingConv();
|
||||
|
||||
|
||||
// 创建新的 AbortController
|
||||
this.streamAbortController = new AbortController();
|
||||
|
||||
@ -472,7 +472,7 @@ export const useAgentStore = defineStore('agent', {
|
||||
if (this.streamAbortController && this.streamAbortController.signal.aborted) {
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
@ -491,7 +491,7 @@ export const useAgentStore = defineStore('agent', {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Process any remaining data in the buffer
|
||||
if (buffer.trim() && (!this.streamAbortController || !this.streamAbortController.signal.aborted)) {
|
||||
try {
|
||||
@ -542,7 +542,7 @@ export const useAgentStore = defineStore('agent', {
|
||||
this.streamAbortController.abort();
|
||||
this.streamAbortController = null;
|
||||
}
|
||||
|
||||
|
||||
this.agents = {};
|
||||
this.selectedAgentId = null;
|
||||
this.defaultAgentId = null;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user