feat(agent): 添加获取智能体详细信息接口并优化前端状态管理

- 添加获取单个智能体完整信息的API接口
- 优化前端智能体状态管理,增加详细信息缓存
- 重构配置项获取逻辑以使用缓存数据
This commit is contained in:
Wenjie Zhang 2025-11-17 20:18:46 +08:00
parent 292237e5e2
commit 4d5c1c0a83
2 changed files with 92 additions and 9 deletions

View File

@ -397,17 +397,16 @@ async def call(query: str = Body(...), meta: dict = Body(None), current_user: Us
@chat.get("/agent") @chat.get("/agent")
async def get_agent(current_user: User = Depends(get_required_user)): async def get_agent(current_user: User = Depends(get_required_user)):
"""获取所有可用智能体(需要登录)""" """获取所有可用智能体的基本信息(需要登录)"""
agents_info = await agent_manager.get_agents_info() agents_info = await agent_manager.get_agents_info()
# Return agents with complete information # Return agents with basic information (without configurable_items for performance)
agents = [ agents = [
{ {
"id": agent_info["id"], "id": agent_info["id"],
"name": agent_info.get("name", "Unknown"), "name": agent_info.get("name", "Unknown"),
"description": agent_info.get("description", ""), "description": agent_info.get("description", ""),
"examples": agent_info.get("examples", []), "examples": agent_info.get("examples", []),
"configurable_items": agent_info.get("configurable_items", []),
"has_checkpointer": agent_info.get("has_checkpointer", False), "has_checkpointer": agent_info.get("has_checkpointer", False),
"capabilities": agent_info.get("capabilities", []), # 智能体能力列表 "capabilities": agent_info.get("capabilities", []), # 智能体能力列表
} }
@ -417,6 +416,34 @@ async def get_agent(current_user: User = Depends(get_required_user)):
return {"agents": agents} return {"agents": agents}
@chat.get("/agent/{agent_id}")
async def get_single_agent(agent_id: str, current_user: User = Depends(get_required_user)):
"""获取指定智能体的完整信息(包含配置选项)(需要登录)"""
try:
# 检查智能体是否存在
if not (agent := agent_manager.get_agent(agent_id)):
raise HTTPException(status_code=404, detail=f"智能体 {agent_id} 不存在")
# 获取智能体的完整信息(包含 configurable_items
agent_info = await agent.get_info()
return {
"id": agent_info["id"],
"name": agent_info.get("name", "Unknown"),
"description": agent_info.get("description", ""),
"examples": agent_info.get("examples", []),
"configurable_items": agent_info.get("configurable_items", []),
"has_checkpointer": agent_info.get("has_checkpointer", False),
"capabilities": agent_info.get("capabilities", []),
}
except HTTPException:
raise
except Exception as e:
logger.error(f"获取智能体 {agent_id} 信息出错: {e}")
raise HTTPException(status_code=500, detail=f"获取智能体信息出错: {str(e)}")
@chat.post("/agent/{agent_id}") @chat.post("/agent/{agent_id}")
async def chat_agent( async def chat_agent(
agent_id: str, agent_id: str,

View File

@ -16,6 +16,9 @@ export const useAgentStore = defineStore('agent', () => {
const agentConfig = ref({}) const agentConfig = ref({})
const originalAgentConfig = ref({}) const originalAgentConfig = ref({})
// 智能体详情相关状态
const agentDetails = ref({}) // 存储每个智能体的详细信息(含 configurable_items
// 工具相关状态 // 工具相关状态
const availableTools = ref([]) const availableTools = ref([])
@ -23,6 +26,7 @@ export const useAgentStore = defineStore('agent', () => {
const isLoadingAgents = ref(false) const isLoadingAgents = ref(false)
const isLoadingConfig = ref(false) const isLoadingConfig = ref(false)
const isLoadingTools = ref(false) const isLoadingTools = ref(false)
const isLoadingAgentDetail = ref(false)
// 错误状态 // 错误状态
const error = ref(null) const error = ref(null)
@ -44,10 +48,12 @@ export const useAgentStore = defineStore('agent', () => {
const isDefaultAgent = computed(() => selectedAgentId.value === defaultAgentId.value) const isDefaultAgent = computed(() => selectedAgentId.value === defaultAgentId.value)
const configurableItems = computed(() => { const configurableItems = computed(() => {
const agent = selectedAgentId.value ? agents.value.find(a => a.id === selectedAgentId.value) : null const agentId = selectedAgentId.value
if (!agent || !agent.configurable_items) return {} if (!agentId || !agentDetails.value[agentId] || !agentDetails.value[agentId].configurable_items) {
return {}
}
const agentConfigurableItems = agent.configurable_items const agentConfigurableItems = agentDetails.value[agentId].configurable_items
const items = { ...agentConfigurableItems } const items = { ...agentConfigurableItems }
Object.keys(items).forEach(key => { Object.keys(items).forEach(key => {
const item = items[key] const item = items[key]
@ -76,13 +82,21 @@ export const useAgentStore = defineStore('agent', () => {
if (!selectedAgentId.value || !agents.value.find(a => a.id === selectedAgentId.value)) { if (!selectedAgentId.value || !agents.value.find(a => a.id === selectedAgentId.value)) {
if (defaultAgentId.value && agents.value.find(a => a.id === defaultAgentId.value)) { if (defaultAgentId.value && agents.value.find(a => a.id === defaultAgentId.value)) {
selectAgent(defaultAgentId.value) await selectAgent(defaultAgentId.value)
} else if (agents.value.length > 0) { } else if (agents.value.length > 0) {
const firstAgentId = agents.value[0].id const firstAgentId = agents.value[0].id
selectAgent(firstAgentId) await selectAgent(firstAgentId)
} }
} else { } else {
console.log('Condition FALSE: Persisted selected agent is valid. Keeping it.') console.log('Condition FALSE: Persisted selected agent is valid. Keeping it.')
// 确保已缓存的智能体详细信息存在
if (selectedAgentId.value && !agentDetails.value[selectedAgentId.value]) {
try {
await fetchAgentDetail(selectedAgentId.value)
} catch (err) {
console.warn(`Failed to fetch agent detail for ${selectedAgentId.value}:`, err)
}
}
} }
if (selectedAgentId.value) { if (selectedAgentId.value) {
@ -120,6 +134,35 @@ export const useAgentStore = defineStore('agent', () => {
} }
} }
/**
* 获取单个智能体的详细信息包含配置选项
* @param {string} agentId - 智能体ID
*/
async function fetchAgentDetail(agentId) {
if (!agentId) return
// 如果已经缓存了详细信息,直接返回
if (agentDetails.value[agentId]) {
return agentDetails.value[agentId]
}
isLoadingAgentDetail.value = true
error.value = null
try {
const response = await agentApi.getAgentDetail(agentId)
agentDetails.value[agentId] = response
return response
} catch (err) {
console.error(`Failed to fetch agent detail for ${agentId}:`, err)
handleChatError(err, 'fetch')
error.value = err.message
throw err
} finally {
isLoadingAgentDetail.value = false
}
}
/** /**
* 获取默认智能体 * 获取默认智能体
*/ */
@ -152,12 +195,20 @@ export const useAgentStore = defineStore('agent', () => {
/** /**
* 选择智能体 * 选择智能体
*/ */
function selectAgent(agentId) { async function selectAgent(agentId) {
if (agents.value.find(a => a.id === agentId)) { if (agents.value.find(a => a.id === agentId)) {
selectedAgentId.value = agentId selectedAgentId.value = agentId
// 清空之前的配置 // 清空之前的配置
agentConfig.value = {} agentConfig.value = {}
originalAgentConfig.value = {} originalAgentConfig.value = {}
// 自动获取智能体详细信息(包含 configurable_items
try {
await fetchAgentDetail(agentId)
} catch (err) {
console.warn(`Failed to fetch agent detail for ${agentId}:`, err)
// 不抛出错误,允许继续选择智能体
}
} }
} }
@ -262,10 +313,12 @@ export const useAgentStore = defineStore('agent', () => {
defaultAgentId.value = null defaultAgentId.value = null
agentConfig.value = {} agentConfig.value = {}
originalAgentConfig.value = {} originalAgentConfig.value = {}
agentDetails.value = {}
availableTools.value = [] availableTools.value = []
isLoadingAgents.value = false isLoadingAgents.value = false
isLoadingConfig.value = false isLoadingConfig.value = false
isLoadingTools.value = false isLoadingTools.value = false
isLoadingAgentDetail.value = false
error.value = null error.value = null
isInitialized.value = false isInitialized.value = false
} }
@ -277,10 +330,12 @@ export const useAgentStore = defineStore('agent', () => {
defaultAgentId, defaultAgentId,
agentConfig, agentConfig,
originalAgentConfig, originalAgentConfig,
agentDetails,
availableTools, availableTools,
isLoadingAgents, isLoadingAgents,
isLoadingConfig, isLoadingConfig,
isLoadingTools, isLoadingTools,
isLoadingAgentDetail,
error, error,
isInitialized, isInitialized,
@ -295,6 +350,7 @@ export const useAgentStore = defineStore('agent', () => {
// 方法 // 方法
initialize, initialize,
fetchAgents, fetchAgents,
fetchAgentDetail,
fetchDefaultAgent, fetchDefaultAgent,
setDefaultAgent, setDefaultAgent,
selectAgent, selectAgent,