Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

850 rindas
35KB

  1. <%
  2. ' ApiContextController: task briefing assembly (spec FR-010, section 9.3, section 10, AC-05, AC-16).
  3. ' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (FTS query).
  4. '
  5. ' POST /api/v1/context
  6. ' {"task", "namespace_ids":[], "session_id", "include":["constraints","preferences","decisions","lessons","knowledge",
  7. ' "references","working_state"], "verification_filter":"verified_only|include_unverified",
  8. ' "detail_level":"full|summary", "max_context_tokens":100..32000, "max_items":1..50, "max_references":0..20,
  9. ' "format":"structured"}
  10. '
  11. ' Matching is hybrid (lexical fused with vector similarity, core/lib.Embeddings.asp) when configured, else lexical.
  12. ' Assembly (all filtered to active, currently valid memories in namespaces the caller can read):
  13. ' constraints every constraint memory in scope, by importance: loaded by scope, not by similarity, and required.
  14. ' If they do not fit the budget the request fails with 422 context_budget_exceeded.
  15. ' working_state latest checkpoint of session_id (404 when the session is not visible)
  16. ' preferences every preference memory in scope, by importance
  17. ' conflicts disputed memories among the above and the task matches (always reported, labelled)
  18. ' decisions / lessons / knowledge matches of the task (hybrid or lexical), by type
  19. ' references matches over current document chunks (untrusted reference content)
  20. ' unverified unverified matches, only with verification_filter include_unverified
  21. ' The budget is filled in that order; an item that does not fit is skipped and counted. Memories with identical
  22. ' content (same text, ignoring case and outer whitespace) appear once. Token counts are estimates (characters / 4) of the included text, not of
  23. ' the JSON envelope. Constraints are always returned in full, also with detail_level summary.
  24. Const CTX_CONSTRAINTS = 0
  25. Const CTX_PREFERENCES = 1
  26. Const CTX_CONFLICTS = 2
  27. Const CTX_DECISIONS = 3
  28. Const CTX_LESSONS = 4
  29. Const CTX_KNOWLEDGE = 5
  30. Const CTX_REFERENCES = 6
  31. Const CTX_UNVERIFIED = 7
  32. Const CTX_SECTION_COUNT = 8
  33. Const CTX_MAX_POLICIES = 200
  34. Class ApiContextController_Class
  35. Private m_errs
  36. ' candidates, in rank order within each section
  37. Private m_cSec(), m_cJson(), m_cTok(), m_cTel(), m_cN, m_spec
  38. Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok, m_strategy, m_rankWarning, m_demoted
  39. Public Property Get useLayout()
  40. useLayout = False
  41. End Property
  42. Public Property Let useLayout(v)
  43. End Property
  44. Public Property Get Title()
  45. Title = "Context API"
  46. End Property
  47. '---------------------------------------------------------------
  48. ' POST /api/v1/context
  49. '---------------------------------------------------------------
  50. Public Sub Assemble()
  51. Dim body, input, task, fts, budget, maxItems, maxRefs, detail, vf, fmt, requested, allowed, sessionId
  52. Dim incPrefs, incDecisions, incLessons, incKnowledge, incRefs, incState
  53. Dim rs, sql, now_, i, j, n, ids(), scores(), idList, sec, json, warnings, complete
  54. Dim stateJson, stateTok, sessNs, sessStatus, sessObjective, curRev, savedAt
  55. Dim used, requiredTok, policyCount, truncated, omittedBudget, omittedLimit, cap
  56. Dim outSec(), cnt(), out, refSeen, txt, policiesCapped, ranker, qid, t0
  57. t0 = Timer
  58. If Not Api_Authenticate() Then Exit Sub
  59. body = Api_ReadBody()
  60. If IsEmpty(body) Then Exit Sub
  61. Set input = JsonLite_Parse(body)
  62. '--- validation -----------------------------------------------
  63. m_errs = ""
  64. task = ReqString(input, "task", 2000)
  65. budget = OptInt(input, "max_context_tokens", 4000, 100, 32000)
  66. maxItems = OptInt(input, "max_items", 10, 1, 50)
  67. maxRefs = OptInt(input, "max_references", 5, 0, 20)
  68. detail = LCase("" & OptStringDefault(input, "detail_level", 20, "full"))
  69. If detail <> "full" And detail <> "summary" Then
  70. AddErr "detail_level must be full or summary."
  71. End If
  72. vf = LCase("" & OptStringDefault(input, "verification_filter", 30, "verified_only"))
  73. If vf <> "verified_only" And vf <> "include_unverified" Then
  74. AddErr "verification_filter must be verified_only or include_unverified."
  75. End If
  76. fmt = LCase("" & OptStringDefault(input, "format", 20, "structured"))
  77. If fmt <> "structured" Then
  78. AddErr "format must be structured."
  79. End If
  80. sessionId = OptStringDefault(input, "session_id", 64, "")
  81. If Len(sessionId) > 0 Then
  82. If Not Api_IsId(sessionId) Then
  83. AddErr "session_id must be a valid id."
  84. End If
  85. End If
  86. requested = IdListSql(input, "namespace_ids")
  87. incPrefs = True
  88. incDecisions = True
  89. incLessons = True
  90. incKnowledge = True
  91. incRefs = True
  92. incState = True
  93. If input.HasRaw("include") Then
  94. Dim incArr, inc
  95. incArr = JsonLite_ParseStringArray(input.Raw("include"))
  96. If IsNull(incArr) Then
  97. AddErr "include must be an array of section names."
  98. Else
  99. incPrefs = False
  100. incDecisions = False
  101. incLessons = False
  102. incKnowledge = False
  103. incRefs = False
  104. incState = False
  105. For i = 0 To UBound(incArr)
  106. inc = LCase(Trim(incArr(i)))
  107. Select Case inc
  108. Case "constraints"
  109. ' always included
  110. Case "preferences"
  111. incPrefs = True
  112. Case "decisions"
  113. incDecisions = True
  114. Case "lessons"
  115. incLessons = True
  116. Case "knowledge"
  117. incKnowledge = True
  118. Case "references"
  119. incRefs = True
  120. Case "working_state"
  121. incState = True
  122. Case Else
  123. AddErr "include contains an unknown section: " & Left(inc, 40) & "."
  124. End Select
  125. Next
  126. End If
  127. ElseIf input.Exists("include") Then
  128. If Not IsNull(input.Item("include")) Then
  129. AddErr "include must be an array of section names."
  130. End If
  131. End If
  132. If Len(m_errs) > 0 Then
  133. Api_Invalid Split(m_errs, Chr(30))
  134. Exit Sub
  135. End If
  136. fts = Search_FtsQuery(task)
  137. If Len(fts) = 0 Then
  138. Api_Invalid Array("task must contain at least one word.")
  139. Exit Sub
  140. End If
  141. '--- session (checked before any retrieval: an invisible session is a 404) ---
  142. stateJson = "null"
  143. stateTok = 0
  144. If Len(sessionId) > 0 Then
  145. Set rs = DAL().Query("SELECT namespace_id, status, objective FROM sessions WHERE id = ? AND tenant_id = ?", Array(sessionId, Api_TenantId))
  146. If rs.EOF Then
  147. rs.Close
  148. Api_Error 404, "session_not_found", "Session not found."
  149. Exit Sub
  150. End If
  151. sessNs = "" & rs(0)
  152. sessStatus = "" & rs(1)
  153. sessObjective = "" & rs(2)
  154. rs.Close
  155. If Not Api_CanAccessNamespace(sessNs, "read") Then
  156. Api_Error 404, "session_not_found", "Session not found."
  157. Exit Sub
  158. End If
  159. If incState Then
  160. curRev = 0
  161. Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", sessionId)
  162. If Not rs.EOF Then
  163. If Not IsNull(rs(0)) Then
  164. curRev = CLng(rs(0))
  165. End If
  166. End If
  167. rs.Close
  168. txt = "null"
  169. savedAt = "null"
  170. If curRev > 0 Then
  171. Set rs = DAL().Query("SELECT state, created_at FROM checkpoints WHERE session_id = ? AND revision = ?", Array(sessionId, curRev))
  172. If Not rs.EOF Then
  173. txt = "" & rs(0)
  174. savedAt = JsonLite_Quote("" & rs(1))
  175. End If
  176. rs.Close
  177. End If
  178. stateTok = Tokens(sessObjective & vbLf & txt)
  179. stateJson = "{""session_id"":" & JsonLite_Quote(sessionId) & ",""status"":" & JsonLite_Quote(sessStatus) & _
  180. ",""objective"":" & JsonLite_Quote(sessObjective) & ",""revision"":" & curRev & ",""state"":" & txt & _
  181. ",""saved_at"":" & savedAt & ",""token_estimate"":" & stateTok & "}"
  182. End If
  183. End If
  184. allowed = Api_AllowedNamespaceIds("read")
  185. If Len(allowed) > 0 And Len(requested) > 0 Then
  186. allowed = IntersectIds(allowed, requested)
  187. End If
  188. m_cN = 0
  189. ReDim m_cSec(31)
  190. ReDim m_cJson(31)
  191. ReDim m_cTok(31)
  192. ReDim m_cTel(31)
  193. m_spec = ""
  194. m_seen = Chr(31)
  195. m_strategy = "lexical"
  196. m_rankWarning = ""
  197. m_demoted = 0
  198. m_dupes = 0
  199. m_unverifiedExcluded = 0
  200. policiesCapped = False
  201. now_ = Api_Now()
  202. If Len(allowed) > 0 Then
  203. '--- 1. policies: constraints and preferences, by scope ------------------
  204. sql = CtxMemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
  205. "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _
  206. "AND r.verification_status <> 'rejected' AND m.type IN ('constraint','preference') " & _
  207. "ORDER BY CASE m.type WHEN 'constraint' THEN 0 ELSE 1 END, COALESCE(r.importance, 0) DESC, m.updated_at DESC LIMIT " & (CTX_MAX_POLICIES + 1)
  208. Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
  209. policyCount = 0
  210. Do While Not rs.EOF
  211. policyCount = policyCount + 1
  212. If policyCount > CTX_MAX_POLICIES Then
  213. policiesCapped = True
  214. Exit Do
  215. End If
  216. If "" & rs(2) = "constraint" Then
  217. AddMemory rs, CTX_CONSTRAINTS, vf, "full", 0
  218. ElseIf incPrefs Then
  219. AddMemory rs, CTX_PREFERENCES, vf, detail, 0
  220. End If
  221. rs.MoveNext
  222. Loop
  223. rs.Close
  224. '--- 2. memory matches (lexical, fused with semantic when configured) ----------
  225. If incDecisions Or incLessons Or incKnowledge Then
  226. Set ranker = New Ranker_Class
  227. ranker.Run "memory", fts, task, Api_TenantId, allowed
  228. NoteRanker ranker
  229. n = ranker.Count
  230. If n > 0 Then
  231. ReDim ids(n - 1)
  232. ReDim scores(n - 1)
  233. For i = 0 To n - 1
  234. ids(i) = ranker.IdAt(i)
  235. scores(i) = -ranker.ScoreAt(i)
  236. Next
  237. End If
  238. idList = IdSqlList(ids, n)
  239. If Len(idList) > 0 Then
  240. ' Read the canonical rows (closing the result set), then add them in rank order.
  241. sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
  242. "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _
  243. "AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')"
  244. Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
  245. Dim rowsTmp
  246. rowsTmp = Empty
  247. If Not rs.EOF Then
  248. rowsTmp = rs.GetRows()
  249. End If
  250. rs.Close
  251. If Not IsEmpty(rowsTmp) Then
  252. ' GetRows is (column, row); walk the ranks and pick the matching row
  253. For i = 0 To n - 1
  254. For j = 0 To UBound(rowsTmp, 2)
  255. If "" & rowsTmp(0, j) = ids(i) Then
  256. sec = TypeSection("" & rowsTmp(2, j))
  257. If sec = CTX_DECISIONS And Not incDecisions Then
  258. sec = -1
  259. ElseIf sec = CTX_LESSONS And Not incLessons Then
  260. sec = -1
  261. ElseIf sec = CTX_KNOWLEDGE And Not incKnowledge Then
  262. sec = -1
  263. End If
  264. If sec >= 0 Then
  265. AddMemoryRow rowsTmp, j, sec, vf, detail, -CDbl(scores(i))
  266. End If
  267. Exit For
  268. End If
  269. Next
  270. Next
  271. End If
  272. End If
  273. End If
  274. '--- 3. reference passages ------------------------------------------------
  275. If incRefs And maxRefs > 0 Then
  276. Set ranker = New Ranker_Class
  277. ranker.Run "chunk", fts, task, Api_TenantId, allowed
  278. NoteRanker ranker
  279. n = ranker.Count
  280. If n > 0 Then
  281. ReDim ids(n - 1)
  282. ReDim scores(n - 1)
  283. For i = 0 To n - 1
  284. ids(i) = ranker.IdAt(i)
  285. scores(i) = -ranker.ScoreAt(i)
  286. Next
  287. End If
  288. idList = IdSqlList(ids, n)
  289. If Len(idList) > 0 Then
  290. Dim chunkRows
  291. chunkRows = Empty
  292. sql = "SELECT c.id, c.document_id, c.document_revision, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, d.namespace_id, d.title, d.source_uri " & _
  293. "FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") " & _
  294. "AND c.document_revision = d.current_revision"
  295. Set rs = DAL().Query(sql, Api_TenantId)
  296. If Not rs.EOF Then
  297. chunkRows = rs.GetRows()
  298. End If
  299. rs.Close
  300. If Not IsEmpty(chunkRows) Then
  301. refSeen = Chr(31)
  302. cap = 0
  303. For i = 0 To n - 1
  304. If cap >= maxRefs Then
  305. Exit For
  306. End If
  307. For j = 0 To UBound(chunkRows, 2)
  308. If "" & chunkRows(0, j) = ids(i) Then
  309. txt = "" & chunkRows(4, j)
  310. If InStr(refSeen, Chr(31) & txt & Chr(31)) > 0 Then
  311. m_dupes = m_dupes + 1
  312. Else
  313. refSeen = refSeen & txt & Chr(31)
  314. json = RefJson(chunkRows, j, detail, -CDbl(scores(i)))
  315. AddCand CTX_REFERENCES, json, m_lastTok, "chunk|" & ids(i) & "|" & CLng(chunkRows(2, j)) & "|" & JsonLite_Num(-CDbl(scores(i)))
  316. cap = cap + 1
  317. End If
  318. Exit For
  319. End If
  320. Next
  321. Next
  322. End If
  323. End If
  324. End If
  325. End If
  326. '--- budget ---------------------------------------------------------------------
  327. requiredTok = 0
  328. For i = 0 To m_cN - 1
  329. If m_cSec(i) = CTX_CONSTRAINTS Then
  330. requiredTok = requiredTok + m_cTok(i)
  331. End If
  332. Next
  333. If requiredTok > budget Then
  334. Api_Audit "context.assemble", "context", "", "budget_exceeded"
  335. Api_Send 422, "{""error"":{""code"":""context_budget_exceeded"",""message"":" & _
  336. JsonLite_Quote("The applicable constraints need about " & requiredTok & " tokens, more than max_context_tokens (" & budget & "). Raise the budget or narrow namespace_ids.") & _
  337. ",""required_tokens"":" & requiredTok & ",""max_context_tokens"":" & budget & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  338. Exit Sub
  339. End If
  340. ReDim outSec(CTX_SECTION_COUNT - 1)
  341. ReDim cnt(CTX_SECTION_COUNT - 1)
  342. For i = 0 To CTX_SECTION_COUNT - 1
  343. outSec(i) = ""
  344. cnt(i) = 0
  345. Next
  346. used = requiredTok
  347. omittedBudget = 0
  348. omittedLimit = 0
  349. For i = 0 To m_cN - 1
  350. If m_cSec(i) = CTX_CONSTRAINTS Then
  351. AppendTo outSec, cnt, CTX_CONSTRAINTS, m_cJson(i)
  352. AddTel i
  353. End If
  354. Next
  355. warnings = ""
  356. If stateTok > 0 Then
  357. If used + stateTok <= budget Then
  358. used = used + stateTok
  359. Else
  360. stateJson = "null"
  361. omittedBudget = omittedBudget + 1
  362. AddWarning warnings, "working_state did not fit the budget and was left out; restore it with GET /sessions/{id}/state"
  363. End If
  364. End If
  365. For sec = CTX_PREFERENCES To CTX_SECTION_COUNT - 1
  366. If sec = CTX_PREFERENCES Then
  367. cap = 50
  368. ElseIf sec = CTX_REFERENCES Then
  369. cap = maxRefs
  370. Else
  371. cap = maxItems
  372. End If
  373. For i = 0 To m_cN - 1
  374. If m_cSec(i) = sec Then
  375. If cnt(sec) >= cap Then
  376. omittedLimit = omittedLimit + 1
  377. ElseIf used + m_cTok(i) > budget Then
  378. omittedBudget = omittedBudget + 1
  379. Else
  380. used = used + m_cTok(i)
  381. AppendTo outSec, cnt, sec, m_cJson(i)
  382. AddTel i
  383. End If
  384. End If
  385. Next
  386. Next
  387. complete = True
  388. If policiesCapped Then
  389. complete = False
  390. AddWarning warnings, "more than " & CTX_MAX_POLICIES & " constraint/preference memories are in scope; only the most important were considered, so the briefing is incomplete. Narrow namespace_ids."
  391. End If
  392. truncated = (omittedBudget > 0)
  393. If omittedBudget > 0 Then
  394. AddWarning warnings, omittedBudget & " item(s) left out to fit max_context_tokens"
  395. End If
  396. If m_unverifiedExcluded > 0 Then
  397. AddWarning warnings, m_unverifiedExcluded & " unverified item(s) excluded; use verification_filter include_unverified to see them"
  398. End If
  399. If cnt(CTX_CONFLICTS) > 0 Then
  400. AddWarning warnings, cnt(CTX_CONFLICTS) & " disputed item(s) included under conflicts; do not rely on them without checking"
  401. End If
  402. If Len(allowed) = 0 Then
  403. AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty"
  404. End If
  405. If m_demoted > 0 Then
  406. AddWarning warnings, m_demoted & " matched item(s) ranked lower because of negative feedback on their current revision"
  407. End If
  408. If Len(m_rankWarning) > 0 Then
  409. AddWarning warnings, m_rankWarning
  410. End If
  411. ' Telemetry: the query id is returned so results can be rated with POST /feedback
  412. qid = Tel_NewQueryId()
  413. Tel_Record qid, "context", m_strategy, task, m_spec, t0
  414. out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""query_id"":" & JsonLite_Quote(qid) & ",""task"":" & JsonLite_Quote(task) & _
  415. ",""strategy"":" & JsonLite_Quote(m_strategy) & ",""format"":""structured"",""verification_filter"":" & JsonLite_Quote(vf) & ",""detail_level"":" & JsonLite_Quote(detail) & _
  416. ",""budget"":{""max_context_tokens"":" & budget & ",""used_tokens"":" & used & ",""counting_method"":""estimate_chars_div_4""" & _
  417. ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _
  418. ",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}"
  419. out = out & ",""constraints"":[" & outSec(CTX_CONSTRAINTS) & "]"
  420. If incState Then
  421. out = out & ",""working_state"":" & stateJson
  422. End If
  423. If incPrefs Then
  424. out = out & ",""preferences"":[" & outSec(CTX_PREFERENCES) & "]"
  425. End If
  426. out = out & ",""conflicts"":[" & outSec(CTX_CONFLICTS) & "]"
  427. If incDecisions Then
  428. out = out & ",""decisions"":[" & outSec(CTX_DECISIONS) & "]"
  429. End If
  430. If incLessons Then
  431. out = out & ",""lessons"":[" & outSec(CTX_LESSONS) & "]"
  432. End If
  433. If incKnowledge Then
  434. out = out & ",""knowledge"":[" & outSec(CTX_KNOWLEDGE) & "]"
  435. End If
  436. If incRefs Then
  437. out = out & ",""references"":[" & outSec(CTX_REFERENCES) & "]"
  438. End If
  439. If vf = "include_unverified" Then
  440. out = out & ",""unverified"":[" & outSec(CTX_UNVERIFIED) & "]"
  441. End If
  442. out = out & ",""warnings"":[" & warnings & "]}"
  443. Api_Audit "context.assemble", "context", "", "ok"
  444. Api_Send 200, out
  445. End Sub
  446. '===============================================================
  447. ' Helpers
  448. '===============================================================
  449. ' Columns relied on by AddMemory / AddMemoryRow:
  450. ' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance,
  451. ' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until
  452. ' Strategy/warning of the last ranking (hybrid unless semantic retrieval was unavailable for any section)
  453. Private Sub NoteRanker(r)
  454. m_demoted = m_demoted + r.Demoted
  455. If Len(r.Warning) > 0 Then
  456. m_rankWarning = r.Warning
  457. m_strategy = "lexical"
  458. ElseIf Len(m_rankWarning) = 0 Then
  459. m_strategy = r.Strategy
  460. End If
  461. End Sub
  462. Private Function CtxMemorySelect()
  463. CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _
  464. "r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _
  465. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
  466. End Function
  467. Private Function TypeSection(t)
  468. Select Case t
  469. Case "decision"
  470. TypeSection = CTX_DECISIONS
  471. Case "lesson"
  472. TypeSection = CTX_LESSONS
  473. Case Else
  474. TypeSection = CTX_KNOWLEDGE
  475. End Select
  476. End Function
  477. ' Copies one result-set row into an array and hands it to AddMemoryRow (single code path for both sources).
  478. Private Sub AddMemory(rs, sec, vf, detail, score)
  479. Dim row(14, 0), k
  480. For k = 0 To 14
  481. row(k, 0) = rs(k)
  482. Next
  483. AddMemoryRow row, 0, sec, vf, detail, score
  484. End Sub
  485. ' rows is GetRows-shaped (column, row). Sorts the memory into its section by verification state and dedupes by content.
  486. Private Sub AddMemoryRow(rows, j, sec, vf, detail, score)
  487. Dim st, key, json, target
  488. st = "" & rows(10, j)
  489. target = sec
  490. If st = "disputed" Then
  491. target = CTX_CONFLICTS
  492. ElseIf st <> "verified" Then
  493. If vf = "include_unverified" Then
  494. target = CTX_UNVERIFIED
  495. Else
  496. m_unverifiedExcluded = m_unverifiedExcluded + 1
  497. Exit Sub
  498. End If
  499. End If
  500. ' The stored content_hash also covers namespace, type and title, so the same text in two namespaces has two
  501. ' hashes. Dedupe on the normalized content instead.
  502. key = LCase(Trim("" & rows(6, j)))
  503. If InStr(m_seen, Chr(31) & key & Chr(31)) > 0 Then
  504. m_dupes = m_dupes + 1
  505. Exit Sub
  506. End If
  507. m_seen = m_seen & key & Chr(31)
  508. json = MemJson(rows, j, detail, score, st, (sec = CTX_CONSTRAINTS))
  509. AddCand target, json, m_lastTok, "memory|" & rows(0, j) & "|" & CLng(rows(3, j)) & "|" & TelScore(score)
  510. End Sub
  511. Private Function MemJson(rows, j, detail, score, st, isPolicy)
  512. Dim s, bodyText, trust
  513. If detail = "summary" Then
  514. If IsNull(rows(5, j)) Then
  515. bodyText = "" & rows(6, j)
  516. If Len(bodyText) > 240 Then
  517. bodyText = Left(bodyText, 240) & "..."
  518. End If
  519. Else
  520. bodyText = "" & rows(5, j)
  521. End If
  522. Else
  523. bodyText = "" & rows(6, j)
  524. End If
  525. m_lastTok = Tokens("" & rows(4, j) & vbLf & bodyText)
  526. Select Case st
  527. Case "verified"
  528. trust = "verified_memory"
  529. Case "disputed"
  530. trust = "disputed_memory"
  531. Case Else
  532. trust = "unverified_memory"
  533. End Select
  534. s = "{""id"":" & JsonLite_Quote("" & rows(0, j)) & ",""revision"":" & CLng(rows(3, j)) & ",""type"":" & JsonLite_Quote("" & rows(2, j)) & _
  535. ",""namespace_id"":" & JsonLite_Quote("" & rows(1, j)) & ",""title"":" & JsonLite_Quote("" & rows(4, j))
  536. If detail = "summary" Then
  537. s = s & ",""summary"":" & JsonLite_Quote(bodyText)
  538. Else
  539. s = s & ",""content"":" & JsonLite_Quote(bodyText)
  540. End If
  541. s = s & ",""verification_status"":" & JsonLite_Quote(st) & ",""content_trust"":" & JsonLite_Quote(trust)
  542. If isPolicy Then
  543. If st = "verified" Then
  544. s = s & ",""authority"":""policy"""
  545. End If
  546. End If
  547. s = s & ",""tags"":" & JRaw(rows(7, j), "[]") & ",""confidence"":" & JNum(rows(8, j)) & ",""importance"":" & JNum(rows(9, j))
  548. If score <> 0 Then
  549. s = s & ",""relevance_score"":" & JsonLite_Num(score)
  550. End If
  551. s = s & ",""valid_until"":" & JStr(rows(14, j)) & ",""provenance"":{""created_by"":" & JsonLite_Quote("" & rows(12, j)) & _
  552. ",""updated_at"":" & JsonLite_Quote("" & rows(13, j)) & "},""token_estimate"":" & m_lastTok & "}"
  553. MemJson = s
  554. End Function
  555. ' Chunk row columns: 0 id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end,
  556. ' 8 namespace id, 9 title, 10 source uri
  557. Private Function RefJson(rows, j, detail, score)
  558. Dim txt, s
  559. txt = "" & rows(4, j)
  560. If detail = "summary" Then
  561. If Len(txt) > 240 Then
  562. txt = Left(txt, 240) & "..."
  563. End If
  564. End If
  565. m_lastTok = Tokens(txt)
  566. s = "{""chunk_id"":" & JsonLite_Quote("" & rows(0, j)) & ",""document_id"":" & JsonLite_Quote("" & rows(1, j)) & _
  567. ",""document_title"":" & JsonLite_Quote("" & rows(9, j)) & ",""source_uri"":" & JStr(rows(10, j)) & _
  568. ",""document_revision"":" & CLng(rows(2, j)) & ",""ordinal"":" & CLng(rows(3, j)) & ",""heading_path"":" & JStr(rows(5, j)) & _
  569. ",""locator"":{""start"":" & CLng(rows(6, j)) & ",""end"":" & CLng(rows(7, j)) & "},""namespace_id"":" & JsonLite_Quote("" & rows(8, j)) & _
  570. ",""relevance_score"":" & JsonLite_Num(score) & ",""content"":" & JsonLite_Quote(txt) & _
  571. ",""content_trust"":""untrusted_reference"",""token_estimate"":" & m_lastTok & "}"
  572. RefJson = s
  573. End Function
  574. ' tel: "kind|id|revision|score" of the item, recorded for feedback if the item makes it into the briefing
  575. Private Sub AddCand(sec, json, tok, tel)
  576. If m_cN > UBound(m_cSec) Then
  577. ReDim Preserve m_cSec(m_cN * 2)
  578. ReDim Preserve m_cJson(m_cN * 2)
  579. ReDim Preserve m_cTok(m_cN * 2)
  580. ReDim Preserve m_cTel(m_cN * 2)
  581. End If
  582. m_cSec(m_cN) = sec
  583. m_cJson(m_cN) = json
  584. m_cTok(m_cN) = tok
  585. m_cTel(m_cN) = tel
  586. m_cN = m_cN + 1
  587. End Sub
  588. Private Sub AddTel(i)
  589. If Len(m_spec) > 0 Then
  590. m_spec = m_spec & Chr(30)
  591. End If
  592. m_spec = m_spec & m_cTel(i)
  593. End Sub
  594. ' Constraints and preferences are loaded by scope and have no similarity score
  595. Private Function TelScore(score)
  596. TelScore = "0"
  597. If IsNumeric(score) Then
  598. If Not IsEmpty(score) Then
  599. TelScore = JsonLite_Num(score)
  600. End If
  601. End If
  602. End Function
  603. Private Sub AppendTo(outSec, cnt, sec, json)
  604. If cnt(sec) > 0 Then
  605. outSec(sec) = outSec(sec) & ","
  606. End If
  607. outSec(sec) = outSec(sec) & json
  608. cnt(sec) = cnt(sec) + 1
  609. End Sub
  610. Private Sub AddWarning(warnings, text)
  611. If Len(warnings) > 0 Then
  612. warnings = warnings & ","
  613. End If
  614. warnings = warnings & JsonLite_Quote(text)
  615. End Sub
  616. ' Token estimate for included text: characters / 4, rounded up (declared as estimate_chars_div_4)
  617. Private Function Tokens(text)
  618. Tokens = Int((Len(text) + 3) / 4)
  619. End Function
  620. ' 'id1','id2' for the first n valid ids
  621. Private Function IdSqlList(ids, n)
  622. Dim i, out
  623. out = ""
  624. For i = 0 To n - 1
  625. If Api_IsId(ids(i)) Then
  626. If Len(out) > 0 Then
  627. out = out & ","
  628. End If
  629. out = out & "'" & ids(i) & "'"
  630. End If
  631. Next
  632. IdSqlList = out
  633. End Function
  634. Private Function JStr(v)
  635. If IsNull(v) Then
  636. JStr = "null"
  637. Else
  638. JStr = JsonLite_Quote("" & v)
  639. End If
  640. End Function
  641. Private Function JNum(v)
  642. If IsNull(v) Then
  643. JNum = "null"
  644. ElseIf Len("" & v) = 0 Then
  645. JNum = "null"
  646. Else
  647. JNum = JsonLite_Num(v)
  648. End If
  649. End Function
  650. Private Function JRaw(v, dflt)
  651. If IsNull(v) Then
  652. JRaw = dflt
  653. ElseIf Len("" & v) = 0 Then
  654. JRaw = dflt
  655. Else
  656. JRaw = "" & v
  657. End If
  658. End Function
  659. Private Sub AddErr(msg)
  660. If Len(m_errs) > 0 Then
  661. m_errs = m_errs & Chr(30)
  662. End If
  663. m_errs = m_errs & msg
  664. End Sub
  665. Private Function ReqString(input, name, maxLen)
  666. Dim v
  667. ReqString = ""
  668. If Not input.Exists(name) Then
  669. AddErr name & " is required."
  670. Exit Function
  671. End If
  672. v = input.Item(name)
  673. If IsNull(v) Then
  674. AddErr name & " is required."
  675. Exit Function
  676. End If
  677. If VarType(v) <> vbString Then
  678. AddErr name & " must be a string."
  679. Exit Function
  680. End If
  681. v = Trim(v)
  682. If Len(v) = 0 Then
  683. AddErr name & " must not be empty."
  684. Exit Function
  685. End If
  686. If Len(v) > maxLen Then
  687. AddErr name & " must be at most " & maxLen & " characters."
  688. Exit Function
  689. End If
  690. ReqString = v
  691. End Function
  692. ' Optional string with a default when absent or null
  693. Private Function OptStringDefault(input, name, maxLen, dflt)
  694. Dim v
  695. OptStringDefault = dflt
  696. If Not input.Exists(name) Then
  697. Exit Function
  698. End If
  699. v = input.Item(name)
  700. If IsNull(v) Then
  701. Exit Function
  702. End If
  703. If VarType(v) <> vbString Then
  704. AddErr name & " must be a string."
  705. Exit Function
  706. End If
  707. If Len(v) > maxLen Then
  708. AddErr name & " must be at most " & maxLen & " characters."
  709. Exit Function
  710. End If
  711. OptStringDefault = v
  712. End Function
  713. ' Optional whole number in lo..hi with a default when absent or null
  714. Private Function OptInt(input, name, dflt, lo, hi)
  715. Dim v
  716. OptInt = dflt
  717. If Not input.Exists(name) Then
  718. Exit Function
  719. End If
  720. v = input.Item(name)
  721. If IsNull(v) Then
  722. Exit Function
  723. End If
  724. If VarType(v) <> vbDouble Then
  725. AddErr name & " must be a number."
  726. Exit Function
  727. End If
  728. If v <> Int(v) Or v < lo Or v > hi Then
  729. AddErr name & " must be a whole number between " & lo & " and " & hi & "."
  730. Exit Function
  731. End If
  732. OptInt = CLng(v)
  733. End Function
  734. Private Function IdListSql(input, name)
  735. Dim arr, i, out
  736. IdListSql = ""
  737. If Not input.HasRaw(name) Then
  738. If input.Exists(name) Then
  739. If Not IsNull(input.Item(name)) Then
  740. AddErr name & " must be an array of ids."
  741. End If
  742. End If
  743. Exit Function
  744. End If
  745. arr = JsonLite_ParseStringArray(input.Raw(name))
  746. If IsNull(arr) Then
  747. AddErr name & " must be an array of ids."
  748. Exit Function
  749. End If
  750. out = ""
  751. For i = 0 To UBound(arr)
  752. If Not Api_IsId(arr(i)) Then
  753. AddErr name & " must contain valid ids."
  754. Exit Function
  755. End If
  756. If Len(out) > 0 Then
  757. out = out & ","
  758. End If
  759. out = out & "'" & arr(i) & "'"
  760. Next
  761. If Len(out) = 0 Then
  762. AddErr name & " must not be empty when given."
  763. End If
  764. IdListSql = out
  765. End Function
  766. Private Function IntersectIds(allowed, requested)
  767. Dim a, i, out
  768. a = Split(allowed, ",")
  769. out = ""
  770. For i = 0 To UBound(a)
  771. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  772. If Len(out) > 0 Then
  773. out = out & ","
  774. End If
  775. out = out & a(i)
  776. End If
  777. Next
  778. IntersectIds = out
  779. End Function
  780. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  781. Public Sub Invoke(actionName, args)
  782. Select Case LCase(actionName)
  783. Case "assemble" : Assemble
  784. Case Else
  785. Err.Raise 438, "ApiContextController_Class", "Action '" & actionName & "' not found"
  786. End Select
  787. End Sub
  788. End Class
  789. Dim ApiContextController_Class__Singleton
  790. Function ApiContextController()
  791. If IsEmpty(ApiContextController_Class__Singleton) Then
  792. Set ApiContextController_Class__Singleton = New ApiContextController_Class
  793. End If
  794. Set ApiContextController = ApiContextController_Class__Singleton
  795. End Function
  796. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  797. Sub ApiContextController_Invoke(actionName, args)
  798. ApiContextController().Invoke actionName, args
  799. End Sub
  800. %>

Powered by TurnKey Linux.