feat: improve agent runtime observability

This commit is contained in:
2026-06-22 07:27:56 +08:00
parent 46248c1745
commit 17031cc3c9
5 changed files with 180 additions and 22 deletions
@@ -43,6 +43,16 @@ class AgentService:
def _attach_agent_collaboration(self, event: Dict[str, Any], agent: Agent) -> Dict[str, Any]:
enriched = dict(event)
collaboration = dict(enriched.get("collaboration") or {})
for key in (
"model_id",
"model",
"model_name",
"provider_id",
"provider_name",
"provider_type",
):
if enriched.get(key):
collaboration.setdefault(key, enriched[key])
for key, value in self._agent_collaboration_metadata(agent).items():
collaboration.setdefault(key, value)
enriched["collaboration"] = collaboration
@@ -55,6 +65,10 @@ class AgentService:
"collaboration_role",
"collaboration_mode",
"model_id",
"model",
"model_name",
"provider_name",
"provider_type",
):
if collaboration.get(key):
actor.setdefault(key, collaboration[key])
@@ -247,6 +261,34 @@ class AgentService:
model.id,
)
return str(model.id)
async def _get_model_runtime_meta(self, model_id: Optional[str]) -> Dict[str, Any]:
if not self._db or not model_id:
return {}
result = await self._db.execute(
select(LLMModel, LLMProvider)
.join(LLMProvider, LLMProvider.id == LLMModel.provider_id)
.where(
LLMModel.id == model_id,
LLMModel.is_deleted == False,
LLMProvider.is_deleted == False,
)
)
row = result.first()
if not row:
return {"model_id": str(model_id)}
model, provider = row[0], row[1]
display_model = model.display_name or model.model_name or str(model.id)
return {
"model_id": str(model.id),
"model": display_model,
"model_name": model.model_name or display_model,
"provider_id": str(provider.id),
"provider_name": provider.name or provider.provider_type,
"provider_type": provider.provider_type,
}
async def _chat_autonomous_function_calling(
self,
@@ -264,6 +306,8 @@ class AgentService:
from ai_platform.providers.base import LLMMessage
start_time = time.time()
model_id: Optional[str] = None
model_meta: Dict[str, Any] = {}
if not self._db:
yield {'type': 'error', 'content': '数据库会话未初始化'}
@@ -315,11 +359,13 @@ class AgentService:
model_id = await self._resolve_agent_model_id(agent)
if not model_id:
raise ValueError('未找到可用的 chat 模型,请先在模型配置中启用一个模型')
model_meta = await self._get_model_runtime_meta(model_id)
event = self._attach_agent_collaboration({
'type': 'thought',
'content': '智能体开始分析用户需求并调用默认 chat 模型',
'model_id': model_id,
**model_meta,
}, agent)
step = self._event_to_reasoning_step(event)
if step:
@@ -390,6 +436,7 @@ class AgentService:
model_id = await self._resolve_agent_model_id(agent)
if not model_id:
raise ValueError('未找到可用的 chat 模型,请先在模型配置中启用一个模型')
model_meta = await self._get_model_runtime_meta(model_id)
total_tokens = 0
final_answer = ''
@@ -410,6 +457,7 @@ class AgentService:
'content': chunk.content,
'accumulated_content': accumulated_content,
'model_id': model_id,
**model_meta,
}
if chunk.is_finished:
@@ -431,6 +479,7 @@ class AgentService:
'type': 'answer',
'content': final_answer,
'model_id': model_id,
**model_meta,
}
# 更新助手消息
@@ -461,21 +510,20 @@ class AgentService:
'conversation_id': str(conversation.id),
'tokens_used': total_tokens,
'elapsed_time': elapsed_time,
**model_meta,
}
except Exception as e:
logger.exception(f'Agent chat error: {e}')
assistant_msg.status = 'failed'
assistant_msg.error_message = str(e)
error_step = self._event_to_reasoning_step({'type': 'error', 'content': str(e)})
error_event = {'type': 'error', 'content': str(e), **model_meta}
error_step = self._event_to_reasoning_step(error_event)
if error_step:
reasoning_steps.append(error_step)
assistant_msg.reasoning_steps = reasoning_steps.copy()
await self._db.commit()
yield {
'type': 'error',
'content': str(e),
}
yield error_event
async def _chat_autonomous_react(
self,