25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

845 satır
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
  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_dupes = 0
  198. m_unverifiedExcluded = 0
  199. policiesCapped = False
  200. now_ = Api_Now()
  201. If Len(allowed) > 0 Then
  202. '--- 1. policies: constraints and preferences, by scope ------------------
  203. sql = CtxMemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
  204. "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _
  205. "AND r.verification_status <> 'rejected' AND m.type IN ('constraint','preference') " & _
  206. "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)
  207. Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
  208. policyCount = 0
  209. Do While Not rs.EOF
  210. policyCount = policyCount + 1
  211. If policyCount > CTX_MAX_POLICIES Then
  212. policiesCapped = True
  213. Exit Do
  214. End If
  215. If "" & rs(2) = "constraint" Then
  216. AddMemory rs, CTX_CONSTRAINTS, vf, "full", 0
  217. ElseIf incPrefs Then
  218. AddMemory rs, CTX_PREFERENCES, vf, detail, 0
  219. End If
  220. rs.MoveNext
  221. Loop
  222. rs.Close
  223. '--- 2. memory matches (lexical, fused with semantic when configured) ----------
  224. If incDecisions Or incLessons Or incKnowledge Then
  225. Set ranker = New Ranker_Class
  226. ranker.Run "memory", fts, task, Api_TenantId, allowed
  227. NoteRanker ranker
  228. n = ranker.Count
  229. If n > 0 Then
  230. ReDim ids(n - 1)
  231. ReDim scores(n - 1)
  232. For i = 0 To n - 1
  233. ids(i) = ranker.IdAt(i)
  234. scores(i) = -ranker.ScoreAt(i)
  235. Next
  236. End If
  237. idList = IdSqlList(ids, n)
  238. If Len(idList) > 0 Then
  239. ' Read the canonical rows (closing the result set), then add them in rank order.
  240. sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
  241. "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _
  242. "AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')"
  243. Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
  244. Dim rowsTmp
  245. rowsTmp = Empty
  246. If Not rs.EOF Then
  247. rowsTmp = rs.GetRows()
  248. End If
  249. rs.Close
  250. If Not IsEmpty(rowsTmp) Then
  251. ' GetRows is (column, row); walk the ranks and pick the matching row
  252. For i = 0 To n - 1
  253. For j = 0 To UBound(rowsTmp, 2)
  254. If "" & rowsTmp(0, j) = ids(i) Then
  255. sec = TypeSection("" & rowsTmp(2, j))
  256. If sec = CTX_DECISIONS And Not incDecisions Then
  257. sec = -1
  258. ElseIf sec = CTX_LESSONS And Not incLessons Then
  259. sec = -1
  260. ElseIf sec = CTX_KNOWLEDGE And Not incKnowledge Then
  261. sec = -1
  262. End If
  263. If sec >= 0 Then
  264. AddMemoryRow rowsTmp, j, sec, vf, detail, -CDbl(scores(i))
  265. End If
  266. Exit For
  267. End If
  268. Next
  269. Next
  270. End If
  271. End If
  272. End If
  273. '--- 3. reference passages ------------------------------------------------
  274. If incRefs And maxRefs > 0 Then
  275. Set ranker = New Ranker_Class
  276. ranker.Run "chunk", fts, task, Api_TenantId, allowed
  277. NoteRanker ranker
  278. n = ranker.Count
  279. If n > 0 Then
  280. ReDim ids(n - 1)
  281. ReDim scores(n - 1)
  282. For i = 0 To n - 1
  283. ids(i) = ranker.IdAt(i)
  284. scores(i) = -ranker.ScoreAt(i)
  285. Next
  286. End If
  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, "chunk|" & ids(i) & "|" & CLng(chunkRows(2, j)) & "|" & JsonLite_Num(-CDbl(scores(i)))
  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. AddTel i
  352. End If
  353. Next
  354. warnings = ""
  355. If stateTok > 0 Then
  356. If used + stateTok <= budget Then
  357. used = used + stateTok
  358. Else
  359. stateJson = "null"
  360. omittedBudget = omittedBudget + 1
  361. AddWarning warnings, "working_state did not fit the budget and was left out; restore it with GET /sessions/{id}/state"
  362. End If
  363. End If
  364. For sec = CTX_PREFERENCES To CTX_SECTION_COUNT - 1
  365. If sec = CTX_PREFERENCES Then
  366. cap = 50
  367. ElseIf sec = CTX_REFERENCES Then
  368. cap = maxRefs
  369. Else
  370. cap = maxItems
  371. End If
  372. For i = 0 To m_cN - 1
  373. If m_cSec(i) = sec Then
  374. If cnt(sec) >= cap Then
  375. omittedLimit = omittedLimit + 1
  376. ElseIf used + m_cTok(i) > budget Then
  377. omittedBudget = omittedBudget + 1
  378. Else
  379. used = used + m_cTok(i)
  380. AppendTo outSec, cnt, sec, m_cJson(i)
  381. AddTel i
  382. End If
  383. End If
  384. Next
  385. Next
  386. complete = True
  387. If policiesCapped Then
  388. complete = False
  389. 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."
  390. End If
  391. truncated = (omittedBudget > 0)
  392. If omittedBudget > 0 Then
  393. AddWarning warnings, omittedBudget & " item(s) left out to fit max_context_tokens"
  394. End If
  395. If m_unverifiedExcluded > 0 Then
  396. AddWarning warnings, m_unverifiedExcluded & " unverified item(s) excluded; use verification_filter include_unverified to see them"
  397. End If
  398. If cnt(CTX_CONFLICTS) > 0 Then
  399. AddWarning warnings, cnt(CTX_CONFLICTS) & " disputed item(s) included under conflicts; do not rely on them without checking"
  400. End If
  401. If Len(allowed) = 0 Then
  402. AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty"
  403. End If
  404. If Len(m_rankWarning) > 0 Then
  405. AddWarning warnings, m_rankWarning
  406. End If
  407. ' Telemetry: the query id is returned so results can be rated with POST /feedback
  408. qid = Tel_NewQueryId()
  409. Tel_Record qid, "context", m_strategy, task, m_spec, t0
  410. out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""query_id"":" & JsonLite_Quote(qid) & ",""task"":" & JsonLite_Quote(task) & _
  411. ",""strategy"":" & JsonLite_Quote(m_strategy) & ",""format"":""structured"",""verification_filter"":" & JsonLite_Quote(vf) & ",""detail_level"":" & JsonLite_Quote(detail) & _
  412. ",""budget"":{""max_context_tokens"":" & budget & ",""used_tokens"":" & used & ",""counting_method"":""estimate_chars_div_4""" & _
  413. ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _
  414. ",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}"
  415. out = out & ",""constraints"":[" & outSec(CTX_CONSTRAINTS) & "]"
  416. If incState Then
  417. out = out & ",""working_state"":" & stateJson
  418. End If
  419. If incPrefs Then
  420. out = out & ",""preferences"":[" & outSec(CTX_PREFERENCES) & "]"
  421. End If
  422. out = out & ",""conflicts"":[" & outSec(CTX_CONFLICTS) & "]"
  423. If incDecisions Then
  424. out = out & ",""decisions"":[" & outSec(CTX_DECISIONS) & "]"
  425. End If
  426. If incLessons Then
  427. out = out & ",""lessons"":[" & outSec(CTX_LESSONS) & "]"
  428. End If
  429. If incKnowledge Then
  430. out = out & ",""knowledge"":[" & outSec(CTX_KNOWLEDGE) & "]"
  431. End If
  432. If incRefs Then
  433. out = out & ",""references"":[" & outSec(CTX_REFERENCES) & "]"
  434. End If
  435. If vf = "include_unverified" Then
  436. out = out & ",""unverified"":[" & outSec(CTX_UNVERIFIED) & "]"
  437. End If
  438. out = out & ",""warnings"":[" & warnings & "]}"
  439. Api_Audit "context.assemble", "context", "", "ok"
  440. Api_Send 200, out
  441. End Sub
  442. '===============================================================
  443. ' Helpers
  444. '===============================================================
  445. ' Columns relied on by AddMemory / AddMemoryRow:
  446. ' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance,
  447. ' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until
  448. ' Strategy/warning of the last ranking (hybrid unless semantic retrieval was unavailable for any section)
  449. Private Sub NoteRanker(r)
  450. If Len(r.Warning) > 0 Then
  451. m_rankWarning = r.Warning
  452. m_strategy = "lexical"
  453. ElseIf Len(m_rankWarning) = 0 Then
  454. m_strategy = r.Strategy
  455. End If
  456. End Sub
  457. Private Function CtxMemorySelect()
  458. CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _
  459. "r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _
  460. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
  461. End Function
  462. Private Function TypeSection(t)
  463. Select Case t
  464. Case "decision"
  465. TypeSection = CTX_DECISIONS
  466. Case "lesson"
  467. TypeSection = CTX_LESSONS
  468. Case Else
  469. TypeSection = CTX_KNOWLEDGE
  470. End Select
  471. End Function
  472. ' Copies one result-set row into an array and hands it to AddMemoryRow (single code path for both sources).
  473. Private Sub AddMemory(rs, sec, vf, detail, score)
  474. Dim row(14, 0), k
  475. For k = 0 To 14
  476. row(k, 0) = rs(k)
  477. Next
  478. AddMemoryRow row, 0, sec, vf, detail, score
  479. End Sub
  480. ' rows is GetRows-shaped (column, row). Sorts the memory into its section by verification state and dedupes by content.
  481. Private Sub AddMemoryRow(rows, j, sec, vf, detail, score)
  482. Dim st, key, json, target
  483. st = "" & rows(10, j)
  484. target = sec
  485. If st = "disputed" Then
  486. target = CTX_CONFLICTS
  487. ElseIf st <> "verified" Then
  488. If vf = "include_unverified" Then
  489. target = CTX_UNVERIFIED
  490. Else
  491. m_unverifiedExcluded = m_unverifiedExcluded + 1
  492. Exit Sub
  493. End If
  494. End If
  495. ' The stored content_hash also covers namespace, type and title, so the same text in two namespaces has two
  496. ' hashes. Dedupe on the normalized content instead.
  497. key = LCase(Trim("" & rows(6, j)))
  498. If InStr(m_seen, Chr(31) & key & Chr(31)) > 0 Then
  499. m_dupes = m_dupes + 1
  500. Exit Sub
  501. End If
  502. m_seen = m_seen & key & Chr(31)
  503. json = MemJson(rows, j, detail, score, st, (sec = CTX_CONSTRAINTS))
  504. AddCand target, json, m_lastTok, "memory|" & rows(0, j) & "|" & CLng(rows(3, j)) & "|" & TelScore(score)
  505. End Sub
  506. Private Function MemJson(rows, j, detail, score, st, isPolicy)
  507. Dim s, bodyText, trust
  508. If detail = "summary" Then
  509. If IsNull(rows(5, j)) Then
  510. bodyText = "" & rows(6, j)
  511. If Len(bodyText) > 240 Then
  512. bodyText = Left(bodyText, 240) & "..."
  513. End If
  514. Else
  515. bodyText = "" & rows(5, j)
  516. End If
  517. Else
  518. bodyText = "" & rows(6, j)
  519. End If
  520. m_lastTok = Tokens("" & rows(4, j) & vbLf & bodyText)
  521. Select Case st
  522. Case "verified"
  523. trust = "verified_memory"
  524. Case "disputed"
  525. trust = "disputed_memory"
  526. Case Else
  527. trust = "unverified_memory"
  528. End Select
  529. s = "{""id"":" & JsonLite_Quote("" & rows(0, j)) & ",""revision"":" & CLng(rows(3, j)) & ",""type"":" & JsonLite_Quote("" & rows(2, j)) & _
  530. ",""namespace_id"":" & JsonLite_Quote("" & rows(1, j)) & ",""title"":" & JsonLite_Quote("" & rows(4, j))
  531. If detail = "summary" Then
  532. s = s & ",""summary"":" & JsonLite_Quote(bodyText)
  533. Else
  534. s = s & ",""content"":" & JsonLite_Quote(bodyText)
  535. End If
  536. s = s & ",""verification_status"":" & JsonLite_Quote(st) & ",""content_trust"":" & JsonLite_Quote(trust)
  537. If isPolicy Then
  538. If st = "verified" Then
  539. s = s & ",""authority"":""policy"""
  540. End If
  541. End If
  542. s = s & ",""tags"":" & JRaw(rows(7, j), "[]") & ",""confidence"":" & JNum(rows(8, j)) & ",""importance"":" & JNum(rows(9, j))
  543. If score <> 0 Then
  544. s = s & ",""relevance_score"":" & JsonLite_Num(score)
  545. End If
  546. s = s & ",""valid_until"":" & JStr(rows(14, j)) & ",""provenance"":{""created_by"":" & JsonLite_Quote("" & rows(12, j)) & _
  547. ",""updated_at"":" & JsonLite_Quote("" & rows(13, j)) & "},""token_estimate"":" & m_lastTok & "}"
  548. MemJson = s
  549. End Function
  550. ' Chunk row columns: 0 id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end,
  551. ' 8 namespace id, 9 title, 10 source uri
  552. Private Function RefJson(rows, j, detail, score)
  553. Dim txt, s
  554. txt = "" & rows(4, j)
  555. If detail = "summary" Then
  556. If Len(txt) > 240 Then
  557. txt = Left(txt, 240) & "..."
  558. End If
  559. End If
  560. m_lastTok = Tokens(txt)
  561. s = "{""chunk_id"":" & JsonLite_Quote("" & rows(0, j)) & ",""document_id"":" & JsonLite_Quote("" & rows(1, j)) & _
  562. ",""document_title"":" & JsonLite_Quote("" & rows(9, j)) & ",""source_uri"":" & JStr(rows(10, j)) & _
  563. ",""document_revision"":" & CLng(rows(2, j)) & ",""ordinal"":" & CLng(rows(3, j)) & ",""heading_path"":" & JStr(rows(5, j)) & _
  564. ",""locator"":{""start"":" & CLng(rows(6, j)) & ",""end"":" & CLng(rows(7, j)) & "},""namespace_id"":" & JsonLite_Quote("" & rows(8, j)) & _
  565. ",""relevance_score"":" & JsonLite_Num(score) & ",""content"":" & JsonLite_Quote(txt) & _
  566. ",""content_trust"":""untrusted_reference"",""token_estimate"":" & m_lastTok & "}"
  567. RefJson = s
  568. End Function
  569. ' tel: "kind|id|revision|score" of the item, recorded for feedback if the item makes it into the briefing
  570. Private Sub AddCand(sec, json, tok, tel)
  571. If m_cN > UBound(m_cSec) Then
  572. ReDim Preserve m_cSec(m_cN * 2)
  573. ReDim Preserve m_cJson(m_cN * 2)
  574. ReDim Preserve m_cTok(m_cN * 2)
  575. ReDim Preserve m_cTel(m_cN * 2)
  576. End If
  577. m_cSec(m_cN) = sec
  578. m_cJson(m_cN) = json
  579. m_cTok(m_cN) = tok
  580. m_cTel(m_cN) = tel
  581. m_cN = m_cN + 1
  582. End Sub
  583. Private Sub AddTel(i)
  584. If Len(m_spec) > 0 Then
  585. m_spec = m_spec & Chr(30)
  586. End If
  587. m_spec = m_spec & m_cTel(i)
  588. End Sub
  589. ' Constraints and preferences are loaded by scope and have no similarity score
  590. Private Function TelScore(score)
  591. TelScore = "0"
  592. If IsNumeric(score) Then
  593. If Not IsEmpty(score) Then
  594. TelScore = JsonLite_Num(score)
  595. End If
  596. End If
  597. End Function
  598. Private Sub AppendTo(outSec, cnt, sec, json)
  599. If cnt(sec) > 0 Then
  600. outSec(sec) = outSec(sec) & ","
  601. End If
  602. outSec(sec) = outSec(sec) & json
  603. cnt(sec) = cnt(sec) + 1
  604. End Sub
  605. Private Sub AddWarning(warnings, text)
  606. If Len(warnings) > 0 Then
  607. warnings = warnings & ","
  608. End If
  609. warnings = warnings & JsonLite_Quote(text)
  610. End Sub
  611. ' Token estimate for included text: characters / 4, rounded up (declared as estimate_chars_div_4)
  612. Private Function Tokens(text)
  613. Tokens = Int((Len(text) + 3) / 4)
  614. End Function
  615. ' 'id1','id2' for the first n valid ids
  616. Private Function IdSqlList(ids, n)
  617. Dim i, out
  618. out = ""
  619. For i = 0 To n - 1
  620. If Api_IsId(ids(i)) Then
  621. If Len(out) > 0 Then
  622. out = out & ","
  623. End If
  624. out = out & "'" & ids(i) & "'"
  625. End If
  626. Next
  627. IdSqlList = out
  628. End Function
  629. Private Function JStr(v)
  630. If IsNull(v) Then
  631. JStr = "null"
  632. Else
  633. JStr = JsonLite_Quote("" & v)
  634. End If
  635. End Function
  636. Private Function JNum(v)
  637. If IsNull(v) Then
  638. JNum = "null"
  639. ElseIf Len("" & v) = 0 Then
  640. JNum = "null"
  641. Else
  642. JNum = JsonLite_Num(v)
  643. End If
  644. End Function
  645. Private Function JRaw(v, dflt)
  646. If IsNull(v) Then
  647. JRaw = dflt
  648. ElseIf Len("" & v) = 0 Then
  649. JRaw = dflt
  650. Else
  651. JRaw = "" & v
  652. End If
  653. End Function
  654. Private Sub AddErr(msg)
  655. If Len(m_errs) > 0 Then
  656. m_errs = m_errs & Chr(30)
  657. End If
  658. m_errs = m_errs & msg
  659. End Sub
  660. Private Function ReqString(input, name, maxLen)
  661. Dim v
  662. ReqString = ""
  663. If Not input.Exists(name) Then
  664. AddErr name & " is required."
  665. Exit Function
  666. End If
  667. v = input.Item(name)
  668. If IsNull(v) Then
  669. AddErr name & " is required."
  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. v = Trim(v)
  677. If Len(v) = 0 Then
  678. AddErr name & " must not be empty."
  679. Exit Function
  680. End If
  681. If Len(v) > maxLen Then
  682. AddErr name & " must be at most " & maxLen & " characters."
  683. Exit Function
  684. End If
  685. ReqString = v
  686. End Function
  687. ' Optional string with a default when absent or null
  688. Private Function OptStringDefault(input, name, maxLen, dflt)
  689. Dim v
  690. OptStringDefault = dflt
  691. If Not input.Exists(name) Then
  692. Exit Function
  693. End If
  694. v = input.Item(name)
  695. If IsNull(v) Then
  696. Exit Function
  697. End If
  698. If VarType(v) <> vbString Then
  699. AddErr name & " must be a string."
  700. Exit Function
  701. End If
  702. If Len(v) > maxLen Then
  703. AddErr name & " must be at most " & maxLen & " characters."
  704. Exit Function
  705. End If
  706. OptStringDefault = v
  707. End Function
  708. ' Optional whole number in lo..hi with a default when absent or null
  709. Private Function OptInt(input, name, dflt, lo, hi)
  710. Dim v
  711. OptInt = dflt
  712. If Not input.Exists(name) Then
  713. Exit Function
  714. End If
  715. v = input.Item(name)
  716. If IsNull(v) Then
  717. Exit Function
  718. End If
  719. If VarType(v) <> vbDouble Then
  720. AddErr name & " must be a number."
  721. Exit Function
  722. End If
  723. If v <> Int(v) Or v < lo Or v > hi Then
  724. AddErr name & " must be a whole number between " & lo & " and " & hi & "."
  725. Exit Function
  726. End If
  727. OptInt = CLng(v)
  728. End Function
  729. Private Function IdListSql(input, name)
  730. Dim arr, i, out
  731. IdListSql = ""
  732. If Not input.HasRaw(name) Then
  733. If input.Exists(name) Then
  734. If Not IsNull(input.Item(name)) Then
  735. AddErr name & " must be an array of ids."
  736. End If
  737. End If
  738. Exit Function
  739. End If
  740. arr = JsonLite_ParseStringArray(input.Raw(name))
  741. If IsNull(arr) Then
  742. AddErr name & " must be an array of ids."
  743. Exit Function
  744. End If
  745. out = ""
  746. For i = 0 To UBound(arr)
  747. If Not Api_IsId(arr(i)) Then
  748. AddErr name & " must contain valid ids."
  749. Exit Function
  750. End If
  751. If Len(out) > 0 Then
  752. out = out & ","
  753. End If
  754. out = out & "'" & arr(i) & "'"
  755. Next
  756. If Len(out) = 0 Then
  757. AddErr name & " must not be empty when given."
  758. End If
  759. IdListSql = out
  760. End Function
  761. Private Function IntersectIds(allowed, requested)
  762. Dim a, i, out
  763. a = Split(allowed, ",")
  764. out = ""
  765. For i = 0 To UBound(a)
  766. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  767. If Len(out) > 0 Then
  768. out = out & ","
  769. End If
  770. out = out & a(i)
  771. End If
  772. Next
  773. IntersectIds = out
  774. End Function
  775. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  776. Public Sub Invoke(actionName, args)
  777. Select Case LCase(actionName)
  778. Case "assemble" : Assemble
  779. Case Else
  780. Err.Raise 438, "ApiContextController_Class", "Action '" & actionName & "' not found"
  781. End Select
  782. End Sub
  783. End Class
  784. Dim ApiContextController_Class__Singleton
  785. Function ApiContextController()
  786. If IsEmpty(ApiContextController_Class__Singleton) Then
  787. Set ApiContextController_Class__Singleton = New ApiContextController_Class
  788. End If
  789. Set ApiContextController = ApiContextController_Class__Singleton
  790. End Function
  791. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  792. Sub ApiContextController_Invoke(actionName, args)
  793. ApiContextController().Invoke actionName, args
  794. End Sub
  795. %>

Powered by TurnKey Linux.