扣子工作流 AI Agent 完全指南:从配置到企业级集成实战
当某电商平台使用扣子工作流重构其客服系统后,异常订单处理时长从平均 45 分钟降至 3 分钟,人工干预率下降 85%。
环境配置与基础概念
项目初始化配置
python
# 扣子工作流 SDK 初始化
import asyncio
from bozai_workflow import WorkflowEngine, Node, Edge
from bozai_workflow.triggers import HTTPTrigger, ScheduleTrigger
from bozai_workflow.actions import AINode, APINode, ConditionNode
class BozaiWorkflowConfig:
"""扣子工作流基础配置类"""
def __init__(self, app_id: str, app_secret: str):
self.app_id = app_id
self.app_secret = app_secret
self.workflow_engine = WorkflowEngine(
base_url="https://api.bozai.com/workflow/v1",
credentials={"app_id": app_id, "app_secret": app_secret}
)
async def initialize_workflow(self, workflow_name: str):
"""初始化工作流实例"""
workflow_spec = {
"name": workflow_name,
"version": "1.0",
"description": f"{workflow_name} 自动化工作流",
"nodes": [],
"edges": []
}
return await self.workflow_engine.create_workflow(workflow_spec)
基础节点定义
python
# 工作流节点类型定义
class BozaiNodeTemplates:
"""扣子工作流节点模板库"""
@staticmethod
def create_ai_node(prompt_template: str, model_config: dict = None):
"""创建 AI 处理节点"""
default_config = {
"model": "bozai-4.0",
"temperature": 0.7,
"max_tokens": 2000
}
config = {**default_config, **(model_config or {})}
return AINode(
id=f"ai_node_{hash(prompt_template)}",
name="AI 处理节点",
config={
"prompt_template": prompt_template,
"model_config": config,
"output_schema": {
"type": "object",
"properties": {
"analysis_result": {"type": "string"},
"confidence": {"type": "number"},
"suggestions": {"type": "array"}
}
}
}
)
@staticmethod
def create_api_node(api_endpoint: str, method: str = "POST"):
"""创建 API 调用节点"""
return APINode(
id=f"api_node_{hash(api_endpoint)}",
name="外部 API 调用",
config={
"endpoint": api_endpoint,
"method": method,
"headers": {
"Content-Type": "application/json"
},
"timeout": 30000,
"retry_policy": {
"max_attempts": 3,
"backoff_factor": 1.5
}
}
)
@staticmethod
def create_condition_node(conditions: list):
"""创建条件分支节点"""
return ConditionNode(
id=f"condition_node_{hash(str(conditions))}",
name="条件判断节点",
config={
"conditions": conditions,
"default_branch": "default"
}
)
工作流配置实战
完整工作流构建示例
python
class CustomerServiceWorkflow:
"""智能客服工作流示例"""
def __init__(self, config: BozaiWorkflowConfig):
self.config = config
self.workflow = None
async def build_complaint_handling_flow(self):
"""构建客诉处理工作流"""
# 定义工作流节点
nodes = [
# 1. 触发节点 - 接收用户投诉
self._create_trigger_node(),
# 2. AI 情感分析节点
self._create_sentiment_analysis_node(),
# 3. 问题分类节点
self._create_issue_classification_node(),
# 4. 条件分支 - 根据紧急程度路由
self._create_priority_routing_node(),
# 5. 解决方案生成节点
self._create_solution_generation_node(),
# 6. API 调用 - 创建工单
self._create_ticket_creation_node(),
# 7. 回复生成节点
self._create_response_generation_node()
]
# 定义节点连接关系
edges = [
{"source": "trigger", "target": "sentiment_analysis", "condition": "default"},
{"source": "sentiment_analysis", "target": "issue_classification", "condition": "default"},
{"source": "issue_classification", "target": "priority_routing", "condition": "default"},
{"source": "priority_routing", "target": "urgent_solution", "condition": "urgent"},
{"source": "priority_routing", "target": "normal_solution", "condition": "normal"},
{"source": "urgent_solution", "target": "ticket_creation", "condition": "default"},
{"source": "normal_solution", "target": "response_generation", "condition": "default"},
{"source": "ticket_creation", "target": "response_generation", "condition": "default"}
]
workflow_spec = {
"name": "智能客诉处理工作流",
"description": "自动处理客户投诉,包含情感分析、问题分类和智能回复",
"nodes": nodes,
"edges": edges
}
self.workflow = await self.config.workflow_engine.create_workflow(workflow_spec)
return self.workflow
def _create_trigger_node(self):
"""创建 HTTP 触发节点"""
return {
"id": "trigger",
"type": "http_trigger",
"name": "投诉接收触发器",
"config": {
"path": "/complaint",
"method": "POST",
"payload_schema": {
"type": "object",
"properties": {
"user_id": {"type": "string"},
"complaint_text": {"type": "string"},
"order_id": {"type": "string"},
"contact_method": {"type": "string"}
},
"required": ["user_id", "complaint_text"]
}
}
}
def _create_sentiment_analysis_node(self):
"""创建情感分析节点"""
prompt = """
分析以下用户投诉的情感倾向和紧急程度:
用户投诉:{{complaint_text}}
请输出 JSON 格式:
{
"sentiment_score": -1 到 1 的数字,
"urgency_level": "low" | "medium" | "high" | "critical",
"key_emotions": ["情绪关键词列表"]
}
"""
return BozaiNodeTemplates.create_ai_node(prompt, {
"model": "bozai-sentiment",
"temperature": 0.1
}).to_dict()
触发器配置详解
多种触发方式实现
python
class BozaiTriggerManager:
"""扣子工作流触发器管理"""
@staticmethod
def create_http_trigger(workflow_id: str, endpoint_config: dict):
"""创建 HTTP 端点触发器"""
trigger_spec = {
"workflow_id": workflow_id,
"trigger_type": "http",
"config": {
"path": endpoint_config.get("path", "/webhook"),
"method": endpoint_config.get("method", "POST"),
"authentication": endpoint_config.get("auth", "bearer"),
"rate_limit": endpoint_config.get("rate_limit", 100),
"timeout": endpoint_config.get("timeout", 30000)
}
}
return trigger_spec
@staticmethod
def create_schedule_trigger(workflow_id: str, schedule_config: dict):
"""创建定时触发器"""
return {
"workflow_id": workflow_id,
"trigger_type": "schedule",
"config": {
"cron_expression": schedule_config["cron"],
"timezone": schedule_config.get("timezone", "Asia/Shanghai"),
"start_time": schedule_config.get("start_time"),
"end_time": schedule_config.get("end_time")
}
}
@staticmethod
def create_event_trigger(workflow_id: str, event_config: dict):
"""创建事件触发器"""
return {
"workflow_id": workflow_id,
"trigger_type": "event",
"config": {
"event_type": event_config["event_type"],
"source": event_config["source"],
"filters": event_config.get("filters", {}),
"debounce_ms": event_config.get("debounce_ms", 1000)
}
}
@staticmethod
def create_manual_trigger(workflow_id: str, ui_config: dict):
"""创建手动触发配置(用于管理后台)"""
return {
"workflow_id": workflow_id,
"trigger_type": "manual",
"config": {
"ui_form_schema": ui_config.get("form_schema", {}),
"required_permissions": ui_config.get("permissions", ["workflow.execute"]),
"confirmation_required": ui_config.get("confirmation", True)
}
}
触发器组合实战
python
class EcommerceWorkflowTriggers:
"""电商场景触发器配置"""
def __init__(self, workflow_manager):
self.workflow_manager = workflow_manager
async def setup_order_processing_triggers(self):
"""设置订单处理相关触发器"""
triggers = [
# 1. 新订单创建触发器
self._create_new_order_trigger(),
# 2. 订单状态更新触发器
self._create_order_update_trigger(),
# 3. 定时库存检查触发器
self._create_inventory_check_trigger(),
# 4. 支付超时监控触发器
self._create_payment_timeout_trigger()
]
for trigger in triggers:
await self.workflow_manager.create_trigger(trigger)
def _create_new_order_trigger(self):
"""新订单事件触发器"""
return BozaiTriggerManager.create_event_trigger(
workflow_id="order_processing_workflow",
event_config={
"event_type": "order.created",
"source": "ecommerce_system",
"filters": {
"order_amount": {">=": 1000} # 只处理金额大于1000的订单
}
}
)
def _create_inventory_check_trigger(self):
"""库存检查定时触发器"""
return BozaiTriggerManager.create_schedule_trigger(
workflow_id="inventory_management_workflow",
schedule_config={
"cron": "0 2 * * *", # 每天凌晨2点执行
"timezone": "Asia/Shanghai"
}
)
节点联动与数据流转
复杂工作流数据传递
python
class WorkflowDataOrchestrator:
"""工作流数据编排器"""
def __init__(self):
self.data_context = {}
self.node_outputs = {}
def process_node_output(self, node_id: str, output_data: dict):
"""处理节点输出数据"""
self.node_outputs[node_id] = output_data
self._update_data_context(node_id, output_data)
# 记录执行日志
self._log_node_execution(node_id, output_data)
return self._prepare_next_node_input(node_id)
def _update_data_context(self, node_id: str, output_data: dict):
"""更新全局数据上下文"""
# 合并输出数据到全局上下文
self.data_context.update(output_data)
# 添加元数据
self.data_context[f"_{node_id}_timestamp"] = datetime.now().isoformat()
self.data_context[f"_{node_id}_success"] = True
def _prepare_next_node_input(self, current_node_id: str):
"""准备下一个节点的输入数据"""
# 基于节点连接关系和数据依赖生成输入
next_nodes = self._get_next_nodes(current_node_id)
inputs = {}
for next_node in next_nodes:
inputs[next_node] = self._build_node_input(next_node)
return inputs
def _build_node_input(self, node_id: str) -> dict:
"""构建节点输入数据"""
node_config = self._get_node_config(node_id)
input_template = node_config.get("input_template", {})
# 使用数据上下文填充模板
return self._render_template(input_template, self.data_context)
@staticmethod
def _render_template(template: dict, context: dict) -> dict:
"""渲染数据模板"""
import json
template_str = json.dumps(template)
# 简单的模板变量替换
for key, value in context.items():
placeholder = f"{{{{{key}}}}}"
if placeholder in template_str:
template_str = template_str.replace(placeholder, json.dumps(value))
return json.loads(template_str)
条件分支与动态路由
python
class DynamicRoutingEngine:
"""动态路由引擎"""
@staticmethod
def evaluate_routing_conditions(context: dict, conditions: list) -> str:
"""评估路由条件"""
for condition in conditions:
if DynamicRoutingEngine._evaluate_single_condition(context, condition):
return condition["target_branch"]
return "default"
@staticmethod
def _evaluate_single_condition(context: dict, condition: dict) -> bool:
"""评估单个条件"""
condition_type = condition.get("type", "expression")
if condition_type == "expression":
return DynamicRoutingEngine._evaluate_expression(context, condition["expression"])
elif condition_type == "ai_judgment":
return DynamicRoutingEngine._evaluate_ai_judgment(context, condition["criteria"])
elif condition_type == "external_check":
return DynamicRoutingEngine._evaluate_external_check(context, condition["endpoint"])
return False
@staticmethod
def _evaluate_expression(context: dict, expression: str) -> bool:
"""评估表达式条件"""
try:
# 简单的表达式求值(生产环境应使用安全的求值方式)
compiled_expr = compile(expression, '<string>', 'eval')
return bool(eval(compiled_expr, {}, context))
except:
return False
@staticmethod
def _evaluate_ai_judgment(context: dict, criteria: dict) -> bool:
"""使用 AI 判断条件"""
# 调用扣子 AI 节点进行复杂条件判断
judgment_prompt = f"""
基于以下上下文和判断标准,输出 true 或 false:
上下文:{json.dumps(context, ensure_ascii=False)}
判断标准:{criteria['description']}
只输出 true 或 false,不要其他内容。
"""
# 这里调用 AI 服务进行判断
# 实际实现中会调用扣子的 AI 节点
return True # 简化实现
企业级集成实战
与现有系统集成
python
class EnterpriseIntegrationAdapter:
"""企业系统集成适配器"""
def __init__(self, base_url: str, auth_token: str):
self.base_url = base_url
self.auth_token = auth_token
self.session = self._create_session()
def _create_session(self):
"""创建 HTTP 会话"""
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {self.auth_token}",
"Content-Type": "application/json"
})
return session
async def sync_crm_data(self, workflow_context: dict):
"""同步 CRM 数据"""
crm_endpoint = f"{self.base_url}/crm/api/customers"
try:
response = await self.session.post(crm_endpoint, json={
"customer_data": workflow_context.get("customer_info"),
"interaction_history": workflow_context.get("interaction_log"),
"update_fields": workflow_context.get("update_fields", {})
})
if response.status_code == 200:
return {
"sync_success": True,
"crm_id": response.json().get("customer_id"),
"timestamp": datetime.now().isoformat()
}
else:
return {
"sync_success": False,
"error": response.text,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
return {
"sync_success": False,
"error": str(e),
"timestamp": datetime.now().isoformat()
}
async def create_erp_order(self, order_data: dict):
"""在 ERP 系统中创建订单"""
erp_endpoint = f"{self.base_url}/erp/api/orders"
# 转换数据格式以适应 ERP 系统
erp_payload = self._transform_to_erp_format(order_data)
response = await self.session.post(erp_endpoint, json=erp_payload)
return response.json()
错误处理与重试机制
python
class WorkflowErrorHandler:
"""工作流错误处理器"""
def __init__(self, max_retries: int = 3):
self.max_retries = max_retries
self.retry_delay = [1, 5, 15] # 重试延迟(秒)
async def execute_with_retry(self, node_func, *args, **kwargs):
"""带重试的执行包装器"""
last_exception = None
for attempt in range(self.max_retries):
try:
result = await node_func(*args, **kwargs)
return result
except TemporaryError as e:
last_exception = e
if attempt < self.max_retries - 1:
delay = self.retry_delay[attempt]
await asyncio.sleep(delay)
continue
else:
break
except PermanentError as e:
# 永久性错误不重试
await self._handle_permanent_error(e, node_func.__name__)
raise
# 重试次数用尽
await self._handle_retry_exhausted(last_exception, node_func.__name__)
raise last_exception
async def _handle_permanent_error(self, error: Exception, node_name: str):
"""处理永久性错误"""
error_context = {
"node_name": node_name,
"error_type": type(error).__name__,
"error_message": str(error),
"timestamp": datetime.now().isoformat(),
"handling_strategy": "circuit_breaker"
}
# 记录错误日志
await self._log_error("permanent_error", error_context)
# 触发告警
await self._trigger_alert(error_context)
async def _handle_retry_exhausted(self, error: Exception, node_name: str):
"""处理重试耗尽"""
error_context = {
"node_name": node_name,
"error_type": type(error).__name__,
"error_message": str(error),
"retry_attempts": self.max_retries,
"timestamp": datetime.now().isoformat(),
"handling_strategy": "fallback"
}
await self._log_error("retry_exhausted", error_context)
await self._trigger_fallback_workflow(error_context)
监控与运维
python
class WorkflowMonitor:
"""工作流监控器"""
def __init__(self, metrics_backend):
self.metrics_backend = metrics_backend
self.performance_metrics = {}
async def track_execution_metrics(self, workflow_id: str, execution_data: dict):
"""跟踪执行指标"""
metrics = {
"execution_time": execution_data.get("duration_ms", 0),
"success_rate": 1.0 if execution_data.get("success") else 0.0,
"node_count": len(execution_data.get("executed_nodes", [])),
"data_volume": self._calculate_data_volume(execution_data),
"timestamp": datetime.now().isoformat()
}
# 存储指标数据
await self.metrics_backend.store_metrics(workflow_id, metrics)
# 更新性能统计
self._update_performance_stats(workflow_id, metrics)
# 检查异常情况
await self._check_anomalies(workflow_id, metrics)
def _calculate_data_volume(self, execution_data: dict) -> int:
"""计算数据处理量"""
total_volume = 0
for node_output in execution_data.get("node_outputs", {}).values():
total_volume += len(str(node_output).encode('utf-8'))
return total_volume
async def _check_anomalies(self, workflow_id: str, metrics: dict):
"""检查异常指标"""
# 执行时间异常检测
avg_execution_time = self.performance_metrics.get(
workflow_id, {}).get("avg_execution_time", 0)
if avg_execution_time > 0 and metrics["execution_time"] > avg_execution_time * 2:
await self._alert_performance_degradation(workflow_id, metrics)
通过这套完整的扣子工作流教程,开发者可以快速掌握从基础配置到复杂企业级集成的全流程。扣子工作流的强大之处在于其灵活的可视化配置与强大的代码扩展能力相结合,让 AI Agent 的开发既简单又强大。