<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Martin Schaer</title>
    <description>The latest articles on DEV Community by Martin Schaer (@martinschaer).</description>
    <link>https://dev.to/martinschaer</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3977858%2F2155aa8e-e361-41f5-8749-3a0e838519ed.jpg</url>
      <title>DEV Community: Martin Schaer</title>
      <link>https://dev.to/martinschaer</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/martinschaer"/>
    <language>en</language>
    <item>
      <title>How to add agent memory to an agent loop with SurrealDB: hybrid search, RRF and decay</title>
      <dc:creator>Martin Schaer</dc:creator>
      <pubDate>Tue, 24 Nov 2026 12:44:09 +0000</pubDate>
      <link>https://dev.to/surrealdb/how-to-add-agent-memory-to-an-agent-loop-with-surrealdb-hybrid-search-rrf-and-decay-j66</link>
      <guid>https://dev.to/surrealdb/how-to-add-agent-memory-to-an-agent-loop-with-surrealdb-hybrid-search-rrf-and-decay-j66</guid>
      <description>&lt;p&gt;Agent memory for a coding agent loop is a table of lessons, decisions and conventions that the agent reads before it starts a task and writes to when it finishes. In SurrealDB, recall combines vector search and full-text search with &lt;code&gt;search::rrf&lt;/code&gt;, then weights each hit by importance and decay, so stale memories fade and the useful ones stay.&lt;/p&gt;

&lt;p&gt;This is part 2. &lt;a href="https://surrealdb.com/blog/how-to-build-an-agent-loop-with-surrealdb-a-task-graph-for-agents" rel="noopener noreferrer"&gt;Part 1&lt;/a&gt; built the loop itself: a task graph with a ready queue, atomic claims and a human review gate. Here we give that loop a memory.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why does an agent loop need memory?
&lt;/h2&gt;

&lt;p&gt;Without memory, every task starts from zero. The agent that fixed a flaky test on Monday meets the same flaky test on Thursday and spends the same tokens working it out again. The team's conventions live in a document the agent may or may not have been shown.&lt;/p&gt;

&lt;p&gt;Memory fixes that, and it brings its own risk. A memory store that only grows becomes a pile of outdated advice, and an agent that trusts a year-old lesson about Node 18 is worse than an agent with no memory at all. So the design question is less "how do we store it?" and more "how do we decide what to trust?". That is what the rest of this post is about, and it is the part to bring to your team: &lt;strong&gt;importance, decay, expiry and replacement&lt;/strong&gt; are product decisions as much as technical ones.&lt;/p&gt;

&lt;h2&gt;
  
  
  What should a coding agent remember?
&lt;/h2&gt;

&lt;p&gt;I split memory into four kinds, because they age differently:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Kind&lt;/th&gt;
&lt;th&gt;Example&lt;/th&gt;
&lt;th&gt;Half-life&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;convention&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;"Every schema change ships as a migration file."&lt;/td&gt;
&lt;td&gt;never decays&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;decision&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;"Saved searches store filters as JSON, so the interface can version them."&lt;/td&gt;
&lt;td&gt;180 days&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;lesson&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;"ECONNRESET from staging means the proxy idle timeout was hit."&lt;/td&gt;
&lt;td&gt;90 days&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;episode&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;"Run on the docs task: regenerate the API docs after a schema change."&lt;/td&gt;
&lt;td&gt;14 days, expires after 30&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Conventions are rules, so they stay. Decisions last a while. Lessons are most useful soon after they are learned and get less certain as the code changes. Episodes are a diary: they are good for a few weeks and then they are noise. These half-lives are starting points I picked, not measured values, so expect to tune them on your own project.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do you model a memory?
&lt;/h2&gt;

&lt;p&gt;One table, linked to the &lt;code&gt;task&lt;/code&gt; table from part 1. The &lt;code&gt;source&lt;/code&gt; field records which task taught the agent the lesson, so you can always trace a memory back to the work that produced it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5pzckisieqh7phfwralr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5pzckisieqh7phfwralr.png" alt="Schema diagram of the memory and task tables, linked by source" width="800" height="559"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The full definition is in the &lt;a href="https://gist.github.com/martinschaer/3f4fb6789196db5c9b4b31f9a81821c1" rel="noopener noreferrer"&gt;schema.surql gist&lt;/a&gt;. The fields that turn a document table into memory:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Field&lt;/th&gt;
&lt;th&gt;What it does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;importance&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;How much the memory counts, from 0 to 1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;last_accessed&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Resets the decay clock each time the memory is used&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;recalls&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;How often it has been used&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;expires_at&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Hard expiry. Episodes get &lt;code&gt;created_at + 30d&lt;/code&gt; by default&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;superseded_by&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Points at the memory that replaced this one&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;scope&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;global&lt;/code&gt;, or a repo, so one project's lessons stay out of another&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Two indexes do the searching. A full-text index with a BM25 ranking, and an HNSW vector index:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DEFINE INDEX memory_fts ON memory FIELDS content FULLTEXT ANALYZER memory_text BM25;
DEFINE INDEX memory_vec ON memory FIELDS embedding HNSW DIMENSION 4 DIST COSINE TYPE F32;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The embeddings in the &lt;a href="https://gist.github.com/martinschaer/5c87a809eb1886ee82dd6838a50ec57d" rel="noopener noreferrer"&gt;seed.surql gist&lt;/a&gt; are hand-made 4-dimensional vectors, with axes for tests, database, deploy and interface, so the numbers stay readable. With a real embedding model you change &lt;code&gt;DIMENSION&lt;/code&gt; and nothing else.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why use both vector and full-text search?
&lt;/h2&gt;

&lt;p&gt;Each one misses something the other finds. Say the agent is debugging &lt;code&gt;ECONNRESET&lt;/code&gt; errors on the staging API. Its embedding points at the deploy and infrastructure axis.&lt;/p&gt;

&lt;p&gt;Vector search alone finds the right area, but the memory we want is third:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT id, vector::distance::knn() AS distance FROM memory
    WHERE embedding &amp;lt;|5, 40|&amp;gt; $vec;
-- memory:conv_branch      0.0077
-- memory:lesson_node      0.0090
-- memory:lesson_econnreset 0.0116
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Full-text search alone nails the exact error code, but it only works when the words match. A query for "connection dropped" returns nothing (I ran it):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT id, search::score(0) AS score FROM memory
    WHERE content @0,OR@ 'ECONNRESET' ORDER BY score DESC LIMIT 5;
-- memory:lesson_econnreset  1.708
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Code and error messages are full of exact tokens, and agents describe situations in loose language. You want both.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does search::rrf merge them?
&lt;/h2&gt;

&lt;p&gt;Reciprocal rank fusion (RRF) merges ranked lists by position, so you never have to compare a vector distance with a BM25 score. Each list gives a memory &lt;code&gt;1 / (k + rank)&lt;/code&gt;, and the scores add up. SurrealQL has it built in as &lt;code&gt;search::rrf&lt;/code&gt;, which takes the lists, a limit and &lt;code&gt;k&lt;/code&gt; (60 is the usual value):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LET $v = SELECT id, vector::distance::knn() AS distance FROM memory WHERE embedding &amp;lt;|20, 40|&amp;gt; $vec;
LET $f = SELECT id, search::score(0) AS score FROM memory WHERE content @0,OR@ 'ECONNRESET' ORDER BY score DESC LIMIT 20;
RETURN search::rrf([$v, $f], 5, 60);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
  { id: memory:lesson_econnreset, rrf_score: 0.0323 },  -- 3rd in vectors, 1st in full-text
  { id: memory:conv_branch,       rrf_score: 0.0164 },
  { id: memory:lesson_node,       rrf_score: 0.0161 },
  ...
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;lesson_econnreset&lt;/code&gt; was third by vector and first by full-text: &lt;code&gt;1/63 + 1/61 = 0.0323&lt;/code&gt;, and it now leads by a wide margin, because it is near the top of both lists. The others appear in one list each.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do importance and decay change the ranking?
&lt;/h2&gt;

&lt;p&gt;Fusion tells you what is relevant. It doesn't tell you what is still true or worth acting on. So the recall function multiplies the fused score by the memory's current strength:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;score = rrf_score × strength
strength = importance × 0.5 ^ (days since last used ÷ half-life)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I multiply instead of adding because the RRF score is tiny (around 0.03) and a weighted sum would let importance drown it. Multiplying keeps relevance in charge and lets strength scale it up or down. Conventions skip the decay term, so their strength is their importance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RETURN fn::strength(memory:lesson_node, $now);       -- 0.0406  (importance 0.8, last used over a year ago)
RETURN fn::strength(memory:conv_migrations, $now);   -- 0.9     (conventions never decay)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The recall function does the whole job: both searches, fusion, then strength. Memories from other repos, replaced memories and expired memories never appear. This is what the agent sees before it starts the flaky-tests task:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RETURN fn::recall('repo:saved-searches', 'flaky tests CI', [0.95, 0.25, 0.1, 0.1], 4, $now);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;kind&lt;/th&gt;
&lt;th&gt;rrf_score&lt;/th&gt;
&lt;th&gt;strength&lt;/th&gt;
&lt;th&gt;score&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;lesson_flaky&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;lesson&lt;/td&gt;
&lt;td&gt;0.0328&lt;/td&gt;
&lt;td&gt;0.616&lt;/td&gt;
&lt;td&gt;0.0202&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;conv_migrations&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;convention&lt;/td&gt;
&lt;td&gt;0.0152&lt;/td&gt;
&lt;td&gt;0.900&lt;/td&gt;
&lt;td&gt;0.0136&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;conv_branch&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;convention&lt;/td&gt;
&lt;td&gt;0.0149&lt;/td&gt;
&lt;td&gt;0.600&lt;/td&gt;
&lt;td&gt;0.0090&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;decision_filters&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;decision&lt;/td&gt;
&lt;td&gt;0.0154&lt;/td&gt;
&lt;td&gt;0.509&lt;/td&gt;
&lt;td&gt;0.0078&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Only the first row is a strong match. The store has nine memories, so the other three are filler that every search returns at this size. In a real store, more relevant memories would take their place. The old "just retry three times" lesson matches the query too, but a newer lesson replaced it, so it isn't listed (more on that below). &lt;code&gt;$now&lt;/code&gt; is pinned in these examples so you get the same numbers. In production, leave it out and the functions use &lt;code&gt;time::now()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do memories expire, get replaced and get forgotten?
&lt;/h2&gt;

