feat:智能体配置加载数据库默认配置

This commit is contained in:
liailing1026
2026-03-13 14:55:58 +08:00
parent a9ae017504
commit 41832ae2d2
3 changed files with 78 additions and 45 deletions

View File

@@ -1604,53 +1604,68 @@ def handle_agent_select_modify_delete_aspect_ws(data):
def handle_set_agents_ws(data): def handle_set_agents_ws(data):
""" """
WebSocket版本设置智能体 WebSocket版本设置智能体
保存到 user_agents 数据库表 保存到 user_agents 数据库表(可选)
""" """
request_id = data.get('id') request_id = data.get('id')
incoming_data = data.get('data', {}) incoming_data = data.get('data', {})
global AgentBoard, AgentProfile_Dict, yaml_data global AgentBoard, AgentProfile_Dict, yaml_data
# 支持新格式:{ agents: [...], save_to_db: true/false }
# 兼容旧格式:直接是数组 [...]
if isinstance(incoming_data, dict):
agents_list = incoming_data.get('agents', incoming_data)
save_to_db = incoming_data.get('save_to_db', False)
else:
agents_list = incoming_data
save_to_db = False
try: try:
AgentBoard = incoming_data # 无论是否保存到数据库,都需要设置全局变量
AgentBoard = agents_list
AgentProfile_Dict = {} AgentProfile_Dict = {}
# 保存到数据库 # 处理每个智能体配置
saved_agents = [] for item in agents_list:
with get_db_context() as db: name = item["Name"]
for item in AgentBoard: if all(item.get(field) for field in ["apiUrl", "apiKey", "apiModel"]):
name = item["Name"] agent_config = {
if all(item.get(field) for field in ["apiUrl", "apiKey", "apiModel"]): "profile": item["Profile"],
agent_config = { "Icon": item.get("Icon", ""),
"profile": item["Profile"], "Classification": item.get("Classification", ""),
"Icon": item.get("Icon", ""), "apiUrl": item["apiUrl"],
"Classification": item.get("Classification", ""), "apiKey": item["apiKey"],
"apiUrl": item["apiUrl"], "apiModel": item["apiModel"],
"apiKey": item["apiKey"], "useCustomAPI": True
"apiModel": item["apiModel"], }
"useCustomAPI": True else:
} agent_config = {
else: "profile": item["Profile"],
agent_config = { "Icon": item.get("Icon", ""),
"profile": item["Profile"], "Classification": item.get("Classification", ""),
"Icon": item.get("Icon", ""), "apiUrl": yaml_data.get("OPENAI_API_BASE"),
"Classification": item.get("Classification", ""), "apiKey": yaml_data.get("OPENAI_API_KEY"),
"apiUrl": yaml_data.get("OPENAI_API_BASE"), "apiModel": yaml_data.get("OPENAI_API_MODEL"),
"apiKey": yaml_data.get("OPENAI_API_KEY"), "useCustomAPI": False
"apiModel": yaml_data.get("OPENAI_API_MODEL"), }
"useCustomAPI": False AgentProfile_Dict[name] = agent_config
}
AgentProfile_Dict[name] = agent_config
# 保存到数据库(使用 upsert相同 user_id + agent_name 则更新,否则创建 # 保存到数据库(仅当 save_to_db 为 true 时
user_id = item.get("user_id", "default_user") saved_agents = []
agent = UserAgentCRUD.upsert( if save_to_db:
db=db, with get_db_context() as db:
user_id=user_id, for item in agents_list:
agent_name=name, name = item["Name"]
agent_config=agent_config, agent_config = AgentProfile_Dict[name]
) # 保存到数据库(使用 upsert相同 user_id + agent_name 则更新,否则创建)
saved_agents.append(agent.to_dict()) user_id = item.get("user_id", "default_user")
agent = UserAgentCRUD.upsert(
db=db,
user_id=user_id,
agent_name=name,
agent_config=agent_config,
)
saved_agents.append(agent.to_dict())
# 返回结果 # 返回结果
emit('response', { emit('response', {
@@ -1697,6 +1712,11 @@ def handle_get_agents_ws(data):
with get_db_context() as db: with get_db_context() as db:
user_agents = UserAgentCRUD.get_by_user_id(db=db, user_id=user_id) user_agents = UserAgentCRUD.get_by_user_id(db=db, user_id=user_id)
# 如果用户没有配置,回退到 default_user 的默认配置
if not user_agents and user_id != 'default_user':
print(f"[get_agents] 用户 {user_id} 无配置,回退到 default_user")
user_agents = UserAgentCRUD.get_by_user_id(db=db, user_id='default_user')
# 转换为前端期望的格式 # 转换为前端期望的格式
agents = [] agents = []
for ua in user_agents: for ua in user_agents:

View File

@@ -89,8 +89,16 @@ class Api {
return `hsl(${h}, ${s}%, ${l}%)` return `hsl(${h}, ${s}%, ${l}%)`
} }
setAgents = (data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[]) => setAgents = (data: Pick<Agent, 'Name' | 'Profile' | 'apiUrl' | 'apiKey' | 'apiModel'>[], saveToDb = false) => {
websocket.send('set_agents', data) const storedUserId = localStorage.getItem('user_id')
// 为每个智能体添加 user_id
const payload = data.map(agent => ({
...agent,
...(storedUserId ? { user_id: storedUserId } : {})
}))
// saveToDb 为 true 时才写入数据库
return websocket.send('set_agents', { agents: payload, save_to_db: saveToDb })
}
getAgents = (user_id?: string) => { getAgents = (user_id?: string) => {
// 优先使用传入的 user_id其次使用 localStorage 存储的,首次访问时不传 // 优先使用传入的 user_id其次使用 localStorage 存储的,首次访问时不传

View File

@@ -15,16 +15,21 @@ const agentsStore = useAgentsStore()
// 如果agentsStore.agents不存在就读取默认配置的json文件 // 如果agentsStore.agents不存在就读取默认配置的json文件
onMounted(async () => { onMounted(async () => {
// 先调用 getAgents检查是否需要生成 user_id // 先调用 getAgents获取用户的智能体配置(后端会自动回退到 default_user
const res = await api.getAgents() const res = await api.getAgents()
if (res && res.user_id) { if (res && res.user_id) {
console.log('[AgentRepo] 获取到 user_id:', res.user_id) console.log('[AgentRepo] 获取到 user_id:', res.user_id)
} }
if (!agentsStore.agents.length) { // 使用后端返回的智能体配置(数据库有就用数据库的,没有会用 default_user 的)
const res = await readConfig<Agent[]>('agent.json') if (res && res.data && res.data.agents && res.data.agents.length > 0) {
agentsStore.setAgents(res) agentsStore.setAgents(res.data.agents as Agent[])
} else if (!agentsStore.agents.length) {
// 只有在完全没有数据时才使用默认 json
const defaultAgents = await readConfig<Agent[]>('agent.json')
agentsStore.setAgents(defaultAgents)
} }
await api.setAgents( await api.setAgents(
agentsStore.agents.map(item => pick(item, ['Name', 'Profile', 'Icon', 'Classification', 'apiUrl', 'apiKey', 'apiModel'])) agentsStore.agents.map(item => pick(item, ['Name', 'Profile', 'Icon', 'Classification', 'apiUrl', 'apiKey', 'apiModel']))
) )
@@ -98,9 +103,9 @@ const readFileContent = (file: File) => {
})) }))
agentsStore.setAgents(processedAgents) agentsStore.setAgents(processedAgents)
// 调用API // 调用APIsaveToDb=true 表示写入数据库
api api
.setAgents(processedAgents) .setAgents(processedAgents, true)
.then(() => { .then(() => {
success('智能体上传成功') success('智能体上传成功')
}) })