cgfixit

OpenClaw + RAG (Without SKYNET vibes ;)

Jan 31st, 2026 (edited)
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.81 KB | Software | 0 0
  1. ═══════════════════════════════════════════════════════════════════════════════
  2. OPENCLAW OFFLINE-FIRST WITH GATED FALLBACK
  3. (Production Flow - Feb 2026)
  4. v2 (refined)
  5. ═══════════════════════════════════════════════════════════════════════════════
  6.  
  7. ┌──────────────────┐
  8. │ User Query │
  9. │ (e.g., Veeam HA)│
  10. └────────┬─────────┘
  11. v
  12. ┌────────────────────────┐
  13. │ OpenClaw Controller │
  14. │ (Clawbot Framework) │
  15. │ Enforce YAML/JSON Rules│
  16. └────────────┬───────────┘
  17. ┌────────────v────────────┐
  18. │ Strong Prompt: │
  19. │ ALWAYS RAG FIRST │
  20. │ (Score ≥0.75) │
  21. └────────────┬────────────┘
  22. ┌──────────────────┴──────────────────┐
  23. │ │
  24. ┌─────────v──────────┐ ┌─────────────v────────┐
  25. │ MCP TOOL (Priority)│ │ FALLBACK PATH │
  26. │ Offline RAG │ │ (Gated) │
  27. │ rag_query.py │ │ │
  28. └─────────┬──────────┘ │ │
  29. │ │ │
  30. ┌───────────┴─────────┐ │ │
  31. │ │ │ │
  32. ┌───v────┐ ┌────v───┐ ┌───v─────┐ │
  33. │ Ollama │ │ ChromaDB│ │ Low Hit │ │
  34. │Embeddings Vault │ │ Rate │ │
  35. │nomic-embed .md Files (<0.75) │ │
  36. └───┬────┘ └────┬───┘ └──┬──────┘ │
  37. │ │ │ │
  38. └────────┬───────────┘ │ Miss or Low Conf │
  39. │ │ │
  40. v └──────────────────────┘
  41. ┌─────────────────┐ │
  42. │ Hit Rate ≥0.75? │ │
  43. └────────┬────────┘ │
  44. │ YES │
  45. v v
  46. ┌──────────────────┐ ┌───────────────────────┐
  47. │ LM Studio Synth │ │ Vault Miss + General │
  48. │ Response Gen │ │ Reasoning (Offline) │
  49. │ llama.cpp GGUF │ │ │
  50. └────────┬─────────┘ └───────────┬───────────┘
  51. │ │
  52. │ ┌──────────v──────────┐
  53. │ │ Ask "Online? (y/n)" │
  54. │ └──────────┬──────────┘
  55. │ │
  56. │ ┌────────────┴─────────┐
  57. │ │ │
  58. │ ┌─────v──┐ ┌───────v───┐
  59. │ │ YES │ │ NO/Retry │
  60. │ │ (User) │ │ (User) │
  61. │ └─────┬──┘ └───┬───────┘
  62. │ │ │
  63. │ ┌─────────v────────┐ │
  64. │ │ Online Fallback │ │
  65. │ │ Grok/Claude │ │
  66. │ │ OpenRouter/xAI │ │
  67. │ │ **RISK-GATED** │ │
  68. │ └─────────┬────────┘ │
  69. │ │ │
  70. └──────────┬───────┴──────────────┘
  71. ┌───────────v────────────┐
  72. │ Response to User │
  73. └───────────┬────────────┘
  74. ┌───────────────┴────────────────┐
  75. │ │
  76. ┌────v──┐ ┌───────v────┐
  77. │Logging │ │ Pite Store │
  78. │System │ │ Hit Rate │
  79. │(SQLite)│ │ Query Log │
  80. └────┬───┘ │ Patterns │
  81. │ └────────────┘
  82. v
  83. ┌──────────────────┐
  84. │ Query Patterns │
  85. │ Hit Rate Stats │
  86. │ Performance │
  87. │ Analysis │
  88. └──────────────────┘
  89.  
  90. ═══════════════════════════════════════════════════════════════════════════════
  91. PRIORITY ENFORCEMENT (Strong Prompt Forces this Flow)
  92. ═══════════════════════════════════════════════════════════════════════════════
  93.  
  94. 1️⃣ OFFLINE RAG FIRST (99% of queries)
  95. - Score ≥0.75: Return Chroma hit + LM Studio synthesis
  96. - Score <0.75: Trigger fallback gate (user confirmation required)
  97. - NEVER call online without explicit user approval
  98.  
  99. 2️⃣ USER CONFIRMATION GATE (Security Boundary)
  100. - "Vault miss. Query online for fallback? (y/n)"
  101. - Prevents silent data exfiltration
  102. - Logs all online-flagged queries to Pite
  103.  
  104. 3️⃣ ONLINE FALLBACK (Gated + Logged)
  105. - Only if user confirms "y"
  106. - Grok/Claude via OpenRouter
  107. - LM Studio can proxy (OPENAIAPIBASE=https://openrouter.ai/api/v1)
  108. - Logged to Pite for audit trail
  109.  
  110. 4️⃣ LOGGING & ANALYTICS (Pite Integration)
  111. - Hit Rate: % queries satisfied offline
  112. - Query Patterns: Common misses for vault expansion
  113. - Performance: Latency per phase (embed → search → synth)
  114.  
  115. ═══════════════════════════════════════════════════════════════════════════════
  116. IMPLEMENTATION SKELETON
  117. ═══════════════════════════════════════════════════════════════════════════════
  118.  
  119. config.yaml (OpenClaw):
  120. tools:
  121. - name: rag_query
  122. script: /path/to/rag_query.py
  123. description: "Offline RAG (ALWAYS called first per strong prompt)"
  124.  
  125. system_prompt: |
  126. CRITICAL: For EVERY user query:
  127. 1. Always call rag_query first (MCP tool)
  128. 2. If hit (score ≥0.75) → use vault context in response
  129. 3. If miss → state "not in vault" + general knowledge
  130. 4. NEVER initiate online fallback yourself
  131. 5. Wait for user confirmation on fallback prompt
  132.  
  133. rag_query.py (MCP Tool):
  134. def rag_query(query):
  135. embeddings = OllamaEmbeddings(model="nomic-embed-text")
  136. vectorstore = Chroma(persist_dir="./chromadb")
  137. docs = vectorstore.as_retriever(
  138. search_type="similarity_score_threshold",
  139. search_kwargs={"score_threshold": 0.75, "k": 5}
  140. ).invoke(query)
  141.  
  142. hit = len(docs) > 0
  143. log_to_pite(query, hit, len(docs)) # Analytics
  144.  
  145. return {
  146. "status": "hit" if hit else "miss",
  147. "chunks": [d.page_content for d in docs] if hit else [],
  148. "hit_count": len(docs)
  149. }
  150.  
  151. fallback_controller.py (OpenClaw Hook):
  152. def handle_fallback(query, rag_result):
  153. if rag_result["status"] == "miss":
  154. user_choice = input("⚠️ Vault miss. Query online? (y/n): ").strip()
  155. log_to_pite(query, "fallback_asked", user_choice)
  156.  
  157. if user_choice.lower() == "y":
  158. response = call_grok_or_claude(query) # OpenRouter
  159. log_to_pite(query, "fallback_used", response)
  160. return response
  161. else:
  162. return "Staying offline. Not in vault & user declined online."
  163.  
  164. pite_logging.py (SQLite + Analytics):
  165. def log_to_pite(query, hit_status, details):
  166. conn = sqlite3.connect("./pite_analytics.db")
  167. conn.execute("""
  168. INSERT INTO query_log (timestamp, query, hit_status, details)
  169. VALUES (datetime('now'), ?, ?, ?)
  170. """, (query, hit_status, json.dumps(details)))
  171. conn.commit()
  172.  
  173. # Dashboard query:
  174. SELECT COUNT(*) as total,
  175. SUM(CASE WHEN hit_status='hit' THEN 1 ELSE 0 END) as vault_hits,
  176. 100.0 * SUM(CASE WHEN hit_status='hit' THEN 1 ELSE 0 END) / COUNT(*) as hit_rate
  177. FROM query_log;
  178.  
  179. ═══════════════════════════════════════════════════════════════════════════════
  180. KEY METRICS TO TRACK (Pite Dashboard)
  181. ═══════════════════════════════════════════════════════════════════════════════
  182.  
  183. Hit Rate: % queries answered offline (goal: >85%)
  184. Miss Patterns: Gaps in vault (e.g., "no docs on X")
  185. Latency: Embed (50ms) → Search (10ms) → Synth (500ms) = ~560ms offline
  186. Online Calls: Count & reasons (audit trail for security)
  187. Score Dist: Histogram of similarity scores (refine threshold)
  188.  
  189. ═══════════════════════════════════════════════════════════════════════════════
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201. ╔═══════════════════════════════════════════════════════════════════╗
  202. ║ CHRIS'S OPENCLAW SETUP ║
  203. ║ (Tier 1: Strong Prompt) ║
  204. ╚═══════════════════════════════════════════════════════════════════╝
  205.  
  206. ┌─────────────────────────┐
  207. │ User Query (HTTP) │ ◄────── Browser/CLI/IDE Extension
  208. │ "Veeam HA best tips?" │
  209. └────────────┬────────────┘
  210. v
  211. ┌───────────────────────────────────────────────────────────────────┐
  212. │ OPENCLAW AGENT │
  213. │ ┌─────────────────────────────────────────────────────────┐ │
  214. │ │ System Prompt (config.yaml) │ │
  215. │ │ ┌─────────────────────────────────────────────────────┐ │ │
  216. │ │ │ CRITICAL: For ANY query, call rag_query first. │ │ │
  217. │ │ │ Vault info → answer from vault only. │ │ │
  218. │ │ │ No vault → state "not in vault" + general answer. │ │ │
  219. │ │ └─────────────────────────────────────────────────────┘ │ │
  220. │ └─────────────────────────────────────────────────────────┘ │
  221. │ │
  222. │ Controller Logic: Decides tools needed based on query │
  223. └───────────────────────┬────────────────────────────────────────────┘
  224. v (1. Query Analysis)
  225. ┌───────────────────────────────┐
  226. │ Should I use RAG? ──> YES │ (Strong prompt forces this)
  227. └───────────────┬───────────────┘
  228. v (2. MCP Tool Call)
  229. ┌───────────────────────────────────────────────────────────────────┐
  230. │ MCP TOOL INTERFACE │
  231. │ ┌─────────────────────────────────────────────────────────┐ │
  232. │ │ rag_script.py (Python Bridge) │ │
  233. │ │ • Receives user query as arg │ │
  234. │ │ • Calls embedding model │ │
  235. │ │ • Returns JSON with retrieved docs │ │
  236. │ └──────────────────────┬──────────────────────────────────┘ │
  237. └─────────────────────────┼─────────────────────────────────────────┘
  238. v (3. Generate Query Embedding)
  239. ┌───────────────────────────────────────────────────────────────────┐
  240. │ OLLAMA SERVICE (Localhost:11434) │
  241. │ ┌─────────────────────────────────────────────────────────┐ │
  242. │ │ Embedding Model: nomic-embed-text (768-dim vectors) │ │
  243. │ │ • Converts query → [0.234, -0.891, 0.445, ...] │ │
  244. │ │ • Cached in RAM for fast repeat queries │ │
  245. │ └──────────────────────┬──────────────────────────────────┘ │
  246. └─────────────────────────┼─────────────────────────────────────────┘
  247. v (4. Similarity Search)
  248. ┌───────────────────────────────────────────────────────────────────┐
  249. │ VECTOR DATABASE │
  250. │ ┌─────────────────────────────────────────────────────────┐ │
  251. │ │ ChromaDB (Persistent Disk Storage) │ │
  252. │ │ • Pre-indexed .md files from /vault/ │ │
  253. │ │ • Cosine similarity search against query embedding │ │
  254. │ │ • Returns top-k chunks (default k=5) │ │
  255. │ │ Collection: "veeam_docs" (or your collection name) │ │
  256. │ └──────────────────────┬──────────────────────────────────┘ │
  257. └─────────────────────────┼─────────────────────────────────────────┘
  258. v (5. Return Context to Agent)
  259. ┌───────────────────────────────────────────────────────────────────┐
  260. │ OPENCLAW AGENT │
  261. │ • Receives: "Top 3 matches from vault + relevance scores" │
  262. │ • Constructs prompt: [CONTEXT] {vault_chunks} [QUERY] {question} │
  263. │ • Sends to LLM for final answer synthesis │
  264. └───────────────────────┬────────────────────────────────────────────┘
  265. v (6. LLM Reasoning)
  266. ┌───────────────────────────────────────────────────────────────────┐
  267. │ LM STUDIO (Inference Engine) │
  268. │ ┌─────────────────────────────────────────────────────────┐ │
  269. │ │ Primary Model: Llama 3.1 8B (or Qwen 2.5 14B) │ │
  270. │ │ • Context: 8k-128k tokens (model dependent) │ │
  271. │ │ • Reads vault context + user query │ │
  272. │ │ • Generates final answer │ │
  273. │ │ Endpoint: http://localhost:1234/v1/chat/completions │ │
  274. │ └─────────────────────────────────────────────────────────┘ │
  275. │ │
  276. │ ┌─────────────────────────────────────────────────────────┐ │
  277. │ │ OPTIONAL: API Proxy (for external models) │ │
  278. │ │ • Grok API (xAI) ────> /v1/chat/completions │ │
  279. │ │ • Claude API (Anthropic) ────> /v1/chat/completions │ │
  280. │ │ LM Studio routes to external endpoints when configured │ │
  281. │ └─────────────────────────────────────────────────────────┘ │
  282. └───────────────────────┬────────────────────────────────────────────┘
  283. v (7. Response Assembly)
  284. ┌───────────────────────────────────────────────────────────────────┐
  285. │ OPENCLAW AGENT │
  286. │ • Final answer from LLM │
  287. │ • Formats response with sources/citations │
  288. │ • Returns to user interface │
  289. └───────────────────────┬────────────────────────────────────────────┘
  290. v (8. Display)
  291. ┌─────────────────────────┐
  292. │ User Interface Output │
  293. │ ┌───────────────────┐ │
  294. │ │ Answer: Based on │ │
  295. │ │ vault doc X... │ │
  296. │ │ │ │
  297. │ │ Sources: │ │
  298. │ │ - veeam_ha.md │ │
  299. │ └───────────────────┘ │
  300. └─────────────────────────┘
  301.  
  302.  
  303. ╔═══════════════════════════════════════════════════════════════════╗
  304. ║ DATA FLOW SUMMARY ║
  305. ╠═══════════════════════════════════════════════════════════════════╣
  306. ║ 1. Query → OpenClaw Agent (strong prompt enforces RAG call) ║
  307. ║ 2. Agent → MCP Tool (rag_script.py) ║
  308. ║ 3. Script → Ollama (embedding generation, cached in RAM) ║
  309. ║ 4. Embedding → ChromaDB (similarity search on .md index) ║
  310. ║ 5. Results → Agent (context chunks returned) ║
  311. ║ 6. Agent → LM Studio (prompt + context for reasoning) ║
  312. ║ 7. LM Studio → Agent (synthesized answer) ║
  313. ║ 8. Agent → User (formatted response with sources) ║
  314. ╚═══════════════════════════════════════════════════════════════════╝
  315.  
  316.  
  317. ╔═══════════════════════════════════════════════════════════════════╗
  318. ║ KEY COMPONENTS ║
  319. ╠═══════════════════════════════════════════════════════════════════╣
  320. ║ OpenClaw Agent │ Orchestration layer (Node/TS + MCP protocol) ║
  321. ║ LM Studio │ LLM inference (local + optional API proxy) ║
  322. ║ Ollama │ Embedding model service (nomic-embed-text) ║
  323. ║ ChromaDB │ Vector store (persistent, indexed .md files) ║
  324. ║ rag_script.py │ Bridge: query → embedding → search → results ║
  325. ║ config.yaml │ System prompt (CRITICAL RAG instruction) ║
  326. ║ /vault/*.md │ Your knowledge base (pre-indexed) ║
  327. ╚═══════════════════════════════════════════════════════════════════╝
  328.  
  329. NOTES:
  330. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  331. • All processing 100% local except optional Grok/Claude API calls
  332. • Ollama embedding model stays resident in RAM (fast repeated queries)
  333. • ChromaDB index built once, queried many times (no re-indexing needed)
  334. • Strong prompt = 85-95% RAG reliability without pre-processor complexity
  335. • LM Studio can hot-swap models (Llama/Qwen/etc.) without code changes
  336. • MCP protocol = language-agnostic tool interface (Python/JS/Rust/etc.)
  337.  
  338. https://www.perplexity.ai/search/whats-the-deal-with-clawbot-mo-6nnbZds4SZmkO8j78nTkMg#16
  339. https://cgfixit.com/livecode
Advertisement
Add Comment
Please, Sign In to add comment