&lt;p&gt;Four mechanisms, all plain fields and a &lt;code&gt;WHERE&lt;/code&gt; clause:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Expiry.&lt;/strong&gt; Episodes get &lt;code&gt;expires_at&lt;/code&gt; from a field default, and recall skips anything past it&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Replacement.&lt;/strong&gt; &lt;code&gt;fn::remember&lt;/code&gt; takes a &lt;code&gt;$supersedes&lt;/code&gt; argument. The old memory stays for the record, with &lt;code&gt;superseded_by&lt;/code&gt; set, and recall skips it&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reinforcement.&lt;/strong&gt; &lt;code&gt;fn::touch&lt;/code&gt; resets &lt;code&gt;last_accessed&lt;/code&gt; and adds one to &lt;code&gt;recalls&lt;/code&gt;. A memory the agent keeps using stays strong&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Forgetting.&lt;/strong&gt; &lt;code&gt;fn::forget&lt;/code&gt; deletes what has expired and what has decayed below a floor (5% strength by default), except memories that were superseded
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Learn something new that replaces an old lesson
RETURN fn::remember('global', 'lesson',
    'Node 20 is now the minimum on CI. Node 22 is the target for next quarter.',
    [0.2, 0.0, 0.8, 0.0], 0.8, NONE, memory:lesson_node);

-- Clean up
RETURN fn::forget($now, NONE);
-- [ memory:episode_lint ]   (expired). lesson_node is superseded, so it stays as history
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;fn::forget&lt;/code&gt; leaves superseded memories alone, so &lt;code&gt;lesson_node&lt;/code&gt; stays as history. Replacing, rather than overwriting, is deliberate: when an agent acts on a memory and gets it wrong, you want to see what it believed at the time.&lt;/p&gt;

&lt;h2&gt;
  
  
  What happens when the store grows?
&lt;/h2&gt;

&lt;p&gt;Filters decide whether the vector side of recall stays correct. The scope and &lt;code&gt;superseded_by&lt;/code&gt; conditions sit in the same &lt;code&gt;WHERE&lt;/code&gt; as the KNN operator, so SurrealDB pushes them into the index walk instead of applying them to a list the walk already chose. I checked it on v4.0.1 with 300 memories from another repo, all nearer to the query than anything in this repo's scope: the vector side still returned every eligible memory for this scope. I wrote about how this works, and how it fails, in &lt;a href="https://surrealdb.com/blog/why-does-my-vector-search-return-nothing-when-i-add-a-filter" rel="noopener noreferrer"&gt;Why does my vector search return nothing when I add a filter?&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The expiry test is the exception. The &lt;code&gt;expires_at = NONE OR expires_at &amp;gt; $t&lt;/code&gt; condition did not push down when I combined it with the scope filter, so recall applies it to the 20 candidates afterwards. That means expired memories hold a candidate slot until &lt;code&gt;fn::forget&lt;/code&gt; removes them, so run it on a schedule.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does the memory plug into the loop?
&lt;/h2&gt;

&lt;p&gt;Two additions to the loop from part 1: recall after claiming a task, and remember before handing it to review. I ran this against both sets of seed data, with a script approving each task in review. It completed all seven tasks and wrote seven new lessons. The setup is the same as part 1 (&lt;code&gt;db&lt;/code&gt;, signed in, &lt;code&gt;use("agents", "loop")&lt;/code&gt;), plus &lt;code&gt;SCOPE = "repo:saved-searches"&lt;/code&gt;. &lt;code&gt;embed&lt;/code&gt; is where your embedding model goes (mine was a toy that counts four keywords), and &lt;code&gt;do_work&lt;/code&gt; is where your LLM goes, with the memories in its prompt.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;claimed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"RETURN fn::claim('agent-1', NONE)"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;task&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;claimed&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;claimed&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;memories&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"RETURN fn::recall($scope, $text, $vec, 3, NONE)"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"scope"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;SCOPE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"text"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"vec"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;embed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"fn::touch($ids, NONE)"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"ids"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;memories&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;lesson&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;do_work&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;memories&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"fn::remember($scope, 'lesson', $lesson, $vec, 0.6, $source, NONE)"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"scope"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;SCOPE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"lesson"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;lesson&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"vec"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;embed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lesson&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"source"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"UPDATE $id SET notes += { at: time::now(), by: 'agent-1', text: $text }, status = 'review'"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"text"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SELECT id FROM task WHERE status IN ['todo', 'in_progress', 'review']"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;break&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The loop still has no ranking logic. Recall is one function call, and swapping the model, the weights or the half-lives never touches the agent code.&lt;/p&gt;

&lt;h2&gt;
  
  
  What should you tune first?
&lt;/h2&gt;

&lt;p&gt;A few things I'd look at before trusting this in production, none of which I have tuned yet:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The full-text query.&lt;/strong&gt; &lt;code&gt;@0,OR@&lt;/code&gt; matches any term, so common words add noise. Pass keywords rather than a whole sentence, or add a stop-word step in the agent&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Half-lives.&lt;/strong&gt; Start from the table above, then look at which memories the agent actually used and which it ignored&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What counts as a lesson.&lt;/strong&gt; Let the agent write memories, and let a person promote the good ones to &lt;code&gt;convention&lt;/code&gt;. That fits the review gate from part 1&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Embeddings.&lt;/strong&gt; Hand-made vectors are for reading. A real model changes the distances, so re-check the candidate count (the &lt;code&gt;20&lt;/code&gt; in &lt;code&gt;fn::recall&lt;/code&gt;) and consider a distance cutoff, so weak vector matches don't fill the tail&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All the queries above are in the &lt;a href="https://gist.github.com/martinschaer/8550e03e9b99905ec9b34c0b475aff03" rel="noopener noreferrer"&gt;queries.surql gist&lt;/a&gt;, in order. Load part 1's schema and seed first, then these three files, into the same database. The queries file shares &lt;code&gt;$now&lt;/code&gt; and &lt;code&gt;$vec&lt;/code&gt; between statements, so send it as one request (the header of each file has the command). I ran everything on SurrealDB v4.0.1 on 23 November 2026.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Give a coding agent four kinds of memory: conventions, decisions, lessons and episodes, each with its own half-life&lt;/li&gt;
&lt;li&gt;Search by vector and by full-text, and merge the ranked lists with &lt;code&gt;search::rrf&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Multiply the fused score by strength (importance with decay), so stale advice fades&lt;/li&gt;
&lt;li&gt;Expire episodes, replace outdated lessons instead of overwriting them, and forget what has decayed&lt;/li&gt;
&lt;li&gt;Reinforce what gets used by resetting &lt;code&gt;last_accessed&lt;/code&gt; on recall&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Get started
&lt;/h2&gt;

&lt;p&gt;Want to try it? Load the two parts into a free instance and point your agent at &lt;code&gt;fn::recall&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/cloud" rel="noopener noreferrer"&gt;Create a free cloud instance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/docs" rel="noopener noreferrer"&gt;Start building&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://discord.gg/surrealdb" rel="noopener noreferrer"&gt;Join our Discord server&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>agents</category>
    </item>
    <item>
      <title>How to build an agent loop with SurrealDB: a task graph for AI agents</title>
      <dc:creator>Martin Schaer</dc:creator>
      <pubDate>Tue, 24 Nov 2026 12:39:45 +0000</pubDate>
      <link>https://dev.to/surrealdb/how-to-build-an-agent-loop-with-surrealdb-a-task-graph-for-ai-agents-4e1b</link>
      <guid>https://dev.to/surrealdb/how-to-build-an-agent-loop-with-surrealdb-a-task-graph-for-ai-agents-4e1b</guid>
      <description>&lt;p&gt;An agent loop is a cycle where an AI agent picks up a task, does the work, records the result and asks for the next task, until nothing is left. To run one safely you need a shared task list that knows what depends on what. In SurrealDB that list is a graph, and the database itself enforces the rules.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why should you care about agent loops?
&lt;/h2&gt;

&lt;p&gt;A single prompt gets you a single answer. An agent loop gets you a finished piece of work: a feature specified, built, tested, documented and released, with agents doing the steps and people approving the ones that matter.&lt;/p&gt;

&lt;p&gt;If you lead engineering, AI transformation or a product organisation, this is the difference between a demo and something you can put into a process. A loop is only as good as the thing that keeps it organised. Four questions decide whether you can trust it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Who is working on what?&lt;/strong&gt; Several agents can run in parallel without two of them doing the same job.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What can start now?&lt;/strong&gt; Work only begins when everything it depends on is finished.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What happened?&lt;/strong&gt; Every step leaves a record you can read later.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Who approved it?&lt;/strong&gt; Agents stop at a review gate, and a person moves the work on.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You don't need to read the SQL to care about those four answers. If you're not hands-on, share the rest of this article with the team who would build it. It is written for them.&lt;/p&gt;

&lt;h2&gt;
  
  
  What does an agent loop need from a database?
&lt;/h2&gt;

&lt;p&gt;The loop itself is small: claim a task, work, report, repeat. Everything that makes it reliable lives in the task list. I keep that list in SurrealDB because the pieces fit in one place:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tasks and their dependencies are a graph (a DAG, a directed acyclic graph), so "what is ready?" and "what slips if this slips?" are queries&lt;/li&gt;
&lt;li&gt;Rules like "no cycles" and "no starting blocked work" are database events, so no prompt has to remember them&lt;/li&gt;
&lt;li&gt;Claiming a task is a single write, so agents can't take the same one&lt;/li&gt;
&lt;li&gt;The progress log lives on the task, so the audit trail and the work item are one record&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Keeping it simple to get started, this post uses a single table. The same model grows into agents, runs and artefacts as you need them.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do you model tasks and dependencies?
&lt;/h2&gt;

