fix: map agent workflow inputs

This commit is contained in:
2026-06-13 12:16:48 +08:00
parent 47da899ff3
commit 5f3b4502f6
3 changed files with 62 additions and 14 deletions
@@ -91,6 +91,8 @@ class TemplateNode(BaseNode):
return NodeResult(success=False, error=f'智能体不存在或未发布: {agent_code}') return NodeResult(success=False, error=f'智能体不存在或未发布: {agent_code}')
model_id = self.config.get('model_id') or agent.model_id model_id = self.config.get('model_id') or agent.model_id
if not model_id:
model_id = await self._resolve_default_chat_model_id(context)
if not model_id: if not model_id:
return NodeResult(success=False, error=f'智能体未配置模型: {agent.name}({agent.code})') return NodeResult(success=False, error=f'智能体未配置模型: {agent.name}({agent.code})')
@@ -148,6 +150,22 @@ class TemplateNode(BaseNode):
elapsed_time=int((time.time() - start_time) * 1000), elapsed_time=int((time.time() - start_time) * 1000),
) )
@staticmethod
async def _resolve_default_chat_model_id(context: NodeContext) -> str:
from ai_platform.models import LLMModel
result = await context.db_session.execute(
select(LLMModel)
.where(
LLMModel.is_deleted == False,
LLMModel.is_active == True,
LLMModel.model_type == 'chat',
)
.order_by(LLMModel.sort.desc(), LLMModel.sys_create_datetime.desc())
)
model = result.scalars().first()
return str(model.id) if model else ''
@staticmethod @staticmethod
def _build_agent_system_prompt(agent: Any) -> str: def _build_agent_system_prompt(agent: Any) -> str:
base_prompt = agent.system_prompt or '' base_prompt = agent.system_prompt or ''
@@ -9,7 +9,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from ai_platform.models import ( from ai_platform.models import (
Agent, AgentConversation, AgentMessage, LLMModel, Agent, AgentConversation, AgentMessage, AIWorkflow, LLMModel,
) )
from .llm_service import LLMService from .llm_service import LLMService
@@ -433,16 +433,16 @@ class AgentService:
if accumulated: if accumulated:
final_content = accumulated final_content = accumulated
elif event_type == 'node_complete': elif event_type == 'node_complete':
node_type = event.get('node_type') output = (event.get('outputs') or {}).get('output', '')
if node_type == 'llm': if output:
outputs = event.get('outputs', {}) final_content = output
output = outputs.get('output', '')
if output:
final_content = output
elif event_type == 'waiting_input': elif event_type == 'waiting_input':
is_waiting = True is_waiting = True
elif event_type == 'complete': elif event_type == 'complete':
total_tokens = event.get('total_tokens', 0) total_tokens = event.get('total_tokens', 0)
output = (event.get('outputs') or {}).get('output', '')
if output:
final_content = output
yield event yield event
else: else:
@@ -465,7 +465,7 @@ class AgentService:
if attachment_texts: if attachment_texts:
enhanced_user_input = user_message + '\n' + '\n'.join(attachment_texts) enhanced_user_input = user_message + '\n' + '\n'.join(attachment_texts)
workflow_inputs = {'user_input': enhanced_user_input} workflow_inputs = await self._build_workflow_inputs(agent, enhanced_user_input)
if application_id: if application_id:
workflow_inputs['application_id'] = application_id workflow_inputs['application_id'] = application_id
if form_code: if form_code:
@@ -495,12 +495,9 @@ class AgentService:
if accumulated: if accumulated:
final_content = accumulated final_content = accumulated
elif event_type == 'node_complete': elif event_type == 'node_complete':
node_type = event.get('node_type') output = (event.get('outputs') or {}).get('output', '')
if node_type == 'llm': if output:
outputs = event.get('outputs', {}) final_content = output
output = outputs.get('output', '')
if output:
final_content = output
elif event_type == 'waiting_input': elif event_type == 'waiting_input':
is_waiting = True is_waiting = True
# 保存工作流运行 ID 到对话元数据 # 保存工作流运行 ID 到对话元数据
@@ -509,6 +506,9 @@ class AgentService:
conversation.extra_data['workflow_run_id'] = current_run_id conversation.extra_data['workflow_run_id'] = current_run_id
elif event_type == 'complete': elif event_type == 'complete':
total_tokens = event.get('total_tokens', 0) total_tokens = event.get('total_tokens', 0)
output = (event.get('outputs') or {}).get('output', '')
if output:
final_content = output
yield event yield event
@@ -552,6 +552,35 @@ class AgentService:
'type': 'error', 'type': 'error',
'content': str(e), 'content': str(e),
} }
async def _build_workflow_inputs(self, agent: Agent, user_input: str) -> Dict[str, Any]:
workflow_inputs: Dict[str, Any] = {'user_input': user_input}
if not self._db or not agent.workflow_id:
return workflow_inputs
result = await self._db.execute(
select(AIWorkflow).where(
AIWorkflow.id == agent.workflow_id,
AIWorkflow.is_deleted == False,
)
)
workflow = result.scalar_one_or_none()
if not workflow:
return workflow_inputs
input_variables = workflow.input_variables or []
if any((item or {}).get('name') == 'request' for item in input_variables):
workflow_inputs.setdefault('request', user_input)
if any((item or {}).get('name') == 'issue_id' for item in input_variables):
workflow_inputs.setdefault('issue_id', self._extract_issue_id(user_input))
return workflow_inputs
@staticmethod
def _extract_issue_id(text: str) -> str:
import re
match = re.search(r'\b[A-Z][A-Z0-9]+-\d+\b', text or '', re.IGNORECASE)
return match.group(0).upper() if match else 'MANUAL-1'
def _build_system_prompt_simple(self, agent: Agent) -> str: def _build_system_prompt_simple(self, agent: Agent) -> str:
"""构建简化的系统提示词""" """构建简化的系统提示词"""
@@ -1594,6 +1594,7 @@ class AIWorkflowService:
node_type, node_type,
status='completed', status='completed',
output=result.output, output=result.output,
metadata=_node_result_metadata(result),
inputs=copy.deepcopy(node_inputs), inputs=copy.deepcopy(node_inputs),
)) ))
yield { yield {