Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

817 lines
34KB

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

Powered by TurnKey Linux.