Spaces:
Running
Running
Download core/workflows/compiler.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/workflows/compiler.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/workflows/compiler.py
-
curl -L -o compiler.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/workflows/compiler.py
14.6 kB
| """Natural language -> workflow DSL, plus the static checks every definition must pass. | |
| The planner model sees only the DSL rules and the tools that tool search offers for the | |
| request (never tenant data). Its output is schema-validated, then statically checked: | |
| * ``unknown_tool`` / ``tool_not_offered``: every tool must exist in the registry (and, for a | |
| compiled draft, be one of the tools offered to the model); | |
| * ``tier_escalation``: no step may use a tool above the workflow's ``max_tier``; | |
| * ``missing_approval``: T3 steps must say ``requires_approval: true``; | |
| * ``bad_ref`` / ``unknown_arg`` / ``missing_arg`` / ``invalid_args``: references point at | |
| earlier steps (or ``$.item`` inside ``for_each``, ``$.event`` for event/manual triggers) and | |
| arguments match the tool's input schema. | |
| Anything with errors is rejected; warnings are shown to the owner with the dry run. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import uuid | |
| from dataclasses import dataclass, field | |
| from typing import Any | |
| from pydantic import BaseModel, ValidationError | |
| from core.agent.models import LLM | |
| from core.db.session import Database | |
| from core.tools.registry import ToolRegistry | |
| from core.tools.search import ToolSearch | |
| from core.tools.spec import RiskTier, ToolSpec | |
| from core.workflows import refs | |
| from core.workflows.dsl import ( | |
| MAX_ITEMS, | |
| EventTrigger, | |
| ScheduleTrigger, | |
| Step, | |
| WorkflowDefinition, | |
| ) | |
| INTERNAL_PREFIX = "workflows." # engine tools (sign-off); never used directly in steps | |
| MAX_OFFERED = 15 | |
| class Issue: | |
| code: str | |
| message: str | |
| step: str | None = None | |
| def as_dict(self) -> dict[str, Any]: | |
| return {"code": self.code, "message": self.message, "step": self.step} | |
| class CheckReport: | |
| errors: list[Issue] = field(default_factory=list) | |
| warnings: list[Issue] = field(default_factory=list) | |
| def ok(self) -> bool: | |
| return not self.errors | |
| def as_dict(self) -> dict[str, Any]: | |
| return { | |
| "ok": self.ok, | |
| "errors": [e.as_dict() for e in self.errors], | |
| "warnings": [w.as_dict() for w in self.warnings], | |
| } | |
| def validation_issues(exc: ValidationError) -> list[Issue]: | |
| out = [] | |
| for e in exc.errors(include_url=False): | |
| loc = ".".join(str(x) for x in e.get("loc", ())) | |
| out.append(Issue("schema", f"{loc}: {e.get('msg')}" if loc else str(e.get("msg")))) | |
| return out | |
| def _has_ref(value: Any) -> bool: | |
| return next(refs.refs_in(value), None) is not None | |
| def _check_refs( | |
| report: CheckReport, | |
| step_id: str | None, | |
| values: list[Any], | |
| earlier: dict[str, Step], | |
| *, | |
| loop: bool, | |
| trigger: Any, | |
| ) -> list[str]: | |
| """Report bad references; return the roots used.""" | |
| roots: list[str] = [] | |
| for value in values: | |
| for ref in refs.refs_in(value): | |
| try: | |
| head = refs.root(ref) | |
| except refs.RefError as exc: | |
| report.errors.append(Issue("bad_ref", str(exc), step_id)) | |
| continue | |
| roots.append(head) | |
| if head in ("item", "index"): | |
| if not loop: | |
| report.errors.append( | |
| Issue( | |
| "bad_ref", f"{ref}: $.{head} is only valid in a for_each step", step_id | |
| ) | |
| ) | |
| elif head == "event": | |
| if isinstance(trigger, ScheduleTrigger): | |
| report.errors.append( | |
| Issue("bad_ref", f"{ref}: a scheduled workflow has no event", step_id) | |
| ) | |
| elif head == "trigger": | |
| if not isinstance(trigger, ScheduleTrigger): | |
| report.errors.append( | |
| Issue("bad_ref", f"{ref}: only scheduled runs have $.trigger", step_id) | |
| ) | |
| elif head == "workflow": | |
| pass | |
| elif head in ("run", "now"): | |
| report.errors.append(Issue("bad_ref", f"{ref}: $.{head} is not supported", step_id)) | |
| elif head not in earlier: | |
| report.errors.append( | |
| Issue( | |
| "bad_ref", | |
| f"{ref}: no earlier step {head!r} (steps can only use outputs of steps " | |
| "before them)", | |
| step_id, | |
| ) | |
| ) | |
| elif earlier[head].kind != "tool": | |
| report.warnings.append( | |
| Issue("bad_ref", f"{ref}: step {head!r} produces no data", step_id) | |
| ) | |
| return roots | |
| def static_check( | |
| defn: WorkflowDefinition, | |
| registry: ToolRegistry, | |
| *, | |
| offered: set[str] | None = None, | |
| ) -> CheckReport: | |
| report = CheckReport() | |
| trigger = defn.trigger | |
| po = defn.policy_overrides | |
| if isinstance(trigger, EventTrigger): | |
| for c in trigger.when: | |
| if refs.root(c.left) != "event": | |
| report.errors.append(Issue("bad_ref", f"trigger condition {c.left}: use $.event")) | |
| for name in po.require_approval_for: | |
| if not registry.has(name): | |
| report.warnings.append(Issue("unknown_tool", f"require_approval_for: {name} unknown")) | |
| earlier: dict[str, Step] = {} | |
| for step in defn.steps: | |
| sid = step.id | |
| _check_refs(report, sid, [step.for_each], earlier, loop=False, trigger=trigger) | |
| cond_values = [c.left for c in step.when] + [c.right for c in step.when] | |
| roots = _check_refs( | |
| report, | |
| sid, | |
| [step.args, *cond_values], | |
| earlier, | |
| loop=step.for_each is not None, | |
| trigger=trigger, | |
| ) | |
| if step.kind == "tool": | |
| _check_tool_step(report, step, registry, offered, po.max_tier, roots) | |
| earlier[sid] = step | |
| return report | |
| def _check_tool_step( | |
| report: CheckReport, | |
| step: Step, | |
| registry: ToolRegistry, | |
| offered: set[str] | None, | |
| max_tier: int, | |
| roots: list[str], | |
| ) -> None: | |
| sid, name = step.id, str(step.tool) | |
| if name.startswith(INTERNAL_PREFIX): | |
| report.errors.append(Issue("reserved_tool", f"{name} is an engine tool", sid)) | |
| return | |
| if not registry.has(name): | |
| report.errors.append(Issue("unknown_tool", f"unknown tool {name}", sid)) | |
| return | |
| if offered is not None and name not in offered: | |
| report.errors.append( | |
| Issue( | |
| "tool_not_offered", f"{name} was not among the tools offered for this request", sid | |
| ) | |
| ) | |
| spec = registry.get(name).spec | |
| tier = int(spec.risk_tier) | |
| if tier > max_tier: | |
| report.errors.append( | |
| Issue( | |
| "tier_escalation", | |
| f"{name} is tier T{tier}, above this workflow's max_tier T{max_tier}", | |
| sid, | |
| ) | |
| ) | |
| if tier >= RiskTier.T3_CRITICAL and not step.requires_approval: | |
| report.errors.append( | |
| Issue( | |
| "missing_approval", | |
| f"{name} is tier T3: the step must declare requires_approval: true", | |
| sid, | |
| ) | |
| ) | |
| _check_args(report, step, spec) | |
| if "event" in roots and spec.sensitive_args: | |
| used = [a for a in spec.sensitive_args if _uses_event(step.args.get(a))] | |
| if used: | |
| report.warnings.append( | |
| Issue( | |
| "untrusted_sink", | |
| f"untrusted event values reach sensitive args {used}: calls need approval " | |
| "unless a validator confirms them", | |
| sid, | |
| ) | |
| ) | |
| if step.for_each and tier >= RiskTier.T2_EXTERNAL and step.max_items is None: | |
| report.warnings.append( | |
| Issue("unbounded_loop", f"no max_items: up to {MAX_ITEMS} external calls", sid) | |
| ) | |
| def _uses_event(value: Any) -> bool: | |
| return any(refs.root(r) == "event" for r in refs.refs_in(value)) | |
| def _check_args(report: CheckReport, step: Step, spec: ToolSpec) -> None: | |
| model: type[BaseModel] = spec.input_model | |
| fields = model.model_fields | |
| unknown = sorted(set(step.args) - set(fields)) | |
| if unknown: | |
| report.errors.append( | |
| Issue("unknown_arg", f"{spec.name} has no argument(s) {unknown}", step.id) | |
| ) | |
| missing = sorted(n for n, f in fields.items() if f.is_required() and n not in step.args) | |
| if missing: | |
| report.errors.append( | |
| Issue("missing_arg", f"{spec.name} needs argument(s) {missing}", step.id) | |
| ) | |
| if not unknown and not missing and not _has_ref(step.args): | |
| try: | |
| model.model_validate(step.args) | |
| except ValidationError as exc: | |
| msgs = "; ".join(i.message for i in validation_issues(exc)) | |
| report.errors.append(Issue("invalid_args", f"{spec.name}: {msgs}", step.id)) | |
| def check( | |
| data: dict[str, Any] | WorkflowDefinition, | |
| registry: ToolRegistry, | |
| *, | |
| offered: set[str] | None = None, | |
| ) -> tuple[WorkflowDefinition | None, CheckReport]: | |
| """Schema validation + static checks.""" | |
| if isinstance(data, WorkflowDefinition): | |
| defn = data | |
| else: | |
| try: | |
| defn = WorkflowDefinition.model_validate(data) | |
| except ValidationError as exc: | |
| return None, CheckReport(errors=validation_issues(exc)) | |
| return defn, static_check(defn, registry, offered=offered) | |
| # ------------------------------------------------------------------- NL compiler | |
| DSL_RULES = """\ | |
| You turn a business owner's request into a workflow definition (JSON). Rules: | |
| - trigger: {"type": "schedule", "cron": "<5-field cron>", "tz": "Asia/Karachi"} for repeated | |
| times ("every morning at 9" -> "0 9 * * *"); {"type": "event", "event_type": "..."} for | |
| "when X happens"; {"type": "manual"} otherwise. | |
| - steps run in order. A tool step: {"id": "snake_case", "tool": "<one of the tools below>", | |
| "args": {...}}. Use only the tools listed below and only their argument names. | |
| - Reference earlier outputs with strings like "$.<step_id>.<field>" (e.g. "$.find.orders"). | |
| To repeat a step for every element of a list, set "for_each": "$.<step_id>.<list field>" | |
| and use "$.item.<field>" in args. A for_each step's output is | |
| {"results": [{"item": ..., "data": ...}]}: a later loop over it uses "$.item.item.<field>" | |
| for the original element and "$.item.data.<field>" for that step's result. | |
| - Use "{{ $.ref }}" inside longer text. | |
| - Filters: "when": [{"left": "$.item.total", "op": "gt", "right": 5000}]. | |
| - Tools marked T3 need "requires_approval": true. Never invent tools or recipients. | |
| - Put limits that the request implies into "policy_overrides" (max_messages, max_tier). | |
| """ | |
| def tool_card(spec: ToolSpec) -> str: | |
| schema = spec.input_model.model_json_schema() | |
| props = schema.get("properties", {}) | |
| required = set(schema.get("required", [])) | |
| args = [] | |
| for name, p in props.items(): | |
| kind = p.get("type") or "/".join( | |
| str(x.get("type")) for x in p.get("anyOf", []) if x.get("type") != "null" | |
| ) | |
| enum = p.get("enum") or next( | |
| (x.get("enum") for x in p.get("anyOf", []) if x.get("enum")), None | |
| ) | |
| desc = f"{name}{'' if name in required else '?'}: {kind}" | |
| if enum: | |
| desc += f" one of {enum}" | |
| args.append(desc) | |
| return ( | |
| f"- {spec.name} [T{int(spec.risk_tier)}]: {spec.description}\n" | |
| f" args: {', '.join(args) or '(none)'}" | |
| ) | |
| def compiler_prompt(specs: list[ToolSpec]) -> str: | |
| cards = "\n".join(tool_card(s) for s in specs) | |
| return f"{DSL_RULES}\nTools you may use:\n{cards}" | |
| class CompileResult: | |
| definition: WorkflowDefinition | None | |
| report: CheckReport | |
| offered: list[str] | |
| def as_dict(self) -> dict[str, Any]: | |
| return { | |
| "definition": self.definition.model_dump(mode="json") if self.definition else None, | |
| **self.report.as_dict(), | |
| "tools_offered": self.offered, | |
| } | |
| async def candidate_tools( | |
| db: Database, | |
| tenant_id: uuid.UUID, | |
| registry: ToolRegistry, | |
| text: str, | |
| *, | |
| search: ToolSearch | None = None, | |
| k: int = MAX_OFFERED, | |
| ) -> list[str]: | |
| """Tools offered to the compiler: hybrid tool search over the index, limited to tools | |
| this process can execute. Falls back to the registry when the index is empty.""" | |
| names: list[str] = [] | |
| if search is not None: | |
| try: | |
| async with db.session(tenant_id=tenant_id) as s: | |
| names = await search.search(s, text, k=k * 2) | |
| except Exception: # index missing (e.g. not synced yet): fall back below | |
| names = [] | |
| names = [n for n in dict.fromkeys(names) if registry.has(n)] | |
| # Fill up from the registry, ranked in process the same way (covers an empty or stale | |
| # index, e.g. tools registered after the last ``sync-tools``). | |
| names += [n for n in rank_locally(registry, text) if n not in names] | |
| return [n for n in names if not n.startswith(INTERNAL_PREFIX)][:k] | |
| def rank_locally(registry: ToolRegistry, text: str) -> list[str]: | |
| from core.tools.search import HashingEmbedder, _search_text | |
| emb = HashingEmbedder() | |
| q = emb.embed(text) | |
| words = set(re.findall(r"[a-z0-9]+", text.lower())) | |
| def score(spec: ToolSpec) -> float: | |
| doc = _search_text(spec) | |
| cosine = sum(a * b for a, b in zip(q, emb.embed(doc), strict=True)) | |
| overlap = len(words & set(re.findall(r"[a-z0-9]+", doc.lower()))) | |
| return cosine + 0.1 * overlap | |
| return [s.name for s in sorted(registry.specs(), key=score, reverse=True)] | |
| async def compile_nl( | |
| text: str, llm: LLM, registry: ToolRegistry, offered: list[str] | |
| ) -> CompileResult: | |
| specs = [registry.get(n).spec for n in offered if registry.has(n)] | |
| try: | |
| draft = await llm.structured(WorkflowDefinition, compiler_prompt(specs), text) | |
| except ValidationError as exc: | |
| return CompileResult(None, CheckReport(errors=validation_issues(exc)), offered) | |
| defn = draft.model_copy(update={"version": None}) | |
| return CompileResult(defn, static_check(defn, registry, offered=set(offered)), offered) | |