Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

947 Zeilen
40KB

  1. <%
  2. ' ApiLearningController: experiences, learning candidates and review, evidence, feedback (spec FR-012, FR-013,
  3. ' FR-014, FR-020, section 12, AC-08, AC-16, AC-18). Stateless JSON API, no layout.
  4. ' Helpers: core/lib.Api.asp (auth, errors), core/lib.Learning.asp (evidence, memory writes, telemetry).
  5. '
  6. ' POST /api/v1/sessions/:id/events RecordEvent {"task","outcome":"success|failure|partial|unknown","problem","action","result","environment":{}}
  7. ' GET /api/v1/sessions/:id/events Events experiences of the session, oldest first
  8. ' POST /api/v1/learn Learn {"namespace_id","type","title","content","summary","tags","confidence",
  9. ' "target_memory_id","base_revision","evidence":[{"kind","id","role","excerpt"}]}
  10. ' GET /api/v1/candidates Candidates ?namespace_id= &state=proposed|accepted|rejected &limit=
  11. ' GET /api/v1/candidates/:id Candidate with its evidence
  12. ' POST /api/v1/candidates/:id/review Review {"decision":"accept|reject","notes","verify":true|false}
  13. ' GET /api/v1/memories/:id/sources Sources evidence and verifications of a revision (?revision=, default current)
  14. ' POST /api/v1/feedback Feedback {"query_id","result_id","usefulness":"useful|not_useful|incorrect|harmful","comment"}
  15. '
  16. ' Permissions on the namespace: write (RecordEvent, Learn), read (Events, Candidates, Candidate, Sources, Feedback),
  17. ' verify (Review). Reviewing your own candidate needs admin: a proposer cannot approve itself. Accepting creates a
  18. ' memory (or a new revision of target_memory_id, if it is still at base_revision) with the candidate's evidence; it
  19. ' stays unverified unless "verify": true, which records a verification by the reviewer. Without permission: 404.
  20. Class ApiLearningController_Class
  21. Private m_errs
  22. Public Property Get useLayout()
  23. useLayout = False
  24. End Property
  25. Public Property Let useLayout(v)
  26. End Property
  27. Public Property Get Title()
  28. Title = "Learning API"
  29. End Property
  30. '---------------------------------------------------------------
  31. ' POST /api/v1/sessions/:id/events
  32. '---------------------------------------------------------------
  33. Public Sub RecordEvent(id)
  34. Dim body, input, idemKey, reqHash, rs, nsId, status, task, outcome, problem, action, result, envRaw, expId, ts, resp, k
  35. If Not Api_Authenticate() Then Exit Sub
  36. If Not Api_IsId(id) Then
  37. Api_NotFound
  38. Exit Sub
  39. End If
  40. body = Api_ReadBody()
  41. If IsEmpty(body) Then Exit Sub
  42. Set input = JsonLite_Parse(body)
  43. idemKey = Api_Header("Idempotency-Key")
  44. If Len(idemKey) > 200 Then
  45. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  46. Exit Sub
  47. End If
  48. reqHash = Api_Sha256("events|" & id & "|" & body)
  49. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  50. Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  51. If rs.EOF Then
  52. rs.Close
  53. Api_Error 404, "session_not_found", "Session not found."
  54. Exit Sub
  55. End If
  56. nsId = "" & rs(0)
  57. status = "" & rs(1)
  58. rs.Close
  59. If Not Api_CanAccessNamespace(nsId, "write") Then
  60. Api_Error 404, "session_not_found", "Session not found."
  61. Exit Sub
  62. End If
  63. m_errs = ""
  64. task = ReqString(input, "task", 2000)
  65. outcome = LCase("" & ReqString(input, "outcome", 20))
  66. problem = OptString(input, "problem", 4000)
  67. action = OptString(input, "action", 4000)
  68. result = OptString(input, "result", 4000)
  69. envRaw = ObjectJson(input, "environment")
  70. If Len(m_errs) = 0 Then
  71. If outcome <> "success" And outcome <> "failure" And outcome <> "partial" And outcome <> "unknown" Then
  72. AddErr "outcome must be success, failure, partial or unknown."
  73. End If
  74. End If
  75. If Len(m_errs) > 0 Then
  76. Api_Invalid Split(m_errs, Chr(30))
  77. Exit Sub
  78. End If
  79. If status <> "active" Then
  80. Api_Error 409, "session_not_active", "The session is " & status & "; experiences can only be recorded in an active session."
  81. Exit Sub
  82. End If
  83. expId = Api_NewId()
  84. ts = Api_Now()
  85. resp = "{""id"":" & JsonLite_Quote(expId) & ",""session_id"":" & JsonLite_Quote(id) & ",""outcome"":" & JsonLite_Quote(outcome) & ",""created_at"":" & JsonLite_Quote(ts) & "}"
  86. On Error Resume Next
  87. DAL().BeginTransaction
  88. DAL().Execute "INSERT INTO experiences (id, tenant_id, namespace_id, session_id, principal_id, task, outcome, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  89. Array(expId, Api_TenantId, nsId, id, Api_PrincipalId, task, outcome, ts)
  90. DAL().Execute "UPDATE experiences SET problem = ?, action = ?, result = ?, environment = ? WHERE id = ?", Array(problem, action, result, envRaw, expId)
  91. Api_IdempotencyStore idemKey, reqHash, 201, resp
  92. If Err.Number <> 0 Then
  93. k = Err.Number : Api_NoteDbError
  94. DAL().RollbackTransaction
  95. Api_DbFailed k, ""
  96. Exit Sub
  97. End If
  98. DAL().CommitTransaction
  99. On Error GoTo 0
  100. Api_Audit "session.event", "experience", expId, "ok"
  101. Api_Send 201, resp
  102. End Sub
  103. '---------------------------------------------------------------
  104. ' GET /api/v1/sessions/:id/events
  105. '---------------------------------------------------------------
  106. Public Sub Events(id)
  107. Dim rs, nsId, out, n
  108. If Not Api_Authenticate() Then Exit Sub
  109. If Not Api_IsId(id) Then
  110. Api_NotFound
  111. Exit Sub
  112. End If
  113. Set rs = DAL().Query("SELECT namespace_id FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  114. If rs.EOF Then
  115. rs.Close
  116. Api_Error 404, "session_not_found", "Session not found."
  117. Exit Sub
  118. End If
  119. nsId = "" & rs(0)
  120. rs.Close
  121. If Not Api_CanAccessNamespace(nsId, "read") Then
  122. Api_Error 404, "session_not_found", "Session not found."
  123. Exit Sub
  124. End If
  125. Set rs = DAL().Query("SELECT id, task, problem, action, result, outcome, environment, principal_id, created_at FROM experiences " & _
  126. "WHERE session_id = ? AND tenant_id = ? ORDER BY created_at, id LIMIT 200", Array(id, Api_TenantId))
  127. out = ""
  128. n = 0
  129. Do While Not rs.EOF
  130. If n > 0 Then
  131. out = out & ","
  132. End If
  133. out = out & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""task"":" & JsonLite_Quote("" & rs(1)) & ",""problem"":" & JStr(rs(2)) & _
  134. ",""action"":" & JStr(rs(3)) & ",""result"":" & JStr(rs(4)) & ",""outcome"":" & JsonLite_Quote("" & rs(5)) & _
  135. ",""environment"":" & JRaw(rs(6), "null") & ",""recorded_by"":" & JsonLite_Quote("" & rs(7)) & ",""created_at"":" & JsonLite_Quote("" & rs(8)) & "}"
  136. n = n + 1
  137. rs.MoveNext
  138. Loop
  139. rs.Close
  140. Api_Send 200, "{""session_id"":" & JsonLite_Quote(id) & ",""data"":[" & out & "]}"
  141. End Sub
  142. '---------------------------------------------------------------
  143. ' POST /api/v1/learn
  144. '---------------------------------------------------------------
  145. Public Sub Learn()
  146. Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, confidence, targetId, baseRev
  147. Dim ev, msg, rs, candId, ts, resp, k
  148. If Not Api_Authenticate() Then Exit Sub
  149. body = Api_ReadBody()
  150. If IsEmpty(body) Then Exit Sub
  151. Set input = JsonLite_Parse(body)
  152. idemKey = Api_Header("Idempotency-Key")
  153. If Len(idemKey) > 200 Then
  154. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  155. Exit Sub
  156. End If
  157. reqHash = Api_Sha256("learn|" & body)
  158. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  159. m_errs = ""
  160. nsId = ReqString(input, "namespace_id", 64)
  161. memType = LCase("" & ReqString(input, "type", 40))
  162. title = ReqString(input, "title", 200)
  163. content = ReqString(input, "content", 100000)
  164. summary = OptString(input, "summary", 2000)
  165. tagsRaw = TagsJson(input)
  166. confidence = OptUnit(input, "confidence")
  167. targetId = OptString(input, "target_memory_id", 64)
  168. baseRev = Null
  169. If Not IsNull(targetId) Then
  170. If Not Api_IsId(targetId) Then
  171. AddErr "target_memory_id must be a valid id."
  172. End If
  173. If Not input.Exists("base_revision") Then
  174. AddErr "base_revision is required with target_memory_id."
  175. ElseIf VarType(input.Item("base_revision")) <> vbDouble Then
  176. AddErr "base_revision must be a number."
  177. Else
  178. baseRev = CLng(input.Item("base_revision"))
  179. End If
  180. End If
  181. If Len(m_errs) > 0 Then
  182. Api_Invalid Split(m_errs, Chr(30))
  183. Exit Sub
  184. End If
  185. If Not Api_CanAccessNamespace(nsId, "write") Then
  186. Api_Audit "candidate.learn", "namespace", nsId, "denied"
  187. Api_Error 404, "namespace_not_found", "Namespace not found."
  188. Exit Sub
  189. End If
  190. Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType)
  191. If rs.EOF Then
  192. rs.Close
  193. Api_Invalid Array("type '" & memType & "' is not a known memory type.")
  194. Exit Sub
  195. End If
  196. rs.Close
  197. If Not IsNull(targetId) Then
  198. ' A revision proposal must target a memory of the same namespace and type that the caller can read.
  199. Set rs = DAL().Query("SELECT 1 FROM memories WHERE id = ? AND tenant_id = ? AND namespace_id = ? AND type = ?", Array(targetId, Api_TenantId, nsId, memType))
  200. If rs.EOF Then
  201. rs.Close
  202. Api_Invalid Array("target_memory_id was not found in this namespace with this type.")
  203. Exit Sub
  204. End If
  205. rs.Close
  206. End If
  207. Set ev = New Evidence_Class
  208. msg = ev.Load(input, "evidence")
  209. If Len(msg) > 0 Then
  210. Api_Invalid Array(msg)
  211. Exit Sub
  212. End If
  213. candId = Api_NewId()
  214. ts = Api_Now()
  215. resp = "{""id"":" & JsonLite_Quote(candId) & ",""state"":""proposed"",""namespace_id"":" & JsonLite_Quote(nsId) & ",""type"":" & JsonLite_Quote(memType) & _
  216. ",""evidence_count"":" & ev.Count & "}"
  217. On Error Resume Next
  218. DAL().BeginTransaction
  219. DAL().Execute "INSERT INTO learning_candidates (id, tenant_id, namespace_id, type, title, content, author_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  220. Array(candId, Api_TenantId, nsId, memType, title, content, Api_PrincipalId, ts)
  221. DAL().Execute "UPDATE learning_candidates SET summary = ?, tags = ?, confidence = ?, target_memory_id = ?, base_revision = ? WHERE id = ?", _
  222. Array(summary, tagsRaw, confidence, targetId, baseRev, candId)
  223. ev.Save "candidate", candId, Null
  224. Api_IdempotencyStore idemKey, reqHash, 201, resp
  225. If Err.Number <> 0 Then
  226. k = Err.Number : Api_NoteDbError
  227. DAL().RollbackTransaction
  228. Api_DbFailed k, ""
  229. Exit Sub
  230. End If
  231. DAL().CommitTransaction
  232. On Error GoTo 0
  233. Api_Audit "candidate.learn", "candidate", candId, "ok"
  234. Response.AddHeader "Location", "/api/v1/candidates/" & candId
  235. Api_Send 201, resp
  236. End Sub
  237. '---------------------------------------------------------------
  238. ' GET /api/v1/candidates
  239. '---------------------------------------------------------------
  240. Public Sub Candidates()
  241. Dim allowed, nsFilter, state, limit, sql, rs, out, n
  242. If Not Api_Authenticate() Then Exit Sub
  243. nsFilter = Trim("" & Request.QueryString("namespace_id"))
  244. state = LCase(Trim("" & Request.QueryString("state")))
  245. limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200)
  246. If Len(state) > 0 Then
  247. If state <> "proposed" And state <> "accepted" And state <> "rejected" Then
  248. Api_Invalid Array("state must be proposed, accepted or rejected.")
  249. Exit Sub
  250. End If
  251. End If
  252. If Len(nsFilter) > 0 Then
  253. If Not Api_IsId(nsFilter) Then
  254. Api_Invalid Array("namespace_id must be a valid id.")
  255. Exit Sub
  256. End If
  257. End If
  258. allowed = Api_AllowedNamespaceIds("read")
  259. out = ""
  260. n = 0
  261. If Len(allowed) > 0 Then
  262. sql = CandidateSelect() & " WHERE tenant_id = ? AND namespace_id IN (" & allowed & ")"
  263. If Len(nsFilter) > 0 Then
  264. sql = sql & " AND namespace_id = '" & nsFilter & "'"
  265. End If
  266. If Len(state) > 0 Then
  267. sql = sql & " AND state = '" & state & "'"
  268. End If
  269. Set rs = DAL().Query(sql & " ORDER BY created_at DESC, id LIMIT " & limit, Api_TenantId)
  270. Do While Not rs.EOF
  271. If n > 0 Then
  272. out = out & ","
  273. End If
  274. out = out & CandidateJson(rs, True)
  275. n = n + 1
  276. rs.MoveNext
  277. Loop
  278. rs.Close
  279. End If
  280. Api_Send 200, "{""data"":[" & out & "]}"
  281. End Sub
  282. '---------------------------------------------------------------
  283. ' GET /api/v1/candidates/:id
  284. '---------------------------------------------------------------
  285. Public Sub Candidate(id)
  286. Dim rs, json, nsId
  287. If Not Api_Authenticate() Then Exit Sub
  288. If Not Api_IsId(id) Then
  289. Api_NotFound
  290. Exit Sub
  291. End If
  292. Set rs = DAL().Query(CandidateSelect() & " WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  293. If rs.EOF Then
  294. rs.Close
  295. Api_NotFound
  296. Exit Sub
  297. End If
  298. nsId = "" & rs(1)
  299. json = CandidateJson(rs, False)
  300. rs.Close
  301. If Not Api_CanAccessNamespace(nsId, "read") Then
  302. Api_NotFound
  303. Exit Sub
  304. End If
  305. json = Left(json, Len(json) - 1) & ",""evidence"":" & EvidenceJson("candidate", id, Null) & "}"
  306. Api_Send 200, "{""data"":" & json & "}"
  307. End Sub
  308. '---------------------------------------------------------------
  309. ' POST /api/v1/candidates/:id/review
  310. '---------------------------------------------------------------
  311. Public Sub Review(id)
  312. Dim body, input, rs, nsId, state, author, memType, title, summary, content, tagsRaw, confidence, targetId, baseRev
  313. Dim decision, notes, doVerify, ts, k, memId, rev, dup, tNs, tType, tRev, tStatus, verStatus, hash
  314. If Not Api_Authenticate() Then Exit Sub
  315. If Not Api_IsId(id) Then
  316. Api_NotFound
  317. Exit Sub
  318. End If
  319. body = Api_ReadBody()
  320. If IsEmpty(body) Then Exit Sub
  321. Set input = JsonLite_Parse(body)
  322. Set rs = DAL().Query("SELECT namespace_id, state, author_principal_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision " & _
  323. "FROM learning_candidates WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  324. If rs.EOF Then
  325. rs.Close
  326. Api_NotFound
  327. Exit Sub
  328. End If
  329. nsId = "" & rs(0)
  330. state = "" & rs(1)
  331. author = "" & rs(2)
  332. memType = "" & rs(3)
  333. title = "" & rs(4)
  334. summary = rs(5)
  335. content = "" & rs(6)
  336. tagsRaw = rs(7)
  337. confidence = rs(8)
  338. targetId = rs(9)
  339. baseRev = rs(10)
  340. rs.Close
  341. If Not Api_CanAccessNamespace(nsId, "verify") Then
  342. Api_Audit "candidate.review", "candidate", id, "denied"
  343. Api_NotFound
  344. Exit Sub
  345. End If
  346. m_errs = ""
  347. decision = LCase("" & ReqString(input, "decision", 20))
  348. notes = OptString(input, "notes", 2000)
  349. doVerify = False
  350. If input.Exists("verify") Then
  351. If VarType(input.Item("verify")) = vbBoolean Then
  352. doVerify = input.Item("verify")
  353. ElseIf Not IsNull(input.Item("verify")) Then
  354. AddErr "verify must be true or false."
  355. End If
  356. End If
  357. If Len(m_errs) = 0 Then
  358. If decision <> "accept" And decision <> "reject" Then
  359. AddErr "decision must be accept or reject."
  360. End If
  361. End If
  362. If Len(m_errs) > 0 Then
  363. Api_Invalid Split(m_errs, Chr(30))
  364. Exit Sub
  365. End If
  366. If state <> "proposed" Then
  367. Api_Error 409, "candidate_already_reviewed", "The candidate was already " & state & "."
  368. Exit Sub
  369. End If
  370. If author = Api_PrincipalId Then
  371. If Not Api_CanAccessNamespace(nsId, "admin") Then
  372. Api_Audit "candidate.review", "candidate", id, "self_review_denied"
  373. Api_Error 403, "self_review_not_allowed", "A candidate cannot be reviewed by its author without admin permission on the namespace."
  374. Exit Sub
  375. End If
  376. End If
  377. ts = Api_Now()
  378. If decision = "reject" Then
  379. On Error Resume Next
  380. DAL().Execute "UPDATE learning_candidates SET state = 'rejected', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ? WHERE id = ? AND state = 'proposed'", _
  381. Array(Api_PrincipalId, notes, ts, id)
  382. If Err.Number <> 0 Then
  383. k = Err.Number : Api_NoteDbError
  384. Api_DbFailed k, ""
  385. Exit Sub
  386. End If
  387. On Error GoTo 0
  388. Api_Audit "candidate.review", "candidate", id, "rejected"
  389. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""rejected""}"
  390. Exit Sub
  391. End If
  392. ' accept: check the target (revision proposals) or look for an identical active memory (new memories)
  393. dup = False
  394. memId = ""
  395. rev = 0
  396. If Not IsNull(targetId) Then
  397. Set rs = DAL().Query("SELECT namespace_id, type, current_revision, lifecycle_status FROM memories WHERE id = ? AND tenant_id = ?", Array("" & targetId, Api_TenantId))
  398. If rs.EOF Then
  399. rs.Close
  400. Api_Error 409, "target_memory_missing", "The memory this candidate revises no longer exists."
  401. Exit Sub
  402. End If
  403. tNs = "" & rs(0)
  404. tType = "" & rs(1)
  405. tRev = CLng(rs(2))
  406. tStatus = "" & rs(3)
  407. rs.Close
  408. If tStatus <> "active" Then
  409. Api_Error 409, "target_memory_not_active", "The memory this candidate revises is " & tStatus & "."
  410. Exit Sub
  411. End If
  412. If tRev <> CLng(baseRev) Then
  413. Api_Error 409, "stale_candidate", "The memory changed since the candidate was proposed (base revision " & baseRev & ", current " & tRev & ")."
  414. Exit Sub
  415. End If
  416. Else
  417. hash = Mem_Hash(nsId, memType, title, content)
  418. Set rs = DAL().Query("SELECT m.id, m.current_revision FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _
  419. "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", Array(Api_TenantId, nsId, memType, hash))
  420. If Not rs.EOF Then
  421. dup = True
  422. memId = "" & rs(0)
  423. rev = CLng(rs(1))
  424. End If
  425. rs.Close
  426. End If
  427. On Error Resume Next
  428. DAL().BeginTransaction
  429. If Not IsNull(targetId) Then
  430. memId = "" & targetId
  431. rev = Mem_Revise(memId, nsId, memType, tRev, title, summary, content, tagsRaw, confidence, "accepted candidate " & id)
  432. ElseIf Not dup Then
  433. memId = Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, "accepted candidate " & id)
  434. rev = 1
  435. End If
  436. Evidence_CopyCandidate id, memId, rev
  437. If doVerify Then
  438. Mem_Verify memId, rev, "candidate_review", notes
  439. End If
  440. DAL().Execute "UPDATE learning_candidates SET state = 'accepted', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ?, resulting_memory_id = ?, resulting_revision = ? " & _
  441. "WHERE id = ? AND state = 'proposed'", Array(Api_PrincipalId, notes, ts, memId, rev, id)
  442. If Err.Number <> 0 Then
  443. k = Err.Number : Api_NoteDbError
  444. DAL().RollbackTransaction
  445. Api_DbFailed k, ""
  446. Exit Sub
  447. End If
  448. DAL().CommitTransaction
  449. If Err.Number <> 0 Then
  450. k = Err.Number : Api_NoteDbError
  451. Api_DbFailed k, ""
  452. Exit Sub
  453. End If
  454. On Error GoTo 0
  455. Set rs = DAL().Query("SELECT verification_status FROM memory_revisions WHERE memory_id = ? AND revision = ?", Array(memId, rev))
  456. verStatus = "unverified"
  457. If Not rs.EOF Then
  458. verStatus = "" & rs(0)
  459. End If
  460. rs.Close
  461. Emb_AfterWrite Api_TenantId, 8
  462. Api_Audit "candidate.review", "candidate", id, "accepted"
  463. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""accepted"",""resulting_memory_id"":" & JsonLite_Quote(memId) & _
  464. ",""resulting_revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(verStatus) & ",""duplicate"":" & LCase(CStr(dup)) & "}"
  465. End Sub
  466. '---------------------------------------------------------------
  467. ' GET /api/v1/memories/:id/sources
  468. '---------------------------------------------------------------
  469. Public Sub Sources(id)
  470. Dim rs, nsId, curRev, rev, q, ver, n, cand
  471. If Not Api_Authenticate() Then Exit Sub
  472. If Not Api_IsId(id) Then
  473. Api_NotFound
  474. Exit Sub
  475. End If
  476. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  477. If rs.EOF Then
  478. rs.Close
  479. Api_NotFound
  480. Exit Sub
  481. End If
  482. nsId = "" & rs(0)
  483. curRev = CLng(rs(1))
  484. rs.Close
  485. If Not Api_CanAccessNamespace(nsId, "read") Then
  486. Api_NotFound
  487. Exit Sub
  488. End If
  489. rev = curRev
  490. q = Trim("" & Request.QueryString("revision"))
  491. If Len(q) > 0 Then
  492. ' Api_ToInt clamps, so check the range on the raw value
  493. rev = -1
  494. If Len(q) <= 9 Then
  495. If IsNumeric(q) Then
  496. If InStr(q, ".") = 0 Then
  497. rev = CLng(q)
  498. End If
  499. End If
  500. End If
  501. If rev < 1 Or rev > curRev Then
  502. Api_Invalid Array("revision must be a whole number between 1 and " & curRev & ".")
  503. Exit Sub
  504. End If
  505. End If
  506. Set rs = DAL().Query("SELECT method, result, notes, reviewer_principal_id, created_at FROM verifications WHERE memory_id = ? AND revision = ? ORDER BY created_at", Array(id, rev))
  507. ver = ""
  508. n = 0
  509. Do While Not rs.EOF
  510. If n > 0 Then
  511. ver = ver & ","
  512. End If
  513. ver = ver & "{""method"":" & JsonLite_Quote("" & rs(0)) & ",""result"":" & JsonLite_Quote("" & rs(1)) & ",""notes"":" & JStr(rs(2)) & _
  514. ",""reviewer"":" & JsonLite_Quote("" & rs(3)) & ",""created_at"":" & JsonLite_Quote("" & rs(4)) & "}"
  515. n = n + 1
  516. rs.MoveNext
  517. Loop
  518. rs.Close
  519. Set rs = DAL().Query("SELECT id FROM learning_candidates WHERE resulting_memory_id = ? AND resulting_revision = ? AND tenant_id = ?", Array(id, rev, Api_TenantId))
  520. cand = "null"
  521. If Not rs.EOF Then
  522. cand = JsonLite_Quote("" & rs(0))
  523. End If
  524. rs.Close
  525. Api_Send 200, "{""memory_id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""current_revision"":" & curRev & _
  526. ",""from_candidate"":" & cand & ",""evidence"":" & EvidenceJson("memory", id, rev) & ",""verifications"":[" & ver & "]}"
  527. End Sub
  528. '---------------------------------------------------------------
  529. ' POST /api/v1/feedback
  530. '---------------------------------------------------------------
  531. Public Sub Feedback()
  532. Dim body, input, queryId, resultId, usefulness, comment, rs, kind, rev, nsId, ts, fbId, k, existing
  533. If Not Api_Authenticate() Then Exit Sub
  534. body = Api_ReadBody()
  535. If IsEmpty(body) Then Exit Sub
  536. Set input = JsonLite_Parse(body)
  537. m_errs = ""
  538. queryId = ReqString(input, "query_id", 80)
  539. resultId = ReqString(input, "result_id", 64)
  540. usefulness = LCase("" & ReqString(input, "usefulness", 20))
  541. comment = OptString(input, "comment", 2000)
  542. If Len(m_errs) = 0 Then
  543. If usefulness <> "useful" And usefulness <> "not_useful" And usefulness <> "incorrect" And usefulness <> "harmful" Then
  544. AddErr "usefulness must be useful, not_useful, incorrect or harmful."
  545. End If
  546. If Left(queryId, 4) <> "qry-" Or Not Api_IsId(Mid(queryId, 5)) Then
  547. AddErr "query_id must be a query id returned by recall, search or context."
  548. End If
  549. If Not Api_IsId(resultId) Then
  550. AddErr "result_id must be a valid id."
  551. End If
  552. End If
  553. If Len(m_errs) > 0 Then
  554. Api_Invalid Split(m_errs, Chr(30))
  555. Exit Sub
  556. End If
  557. ' The result must belong to that query, in this tenant, and still be readable by the caller.
  558. Set rs = DAL().Query("SELECT r.target_kind, r.target_revision FROM retrieval_results r JOIN retrieval_queries q ON q.id = r.query_id " & _
  559. "WHERE r.query_id = ? AND r.target_id = ? AND q.tenant_id = ?", Array(queryId, resultId, Api_TenantId))
  560. If rs.EOF Then
  561. rs.Close
  562. Api_Error 404, "result_not_found", "That result was not returned by that query."
  563. Exit Sub
  564. End If
  565. kind = "" & rs(0)
  566. rev = CLng(rs(1))
  567. rs.Close
  568. nsId = ""
  569. If kind = "memory" Then
  570. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(resultId, Api_TenantId))
  571. Else
  572. Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(resultId, Api_TenantId))
  573. End If
  574. If Not rs.EOF Then
  575. nsId = "" & rs(0)
  576. End If
  577. rs.Close
  578. If Len(nsId) = 0 Then
  579. Api_Error 404, "result_not_found", "That result was not returned by that query."
  580. Exit Sub
  581. End If
  582. If Not Api_CanAccessNamespace(nsId, "read") Then
  583. Api_Error 404, "result_not_found", "That result was not returned by that query."
  584. Exit Sub
  585. End If
  586. ' One rating per principal, query and result; a new submission replaces the earlier one.
  587. Set rs = DAL().Query("SELECT id FROM feedback WHERE query_id = ? AND target_kind = ? AND target_id = ? AND principal_id = ?", Array(queryId, kind, resultId, Api_PrincipalId))
  588. existing = ""
  589. If Not rs.EOF Then
  590. existing = "" & rs(0)
  591. End If
  592. rs.Close
  593. ts = Api_Now()
  594. On Error Resume Next
  595. If Len(existing) > 0 Then
  596. fbId = existing
  597. DAL().Execute "UPDATE feedback SET usefulness = ?, comment = ?, updated_at = ? WHERE id = ?", Array(usefulness, comment, ts, fbId)
  598. Else
  599. fbId = Api_NewId()
  600. ' 8-parameter limit: the server-generated timestamp is inlined (ISO text from Api_Now, no user input)
  601. DAL().Execute "INSERT INTO feedback (id, tenant_id, query_id, target_kind, target_id, target_revision, principal_id, usefulness, created_at, updated_at) " & _
  602. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & ts & "', '" & ts & "')", Array(fbId, Api_TenantId, queryId, kind, resultId, rev, Api_PrincipalId, usefulness)
  603. DAL().Execute "UPDATE feedback SET comment = ? WHERE id = ?", Array(comment, fbId)
  604. End If
  605. If Err.Number <> 0 Then
  606. k = Err.Number : Api_NoteDbError
  607. Api_DbFailed k, ""
  608. Exit Sub
  609. End If
  610. On Error GoTo 0
  611. Api_Audit "retrieval.feedback", kind, resultId, usefulness
  612. If Len(existing) > 0 Then
  613. Api_Send 200, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness)
  614. Else
  615. Api_Send 201, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness)
  616. End If
  617. End Sub
  618. '===============================================================
  619. ' Helpers
  620. '===============================================================
  621. Private Function FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness)
  622. FeedbackJson = "{""id"":" & JsonLite_Quote(fbId) & ",""query_id"":" & JsonLite_Quote(queryId) & ",""target_kind"":" & JsonLite_Quote(kind) & _
  623. ",""target_id"":" & JsonLite_Quote(resultId) & ",""target_revision"":" & rev & ",""usefulness"":" & JsonLite_Quote(usefulness) & "}"
  624. End Function
  625. ' Columns: 0 id, 1 namespace_id, 2 type, 3 title, 4 summary, 5 content, 6 tags, 7 confidence, 8 target_memory_id, 9 base_revision,
  626. ' 10 state, 11 author, 12 reviewer, 13 review_notes, 14 resulting_memory_id, 15 resulting_revision, 16 created_at, 17 reviewed_at
  627. Private Function CandidateSelect()
  628. CandidateSelect = "SELECT id, namespace_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision, state, " & _
  629. "author_principal_id, reviewer_principal_id, review_notes, resulting_memory_id, resulting_revision, created_at, reviewed_at FROM learning_candidates"
  630. End Function
  631. Private Function CandidateJson(rs, brief)
  632. Dim s
  633. s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  634. ",""title"":" & JsonLite_Quote("" & rs(3)) & ",""summary"":" & JStr(rs(4))
  635. If Not brief Then
  636. s = s & ",""content"":" & JsonLite_Quote("" & rs(5))
  637. End If
  638. s = s & ",""tags"":" & JRaw(rs(6), "[]") & ",""confidence"":" & JNum(rs(7)) & ",""target_memory_id"":" & JStr(rs(8)) & ",""base_revision"":" & JNum(rs(9)) & _
  639. ",""state"":" & JsonLite_Quote("" & rs(10)) & ",""author"":" & JsonLite_Quote("" & rs(11)) & ",""reviewer"":" & JStr(rs(12)) & _
  640. ",""review_notes"":" & JStr(rs(13)) & ",""resulting_memory_id"":" & JStr(rs(14)) & ",""resulting_revision"":" & JNum(rs(15)) & _
  641. ",""created_at"":" & JsonLite_Quote("" & rs(16)) & ",""reviewed_at"":" & JStr(rs(17)) & ",""content_trust"":""proposed_knowledge""}"
  642. CandidateJson = s
  643. End Function
  644. ' Evidence of an owner as a JSON array. A target the caller cannot read (or that is gone) is shown without its id.
  645. Private Function EvidenceJson(ownerKind, ownerId, ownerRev)
  646. Dim rs, rows, i, out, kind, tid, ns, avail, r2
  647. If IsNull(ownerRev) Then
  648. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND tenant_id = ? ORDER BY created_at, id", _
  649. Array(ownerKind, ownerId, Api_TenantId))
  650. Else
  651. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND owner_revision = ? AND tenant_id = ? ORDER BY created_at, id", _
  652. Array(ownerKind, ownerId, CLng(ownerRev), Api_TenantId))
  653. End If
  654. rows = Empty
  655. If Not rs.EOF Then
  656. rows = rs.GetRows()
  657. End If
  658. rs.Close
  659. out = ""
  660. If Not IsEmpty(rows) Then
  661. For i = 0 To UBound(rows, 2)
  662. kind = "" & rows(0, i)
  663. tid = "" & rows(1, i)
  664. ns = TargetNamespace(kind, tid)
  665. avail = False
  666. If Len(ns) > 0 Then
  667. avail = Api_CanAccessNamespace(ns, "read")
  668. End If
  669. If i > 0 Then
  670. out = out & ","
  671. End If
  672. out = out & "{""kind"":" & JsonLite_Quote(kind)
  673. If avail Then
  674. out = out & ",""id"":" & JsonLite_Quote(tid) & ",""revision"":" & JNum(rows(2, i))
  675. End If
  676. out = out & ",""available"":" & LCase(CStr(avail)) & ",""role"":" & JsonLite_Quote("" & rows(3, i))
  677. If avail Then
  678. out = out & ",""excerpt"":" & JStr(rows(4, i))
  679. End If
  680. out = out & ",""content_trust"":"""
  681. If kind = "chunk" Or kind = "document" Then
  682. out = out & "untrusted_reference"
  683. Else
  684. out = out & "evidence"
  685. End If
  686. out = out & """}"
  687. Next
  688. End If
  689. EvidenceJson = "[" & out & "]"
  690. End Function
  691. Private Function TargetNamespace(kind, tid)
  692. Dim rs
  693. TargetNamespace = ""
  694. Select Case kind
  695. Case "experience"
  696. Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  697. Case "chunk"
  698. Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(tid, Api_TenantId))
  699. Case "memory"
  700. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  701. Case Else
  702. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  703. End Select
  704. If Not rs.EOF Then
  705. TargetNamespace = "" & rs(0)
  706. End If
  707. rs.Close
  708. End Function
  709. Private Function JStr(v)
  710. If IsNull(v) Then
  711. JStr = "null"
  712. Else
  713. JStr = JsonLite_Quote("" & v)
  714. End If
  715. End Function
  716. Private Function JNum(v)
  717. If IsNull(v) Then
  718. JNum = "null"
  719. ElseIf Len("" & v) = 0 Then
  720. JNum = "null"
  721. Else
  722. JNum = JsonLite_Num(v)
  723. End If
  724. End Function
  725. Private Function JRaw(v, dflt)
  726. If IsNull(v) Then
  727. JRaw = dflt
  728. ElseIf Len("" & v) = 0 Then
  729. JRaw = dflt
  730. Else
  731. JRaw = "" & v
  732. End If
  733. End Function
  734. Private Sub AddErr(msg)
  735. If Len(m_errs) > 0 Then
  736. m_errs = m_errs & Chr(30)
  737. End If
  738. m_errs = m_errs & msg
  739. End Sub
  740. Private Function ReqString(input, name, maxLen)
  741. Dim v
  742. ReqString = ""
  743. If Not input.Exists(name) Then
  744. AddErr name & " is required."
  745. Exit Function
  746. End If
  747. v = input.Item(name)
  748. If IsNull(v) Then
  749. AddErr name & " is required."
  750. Exit Function
  751. End If
  752. If VarType(v) <> vbString Then
  753. AddErr name & " must be a string."
  754. Exit Function
  755. End If
  756. v = Trim(v)
  757. If Len(v) = 0 Then
  758. AddErr name & " must not be empty."
  759. Exit Function
  760. End If
  761. If Len(v) > maxLen Then
  762. AddErr name & " must be at most " & maxLen & " characters."
  763. Exit Function
  764. End If
  765. ReqString = v
  766. End Function
  767. Private Function OptString(input, name, maxLen)
  768. Dim v
  769. OptString = Null
  770. If Not input.Exists(name) Then
  771. Exit Function
  772. End If
  773. v = input.Item(name)
  774. If IsNull(v) Then
  775. Exit Function
  776. End If
  777. If VarType(v) <> vbString Then
  778. AddErr name & " must be a string."
  779. Exit Function
  780. End If
  781. If Len(v) > maxLen Then
  782. AddErr name & " must be at most " & maxLen & " characters."
  783. Exit Function
  784. End If
  785. OptString = v
  786. End Function
  787. Private Function OptUnit(input, name)
  788. Dim v
  789. OptUnit = Null
  790. If Not input.Exists(name) Then
  791. Exit Function
  792. End If
  793. v = input.Item(name)
  794. If IsNull(v) Then
  795. Exit Function
  796. End If
  797. If VarType(v) <> vbDouble Then
  798. AddErr name & " must be a number between 0 and 1."
  799. Exit Function
  800. End If
  801. If v < 0 Or v > 1 Then
  802. AddErr name & " must be between 0 and 1."
  803. Exit Function
  804. End If
  805. OptUnit = v
  806. End Function
  807. Private Function TagsJson(input)
  808. Dim arr, i, out, t
  809. TagsJson = Null
  810. If Not input.HasRaw("tags") Then
  811. If input.Exists("tags") Then
  812. If Not IsNull(input.Item("tags")) Then
  813. AddErr "tags must be an array of strings."
  814. End If
  815. End If
  816. Exit Function
  817. End If
  818. arr = JsonLite_ParseStringArray(input.Raw("tags"))
  819. If IsNull(arr) Then
  820. AddErr "tags must be an array of strings."
  821. Exit Function
  822. End If
  823. If UBound(arr) > 31 Then
  824. AddErr "tags may contain at most 32 entries."
  825. Exit Function
  826. End If
  827. out = ""
  828. For i = 0 To UBound(arr)
  829. t = Trim(arr(i))
  830. If Len(t) = 0 Or Len(t) > 64 Then
  831. AddErr "each tag must be 1 to 64 characters."
  832. Exit Function
  833. End If
  834. If i > 0 Then
  835. out = out & ","
  836. End If
  837. out = out & JsonLite_Quote(t)
  838. Next
  839. TagsJson = "[" & out & "]"
  840. End Function
  841. ' Optional JSON object stored as raw text (max 16 KB), or Null
  842. Private Function ObjectJson(input, name)
  843. Dim raw
  844. ObjectJson = Null
  845. If Not input.HasRaw(name) Then
  846. If input.Exists(name) Then
  847. If Not IsNull(input.Item(name)) Then
  848. AddErr name & " must be a JSON object."
  849. End If
  850. End If
  851. Exit Function
  852. End If
  853. raw = input.Raw(name)
  854. If Left(raw, 1) <> "{" Then
  855. AddErr name & " must be a JSON object."
  856. Exit Function
  857. End If
  858. If Len(raw) > 16384 Then
  859. AddErr name & " must be at most 16 KB."
  860. Exit Function
  861. End If
  862. ObjectJson = raw
  863. End Function
  864. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  865. Public Sub Invoke(actionName, args)
  866. Select Case LCase(actionName)
  867. Case "recordevent" : RecordEvent args(0)
  868. Case "events" : Events args(0)
  869. Case "learn" : Learn
  870. Case "candidates" : Candidates
  871. Case "candidate" : Candidate args(0)
  872. Case "review" : Review args(0)
  873. Case "sources" : Sources args(0)
  874. Case "feedback" : Feedback
  875. Case Else
  876. Err.Raise 438, "ApiLearningController_Class", "Action '" & actionName & "' not found"
  877. End Select
  878. End Sub
  879. End Class
  880. Dim ApiLearningController_Class__Singleton
  881. Function ApiLearningController()
  882. If IsEmpty(ApiLearningController_Class__Singleton) Then
  883. Set ApiLearningController_Class__Singleton = New ApiLearningController_Class
  884. End If
  885. Set ApiLearningController = ApiLearningController_Class__Singleton
  886. End Function
  887. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  888. Sub ApiLearningController_Invoke(actionName, args)
  889. ApiLearningController().Invoke actionName, args
  890. End Sub
  891. %>

Powered by TurnKey Linux.