Retrieve-Augment-Generate: compose memory search with AI generation. Accepts chat-fn parameter for provider-free AI calls.
Values
DEFAULT_MEMORY_HEADING
DEFAULT_MEMORY_HEADING: Str "## Memory"
DEFAULT_SUMMARY_INSTRUCTION
DEFAULT_SUMMARY_INSTRUCTION: Str "Summarize the key topics, decisions, and action items from this conversation."
DEFAULT_SUMMARY_SYSTEM
DEFAULT_SUMMARY_SYSTEM: Str "You are a helpful assistant that summarizes conversations concisely."
DEFAULT_SYSTEM
DEFAULT_SYSTEM: Str "You are a helpful AI assistant. Answer based on the provided context. Cite sources when possible."
DEFAULT_SYSTEM_THREAD
DEFAULT_SYSTEM_THREAD: Str "You are a helpful AI assistant. Answer based on the provided context and conversation history."
Functions
ask
fn (mem: ::ai::memory/AgentMemory, question: Str, chat-opts: ::ai::chat/ChatOptions, opts: Map?): Map
Search memory for relevant context, then generate an AI answer. Returns {answer, sources}.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Any provider's chat function fits here
chat-fn (model, prompt, system) { `Answer to: ${prompt}` }
opts ::ai::chat/ChatOptions({chat-fn: chat-fn, model: "claude-sonnet-4-5"})
result ::ai::rag/ask(mem, "How long do refunds take?", opts, {limit: 5})
result.answer
length(result.sources)
ask-with-context
fn (mem: ::ai::memory/AgentMemory, question: Str, chat-opts: ::ai::chat/ChatOptions, opts: Map?, context: Str): Map
Like ask, for a context string you built yourself. Generates the
answer from it, then searches session memory for sources. Returns
{answer, sources}.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Any provider's chat function fits here
chat-fn (model, prompt, system) { `Answer to: ${prompt}` }
opts ::ai::chat/ChatOptions({chat-fn: chat-fn, model: "claude-sonnet-4-5"})
context ::ai::rag/build-context-safe(mem, "refund policy", null)
result ::ai::rag/ask-with-context(mem, "How long do refunds take?", opts, {limit: 5}, context)
result.answer
ask-with-thread
fn (mem: ::ai::memory/AgentMemory, t: ::ai::memory/Thread, question: Str, chat-opts: ::ai::chat/ChatOptions, opts: Map?): Map
Like ask, but includes thread history for multi-turn context. Appends question and answer to the thread automatically.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Any provider's chat function fits here
chat-fn (model, prompt, system) { `Answer to: ${prompt}` }
opts ::ai::chat/ChatOptions({chat-fn: chat-fn, model: "claude-sonnet-4-5"})
t ::mem/thread(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"}),
null
)
result ::ai::rag/ask-with-thread(mem, t, "And for digital orders?", opts, null)
result.answer
build-context
fn (mem: ::ai::memory/AgentMemory, query: Str, opts: Map?): Str
Search session memory and KB, format as a context string for AI prompts. Options: limit (default 10), min-score (default 0.5).
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
context ::ai::rag/build-context(mem, "refund policy", {limit: 5, min-score: 0.7})
if(is-err(context), "search failed", context)
build-context-safe
fn (mem: ::ai::memory/AgentMemory, query: Str, opts: Map?): Str
Best-effort build-context. Any failure (no embedding provider
configured, transient store error, etc.) degrades to "" so callers
can still answer ungrounded rather than aborting the whole reply.
Use this in interactive request paths and demos / CI / offline
tutorials where an embedding backend may not be wired. Prefer
build-context directly in code paths that should propagate errors.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Empty string when the store or embedding provider is unavailable
context ::ai::rag/build-context-safe(mem, "refund policy", null)
::ai::rag/with-memory-block("You are a support agent.", context, null)
build-hybrid-context
fn (mem: ::ai::memory/AgentMemory, query: Str, opts: Map?): Str
Build a citation-preserving context string from hybrid vector + graph retrieval.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
::ai::rag/build-hybrid-context(mem, "refund policy", {limit: 5, seed-node-ids: ["topic:refunds"]})
build-rag-prompt
fn (history-text: Str, context: Str, question: Str): Str
Compose a RAG prompt from optional history, optional context, and a question.
Example
::ai::rag/build-rag-prompt("", "", "What is Hot?") // "What is Hot?"
::ai::rag/build-rag-prompt("", "Hot is a language.", "What is Hot?")
// "Context from memory:\nHot is a language.\n\n---\nQuestion: What is Hot?"
compact-window
fn (mem: ::ai::memory/AgentMemory, chat-opts: ::ai::chat/ChatOptions, opts: Map?): ::ai::memory/MemoryCapsule
Summarize a recent memory window into a durable MemoryCapsule and store it in the KB. Options: hours, limit, id, instruction, metadata, emit-stream.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Any provider's chat function fits here
chat-fn (model, prompt, system) { `Answer to: ${prompt}` }
opts ::ai::chat/ChatOptions({chat-fn: chat-fn, model: "claude-sonnet-4-5"})
capsule ::ai::rag/compact-window(mem, opts, {hours: 24, id: "2026-11-09"})
capsule.summary
capsule.source-ids
compact-window-safe
fn (mem: ::ai::memory/AgentMemory, chat-opts: ::ai::chat/ChatOptions, opts: Map?): Map
Like compact-window, returning {ok, capsule, error} and emitting
compaction errors when requested.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Any provider's chat function fits here
chat-fn (model, prompt, system) { `Answer to: ${prompt}` }
opts ::ai::chat/ChatOptions({chat-fn: chat-fn, model: "claude-sonnet-4-5"})
result ::ai::rag/compact-window-safe(mem, opts, {hours: 24, emit-stream: true})
if(result.ok, result.capsule.id, result.error)
format-kb-results
fn (results: Vec): Vec
Format a Vec of KB search results as [KB] content lines.
Example
::ai::rag/format-kb-results([{value: {content: "Refunds take 5 days."}}]) // ["[KB] Refunds take 5 days."]
format-session-results
fn (results: Vec): Vec
Format a Vec of store search results (with v.sender-name, v.content) as
[name]: content lines.
Example
::ai::rag/format-session-results([{value: {sender-name: "Ada", content: "Hello"}}]) // ["[Ada]: Hello"]
format-thread-lines
fn (history: Vec): Str
Format a Vec of ChatMessages as role: content lines.
Example
::ai::rag/format-thread-lines([::ai::message/user-msg("Hi")])
// "Previous conversation:\nuser: Hi\n---\n"
::ai::rag/format-thread-lines([]) // ""
passes-role-filter
fn (entry: Map, include-roles: Vec?, exclude-roles: Vec?): Bool
Apply include-roles / exclude-roles semantics:
- When
include-rolesis non-empty, the entry must have a role in that list. Untagged entries are dropped. exclude-rolesis a blacklist applied next. Tagged matches are dropped; untagged entries pass.- With neither set, every entry passes.
Example
entry {value: {metadata: {role: "assistant"}}}
::ai::rag/passes-role-filter(entry, ["assistant"], null) // true
::ai::rag/passes-role-filter(entry, null, ["assistant"]) // false
::ai::rag/passes-role-filter({value: {}}, null, ["assistant"]) // true
recent-text
fn (mem: ::ai::memory/AgentMemory, opts: Map?): Str
Format recent session memory as bulleted - <content> lines, oldest
first.
Convenience over ::ai::memory/recent for synthesis prompts that want
the raw window as text rather than a finished summary. Errors degrade
to "" so missing stores / providers don't crash callers.
Options:
limit— number of records to include (default 100, matches::ai::memory/recent).hours— recency window in hours (default 24).include-roles—Vec<Str>?. When set, only records whosemetadata.roleis in this list are kept. Untagged records are dropped.exclude-roles—Vec<Str>?. When set, records whosemetadata.roleis in this list are dropped. Untagged records pass.
The role filters compose with limit: filtering happens after
recent, so limit bounds the window, not the post-filter count.
For synthesis prompts that want only user turns + task records,
pass exclude-roles: ["assistant"].
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
::ai::rag/recent-text(mem, {hours: 6, limit: 20, exclude-roles: ["assistant"]})
role-in
fn (roles: Vec, role: Str): Bool
True when role equals any element of roles.
Example
::ai::rag/role-in(["user", "tool"], "user") // true
::ai::rag/role-in(["user", "tool"], "assistant") // false
role-of
fn (entry: Map): Str
Read the role tag from a ::ai::memory/recent entry's metadata.
Returns "" when unset so role filters never accidentally drop
untagged records (callers asking to exclude assistant shouldn't
also exclude legacy un-roled writes).
Example
::ai::rag/role-of({value: {metadata: {role: "user"}}}) // "user"
::ai::rag/role-of({value: {}}) // ""
summarize
fn (mem: ::ai::memory/AgentMemory, chat-opts: ::ai::chat/ChatOptions, opts: Map?): Str
Summarize recent messages from session memory using AI. Options: hours, limit, instruction.
Example
::mem ::ai::memory
mem ::mem/create-memory(
"support-bot",
::ai::session/Session({id: "slack:C123"}),
::ai::session/Identity({id: "u1", name: "Ada"})
)
// Any provider's chat function fits here
chat-fn (model, prompt, system) { `Answer to: ${prompt}` }
opts ::ai::chat/ChatOptions({chat-fn: chat-fn, model: "claude-sonnet-4-5"})
::ai::rag/summarize(mem, opts, {hours: 24, instruction: "List the open issues."})
with-memory-block
fn (base: Str, context: Str, heading: Str?): Str
Compose a system prompt by appending a memory-context section to base.
Returns base unchanged when context is empty (or whitespace only), so
callers can pass the result of build-context / build-context-safe
directly without branching. When context is non-empty, the result is
${base}\n\n${heading}\n${context}. heading defaults to ## Memory.
Example
::ai::rag/with-memory-block("You help.", "Ada likes tea.", null) // "You help.\n\n## Memory\nAda likes tea."
::ai::rag/with-memory-block("You help.", "", null) // "You help."