&lt;p&gt;A task has a status, a priority, an optional assignee, a progress log, and a list of &lt;code&gt;blockers&lt;/code&gt;: the tasks that must finish first. The edges point at prerequisites, so a task's blockers are its parents in the dependency graph.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnl3t01cxen5lln9rl6n0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnl3t01cxen5lln9rl6n0.png" alt="Schema diagram of the task table, with blockers pointing back at task" width="800" height="1042"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The full definition is in the &lt;a href="https://gist.github.com/martinschaer/6bef746bd5b1f0b0975365853373e0c6" rel="noopener noreferrer"&gt;schema.surql gist&lt;/a&gt;. The part that does the work is one field:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DEFINE FIELD blockers ON task TYPE array&amp;lt;record&amp;lt;task&amp;gt;&amp;gt; DEFAULT []
    REFERENCE ON DELETE REJECT;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;REFERENCE&lt;/code&gt; makes the link two-way. &lt;code&gt;task:release.blockers&lt;/code&gt; lists what the release waits on, and &lt;code&gt;task:api&amp;lt;~task&lt;/code&gt; lists what the API blocks, without defining a second field. &lt;code&gt;ON DELETE REJECT&lt;/code&gt; stops anyone deleting a task that others still depend on.&lt;/p&gt;

&lt;p&gt;The &lt;a href="https://gist.github.com/martinschaer/75c6cb8db36d1ff902e98e270b2b17ad" rel="noopener noreferrer"&gt;seed.surql gist&lt;/a&gt; loads a small project, shipping a "saved searches" feature. The API and the UI both wait for the data model, the tests wait for both, and the release waits for the tests and the docs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spec → data_model → api ─┬→ tests ─┐
                   └→ ui ┘         ├→ release
                      api → docs ──┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How does an agent pick its next task?
&lt;/h2&gt;

