-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcentral_agent.py
More file actions
659 lines (593 loc) · 29.6 KB
/
Copy pathcentral_agent.py
File metadata and controls
659 lines (593 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
from __future__ import annotations
import datetime
import json
import logging
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from core.config import settings
from core.llm.factory import get_llm
from core.logging import log_event, log_llm_request_pretty, log_llm_response_pretty
from core.models.node_template import NodeTemplate
from core.models.task_intent import TaskIntent
from core.models.workflow import WorkflowDefinition, TriggerSpec, CoreGraph, NodeSpec, EdgeSpec, ReportSpec, SecuritySpec
from core.registry.node_template_registry import NodeTemplateRegistry
from core.utils.json_utils import extract_first_json_object
WORKFLOW_SCHEMA_HINT = """你是企业工作流平台的【中枢 Agent】。你的任务是把用户的一句话需求,转成可执行的 WorkflowDefinition JSON。
硬性规则:
- 只输出【严格 JSON】(不要 markdown/解释/多余文本)。
- JSON 必须能通过 WorkflowDefinition 校验(字段齐全、类型正确)。
- 工作流保持最小可运行(优先 1-3 个节点;如果识别为 onboarding 场景,可输出多节点工作流)。
- 优先使用离线、确定性的 demo 工具/agent(避免外部依赖)。
你可以使用的 demo 场景(意图很简单也要能命中):
0) 员工入职 Onboarding Digital Worker(关键词包含任意:入职/onboarding/账号/权限/设备/工单/实习/外包)
- 优先使用系统内置的 onboarding archetype(不要自己编造复杂 JSON 结构)。
1) 下午茶采购预算(中文关键词包含任意:下午茶/采购/预算/清单/办公室)
- 生成 2 个节点:
- n1: agent_specs/procurement_planner.json,tool_scopes: ["tool.catalog.pick_bundle"]
- n2: agent_specs/procurement_quoter.json,tool_scopes: ["tool.catalog.quote","tool.math.multiply"]
- trigger.input_mapping 至少包含:
- people (int)
- budget_per_person_cents (int, 单位: 分)
- must_include_skus (array of string, 例如 ["COFFEE","COOKIE"])
- max_distinct_items (int)
- 如果用户没给数字:默认 people=8, budget_per_person_cents=3500, must_include_skus=["COFFEE","COOKIE"], max_distinct_items=4
2) 天气查询(关键词包含:天气 或 weather)
- 生成 1 个节点:
- n1: agent_specs/weather_agent.json,tool_scopes: ["tool.weather.get"]
- trigger.input_mapping 至少包含 city (string),没给则默认 "Paris"
3) LLM 微调/finetune(关键词包含:微调/finetune/训练模型/小模型)
- 使用系统内置 finetune archetype(不要自己编造复杂 JSON 结构)
"""
TASK_INTENT_SCHEMA_HINT = """你是企业工作流平台的【Workflow Compiler - Understand 阶段】。
你的任务:把用户的自然语言需求抽象为 TaskIntent(严格 JSON)。
硬性规则:
- 只输出【严格 JSON】(不要 markdown/解释/多余文本)。
- JSON 必须能通过 TaskIntent 校验(字段齐全、类型正确)。
- LLM 输出不可信:不要执行任何动作,只做语义理解与缺失字段标注。
TaskIntent JSON 结构:
{
"intent_type": "access_request|unknown",
"entities": {
"person": "Alice",
"manager": "Bob",
"role": "Security Engineer",
"system": "Jira",
"systems": ["Jira"],
"access_level": "readonly|write|admin",
"start_date": "YYYY-MM-DD",
"constraints": [],
"extra": {}
},
"risk_sensitivity": false,
"missing_fields": [],
"request_text": "原始用户输入"
}
说明:
- access_level 规范化:只读/Read-only -> readonly;写入/Write -> write;管理员/admin/高危/特权 -> admin。
- start_date:尽量转成 YYYY-MM-DD;无法确定则留空并在 missing_fields 中标注。
"""
class CentralAgent:
"""Draft workflow JSON from natural language intent.
MVA: uses a robust fallback template even if the model fails.
"""
def __init__(self):
self.llm = get_llm()
self.logger = logging.getLogger("mva.central_agent")
def _archetypes_dir(self) -> Path:
return Path(settings.data_dir) / "workflow_archetypes"
def _node_templates_dir(self) -> Path:
return Path(settings.data_dir) / "node_templates"
def _load_archetype_json(self, archetype_filename: str) -> Dict[str, Any]:
p = self._archetypes_dir() / archetype_filename
data = json.loads(p.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("archetype JSON must be an object")
return data
@staticmethod
def _looks_like_onboarding_intent(text: str) -> bool:
t = (text or "").lower()
keywords = (
# Keep onboarding detection specific; avoid matching generic access requests.
"入职", "onboarding", "办入职", "入职流程", "入职申请", "入职办理",
)
return any(k.lower() in t for k in keywords)
@staticmethod
def _looks_like_access_request_intent(text: str) -> bool:
t = (text or "").lower()
keywords = (
"权限申请", "开通权限", "访问申请", "access request", "grant access", "申请访问",
"开通", "权限", "只读", "read-only", "readonly", "管理员", "admin", "高危", "特权",
)
return any(k.lower() in t for k in keywords)
@staticmethod
def _looks_like_incident_intent(text: str) -> bool:
t = (text or "").lower()
keywords = ("incident", "告警", "故障", "宕机", "异常", "安全事件", "报警", "triage")
return any(k.lower() in t for k in keywords)
@staticmethod
def _looks_like_finetune_intent(text: str) -> bool:
t = (text or "").lower()
keywords = ("finetune", "微调", "训练模型", "小模型", "模型训练")
return any(k.lower() in t for k in keywords)
def _draft_from_archetype(self, *, archetype_filename: str, user_intent: str) -> WorkflowDefinition:
version = datetime.datetime.utcnow().strftime("%Y.%m.%d+1")
tmpl = self._load_archetype_json(archetype_filename)
# Fill safe runtime fields
tmpl["version"] = version
tmpl.setdefault("status", "draft")
if isinstance(tmpl.get("trigger"), dict):
im = tmpl["trigger"].get("input_mapping")
if not isinstance(im, dict):
im = {}
tmpl["trigger"]["input_mapping"] = im
# Always carry original user intent.
im["request_text"] = user_intent.strip()
# Back-compat / other archetypes may expect "question".
im.setdefault("question", user_intent.strip())
return WorkflowDefinition.model_validate(tmpl)
@staticmethod
def _utc_version() -> str:
return datetime.datetime.utcnow().strftime("%Y.%m.%d+1")
@staticmethod
def _next_monday_iso() -> str:
today = datetime.date.today()
# weekday: Mon=0..Sun=6
delta = (7 - today.weekday()) % 7
delta = 7 if delta == 0 else delta
return (today + datetime.timedelta(days=delta)).isoformat()
@staticmethod
def _parse_date_best_effort(text: str) -> Optional[str]:
t = (text or "").strip()
if not t:
return None
# ISO YYYY-MM-DD
m = re.search(r"\b(20\d{2})-(\d{1,2})-(\d{1,2})\b", t)
if m:
try:
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
return datetime.date(y, mo, d).isoformat()
except Exception:
return None
# Chinese "1月6号"
m = re.search(r"(\d{1,2})\s*月\s*(\d{1,2})\s*(?:日|号)", t)
if m:
today = datetime.date.today()
mo, d = int(m.group(1)), int(m.group(2))
y = today.year
try:
dt = datetime.date(y, mo, d)
if dt < today:
dt = datetime.date(y + 1, mo, d)
return dt.isoformat()
except Exception:
return None
if "下周一" in t or "下週一" in t:
return CentralAgent._next_monday_iso()
if "明天" in t:
return (datetime.date.today() + datetime.timedelta(days=1)).isoformat()
return None
def _understand_task_intent(self, user_text: str) -> Tuple[TaskIntent, Dict[str, Any]]:
"""Phase 1: Understand. Returns (TaskIntent, audit_dict)."""
audit: Dict[str, Any] = {"phase": "understand", "llm_used": False, "errors": []}
raw = (user_text or "").strip()
if not raw:
ti = TaskIntent(intent_type="unknown", request_text="")
ti.missing_fields = ["request_text"]
return ti, audit
# LLM-first (untrusted -> validated). If anything fails, fall back to deterministic parsing.
try:
messages = [
{"role": "system", "content": TASK_INTENT_SCHEMA_HINT},
{"role": "user", "content": raw},
]
result = self.llm.chat(model=settings.ollama_model, messages=messages, tools=None, think=False)
audit["llm_used"] = True
audit["llm_raw_preview"] = (result.content or "")[:1200]
obj = extract_first_json_object(result.content)
if isinstance(obj, dict):
ti = TaskIntent.model_validate(obj)
ti.request_text = ti.request_text or raw
return ti, audit
except Exception as e:
audit["errors"].append(f"llm_understand_failed: {e}")
# Deterministic fallback: robust enough for demo prompts & CI.
t = raw
tl = t.lower()
intent_type = "access_request" if self._looks_like_access_request_intent(t) else "unknown"
person = None
m = re.search(r"(?:帮我)?给\s*([A-Za-z][A-Za-z0-9_\-]*|[\u4e00-\u9fff]{1,6})", t)
if m:
person = m.group(1).strip()
if not person:
m = re.search(r"为\s*([A-Za-z][A-Za-z0-9_\-]*|[\u4e00-\u9fff]{1,6})\s*(?:开通|申请)", t)
if m:
person = m.group(1).strip()
manager = None
m = re.search(r"经理\s*(?:是|为|:|:)?\s*([A-Za-z][A-Za-z0-9_\-]*|[\u4e00-\u9fff]{1,6})", t)
if m:
manager = m.group(1).strip()
if not manager:
m = re.search(r"\bmanager\s+is\s+([A-Za-z][A-Za-z0-9_\-]*)\b", tl)
if m:
manager = m.group(1).strip()
systems: List[str] = []
if "jira" in tl:
systems.append("Jira")
if "github" in tl:
systems.append("GitHub")
if "db" in tl or "database" in tl or "数据库" in t:
systems.append("DB")
if "analytics" in tl or "数仓" in t or "分析" in t:
systems.append("Analytics")
system = systems[0] if systems else None
access_level = None
if any(k in tl for k in ["readonly", "read-only"]) or "只读" in t or "读权限" in t:
access_level = "readonly"
if any(k in tl for k in ["write", "edit"]) or "写入" in t or "写权限" in t or "编辑" in t:
access_level = "write"
if "管理员" in t or "admin" in tl or "高危" in t or "特权" in t:
access_level = "admin"
start_date = self._parse_date_best_effort(t)
constraints: List[str] = []
if "最小权限" in t:
constraints.append("least_privilege")
if "合规" in t:
constraints.append("compliance_required")
if "不要管理员" in t or "别给管理员" in t:
constraints.append("no_admin")
if "必须审批" in t or "需要审批" in t:
constraints.append("approval_required")
risk_sensitivity = bool(access_level == "admin" or "高危" in t or "特权" in t)
missing: List[str] = []
if intent_type == "access_request":
if not person:
missing.append("person")
if not system:
missing.append("system")
if not access_level:
missing.append("access_level")
if not manager:
missing.append("manager")
if ("生效" in t or "起" in t) and not start_date:
missing.append("start_date")
if intent_type == "access_request":
if not access_level:
access_level = "readonly"
if not start_date and ("下周" in t or "下週" in t):
start_date = self._next_monday_iso()
ti = TaskIntent(
intent_type=intent_type, # type: ignore[arg-type]
risk_sensitivity=risk_sensitivity,
missing_fields=missing,
request_text=raw,
)
ti.entities.person = person
ti.entities.manager = manager
ti.entities.system = system
ti.entities.systems = systems
ti.entities.access_level = access_level
ti.entities.start_date = start_date
ti.entities.constraints = constraints
return ti, audit
@staticmethod
def _score_template_for_role(
tmpl: NodeTemplate,
*,
required_caps: List[str],
tool_snapshot: Optional[List[str]],
prefer_terms: Optional[List[str]] = None,
) -> Tuple[int, Dict[str, Any]]:
caps = set([c.strip() for c in (tmpl.capabilities or []) if str(c).strip()])
req = set([c.strip() for c in (required_caps or []) if str(c).strip()])
score = 0
score += 10 * len(caps & req)
missing_tools: List[str] = []
if tool_snapshot:
snap = set(tool_snapshot)
for tid in (tmpl.tool_scopes_default or []):
if tid not in snap:
missing_tools.append(tid)
score -= 3 * len(missing_tools)
if prefer_terms:
text = f"{tmpl.title}\n{tmpl.description}".lower()
for term in prefer_terms:
if term.lower() in text:
score += 2
return score, {"template_id": tmpl.template_id, "missing_tools": missing_tools}
@staticmethod
def _check_sequential_io_contract(*, trigger_keys: List[str], templates_in_order: List[NodeTemplate]) -> List[str]:
errors: List[str] = []
available = set([k for k in (trigger_keys or []) if isinstance(k, str) and k.strip()])
for idx, tmpl in enumerate(templates_in_order, start=1):
need = set([k for k in (tmpl.expected_input_keys or []) if isinstance(k, str) and k.strip()])
missing = sorted(list(need - available))
if missing:
errors.append(f"node#{idx}({tmpl.template_id}) missing input keys: {missing}")
produced = set([k for k in (tmpl.produced_output_keys or []) if isinstance(k, str) and k.strip()])
if tmpl.preserve_input_keys:
available |= produced
else:
available = produced
return errors
@staticmethod
def _check_tools_available(*, tool_snapshot: Optional[List[str]], tool_scopes: List[str], node_id: str) -> List[str]:
if not tool_snapshot:
return []
snap = set(tool_snapshot)
missing = [t for t in (tool_scopes or []) if t not in snap]
if not missing:
return []
return [f"{node_id} missing tools: {missing}"]
def _fallback_workflow(self, *, intent: str, reason: str) -> WorkflowDefinition:
version = self._utc_version()
wf = WorkflowDefinition(
id="wf_compiler_fallback_minimal",
name="Compiler Fallback (Minimal Runnable)",
version=version,
status="draft",
trigger=TriggerSpec(
type="manual",
spec=None,
input_mapping={"request_text": (intent or "").strip(), "compiler_fallback_reason": str(reason or "")[:500]},
approval={"mode": "manual"},
),
core_graph=CoreGraph(
entry="n1",
nodes=[
NodeSpec(
id="n1",
type="agent_node",
agent_spec_ref="agent_specs/formatter_agent.json",
input_schema_ref="schemas/formatter_input.json",
tool_scopes=[],
)
],
edges=[],
),
report=ReportSpec(templates=[], destinations=["stdout"], writeback=[]),
security=SecuritySpec(data_classification="internal", audit_level="full", network_zone="dev"),
)
log_event(self.logger, "compiler.compile.fallback", reason=reason, workflow_id=wf.id, version=wf.version)
return wf
def compile_workflow(
self,
intent: str,
*,
tool_snapshot: Optional[List[str]] = None,
max_repairs: int = 2,
) -> Tuple[WorkflowDefinition, Dict[str, Any]]:
"""Two-phase workflow compiler: Understand -> Compose -> Validate/Repair -> Fallback."""
compile_audit: Dict[str, Any] = {"compiler": "central_agent", "user_intent": intent, "repairs": []}
ti, understand_audit = self._understand_task_intent(intent)
compile_audit["task_intent"] = ti.model_dump()
compile_audit["understand_audit"] = understand_audit
log_event(self.logger, "compiler.understand", task_intent=compile_audit["task_intent"], audit=understand_audit)
reg = NodeTemplateRegistry(self._node_templates_dir())
templates = reg.load_all()
compile_audit["templates_loaded"] = len(templates)
if not templates:
compile_audit["errors"] = ["no_node_templates_found"]
return self._fallback_workflow(intent=intent, reason="no_node_templates_found"), compile_audit
prefer_terms = ["access", "权限", "policy", "rag", "provision", "execute"]
role_specs = [
("intake", ["intent_extract"]),
("policy", ["policy_check", "rag"]),
("executor", ["execute", "provision", "report"]),
]
selected: List[Dict[str, Any]] = []
selected_templates: List[NodeTemplate] = []
used_ids: set[str] = set()
for role, req_caps in role_specs:
best: Optional[Tuple[int, Dict[str, Any], NodeTemplate]] = None
for tmpl in templates:
if tmpl.template_id in used_ids:
continue
score, details = self._score_template_for_role(
tmpl,
required_caps=req_caps,
tool_snapshot=tool_snapshot,
prefer_terms=prefer_terms if ti.intent_type == "access_request" else None,
)
details["role"] = role
details["score"] = score
if best is None or score > best[0]:
best = (score, details, tmpl)
if best is None:
continue
_, details, tmpl = best
used_ids.add(tmpl.template_id)
selected.append(details)
selected_templates.append(tmpl)
compile_audit["selected_templates"] = selected
log_event(self.logger, "compiler.compose.select", selected=selected, tool_snapshot_count=len(tool_snapshot or []))
version = self._utc_version()
wf_id = "wf_access_request_compiler_demo" if ti.intent_type == "access_request" else "wf_compiled_demo"
wf_name = "Policy-aware Access Request (Compiled)" if ti.intent_type == "access_request" else "Compiled Workflow (Demo)"
trigger_im: Dict[str, Any] = {"request_text": (intent or "").strip(), "question": (intent or "").strip()}
nodes: List[NodeSpec] = []
for i, tmpl in enumerate(selected_templates[:3], start=1):
tool_scopes = list(tmpl.tool_scopes_default or [])
dropped: List[str] = []
if tool_snapshot:
snap = set(tool_snapshot)
for tid in list(tool_scopes):
if tid not in snap:
tool_scopes.remove(tid)
dropped.append(tid)
if dropped:
compile_audit.setdefault("tool_degraded", []).append({"node": f"n{i}", "template_id": tmpl.template_id, "dropped": dropped})
nodes.append(
NodeSpec(
id=f"n{i}",
type="agent_node",
agent_spec_ref=tmpl.agent_spec_ref(),
input_schema_ref=str(tmpl.input_schema_ref or "schemas/unknown.json"),
tool_scopes=tool_scopes,
principal_scopes=list(tmpl.principal_scopes_default or []),
)
)
candidate = WorkflowDefinition(
id=wf_id,
name=wf_name,
version=version,
status="draft",
trigger=TriggerSpec(type="manual", spec=None, input_mapping=trigger_im, approval={"mode": "manual"}),
core_graph=CoreGraph(entry="n1", nodes=nodes, edges=[]),
report=ReportSpec(templates=[], destinations=["stdout"], writeback=[]),
security=SecuritySpec(data_classification="internal", audit_level="full", network_zone="dev"),
)
def _validate_candidate(wf: WorkflowDefinition) -> List[str]:
errs: List[str] = []
errs.extend(self._check_sequential_io_contract(trigger_keys=list(trigger_im.keys()), templates_in_order=selected_templates[: len(wf.core_graph.nodes)]))
for n in wf.core_graph.nodes:
errs.extend(self._check_tools_available(tool_snapshot=tool_snapshot, tool_scopes=n.tool_scopes, node_id=n.id))
return errs
validation_errors = _validate_candidate(candidate)
compile_audit["validation_errors"] = list(validation_errors)
if not validation_errors:
log_event(self.logger, "compiler.compile.ok", workflow_id=candidate.id, version=candidate.version, nodes=[n.model_dump() for n in candidate.core_graph.nodes])
return candidate, compile_audit
log_event(self.logger, "compiler.compile.validation_failed", errors=validation_errors)
repaired: Optional[WorkflowDefinition] = None
if max_repairs > 0:
for attempt in range(1, int(max_repairs) + 1):
try:
prompt = (
"你生成的 workflow 校验失败。请只输出修复后的 WorkflowDefinition 严格 JSON。\n"
f"错误列表: {json.dumps(validation_errors, ensure_ascii=False)}\n"
"约束:只用 3 个节点(尽量),串行执行,必须满足 I/O keys 覆盖与工具可用性。\n"
f"用户原始 intent: {intent}\n"
f"可用模板(JSON 列表): {json.dumps([t.model_dump() for t in templates], ensure_ascii=False)}\n"
f"MCP 工具快照(tool_id 列表): {json.dumps(tool_snapshot or [], ensure_ascii=False)}\n"
)
messages = [{"role": "system", "content": WORKFLOW_SCHEMA_HINT}, {"role": "user", "content": prompt}]
result = self.llm.chat(model=settings.ollama_model, messages=messages, tools=None, think=False)
obj = extract_first_json_object(result.content)
if not isinstance(obj, dict):
raise ValueError("repair: no json object")
obj.setdefault("version", version)
obj.setdefault("status", "draft")
obj.setdefault("report", candidate.report.model_dump())
obj.setdefault("security", candidate.security.model_dump())
wf = WorkflowDefinition.model_validate(obj)
validation_errors = _validate_candidate(wf)
compile_audit["repairs"].append({"attempt": attempt, "llm_preview": (result.content or "")[:800], "errors": list(validation_errors)})
if not validation_errors:
repaired = wf
break
except Exception as e:
compile_audit["repairs"].append({"attempt": attempt, "error": str(e), "errors": list(validation_errors)})
if repaired is not None:
log_event(self.logger, "compiler.compile.repaired_ok", workflow_id=repaired.id, version=repaired.version, repairs=compile_audit["repairs"])
return repaired, compile_audit
fb = self._fallback_workflow(intent=intent, reason="; ".join(validation_errors[:5]))
compile_audit["fallback_reason"] = "validation_failed"
return fb, compile_audit
def draft_workflow(self, intent: str) -> WorkflowDefinition:
# Always produce a valid baseline skeleton (so the MVA runs).
version = self._utc_version()
baseline = WorkflowDefinition(
id="wf_weather_demo",
name="Weather Demo Digital Worker",
version=version,
status="draft",
trigger=TriggerSpec(type="manual", spec=None, input_mapping={"city": "Paris"}, approval={"mode": "manual"}),
core_graph=CoreGraph(
entry="n1",
nodes=[
NodeSpec(
id="n1",
type="agent_node",
agent_spec_ref="agent_specs/weather_agent.json",
input_schema_ref="schemas/weather_input.json",
tool_scopes=["tool.weather.get"],
)
],
edges=[],
),
report=ReportSpec(templates=["tpls/demo_report.md"], destinations=["stdout"], writeback=[]),
security=SecuritySpec(data_classification="internal", audit_level="full", network_zone="dev"),
)
# Archetype-first for complex enterprise demos (deterministic + JSON-first).
try:
if self._looks_like_onboarding_intent(intent):
return self._draft_from_archetype(archetype_filename="onboarding_digital_worker_v1.json", user_intent=intent)
if self._looks_like_incident_intent(intent):
return self._draft_from_archetype(archetype_filename="incident_triage_v1.json", user_intent=intent)
if self._looks_like_finetune_intent(intent):
return self._draft_from_archetype(archetype_filename="finetune_llm_auto_v1.json", user_intent=intent)
except Exception:
# Fall back to the baseline/LLM path below
pass
# Access request: compile from NodeTemplate catalog (do NOT rely on pre-baked workflow assets).
if self._looks_like_access_request_intent(intent):
wf, audit = self.compile_workflow(intent, tool_snapshot=None, max_repairs=2)
log_event(self.logger, "compiler.draft_workflow.access_request", workflow_id=wf.id, version=wf.version, audit=audit)
return wf
# Try to let the model refine fields (id/name/city/trigger). If parse fails, return baseline.
try:
messages = [
{"role": "system", "content": WORKFLOW_SCHEMA_HINT},
{"role": "user", "content": intent.strip()},
]
if settings.trace_llm:
if settings.trace_format.lower() == "json":
log_event(
self.logger,
"llm.chat.request",
agent_id="central_agent",
model=settings.ollama_model,
tools=[],
messages=messages,
)
else:
log_llm_request_pretty(
self.logger,
agent_id="central_agent",
model=settings.ollama_model,
tools=[],
messages=messages,
)
result = self.llm.chat(model=settings.ollama_model, messages=messages, tools=None, think=False)
if settings.trace_llm:
if settings.trace_format.lower() == "json":
log_event(
self.logger,
"llm.chat.response",
agent_id="central_agent",
model=settings.ollama_model,
content=result.content,
tool_calls=result.tool_calls,
)
else:
log_llm_response_pretty(
self.logger,
agent_id="central_agent",
model=settings.ollama_model,
content=result.content,
tool_calls=result.tool_calls,
)
obj = extract_first_json_object(result.content)
if not obj:
return baseline
# If the model produced a full WorkflowDefinition, accept it (with safe defaults).
if isinstance(obj.get("core_graph"), dict) and isinstance(obj.get("trigger"), dict):
candidate = dict(obj)
candidate.setdefault("version", baseline.version)
candidate.setdefault("status", baseline.status)
candidate.setdefault("report", baseline.report.model_dump())
candidate.setdefault("security", baseline.security.model_dump())
return WorkflowDefinition.model_validate(candidate)
# Otherwise: merge a few safe fields into the baseline.
for k in ["id", "name"]:
if isinstance(obj.get(k), str) and obj.get(k).strip():
setattr(baseline, k, obj[k].strip())
trig = obj.get("trigger", {})
if isinstance(trig, dict):
im = trig.get("input_mapping", {})
if isinstance(im, dict) and im:
baseline.trigger.input_mapping.update(im)
return WorkflowDefinition.model_validate(baseline.model_dump())
except Exception:
return baseline