Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

808 рядки
33KB

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

Powered by TurnKey Linux.