Memory & Context

The Context Engine is the unified memory layer for agents. It handles document ingestion, scoped retrieval, deduplication, and lifecycle management. Pass it as memory= to any agent for zero-change RAG integration.

from sagewai import ContextEngine, UniversalAgent
from sagewai.context import InMemoryMetadataStore, InMemoryVectorStore

engine = ContextEngine(
    metadata_store=InMemoryMetadataStore(),
    vector_store=InMemoryVectorStore(),
)
agent = UniversalAgent(name="assistant", model="gpt-4o", memory=engine)

ContextEngine

Unified context creation and management. Implements the MemoryProvider protocol.

Handles:

  • Universal data ingestion (files, directories, URLs, text)
  • Scoped retrieval with inheritance (org, project)
  • Multi-strategy search (vector + BM25 + graph, merged via RRF)
  • Automatic deduplication
  • Lifecycle management (compress, archive, discard)
from sagewai import ContextEngine
from sagewai.context import InMemoryMetadataStore, InMemoryVectorStore

engine = ContextEngine(
    metadata_store=InMemoryMetadataStore(),
    vector_store=InMemoryVectorStore(),
)

Constructor

ParameterTypeDefaultDescription
metadata_storeContextMetadataStorerequiredStore for document metadata
vector_storeContextVectorStorerequiredStore for vector embeddings
graph_storeAny | NoneNoneGraph store for knowledge graph retrieval
embedding_modelstr"text-embedding-3-small"Embedding model for vectorization
chunking_configChunkingConfig | NoneNoneCustom chunking settings
project_idstr | NoneNoneProject scope for isolation
org_idstr | NoneNoneOrganization scope
rerankerAny | NoneNoneCross-encoder re-ranker
enable_bm25boolTrueEnable BM25 keyword search
event_callbackAny | NoneNoneObservability callback
lifecycle_configAny | NoneNoneAuto-trigger lifecycle settings

Key Methods

MethodSignatureReturnsDescription
retrieveasync retrieve(query, top_k=5)list[str]MemoryProvider protocol -- retrieve context strings
storeasync store(content, metadata=None)NoneMemoryProvider protocol -- store content
searchasync search(query, top_k=5)list[ContextSearchResult]Multi-strategy search with full result objects
ingest_fileasync ingest_file(data, filename, scope, scope_id)ContextDocumentIngest a file (PDF, code, text, etc.)
ingest_textasync ingest_text(text, title, scope, scope_id)ContextDocumentIngest raw text
ingest_urlasync ingest_url(url, scope, scope_id)ContextDocumentFetch and ingest a URL

Production Stores

For production deployments, use persistent stores:

from sagewai.context import PostgresContextStore, MilvusContextVectorStore

engine = ContextEngine(
    metadata_store=PostgresContextStore(pool=asyncpg_pool),
    vector_store=MilvusContextVectorStore(uri="http://localhost:19530"),
)

ContextScope

Access scope levels for context entries. Two levels:

from sagewai import ContextScope

ContextScope.ORG       # Visible to all projects in the organization
ContextScope.PROJECT   # Visible only within the owning project
ValueDescription
ORGOrganization-wide visibility
PROJECTProject-scoped visibility

ContextSource

Origin of context data.

from sagewai import ContextSource

ContextSource.UPLOAD        # File upload
ContextSource.DIRECTORY     # Directory indexing
ContextSource.URL           # URL fetch
ContextSource.CONVERSATION  # Extracted from conversation
ContextSource.WORKFLOW      # Workflow output
ContextSource.RESEARCH      # Research task
ContextSource.MANUAL        # Manual entry
ContextSource.EPISODE       # Episodic memory

ChatMessage

Immutable message in a conversation. Used throughout the SDK for message passing.

from sagewai import ChatMessage

msg = ChatMessage.system("You are a helpful assistant.")
msg = ChatMessage.user("Hello!")
msg = ChatMessage.assistant("Hi there!")
msg = ChatMessage.tool_result(
    tool_call_id="tc_1",
    name="search",
    content="Found 3 results...",
)

Fields

FieldTypeDescription
roleRolesystem, user, assistant, or tool
contentstr | NoneText content
tool_callslist[ToolCall] | NoneTool calls requested by the assistant
tool_call_idstr | NoneID linking a tool result to its call
namestr | NoneTool name (for tool results)
usageUsageInfo | NoneToken usage info

Factory Methods

MethodParametersDescription
ChatMessage.system(content)content: strCreate a system message
ChatMessage.user(content)content: strCreate a user message
ChatMessage.assistant(content)content: strCreate an assistant message
ChatMessage.tool_result(...)tool_call_id, name, contentCreate a tool result message