&lt;p&gt;It asks for the ready queue: &lt;code&gt;todo&lt;/code&gt; tasks whose blockers are all &lt;code&gt;done&lt;/code&gt; or &lt;code&gt;cancelled&lt;/code&gt;, most urgent first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DEFINE FUNCTION fn::ready() {
    RETURN SELECT * FROM task
        WHERE status = 'todo'
        AND array::len(blockers[WHERE !(status INSIDE ['done', 'cancelled'])]) = 0
        ORDER BY priority ASC, created_at ASC;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the seed data, only the spec is ready:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT id, title, priority FROM fn::ready();
-- [{ id: task:spec, priority: 0, title: 'Write the spec for saved searches' }]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The queue is a query, not a table you keep in sync. When a blocker finishes, the next call to &lt;code&gt;fn::ready()&lt;/code&gt; already includes whatever it unlocked.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do agents avoid taking the same task?
&lt;/h2&gt;

&lt;p&gt;They claim it. &lt;code&gt;fn::claim&lt;/code&gt; picks the top ready task (or a specific one) and flips it to &lt;code&gt;in_progress&lt;/code&gt; in a single statement, and only if it is still &lt;code&gt;todo&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RETURN fn::claim('agent-1', NONE);        -- returns the spec, now in_progress
RETURN fn::claim('agent-2', task:spec);   -- returns NONE: it is already taken
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I also tried it under load, on v4.0.1 with a single in-memory node, on 23 November 2026. Eight connections claimed the same task at once, three times over. Each time exactly one claim returned the task and the other seven returned &lt;code&gt;NONE&lt;/code&gt;. A &lt;code&gt;NONE&lt;/code&gt; on its own doesn't mean the work is done, so a loop should stop only when the ready queue is empty and no task is still open.&lt;/p&gt;

&lt;h2&gt;
  
  
  What stops an agent from breaking the rules?
&lt;/h2&gt;

&lt;p&gt;Two events on the table. The first keeps the graph acyclic: after a change to &lt;code&gt;blockers&lt;/code&gt;, a task may not appear in its own chain of prerequisites. The second refuses to start or finish work that still has open blockers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DEFINE EVENT task_unblocked ON task
    WHEN $event INSIDE ['CREATE', 'UPDATE'] AND $after.status INSIDE ['in_progress', 'review', 'done'] THEN {
        IF array::len($after.blockers[WHERE !(status INSIDE ['done', 'cancelled'])]) &amp;gt; 0 {
            THROW &amp;lt;string&amp;gt;$after.id + ' has open blockers';
        };
    };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An agent that tries to skip ahead gets an error instead of a half-built release:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UPDATE task:release SET status = 'in_progress';
-- Error while processing event task_unblocked: ... task:release has open blockers

UPDATE task:spec SET blockers = [task:release];
-- Error while processing event task_acyclic: ... blockers of task:spec form a cycle
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the point I'd make to anyone building agents: put the rules in the database, not in the prompt. A prompt is a request. An event is a guarantee, for every agent, written in any framework.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does a person stay in the loop?
&lt;/h2&gt;

&lt;p&gt;Agents move a task to &lt;code&gt;review&lt;/code&gt; and stop. A task in review still blocks its dependents, so nothing downstream starts until a person approves it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;UPDATE task:spec SET notes += { at: time::now(), by: 'agent-1', text: 'Spec drafted, 3 open questions listed' };
UPDATE task:spec SET status = 'review';
SELECT id FROM fn::ready();                 -- []  nothing new, the spec is waiting for a human

UPDATE task:spec SET status = 'done', notes += { at: time::now(), by: 'martin', text: 'Approved' };
SELECT id FROM fn::ready();                 -- [{ id: task:data_model }]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;notes&lt;/code&gt; field is the audit trail: who did what, and when. Approving the spec is what unblocked the data model. After that task is done, the API and the UI become ready together, so two agents can work in parallel.&lt;/p&gt;

&lt;h2&gt;
  
  
  What does the loop look like in code?
&lt;/h2&gt;

&lt;p&gt;Here is a sketch with the Python SDK. I ran it against the seed data, with a script approving each task in review, and it worked through all seven tasks to &lt;code&gt;done&lt;/code&gt;. &lt;code&gt;do_work&lt;/code&gt; is where your model and tools go.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;surrealdb&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Surreal&lt;/span&gt;

&lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Surreal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ws://127.0.0.1:8000/rpc"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;signin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"username"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"root"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"password"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"root"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"agents"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"loop"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;do_work&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;                      &lt;span class="c1"&gt;# call your LLM or tools here&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"finished: {task['title']}"&lt;/span&gt;

&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;claimed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"RETURN fn::claim('agent-1', NONE)"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;task&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;claimed&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;claimed&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"UPDATE $id SET notes += { at: time::now(), by: 'agent-1', text: $text }, status = 'review'"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"text"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;do_work&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SELECT id FROM task WHERE status IN ['todo', 'in_progress', 'review']"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;break&lt;/span&gt;                           &lt;span class="c1"&gt;# nothing ready and nothing left&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                   &lt;span class="c1"&gt;# a human is reviewing, or other agents are working&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it 🤯 The loop has no logic about dependencies, ordering or concurrency. All of that is in the schema. It also means you can swap the agent, the model or the language without touching the rules.&lt;/p&gt;

&lt;p&gt;One thing I haven't covered: a task abandoned by a crashed agent stays &lt;code&gt;in_progress&lt;/code&gt; until someone resets it. &lt;code&gt;claimed_at&lt;/code&gt; is there so you can find those tasks and decide what the timeout should be.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which questions can you ask the graph?
&lt;/h2&gt;

&lt;p&gt;Because the dependencies are a graph, the planning questions are one-liners:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RETURN task:data_model&amp;lt;~task;                      -- what it directly blocks
-- [task:api, task:ui]

RETURN task:data_model.{..+collect}&amp;lt;~task;         -- everything downstream, transitively
-- [task:api, task:ui, task:docs, task:tests, task:release]

RETURN task:release.{..+collect}.blockers;         -- everything it waits on, transitively
-- [task:tests, task:docs, task:api, task:ui, task:data_model, task:spec]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second one answers "what slips if the data model slips?". The third answers "what has to happen before we can release?". Both are the questions a manager asks, and both come straight out of the same table the agents use.&lt;/p&gt;

&lt;p&gt;All the queries above are in the &lt;a href="https://gist.github.com/martinschaer/40d9100053df11094dc08ff7283cbf42" rel="noopener noreferrer"&gt;queries.surql gist&lt;/a&gt;, in the order they ran, with the two expected errors marked. Load the schema, then the seed, then work through them one at a time. I ran everything on SurrealDB v4.0.1.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;An agent loop is claim, work, report, repeat, and it is only as reliable as the task list behind it&lt;/li&gt;
&lt;li&gt;Model tasks as a DAG: a &lt;code&gt;blockers&lt;/code&gt; field, with &lt;code&gt;REFERENCE&lt;/code&gt; to get the reverse direction&lt;/li&gt;
&lt;li&gt;Make the ready queue a function, so it is always current&lt;/li&gt;
&lt;li&gt;Claim with a single conditional update, so one agent gets each task&lt;/li&gt;
&lt;li&gt;Put the rules in events, so no prompt has to remember them&lt;/li&gt;
&lt;li&gt;Stop at &lt;code&gt;review&lt;/code&gt; and let a person move the work on&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Get started
&lt;/h2&gt;

&lt;p&gt;Want to run this yourself? Load the three gists into a free instance and point your agent at &lt;code&gt;fn::claim&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/cloud" rel="noopener noreferrer"&gt;Create a free cloud instance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/docs" rel="noopener noreferrer"&gt;Start building&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://discord.gg/surrealdb" rel="noopener noreferrer"&gt;Join our Discord server&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>agents</category>
    </item>
    <item>
      <title>How to build a company brain: where to start and what it costs</title>
      <dc:creator>Martin Schaer</dc:creator>
      <pubDate>Mon, 23 Nov 2026 17:44:25 +0000</pubDate>
      <link>https://dev.to/surrealdb/how-to-build-a-company-brain-where-to-start-and-what-it-costs-351c</link>
      <guid>https://dev.to/surrealdb/how-to-build-a-company-brain-where-to-start-and-what-it-costs-351c</guid>
      <description>&lt;p&gt;To build a company brain, start with one workflow where missing context hurts, such as product and engineering alignment meetings. Capture those conversations automatically, give them permissions that match who was in the room, and serve them to the agents doing the follow-up work. Prove that one use case, then add sources.&lt;/p&gt;

&lt;p&gt;This is the practical follow-up to &lt;a href="https://surrealdb.com/blog/what-is-a-company-brain" rel="noopener noreferrer"&gt;What is a company brain?&lt;/a&gt;. That post covers the idea. This one covers the decisions: where to start, who owns it, what to buy or build, and what it costs.&lt;/p&gt;



&lt;h2&gt;
  
  
  Is a company brain the same as a context layer?
&lt;/h2&gt;

&lt;p&gt;No. A context layer gives agents access to data that is already recorded and structured: the CRM, the data warehouse, policy documents. A company brain adds what was never written down: what was decided on a call, why it was decided in a chat thread, what a client said in passing.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Context layer&lt;/th&gt;
&lt;th&gt;Enterprise search&lt;/th&gt;
&lt;th&gt;Company brain&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;What it holds&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Structured data you already store&lt;/td&gt;
&lt;td&gt;Documents and messages across your apps&lt;/td&gt;
&lt;td&gt;Decisions, reasons and commitments, including from calls and private chats&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;How it learns&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;When someone updates a system&lt;/td&gt;
&lt;td&gt;When a document changes&lt;/td&gt;
&lt;td&gt;Continuously, from everyday work&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Who uses it&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Agents&lt;/td&gt;
&lt;td&gt;People&lt;/td&gt;
&lt;td&gt;People and agents&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Hardest problem&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Data quality&lt;/td&gt;
&lt;td&gt;Relevance&lt;/td&gt;
&lt;td&gt;Permissions on private conversations&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Most organisations need both. The context layer tells an agent what the records say. The company brain tells it why. I go deeper into the difference, and why permissions decide it, in &lt;a href="https://surrealdb.com/blog/what-is-a-company-brain" rel="noopener noreferrer"&gt;What is a company brain?&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Where should you start building a company brain?
&lt;/h2&gt;

&lt;p&gt;Start with a quick win that has a clear benefit for the business. The trap is designing an organisation-wide system on day one. You learn more from one working use case than from months of planning, and that learning shapes the next step.&lt;/p&gt;

&lt;p&gt;My recommendation is to start as if you were deploying a fleet of notetakers. Picture a product manager and two engineers discussing a feature on a call. Today, the coding agent that later picks up that ticket knows none of it. With a company brain, it automatically gets the decisions, the constraints and the reasons from that meeting. For the people involved, that feels like a&lt;br&gt;
superpower.&lt;/p&gt;

&lt;p&gt;A sequence that works:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Pick one recurring meeting&lt;/strong&gt; where decisions get made and work follows, such as product and engineering alignment.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Capture it automatically&lt;/strong&gt;, with the people in the room knowing what is captured and who can see it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scope each memory to its participants and their teams&lt;/strong&gt;, so access matches who was there.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Serve it to the agents doing the follow-up work&lt;/strong&gt;, starting with agents.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Add the sources that record the outcome&lt;/strong&gt;, such as tickets and product requirement documents, so the brain knows what was decided and what was delivered.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Move to the next workflow&lt;/strong&gt; where context nobody could reach before would change how people work.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Engineering is a good first partner. Engineers tend to use AI the most, their agents benefit immediately, and they often arrive with ideas of their own.&lt;/p&gt;

&lt;h2&gt;
  
  
  Who should own a company brain?
&lt;/h2&gt;

&lt;p&gt;A business unit or a dedicated role with a broad view of the business should own it. It is a company-wide asset, and its owner needs to understand where the business value is. Pair that owner closely with engineering, which will build most of the integrations and is usually the first team to benefit.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the tech stack for a company brain?
&lt;/h2&gt;

&lt;p&gt;A company brain has four layers. You can buy, build or assemble each one separately.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Capture:&lt;/strong&gt; connectors that pull in meetings, chats, tickets and documents. This is where most of the custom work goes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Understanding:&lt;/strong&gt; turning raw transcripts and files into facts, people, decisions and relationships, and reconciling them when they contradict each other.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Memory:&lt;/strong&gt; the database that stores all of it, finds it by meaning, by keyword and by relationship, and enforces who can see what.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Serving:&lt;/strong&gt; the interface agents and people use to ask questions, usually through MCP or a native integration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The memory layer is the one to choose most carefully. It holds the private data and enforces the permissions, and replacing it later means migrating everything.&lt;/p&gt;

&lt;h2&gt;
  
  
  What does MCP have to do with a company brain?
&lt;/h2&gt;

&lt;p&gt;MCP (Model Context Protocol) is the plug, not the brain. It is an open standard that lets any AI agent connect to a tool or data source in the same way. That makes it a fast way to connect your company brain to Claude, ChatGPT, coding agents and internal assistants without building each integration by hand.&lt;/p&gt;

&lt;p&gt;Storing knowledge and deciding who may see it are jobs for the memory layer underneath. Two more points matter when you plan:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;MCP is not the only protocol.&lt;/strong&gt; Agents can also reach data through APIs, command-line tools and native integrations.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Native plugs can be cheaper.&lt;/strong&gt; A purpose-built integration is often faster and uses fewer tokens than a generic MCP server, which adds up when thousands of agent calls run every day.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use MCP to move fast, and switch to a native integration where volume makes the token bill matter.&lt;/p&gt;

&lt;h2&gt;
  
  
  Should you build, buy or assemble?
&lt;/h2&gt;

&lt;p&gt;Assemble. Off-the-shelf work AI such as Glean or Microsoft Copilot covers search across popular apps well. It reaches its limits where your knowledge lives in internal tools, private conversations and workflows nobody else has.&lt;/p&gt;

&lt;p&gt;Most of the effort goes into integrations that have to be custom-made. This is why forward-deployed engineers, who build inside the customer's organisation, have become so common. AI has also made building much cheaper than it was. The sweet spot is to keep the tools your teams already use and build the bridges between them, on top of a memory layer you control.&lt;/p&gt;

&lt;h2&gt;
  
  
  What should you evaluate?
&lt;/h2&gt;

&lt;p&gt;Most buyers are still working this out, and they are right to be cautious. These questions separate a demo from something you can run:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Permissions:&lt;/strong&gt; are they enforced inside every search, or applied afterwards by the application?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deployment:&lt;/strong&gt; does it run where your data rules require?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cost:&lt;/strong&gt; what does a sample of your own content cost per page and per query?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Freshness:&lt;/strong&gt; can it tell a reversed decision from a current one?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Integrations:&lt;/strong&gt; does it connect to the tools your teams actually use?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Exit:&lt;/strong&gt; how hard is it to move your memory somewhere else later?&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Which deployment model should you choose?
&lt;/h2&gt;

&lt;p&gt;It depends on how regulated you are.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Model&lt;/th&gt;
&lt;th&gt;Best for&lt;/th&gt;
&lt;th&gt;Trade-off&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;SaaS or managed cloud&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Companies without strict data rules&lt;/td&gt;
&lt;td&gt;Easiest and cheapest to run&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Bring your own cloud (BYOC)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Companies that need data in their own cloud account&lt;/td&gt;
&lt;td&gt;More control, more operational work&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;On-premises&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Banks, healthcare, government&lt;/td&gt;
&lt;td&gt;Full control, highest cost&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;A company brain holds your most sensitive conversations, so involve legal and security early. Settle the deployment model before you choose vendors, because it rules some of them out.&lt;/p&gt;

&lt;h2&gt;
  
  
  How much does a company brain cost?
&lt;/h2&gt;

&lt;p&gt;The cost depends on how many sources you connect, how complex your permissions are, and how much content you process. Published estimates for custom enterprise search, the closest comparable, range from $40,000 to $200,000 and 12 to 24 months to build (&lt;a href="https://www.raftlabs.com/blog/cost-to-build-enterprise-search-software" rel="noopener noreferrer"&gt;RaftLabs&lt;/a&gt;, &lt;a href="https://www.gosearch.ai/blog/how-much-does-enterprise-search-cost/" rel="noopener noreferrer"&gt;GoSearch&lt;/a&gt;, both vendors, 2026).&lt;/p&gt;

&lt;p&gt;The main cost drivers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Connectors.&lt;/strong&gt; One SharePoint connector with nested folder permissions can take three to five weeks and 30 to 40% of the project timeline, according to GoSearch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Document processing.&lt;/strong&gt; Turning PDFs, slides and transcripts into usable text, at a price per page.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Model and token usage.&lt;/strong&gt; Every question an agent asks costs tokens, and agents ask a lot.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;People's time.&lt;/strong&gt; Someone has to own sources, settle conflicts and review what the brain gets wrong.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  What are the hidden costs?
&lt;/h3&gt;

&lt;p&gt;The hidden costs are the choices that look small at the start. I saw one company building a context layer spend its whole budget on document ingestion. It picked the most accurate document parser available, which cost at least 30 times more per page than a standard one. Nobody had compared cost against accuracy, or looked at hybrid methods that don't run everything on GPUs.&lt;/p&gt;

&lt;p&gt;Other costs that tend to surprise teams:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Re-processing.&lt;/strong&gt; Changing your AI model or parser can mean processing everything again.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Permission syncing.&lt;/strong&gt; Keeping access in step with your identity system as people join, move and leave.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Legal and privacy review&lt;/strong&gt;, especially for recorded calls.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Change management.&lt;/strong&gt; Explaining to employees what is captured, and earning their trust.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Run a small sample through two or three options before committing to any per-page or per-token price at scale.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why do most company brain projects fail?
&lt;/h2&gt;

&lt;p&gt;Most fail on permissions and governance. Recorded conversations mix information with different audiences. When a team can't enforce access per conversation, the safe choice is to include only what everyone may see. The result is a brain built to the lowest common level of access. It misses exactly the private context that made it worth building.&lt;/p&gt;

&lt;p&gt;The wider numbers point the same way. MIT's NANDA initiative found that 95% of generative AI pilots delivered no measurable return, and blamed tools that don't learn from real workflows (&lt;a href="https://www.healthcareitnews.com/news/mit-95-enterprise-ai-pilots-fail-deliver-measurable-roi" rel="noopener noreferrer"&gt;MIT NANDA, July 2025&lt;/a&gt;). Gartner predicts that over 40% of agentic AI projects will be cancelled by the end of 2027, citing costs, unclear value and weak risk controls (&lt;a href="https://www.gartner.com/en/newsroom/press-releases/2025-06-25-gartner-predicts-over-40-percent-of-agentic-ai-projects-will-be-canceled-by-end-of-2027" rel="noopener noreferrer"&gt;Gartner, June 2025&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The other common causes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Starting too big&lt;/strong&gt;, so nothing reaches users before the budget runs out.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No clear business benefit&lt;/strong&gt;, so nobody defends the project when priorities change.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stale answers&lt;/strong&gt;, when the brain can't tell a reversed decision from a current one.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Where does SurrealDB fit?
&lt;/h2&gt;

&lt;p&gt;SurrealDB is the memory layer. It keeps documents, relationships, vector search and full-text search in one database, so an agent can find a memory by meaning, follow it to the people and decisions it relates to, and filter by date in one request. Permissions are checked inside every search, on every record, so a forgotten filter in an application can't leak a private&lt;br&gt;
conversation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://surrealdb.com/docs/agent-memory/mental-model/contexts-and-scope" rel="noopener noreferrer"&gt;SurrealDB Agent Memory&lt;/a&gt; builds on that to ingest conversations and serve them to agents. Each memory is scoped to the people it belongs to, and an agent can never see more than the person it works for, and agents can reach it through MCP. SurrealDB itself runs as a managed service, in your own cloud or on-premises.&lt;/p&gt;

&lt;p&gt;That is what makes the notetaker approach safe. A product meetingstays with the people who were in it and their team, and their coding agents can still use it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Frequently asked questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  How long does it take to build a company brain?
&lt;/h3&gt;

&lt;p&gt;A single use case is much faster than an organisation-wide brain. Comparable enterprise search projects built from scratch quote 12 to 24 months.&lt;/p&gt;

&lt;h3&gt;
  
  
  Is a company brain the same as RAG?
&lt;/h3&gt;

&lt;p&gt;RAG is a technique for feeding retrieved text to a model. A company brain uses retrieval, but also captures knowledge continuously, reconciles contradictions and enforces who can see what.&lt;/p&gt;

&lt;h3&gt;
  
  
  What data should a company brain start with?
&lt;/h3&gt;

&lt;p&gt;Meeting transcripts from one recurring decision-making meeting, then the tickets and documents that record what came out of it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get started
&lt;/h2&gt;

&lt;p&gt;If you're planning a company brain, our solutions engineers can help you pick the first use case and the right deployment model:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/blog/what-is-a-company-brain" rel="noopener noreferrer"&gt;Read what a company brain is&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/solutions" rel="noopener noreferrer"&gt;See how teams use SurrealDB&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/whitepapers" rel="noopener noreferrer"&gt;Read our whitepapers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>agents</category>
    </item>
    <item>
      <title>What is a company brain?</title>
      <dc:creator>Martin Schaer</dc:creator>
      <pubDate>Mon, 23 Nov 2026 17:38:05 +0000</pubDate>
      <link>https://dev.to/surrealdb/what-is-a-company-brain-2apn</link>
      <guid>https://dev.to/surrealdb/what-is-a-company-brain-2apn</guid>
      <description>&lt;p&gt;A company brain is a shared memory of what your organisation knows but never wrote down: what was decided on a call, why it was decided in a Slack thread, what a client mentioned in passing. It keeps learning from everyday work and serves that knowledge to people and AI agents, each seeing only what they are allowed to see.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why is everyone talking about it now?
&lt;/h2&gt;

&lt;p&gt;Y Combinator put "Company Brain" on its Summer 2026 list of startup ideas it wants to fund. The reasoning, as reported, is that the biggest blocker to AI automation is no longer the model. It's domain knowledge, which is "trapped in Slack threads, email chains, Notion docs, Jira tickets, and people's heads."&lt;/p&gt;

&lt;p&gt;Meta's analytics team published how they built an internal "AI second brain" that reads meeting notes, tracks projects and builds on earlier conversations. It went from zero to more than 63,000 installs in three months, with 10,000 daily users across engineering, legal, finance, sales and other teams (&lt;a href="https://medium.com/@AnalyticsAtMeta/how-we-built-an-ai-second-brain-for-60k-knowledge-workers-78c507dd795b" rel="noopener noreferrer"&gt;Analytics at Meta&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;And the problem it goes after is old. A 2018 Panopto study found that 42% of institutional knowledge is unique to the individual who holds it (&lt;a href="https://www.panopto.com/company/news/inefficient-knowledge-sharing-costs-large-businesses-47-million-per-year/" rel="noopener noreferrer"&gt;Panopto&lt;/a&gt;). When that person changes role or leaves, the knowledge goes with them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Isn't that just a context layer for agents?
&lt;/h2&gt;

&lt;p&gt;Most AI projects I see in large organisations start with a context layer: give the agents access to data that already lives in databases. The CRM, the transaction history, the policy documents, the data warehouse. That's useful, and it's the right place to start. But that data was already recorded, structured and governed. Someone decided it was worth keeping.&lt;/p&gt;

&lt;p&gt;My take is that a company brain is about the other part: the institutional (or tribal) knowledge that was never recorded or structured. In a bank, for example, it's why a client was given an exception on a fee, or what the risk committee was really worried about. Or the moment on a call when a client mentioned they were thinking of moving part of their portfolio. None of that is in a table. It's in transcripts, chat threads and people's heads.&lt;/p&gt;

&lt;p&gt;When your agents automatically remember last week's meeting and the Slack thread that followed it, without anyone writing a summary, it starts feeling like a superpower. It brings context that, until recently, nobody even considered possible to make available to an agent.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why do most teams leave the best context out?
&lt;/h2&gt;

&lt;p&gt;Because it's private. The conversations that hold the most valuable knowledge are also the ones with client data, deal details, personnel issues and everything else you can't show to the whole company (or to every agent).&lt;/p&gt;

&lt;p&gt;So the usual answer is to not ingest them. Teams connect the public channels and the shared drive, and leave out the private channels and meeting transcripts. The result is a company brain that only knows what was already public, which is mostly what was already recorded somewhere. That's a context layer again.&lt;/p&gt;

&lt;p&gt;For regulated industries like financial services there's a second requirement: being able to show who could see what, and when. Employees also have to trust it, and they won't if they can't tell who will see what they say on a call.&lt;/p&gt;

&lt;p&gt;This is why I think permissions are the most important part of a company brain. If access is enforced properly, you can ingest everything, because each memory stays visible only to the people who should see it. Without that, the safe choice is to leave the best context out.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where does SurrealDB fit?
&lt;/h2&gt;

&lt;p&gt;There are two layers, and we build both.&lt;/p&gt;

&lt;h3&gt;
  
  
  The database
&lt;/h3&gt;

&lt;p&gt;SurrealDB keeps documents, graph relationships, vector embeddings and full-text search in one engine, and queries them together. That matters for a company brain because its knowledge is connected: people, clients, meetings, decisions and the teams they belong to. An agent can search by meaning, follow the relationships, and filter by date in a single query.&lt;/p&gt;

&lt;p&gt;Permissions are defined in the database, on each record, and they're checked inside the search itself. Checking them after the search, in the application, is the easy mistake: one forgotten filter and an agent sees everyone's results. Access can also follow relationships. If access to a memory depends on team membership, it changes the moment someone joins or leaves the team, with no list of permissions to copy and keep in sync.&lt;/p&gt;

&lt;h3&gt;
  
  
  Agent Memory
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://surrealdb.com/docs/agent-memory/mental-model/contexts-and-scope" rel="noopener noreferrer"&gt;SurrealDB Agent Memory&lt;/a&gt; is the memory layer we're building on top of SurrealDB. It ingests conversations and facts, and lets agents recall them. Four ideas decide who sees what:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Contexts:&lt;/strong&gt; separate memories with nothing crossing between them (for example, one per legal entity or business unit).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scopes:&lt;/strong&gt; every memory is tagged with who it belongs to. A call between two people can be scoped to exactly those two, and a team's memories to that team.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Grants:&lt;/strong&gt; what each person, or each agent acting for them, may read or write.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lenses:&lt;/strong&gt; narrow what an agent looks at for the task in hand. A lens can never widen what the grant allows.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Two rules make it safe to ingest private conversations. It fails closed: anything outside your grants is invisible to you, whatever you ask. And a key given to an agent can carry less access than the person it works for, never more. So you can give a sub-agent access to one client's history, even when the relationship manager it works for sees the whole book.&lt;/p&gt;

&lt;p&gt;In practice, a relationship manager's call with a client becomes memories scoped to the people on the call and their team. Their agent can recall it next week. An agent in another division never sees it, whatever it asks.&lt;/p&gt;

&lt;h2&gt;
  
  
  What a database won't do for you
&lt;/h2&gt;

&lt;p&gt;A database isn't a company brain on its own. A few parts are still your decisions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Which sources to connect.&lt;/strong&gt; Calls and chats are where decisions get made. Tickets, the CRM and policy documents are where they get recorded. The brain needs both, and needs to know which one wins when they disagree.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Where to start.&lt;/strong&gt; One team or one workflow, not the whole organisation on day one.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;How you tell people.&lt;/strong&gt; Employees should know what's captured and who can see it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, before you start, make sure you know which conversations hold the knowledge your agents are missing, who should be able to see each of them, and which source is the authority when two of them disagree. If you can answer the second question with permissions you trust, you can ingest much more than you probably think.&lt;/p&gt;

&lt;p&gt;For the practical side (where to start, who should own it, the tech stack, deployment models and costs), read &lt;a href="https://surrealdb.com/blog/how-to-build-a-company-brain-where-to-start-and-what-it-costs" rel="noopener noreferrer"&gt;How to build a company brain: where to start and what it costs&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get started
&lt;/h2&gt;

&lt;p&gt;If you're planning a company brain, our solutions engineers can help you pick the first use case and the right deployment model:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/blog/how-to-build-a-company-brain-where-to-start-and-what-it-costs" rel="noopener noreferrer"&gt;Read how to build a company brain&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/solutions" rel="noopener noreferrer"&gt;See how teams use SurrealDB&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/whitepapers" rel="noopener noreferrer"&gt;Read our whitepapers&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>agents</category>
    </item>
    <item>
      <title>GTA 6 easter eggs: a live tracker built on SurrealDB</title>
      <dc:creator>Martin Schaer</dc:creator>
      <pubDate>Sat, 21 Nov 2026 01:11:00 +0000</pubDate>
      <link>https://dev.to/surrealdb/gta-6-easter-eggs-a-live-tracker-built-on-surrealdb-5e1</link>
      <guid>https://dev.to/surrealdb/gta-6-easter-eggs-a-live-tracker-built-on-surrealdb-5e1</guid>
      <description>&lt;p&gt;GTA 6 players have already found a literal Easter egg: a painted egg in a bird's nest on a tower in Leonida, and throwing it triggers a cutscene (&lt;a href="https://www.ibtimes.co.uk/gta-6-player-discovers%20literal-easter-egg-leonida-1833342" rel="noopener noreferrer"&gt;IBTimes&lt;/a&gt;, 19 November 2026). The other finds are scattered across Reddit, X and Discord, so I built a live tracker on one SurrealDB database where you can add yours.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sites.surrealdb.com/s/XIEVSkxThaszNm1yQCNSfsGH%22" rel="noopener noreferrer"&gt;Open the egg tracker&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Press "Report a find", click the map where you found it, then describe it and say which older game or show it nods to. If someone has already reported something close by, the tracker shows it first, so you can confirm theirs instead of adding a duplicate. You can attach a screenshot too: your browser shrinks it before it is sent. A moderator checks every new find, and until then only you can see it.&lt;/p&gt;

&lt;p&gt;The tracker is a small tour of what one database can do:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://surrealdb.com/docs/learn/data-models/vector-search/overview" rel="noopener noreferrer"&gt;Vector search&lt;/a&gt; finds a find from a screenshot.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://surrealdb.com/docs/learn/data-models/geospatial/overview" rel="noopener noreferrer"&gt;Geospatial queries&lt;/a&gt; answer "what else is near me?".&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://surrealdb.com/docs/learn/data-models/graph/overview" rel="noopener noreferrer"&gt;Graph relations&lt;/a&gt; link each find to the older game it nods to.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://surrealdb.com/docs/learn/security/authorization/permissions-and-row-level-security" rel="noopener noreferrer"&gt;Row-level permissions&lt;/a&gt; and [live queries (&lt;a href="https://surrealdb.com/docs/learn/querying/real-time/live-queries" rel="noopener noreferrer"&gt;https://surrealdb.com/docs/learn/querying/real-time/live-queries&lt;/a&gt;) let a public page talk straight to the database, with no API server in between.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://surrealdb.com/docs/agent-memory" rel="noopener noreferrer"&gt;Agent Memory&lt;/a&gt; can remember what an NPC said.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What does a GTA 6 easter egg look like as data?
&lt;/h2&gt;

&lt;p&gt;An egg is a place, a picture and a reference to something else. Most databases make you pick one of those. SurrealDB stores all three on the same record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DEFINE TABLE egg SCHEMAFULL;
DEFINE FIELD name ON egg TYPE string;
DEFINE FIELD at   ON egg TYPE geometry&amp;lt;point&amp;gt;;          -- where on the map
DEFINE FIELD image ON egg TYPE option&amp;lt;bytes&amp;gt;;           -- the screenshot, shrunk in the browser
DEFINE FIELD shot ON egg TYPE option&amp;lt;array&amp;lt;float&amp;gt;&amp;gt;;     -- its embedding, written by a worker
DEFINE INDEX egg_shot ON egg FIELDS shot HNSW DIMENSION 512 DIST COSINE;

-- egg -&amp;gt;references-&amp;gt; work   (GTA IV, GTA V, Dexter, ...)
DEFINE TABLE references TYPE RELATION IN egg OUT work;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Positions use the grid from the open &lt;a href="https://github.com/lociAI/gta6-leonida-community-map" rel="noopener noreferrer"&gt;community map of Leonida&lt;/a&gt;: 0 to 2000 on each axis. The starting data is a handful of launch-week finds reported by &lt;a href="https://www.gamespot.com/articles/gta-6-easter-eggs-list-and-locations/" rel="noopener noreferrer"&gt;GameSpot&lt;/a&gt; and IBTimes, with approximate positions.&lt;/p&gt;

&lt;p&gt;Every query below was run on SurrealDB v3.3.5 and v4.0.1 on 20 November 2026.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where was this GTA 6 screenshot taken?
&lt;/h2&gt;

&lt;p&gt;You've got a screenshot of a mural, a sign or a strange statue, and no idea where it was. Turn it into an embedding with CLIP, then ask for the nearest screenshots, but only inside the part of the map you're searching:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LET $vice_city = { type: 'Polygon', coordinates: [[[1150, 650], [1700, 650], [1700, 1150], [1150, 1150], [1150, 650]]] };

SELECT name, hint, at, vector::distance::knn() AS dist
FROM egg
WHERE shot &amp;lt;|3,40|&amp;gt; $shot AND at INSIDE $vice_city
ORDER BY dist;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The polygon filter sits in the same &lt;code&gt;WHERE&lt;/code&gt; as the vector search, so it's applied during the index walk rather than after it. Filtering after the walk can leave you with nothing (&lt;a href="https://surrealdb.com/blog/why-does-my-vector-search-return-nothing-when-i-add-a-filter-2" rel="noopener noreferrer"&gt;I measured it here&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;CLIP puts images and text in the same space, so &lt;code&gt;$shot&lt;/code&gt; can also come from a sentence. "A pink flamingo mural" finds the screenshot of a pink flamingo mural.&lt;/p&gt;

&lt;h3&gt;
  
  
  How does the tracker do this without you running any code?
&lt;/h3&gt;

&lt;p&gt;Your browser shrinks the screenshot before it leaves your computer. In my test, a 1.9 MB photo of 4000×3000 pixels became a 67 KB WebP, and the re-encoding drops photo details such as GPS. The image goes to SurrealDB as &lt;code&gt;bytes&lt;/code&gt;. A small Python worker on my computer, &lt;a href="https://gist.github.com/martinschaer/34a4ce03497183efa566702e1df52b91" rel="noopener noreferrer"&gt;&lt;code&gt;embed.py&lt;/code&gt;&lt;/a&gt;, finds the images that have no embedding yet, runs CLIP and writes the 512 numbers to &lt;code&gt;shot&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;pre data-lang="mermaid"&gt;&lt;code&gt;flowchart LR
  A["Your browser shrinks the screenshot"] --&amp;gt; B[("SurrealDB: the image as bytes")]
  B --&amp;gt; C["embed.py runs CLIP on a schedule"]
  C --&amp;gt;|"512 numbers"| B
  B --&amp;gt; D["Vector search with a map filter"]&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;"Search by screenshot" takes the same route through a short-lived &lt;code&gt;search_request&lt;/code&gt; record, so a search waits for the worker's next run.&lt;/p&gt;

&lt;p&gt;The same script embeds by hand, which is how I made this post's demo data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;uv run embed.py --image screenshot.png
uv run embed.py --text &lt;span class="s2"&gt;"a pink flamingo mural"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What else is near me in GTA 6?
&lt;/h2&gt;

&lt;p&gt;You're standing at the foot of the radio tower. What else has been found within 100 map units?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LET $here = [1280, 950];
SELECT name, math::round(vector::distance::euclidean(at.coordinates, $here)) AS away
FROM egg
WHERE vector::distance::euclidean(at.coordinates, $here) &amp;lt; 100
ORDER BY away;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
  { away: 14, name: 'The literal Easter egg' },
  { away: 54, name: "Dexter's apartment" },
  { away: 81, name: 'Wade on the Final Act podcast' }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The map grid is flat, so this uses straight-line distance. &lt;code&gt;geo::distance&lt;/code&gt; would assume latitude and longitude and give you metres on a sphere. The &lt;a href="https://surrealdb.com/docs/learn/data-models/geospatial/distance-and-proximity" rel="noopener noreferrer"&gt;geospatial docs&lt;/a&gt; cover both.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which games does GTA 6 reference most?
&lt;/h2&gt;

&lt;p&gt;Easter eggs are mostly callbacks: to GTA V's Mount Chiliad mystery, to GTA Online's jetpack, to a TV serial killer's flat in Miami. A callback is an edge, so the question is a graph query.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT name, count(&amp;lt;-references) AS eggs FROM work ORDER BY eggs DESC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Turn the arrow around and you get every nod to one game. The&lt;br&gt;
&lt;a href="https://surrealdb.com/docs/reference/query-language/statements/relate" rel="noopener noreferrer"&gt;&lt;code&gt;RELATE&lt;/code&gt; statement&lt;/a&gt; creates the edges:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT VALUE name FROM work:gta_v&amp;lt;-references&amp;lt;-egg;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['Wade on the Final Act podcast', 'The bunker under the mountain']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How does a public form survive the internet without an API server?
&lt;/h2&gt;

&lt;p&gt;The tracker talks straight to SurrealDB from your browser. Each visitor signs up anonymously: the browser makes up a random secret and keeps it. The rules live in the schema, so they apply whichever client connects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DEFINE TABLE egg SCHEMAFULL
  PERMISSIONS
    FOR select WHERE status = 'approved' OR found_by = $auth.id
    FOR create WHERE $access = 'hunter'
    FOR update, delete NONE;

DEFINE FIELD status ON egg TYPE string
  VALUE IF $access = 'hunter' THEN 'pending' ELSE $value ?? 'pending' END;

-- The screenshot: 200 KB at most, and only its finder can read it back
DEFINE FIELD image ON egg TYPE option&amp;lt;bytes&amp;gt;
  ASSERT $value = NONE OR bytes::len($value) &amp;lt;= 204800
  PERMISSIONS FOR select WHERE found_by = $auth.id;

-- One "I found it too" per hunter per egg
DEFINE INDEX confirmed_pair ON confirmed FIELDS in, out UNIQUE;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A new find is visible only to the person who reported it until I approve it. Sending &lt;code&gt;status: 'approved'&lt;/code&gt; from the browser console gets you a &lt;code&gt;pending&lt;/code&gt; egg. The real schema also checks that an upload is a JPEG or WebP, and visitors cannot write the embedding, so a find always matches the picture a moderator approved. The counter at the top of the tracker updates from a &lt;code&gt;LIVE SELECT&lt;/code&gt;, and every refresh goes through the same permissions. For the thinking behind this, read &lt;a href="https://surrealdb.com/blog/even-a-jailbroken-llm-cant-exceed-its-database-permissions-heres-how" rel="noopener noreferrer"&gt;even a jailbroken LLM can't exceed its database permissions&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Can an agent remember what an NPC said in GTA 6?
&lt;/h2&gt;

&lt;p&gt;A Rockstar studio lead said in August 2026 that GTA 6 takes NPC interactions &lt;a href="https://www.gamesradar.com/games/grand-theft-auto/rockstar-lead-says-gta-6-takes-npc-interactions-much-further-than-red-dead-redemption-2-and-its-system-is-returning-and-evolved/" rel="noopener noreferrer"&gt;"much further"&lt;/a&gt; than Red Dead Redemption 2. A hint like the reported one about a bunker under a mountain is two strangers in a bar, said once, in passing. If your captions go into &lt;a href="https://surrealdb.com/blog/introducing-surrealdb-agent-memory" rel="noopener noreferrer"&gt;SurrealDB Agent Memory&lt;/a&gt; as you play, an agent can find that line days later:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;surrealdb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;memory&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Memory&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nc"&gt;Memory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"leonida"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;endpoint&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;ENDPOINT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;api_key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;memory&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;memory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;remember&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s2"&gt;"NPC in a bar: there's a bunker under the mountain, full of jetpacks."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;labels&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"source=captions"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"place=545,1465"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Days later:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;You:&lt;/strong&gt; Someone mentioned a bunker. Where was I?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Agent:&lt;/strong&gt; On Tuesday evening, two NPCs in a bar said there's a bunker under&lt;br&gt;
the mountain, full of jetpacks. You were at 545, 1465 on the map. Want me to&lt;br&gt;
add it to the tracker as a lead?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;(The conversation above is illustrative.)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Agent Memory pulls entities and relations out of the text, such as the bunker, the mountain and the jetpacks. So "where did I hear about jetpacks?" finds the same line.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do you build your own app or POC with SurrealDB?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://github.com/martinschaer/create-surrealdb-poc" rel="noopener noreferrer"&gt;&lt;code&gt;create-surrealdb-poc&lt;/code&gt;&lt;/a&gt; scaffolds a SurrealDB proof of concept in TypeScript or Python, with the SurrealDB agent skills already installed. It asks for a project name and a language, and flags skip the questions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm create @martinschaer/surrealdb-poc
&lt;span class="c"&gt;# or: bun create @martinschaer/surrealdb-poc&lt;/span&gt;
&lt;span class="c"&gt;# without the questions:&lt;/span&gt;
npm create @martinschaer/surrealdb-poc my-poc -- --lang py --install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The new folder has:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The skills from &lt;a href="https://github.com/surrealdb/agent-skills" rel="noopener noreferrer"&gt;&lt;code&gt;surrealdb/agent-skills&lt;/code&gt;&lt;/a&gt;: &lt;code&gt;surrealql&lt;/code&gt;, &lt;code&gt;surrealql-functions&lt;/code&gt;, &lt;code&gt;surrealql-performance&lt;/code&gt;, &lt;code&gt;surrealdb-cli&lt;/code&gt; and &lt;code&gt;surrealdb-docs&lt;/code&gt;, plus &lt;code&gt;surrealdb-js&lt;/code&gt; or &lt;code&gt;surrealdb-python&lt;/code&gt; for the language you picked. They live in &lt;code&gt;.agents/skills/&lt;/code&gt;, are linked into &lt;code&gt;.claude/skills/&lt;/code&gt; for Claude Code, and &lt;code&gt;skills-lock.json&lt;/code&gt; records where they came from.&lt;/li&gt;
&lt;li&gt;A starter that connects, signs in and runs a query. TypeScript needs Node 22.18+ or Bun, and Python uses &lt;code&gt;uv&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;Justfile&lt;/code&gt; and a &lt;code&gt;.env.example&lt;/code&gt; for a throwaway local server.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;README.md&lt;/code&gt; that also covers SurrealDB Studio and deploying to SurrealDB Earth.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Four commands later you have a result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;cp .env.example .env
just install
just db     &lt;span class="c"&gt;# an in-memory database, in one terminal&lt;/span&gt;
just run    &lt;span class="c"&gt;# in another: prints "hello from SurrealDB"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then open the folder in an agent that loads skills, such as Claude Code, and ask it to interview you and write a spec for your POC. The skills tell it how SurrealQL really works, and the in-memory database lets it test its own schema and queries instead of guessing. When the POC needs to leave your machine, one command creates an Earth instance (after &lt;code&gt;surreal install cloud&lt;/code&gt; and &lt;code&gt;surreal cloud login&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;surreal cloud instance create my-poc --region earth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Frequently asked questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Can I add my own GTA 6 easter egg to the tracker?
&lt;/h3&gt;

&lt;p&gt;Yes. Open the tracker, press "Report a find", click the map and describe it. A moderator checks every find before other players see it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Do I need to install anything to search by screenshot?
&lt;/h3&gt;

&lt;p&gt;No. Your browser shrinks the image and sends it, and a worker turns it into an embedding. You only run &lt;code&gt;embed.py&lt;/code&gt; yourself if you want to reproduce the queries in this post.&lt;/p&gt;

&lt;h3&gt;
  
  
  What does the tracker run on?
&lt;/h3&gt;

&lt;p&gt;One SurrealDB instance, queried straight from the browser, with a small Python worker for the embeddings. The queries in this post work on SurrealDB v3.3.5 and v4.0.1.&lt;/p&gt;

&lt;h3&gt;
  
  
  How do I start my own SurrealDB project like this?
&lt;/h3&gt;

&lt;p&gt;Run &lt;code&gt;npm create @martinschaer/surrealdb-poc&lt;/code&gt; and pick TypeScript or Python. It sets up the SurrealDB agent skills and a starter that connects to a local database.&lt;/p&gt;

&lt;h3&gt;
  
  
  Is this affiliated with Rockstar Games?
&lt;/h3&gt;

&lt;p&gt;No. It is an unofficial fan project built to show what SurrealDB can do.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get started
&lt;/h2&gt;

&lt;p&gt;Found something Rockstar hid? Add it to the tracker, and share this post with the friend who still hasn't found the egg.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://sites.surrealdb.com/s/XIEVSkxThaszNm1yQCNSfsGH" rel="noopener noreferrer"&gt;Add your find&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here are the &lt;a href="https://gist.github.com/martinschaer/94e7ef0876f66aa08cc165c34ee61cf7" rel="noopener noreferrer"&gt;schema&lt;/a&gt;, &lt;a href="https://gist.github.com/martinschaer/b7448fea1e1070ca5c01b2ba8e405936" rel="noopener noreferrer"&gt;seed data&lt;/a&gt;, &lt;a href="https://gist.github.com/martinschaer/1dd7cb5fce817737b94589938df629d3" rel="noopener noreferrer"&gt;queries&lt;/a&gt; and the &lt;a href="https://gist.github.com/martinschaer/34a4ce03497183efa566702e1df52b91" rel="noopener noreferrer"&gt;worker&lt;/a&gt; files.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/martinschaer/create-surrealdb-poc" rel="noopener noreferrer"&gt;Scaffold your own POC&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/cloud" rel="noopener noreferrer"&gt;Create a free cloud instance&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://surrealdb.com/docs" rel="noopener noreferrer"&gt;Start building&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://discord.gg/surrealdb" rel="noopener noreferrer"&gt;Join our Discord server&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;GTA VI and Grand Theft Auto are trademarks of Take-Two Interactive. This post isn't affiliated with or endorsed by Rockstar Games.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>gta</category>
      <category>surrealdb</category>
      <category>vibecoding</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Agentic retrieval for structured data with text-to-surql</title>
      <dc:creator>Martin Schaer</dc:creator>
      <pubDate>Tue, 04 Aug 2026 14:00:00 +0000</pubDate>
      <link>https://dev.to/surrealdb/agentic-retrieval-for-structured-data-with-text-to-surql-21k1</link>
      <guid>https://dev.to/surrealdb/agentic-retrieval-for-structured-data-with-text-to-surql-21k1</guid>
      <description>&lt;p&gt;RAG pipelines are commonly centred around processing unstructured data and indexing it with vectors or BM25. But when you have structured data, things change. You may still need semantic and full-text search, but the main challenge now is how to retrieve the structured data that sits in tables.&lt;/p&gt;

&lt;p&gt;Yes, you could create an agent tool with a query to the DB to –for example– &lt;em&gt;fetch the records in the products table that match a specific category&lt;/em&gt;. But then, you’ll need a new tool for each other query pattern, and unless you want your agent to have a very limited range of action, this is not the best solution.&lt;/p&gt;

&lt;p&gt;This is where &lt;strong&gt;text-to-surql&lt;/strong&gt; comes to help.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using a retrieval tool
&lt;/h2&gt;

&lt;p&gt;Give the agent tools that speak the language of your database, and you’ll support infinite types of questions from your users [1].&lt;/p&gt;

&lt;p&gt;Here's the flow:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftyqxx19kgyx355legwss.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftyqxx19kgyx355legwss.png" alt="diagram" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The agent, with the LLM doing the reasoning, decides when to hit the database using the retrieval tool, which generates a valid SurrealQL query, executes it, and returns structured results.&lt;/p&gt;

&lt;h2&gt;
  
  
  The SurrealQL generation tool
&lt;/h2&gt;

&lt;p&gt;SurrealQL is uniquely well-suited for this because it’s a multi-model query language. In a single query, you can traverse graph relationships, filter document fields, and run relational aggregations. That means your agent doesn't need to orchestrate across multiple databases or data layers. One tool, one query, one result.&lt;/p&gt;

&lt;p&gt;Let's walk through a real example first.&lt;/p&gt;

&lt;p&gt;The tool itself is straightforward to build: a prompt template that includes the schema, a few-shot examples of good SurrealQL queries, and a SurrealDB client to execute the result. We'll cover that later.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User asks:&lt;/strong&gt; &lt;em&gt;"can you summarize the reviews of my top 3 best selling products?"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The tool generates:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;LET $top = SELECT in.{id, name} AS product,
    math::sum(qty) AS total_sales
    FROM REL_PRODUCT_IN_ORDER
    GROUP BY product
    ORDER BY total_sales DESC
    LIMIT 3;

RETURN $top.map(
    |$p| {
        $p + {
            average_rating: (
                SELECT
                    product,
                    math::mean(score) AS avg_rating,
                    math::sum(1) AS review_count
                FROM review
                WHERE product = $p.product.id
                GROUP BY product
            )[0].avg_rating,
            review_count: (
                SELECT
                    product,
                    math::mean(score) AS avg_rating,
                    math::sum(1) AS review_count
                FROM review
                WHERE product = $p.product.id
                GROUP BY product
            )[0].review_count,
            sentiment_breakdown: (
                SELECT
                    sentiment,
                    math::sum(1) AS count
                FROM review
                WHERE product = $p.product.id
                GROUP BY sentiment
                ORDER BY count DESC
            ),
            recent_reviews: (
                SELECT
                    score AS rating,
                    created_at AS date,
                    text,
                    sentiment,
                    flow_sentiment
                FROM review
                WHERE product = $p.product.id
                ORDER BY created_at DESC
                LIMIT 10
            ),
        };
    }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result returned to agent:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    {
        average_rating: 4.75f,
        product: {
            id: product:26,
            name: 'Yoga Mat Pro',
        },
        recent_reviews: [
            {
                date: d'2026-04-20T11:11:27.427351302Z',
                rating: 5,
                sentiment: 'possitive',
                text: "I bought this primarily for stretching and cool-down after lifting sessions rather than yoga proper. It does that job perfectly - thick enough that kneeling on a hard floor is comfortable, and it doesn't slide even on polished concrete. Rolled up it's compact enough to slip under my desk. No complaints whatsoever.",
            },
            {
                date: d'2026-04-20T11:11:27.427112844Z',
                rating: 4.5f,
                sentiment: 'possitive',
                text: "Non-slip is not an exaggeration - this mat grips the floor and my hands equally well even in sweaty hot yoga sessions. The 6mm thickness is the sweet spot between cushioning and stability for balance poses. TPE material doesn't have the chemical smell that cheaper PVC mats have. The carrying strap is a bit flimsy but functional.",
            },
        ],
        review_count: 2,
        sentiment_breakdown: [{ count: 2, sentiment: 'possitive' }],
        total_sales: 5,
    },
    {
        average_rating: 4.5f,
        product: {
            id: product:9,
            name: 'Canvas Tote Bag',
        },
        recent_reviews: [
            {
                date: d'2026-04-20T11:11:27.426732636Z',
                rating: 4.5f,
                sentiment: 'possitive',
                text: 'I use this as a daily carry and it holds everything - laptop, gym clothes, lunch, groceries. The interior zipper pocket is a lifesaver for keys and cards. Handles are reinforced and show no signs of wear after months of heavy use. The canvas has a slight stiffness that I actually like.',
            },
        ],
        review_count: 1,
        sentiment_breakdown: [{ count: 1, sentiment: 'possitive' }],
        total_sales: 3,
    },
    {
        average_rating: 5,
        product: {
            id: product:7,
            name: 'Linen Wrap Dress',
        },
        recent_reviews: [
            {
                date: d'2026-04-20T11:11:27.426633136Z',
                rating: 5,
                sentiment: 'possitive',
                text: 'This dress is exactly what summer dressing should be. The linen is lightweight and breathable, the wrap silhouette is flattering on multiple body types, and the tie actually stays put throughout the day. Ordered two in different colors.',
            },
        ],
        review_count: 1,
        sentiment_breakdown: [{ count: 1, sentiment: 'possitive' }],
        total_sales: 2,
    },
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The agent now has exact numbers and reviews it can cite with confidence and trace back to a specific query against a specific table. That's what auditability looks like in production.&lt;/p&gt;

&lt;h2&gt;
  
  
  Built-in permissions
&lt;/h2&gt;

&lt;p&gt;SurrealDB's record- and field-level permissions and RBAC model mean that agents only see the data they're supposed to see – enforced at the database layer, not bolted on in application code. Multi-tenant agent deployments become straightforward: each agent session operates within the appropriate permission scope automatically.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://surrealdb.com/docs/learn/security" rel="noopener noreferrer"&gt;Learn more about SurrealDB’s security model.&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to build it
&lt;/h2&gt;

&lt;p&gt;Here's how to put the pattern together from scratch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Define your schema and expose it to the agent&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The SurrealQL generation tool needs schema context to know what tables, fields, and indexes it can play with. It needs this information to infer where to get the data from to answer the user’s question.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- TABLE: product
DEFINE TABLE product SCHEMAFULL;
DEFINE FIELD category ON product TYPE record&amp;lt;category&amp;gt;;
DEFINE FIELD description ON product TYPE string;
DEFINE FIELD embedding ON product TYPE array&amp;lt;float&amp;gt; | none;
DEFINE FIELD name ON product TYPE string;
DEFINE FIELD price ON product TYPE float;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The schema context can be dynamically generated, see snippet below. But once your schema is stable, to avoid extra calls to the DB you can hardcode it (which also gives you more control on what to include in the context) or at least cache it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- example of how to dynamically generate your schema context
LET $db = INFO FOR DB;
$db.tables.values() +
$db.users.values() + 
$db.tables.keys().map(|$t| {
    LET $i = INFO FOR TABLE $t;
    $i.fields.?.values() + $i.indexes.?.values()
}).flatten().filter(|$v| !!$v);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Build the SurrealQL generation tool&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is a function your agent can call. At minimum it needs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A system prompt with schema context and a few-shot examples of valid SurrealQL queries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A SurrealDB client to execute the query and return results&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Optional but recommended: catch any errors when executing the query, and ask the LLM to fix them and try again. Without this retry logic within the tool, the agent may retry the tool altogether, but the LLM call that generates the SurrealQL won’t include the error as context, because it’s not a parameter of the tool. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Wire up the agent tool&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This pattern is framework-agnostic. It works with Pydantic AI agents, LangChain's tool-calling agents, LlamaIndex's ReAct agents, or a custom loop. The key is to provide the agent with a clear tool description so it knows when to use it, e.g. “Use this tool to answer questions about products, orders, reviews, or users”. In the following example, you can see a fine-tuned description that hints to LLM to leverage the vector embeddings when available. In my use case, this prevents the LLM from searching products or categories by matching keywords, preferring vector search instead [2].&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;query_db&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;RunContext&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;Deps&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Use this tool to answer questions about products, orders, reviews,
    or users.

    If required, you can do vector search against any table with an
    embeddings field.
    E.g: `WHERE embedding &amp;lt;|20,40|&amp;gt; fn::embed(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text to embed&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;)`.

    Args:
        question: The user question.
    &lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
    &lt;span class="bp"&gt;...&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;PROMPT_GEN_SURQL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;
You are an expert in SurrealQL (surql, SurrealDB&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s query language).

Generate a valid surql query to get the information required to answer the user&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s prompt.

PROMPT: {prompt}

&amp;lt;schema&amp;gt;
{schema}
&amp;lt;/schema&amp;gt;

&amp;lt;best-practices&amp;gt;
{notes}
&amp;lt;/best-practices&amp;gt;

&amp;lt;examples&amp;gt;
{examples}
&amp;lt;/examples&amp;gt;
&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Find more in &lt;a href="https://github.com/surrealdb/kaig/blob/main/examples/knowledge-graph/tools/query_db.py" rel="noopener noreferrer"&gt;query_db.py&lt;/a&gt; and the &lt;a href="https://github.com/surrealdb/kaig/blob/main/src/kaig/prompts/text_to_surql.py" rel="noopener noreferrer"&gt;prompt template&lt;/a&gt; in the &lt;a href="https://github.com/surrealdb/kaig" rel="noopener noreferrer"&gt;Kai G repo&lt;/a&gt;. If you are new to prompt engineering –or want a good refresher, I recommend watching &lt;a href="https://www.youtube.com/watch?v=ysPbXH0LpIE" rel="noopener noreferrer"&gt;Prompting 101&lt;/a&gt; by Anthropic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Fine-tuning
&lt;/h2&gt;

&lt;p&gt;LLMs are getting better and better at writing complex queries, but they don’t get it right all the time. This is why the prompt and few-shot examples are so important. The ones I shared above were the result of a few manual iterations. You can borrow them for your project, but your specific use case (and model) will require different hints.&lt;/p&gt;

&lt;p&gt;Design your solution in a way that you have good observability to iterate quickly, and metrics to make sure you are moving forward. In my demo, I use Pydantic’s Logfire for observability, and store the results from the text-to-surql function and the query execution with a score. This allows me to capture queries that failed, identify the anti-pattern, and add a line to the tool prompt or a new example to avoid that mistake from surfacing again.&lt;/p&gt;

&lt;p&gt;Some examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;don't use `math::avg`, the correct one is `math::mean`.&lt;/span&gt;
&lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;always `OMIT` the `embedding` field from the final result to avoid large results.&lt;/span&gt;
&lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;vector::distance::knn() must be in SELECT to use in ORDER BY&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The next generation of production AI agents won't be distinguished by how good their embeddings are. They'll be distinguished by &lt;strong&gt;how precisely they can retrieve and present facts&lt;/strong&gt; - with full auditability back to the source.&lt;/p&gt;

&lt;p&gt;Agentic retrieval with a SurrealQL generation tool closes that gap. Instead of hoping a vector similarity search lands close enough, the agent reasons about your question, writes a precise query, and returns exactly the data you asked for. Every answer is traceable to a specific query against a specific table.&lt;/p&gt;

&lt;p&gt;SurrealDB makes this pattern practical: multi-model queries mean the agent handles graph traversals, document lookups, and relational aggregations in a single round-trip, while record-level permissions keep data access secure by default.&lt;/p&gt;

&lt;p&gt;If you're building agents that need to answer questions from structured data - and answer them &lt;strong&gt;correctly&lt;/strong&gt; - this is the architecture worth building toward.&lt;/p&gt;




&lt;h2&gt;
  
  
  Footnotes
&lt;/h2&gt;

&lt;p&gt;[1] You probably don’t want users to have such power. If you allow users to ask any question, they may ask “change the price of SKU-0042 to $0, and create an order with 10 of them ready to checkout”.&lt;/p&gt;

&lt;p&gt;[2] A full-text index could be a better idea, if what you are searching for can effectively be retrieved by lexical means, rather than semantically. And for some use cases &lt;a href="https://surrealdb.com/blog/a-real-world-example-of-hybrid-fusion-search-using-the-surrealdb-docs-search" rel="noopener noreferrer"&gt;reranked hybrid search&lt;/a&gt; could be the right choice. Consider all alternatives based on your use case, and what you are optimising for.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Ready to try it?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://surrealdb.com/cloud" rel="noopener noreferrer"&gt;Create a free SurrealDB Cloud instance&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://surrealdb.com/docs" rel="noopener noreferrer"&gt;Explore the SurrealQL docs&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://discord.gg/surrealdb" rel="noopener noreferrer"&gt;Join the SurrealDB Discord&lt;/a&gt; - new here? The #all-ai and #surrealql channels are the best places to get started.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
