File size: 13,478 Bytes
93117c2 | 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 | """
Workflow CRUD router β POST/GET/PUT/DELETE /api/workflows
On POST and PUT: if intent_definition or few_shot_examples changed,
embed (intent_definition + few_shot_examples) and store the averaged vector
as intent_embedding. The in-memory workflow cache is reloaded after every
mutating operation.
"""
from __future__ import annotations
import logging
import uuid
from datetime import datetime, timezone
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import select, text as sa_text
from sqlalchemy.ext.asyncio import AsyncSession
from database import get_db
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/workflows", tags=["workflows"])
# ββ Request / response models βββββββββββββββββββββββββββββββββββββββββββββββββ
class WorkflowCreate(BaseModel):
name: str
description: Optional[str] = ""
intent_definition: Optional[str] = ""
few_shot_examples: list[str] = []
intent_threshold: float = 0.72
definition: dict # serialized WorkflowDefinition node graph
is_active: bool = True
class WorkflowUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
intent_definition: Optional[str] = None
few_shot_examples: Optional[list[str]] = None
intent_threshold: Optional[float] = None
definition: Optional[dict] = None
is_active: Optional[bool] = None
class WorkflowSummary(BaseModel):
id: str
name: str
description: Optional[str]
intent_definition: Optional[str]
intent_threshold: float
is_active: bool
version: int
node_count: int
updated_at: str
class WorkflowDetail(WorkflowSummary):
few_shot_examples: list[str]
definition: dict
has_embedding: bool
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _tenant_id() -> str:
try:
from config_loader import get_config
return get_config().tenant_id
except Exception:
return "default"
async def _compute_embedding(intent_definition: str, few_shot_examples: list[str]) -> Optional[list[float]]:
"""Embed intent_definition + few_shot_examples; return averaged vector."""
texts = [t for t in ([intent_definition] + few_shot_examples) if t.strip()]
if not texts:
return None
try:
from knowledge.embeddings import embed_texts
vectors = await embed_texts(texts)
if not vectors:
return None
n = len(vectors)
dim = len(vectors[0])
averaged = [sum(v[i] for v in vectors) / n for i in range(dim)]
return averaged
except Exception:
logger.exception("workflows_router: embedding failed")
return None
async def _reload_cache() -> None:
try:
from config_loader import reload_workflows
await reload_workflows()
except Exception:
logger.exception("workflows_router: cache reload failed (non-fatal)")
def _row_to_summary(row) -> WorkflowSummary:
defn = row["definition"] or {}
nodes = defn.get("nodes", {})
return WorkflowSummary(
id=str(row["id"]),
name=row["name"],
description=row["description"],
intent_definition=row["intent_definition"],
intent_threshold=float(row["intent_threshold"] or 0.72),
is_active=bool(row["is_active"]),
version=int(row["version"] or 1),
node_count=len(nodes),
updated_at=row["updated_at"].isoformat() if row["updated_at"] else "",
)
def _row_to_detail(row) -> WorkflowDetail:
summary = _row_to_summary(row)
return WorkflowDetail(
**summary.model_dump(),
few_shot_examples=list(row["few_shot_examples"] or []),
definition=dict(row["definition"] or {}),
has_embedding=bool(row["intent_embedding"]),
)
# ββ Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@router.get("", response_model=list[WorkflowSummary])
async def list_workflows(db: AsyncSession = Depends(get_db)):
rows = await db.execute(
sa_text(
"SELECT id, name, description, intent_definition, intent_threshold, "
"is_active, version, definition, intent_embedding, few_shot_examples, updated_at "
"FROM workflow_definitions WHERE tenant_id = :tid ORDER BY created_at"
),
{"tid": _tenant_id()},
)
return [_row_to_summary(r) for r in rows.mappings()]
@router.post("", response_model=WorkflowDetail, status_code=201)
async def create_workflow(body: WorkflowCreate, db: AsyncSession = Depends(get_db)):
wf_id = str(uuid.uuid4())
embedding = await _compute_embedding(
body.intent_definition or "", body.few_shot_examples
)
# Ensure the definition carries the canonical id
defn = dict(body.definition)
defn["id"] = wf_id
defn["name"] = body.name
await db.execute(
sa_text(
"INSERT INTO workflow_definitions "
"(id, tenant_id, name, description, intent_definition, few_shot_examples, "
" intent_embedding, intent_threshold, definition, is_active) "
"VALUES (:id, :tid, :name, :desc, :idef, :fse, :emb, :thr, :defn, :active)"
),
{
"id": wf_id,
"tid": _tenant_id(),
"name": body.name,
"desc": body.description or "",
"idef": body.intent_definition or "",
"fse": body.few_shot_examples,
"emb": embedding,
"thr": body.intent_threshold,
"defn": defn,
"active": body.is_active,
},
)
await db.commit()
await _reload_cache()
row = (await db.execute(
sa_text("SELECT * FROM workflow_definitions WHERE id = :id"),
{"id": wf_id},
)).mappings().one()
return _row_to_detail(row)
@router.get("/{workflow_id}", response_model=WorkflowDetail)
async def get_workflow(workflow_id: str, db: AsyncSession = Depends(get_db)):
row = (await db.execute(
sa_text("SELECT * FROM workflow_definitions WHERE id = :id AND tenant_id = :tid"),
{"id": workflow_id, "tid": _tenant_id()},
)).mappings().one_or_none()
if row is None:
raise HTTPException(404, "Workflow not found")
return _row_to_detail(row)
@router.put("/{workflow_id}", response_model=WorkflowDetail)
async def update_workflow(
workflow_id: str,
body: WorkflowUpdate,
db: AsyncSession = Depends(get_db),
):
existing = (await db.execute(
sa_text("SELECT * FROM workflow_definitions WHERE id = :id AND tenant_id = :tid"),
{"id": workflow_id, "tid": _tenant_id()},
)).mappings().one_or_none()
if existing is None:
raise HTTPException(404, "Workflow not found")
# Determine if embedding needs recompute
new_idef = body.intent_definition if body.intent_definition is not None else existing["intent_definition"]
new_fse = body.few_shot_examples if body.few_shot_examples is not None else list(existing["few_shot_examples"] or [])
intent_changed = (
body.intent_definition is not None or body.few_shot_examples is not None
)
embedding = (
await _compute_embedding(new_idef or "", new_fse)
if intent_changed
else existing["intent_embedding"]
)
new_defn = dict(body.definition) if body.definition is not None else dict(existing["definition"] or {})
new_name = body.name or existing["name"]
new_defn.setdefault("id", workflow_id)
new_defn["name"] = new_name
await db.execute(
sa_text(
"UPDATE workflow_definitions SET "
"name = :name, description = :desc, intent_definition = :idef, "
"few_shot_examples = :fse, intent_embedding = :emb, "
"intent_threshold = :thr, definition = :defn, "
"is_active = :active, version = version + 1, updated_at = :now "
"WHERE id = :id"
),
{
"id": workflow_id,
"name": new_name,
"desc": body.description if body.description is not None else existing["description"],
"idef": new_idef,
"fse": new_fse,
"emb": embedding,
"thr": body.intent_threshold if body.intent_threshold is not None else existing["intent_threshold"],
"defn": new_defn,
"active": body.is_active if body.is_active is not None else existing["is_active"],
"now": datetime.now(timezone.utc),
},
)
await db.commit()
await _reload_cache()
row = (await db.execute(
sa_text("SELECT * FROM workflow_definitions WHERE id = :id"),
{"id": workflow_id},
)).mappings().one()
return _row_to_detail(row)
@router.delete("/{workflow_id}", status_code=204)
async def delete_workflow(workflow_id: str, db: AsyncSession = Depends(get_db)):
result = await db.execute(
sa_text(
"UPDATE workflow_definitions SET is_active = false "
"WHERE id = :id AND tenant_id = :tid"
),
{"id": workflow_id, "tid": _tenant_id()},
)
await db.commit()
await _reload_cache()
if result.rowcount == 0:
raise HTTPException(404, "Workflow not found")
@router.post("/{workflow_id}/activate", response_model=WorkflowDetail)
async def activate_workflow(workflow_id: str, db: AsyncSession = Depends(get_db)):
await db.execute(
sa_text(
"UPDATE workflow_definitions SET is_active = true, updated_at = :now "
"WHERE id = :id AND tenant_id = :tid"
),
{"id": workflow_id, "tid": _tenant_id(), "now": datetime.now(timezone.utc)},
)
await db.commit()
await _reload_cache()
row = (await db.execute(
sa_text("SELECT * FROM workflow_definitions WHERE id = :id"),
{"id": workflow_id},
)).mappings().one_or_none()
if row is None:
raise HTTPException(404, "Workflow not found")
return _row_to_detail(row)
@router.get("/{workflow_id}/versions")
async def list_versions(workflow_id: str):
"""Stub β version history is a future feature."""
return {"workflow_id": workflow_id, "versions": [], "note": "version history not yet implemented"}
# ββ Internal endpoint used by the LiveKit worker ββββββββββββββββββββββββββββββ
def _cosine_similarity(a: list[float], b: list[float]) -> float:
import math
dot = sum(ai * bi for ai, bi in zip(a, b))
mag_a = math.sqrt(sum(ai * ai for ai in a))
mag_b = math.sqrt(sum(bi * bi for bi in b))
if mag_a == 0.0 or mag_b == 0.0:
return 0.0
return dot / (mag_a * mag_b)
class _MatchRequest(BaseModel):
text: str
@router.post("/internal/match", include_in_schema=False) # mounts as /api/workflows/internal/match
async def match_workflow_intent(body: _MatchRequest):
"""Called by the LiveKit worker on every utterance (GENERAL mode only).
Embeds the utterance text and cosine-compares against all active workflow
intent embeddings cached in memory. Returns the best match or
{"matched": false} so the worker stays in GENERAL mode.
The worker must NOT load sentence-transformers β all embedding lives here.
"""
from config_loader import get_active_workflows
from knowledge.embeddings import embed_single
text = (body.text or "").strip()
if not text:
return {"matched": False}
workflows = get_active_workflows()
candidates = [wf for wf in workflows if wf.intent_embedding]
if not candidates:
return {"matched": False}
try:
utterance_vec = await embed_single(text)
except Exception:
logger.exception("workflow/internal/match: embed failed")
return {"matched": False}
best_wf = None
best_score = -1.0
all_scores: list[dict] = []
for wf in candidates:
score = _cosine_similarity(utterance_vec, wf.intent_embedding)
all_scores.append({"name": wf.name, "score": round(score, 4), "threshold": wf.intent_threshold, "matched": score >= wf.intent_threshold})
if score >= wf.intent_threshold and score > best_score:
best_score = score
best_wf = wf
logger.info(
"workflow/match utterance=%r scores=%s",
text[:80],
[{s["name"]: f"{s['score']:.3f}/{s['threshold']:.2f}{'β' if s['matched'] else 'β'}"} for s in all_scores],
)
if best_wf is None:
return {"matched": False}
return {
"matched": True,
"id": best_wf.id,
"name": best_wf.name,
"description": best_wf.description,
"intent_definition": best_wf.intent_definition,
"intent_threshold": best_wf.intent_threshold,
"entry_node_id": best_wf.entry_node_id,
}
|