How to Implement Agent Memory Using Oracle AI Database with the oracleagentmemory Package

The oracleagentmemory package provides a Python SDK that transforms Oracle AI Database into a persistent, ACID-compliant memory store for AI agents using native vector capabilities.

The oracle-devrel/oracle-ai-developer-hub repository delivers a production-ready framework for implementing agent memory using Oracle AI Database. By leveraging the Oracle AI Agent Memory Package (OAMP)—oracleagentmemory—you can store embeddings, manage conversation threads, and retrieve context using the database's native VECTOR column type and HNSW indexes, eliminating the need for separate vector databases.

Why Use Oracle AI Database for Agent Memory?

Traditional AI architectures often split transactional data and vector embeddings across separate systems, creating synchronization headaches and consistency risks. Oracle AI Database solves this by combining relational ACID compliance with native vector operations.

Unified storage means your agent's memories live in the same database as your business data. You can query memories using standard SQL, join them with operational tables, and maintain transactional integrity. The database handles HNSW (Hierarchical Navigable Small World) indexes internally, delivering sub-millisecond similarity searches even at millions of vectors without external vector stores.

Architecture Overview

Database Layer with Native Vector Support

At the foundation, Oracle AI Database provides the VECTOR column type and VECTOR_DISTANCE() function for similarity calculations. The repository includes a Docker-based lab environment that provisions a pre-configured VECTOR schema (username: VECTOR, password: VectorPwd_2025) with HNSW indexes ready for immediate use. See the setup instructions in [workshops/agent_memory_workshop/docs/part-1-oracle-setup.md](https://github.com/oracle-devrel/oracle-ai-developer-hub/blob/main/workshops/agent_memory_workshop/docs/part-1-oracle-setup.md).

The OracleAgentMemory Python SDK

The oracleagentmemory package wraps database primitives behind a clean Python API. The core class, oracleagentmemory.core.OracleAgentMemory, manages connection pooling, automatic table creation, and embedding generation. It handles entity CRUD operations for users, agents, and memories while abstracting the underlying SQL and vector math.

Agent Memory Primitives

The SDK implements four key abstractions:

  • Users – Own memory collections and provide isolation boundaries
  • Agents – Represent AI personalities that generate memories
  • Memories – Text content paired with vector embeddings, optionally scoped to specific users, agents, or threads
  • Threads – Logical conversation containers that aggregate relevant memories into context cards for LLM prompts

Environment Setup

Before implementing memory operations, you need a running Oracle AI Database instance. The repository provides a Docker container with the necessary schema:

  1. Clone the oracle-devrel/oracle-ai-developer-hub repository
  2. Follow the Docker setup in part-1-oracle-setup.md to launch the database
  3. Verify connectivity to localhost:1521/FREEPDB1 with the VECTOR user

The setup guide includes a reusable connection helper that implements retry logic for container startup timing.

Implementing Memory Storage and Retrieval

Once your database is running, implement agent memory in Python using the following workflow derived from notebooks/agent_memory/oracle_agent_memory_developer_guide.ipynb:

Install the Package

%pip install "oracleagentmemory[litellm]"

Connect to the Database

import oracledb
from oracleagentmemory.core import OracleAgentMemory

def connect_to_oracle(user="VECTOR", password="VectorPwd_2025",
                      dsn="localhost:1521/FREEPDB1", max_retries=3, retry_delay=5):
    for attempt in range(1, max_retries + 1):
        try:
            conn = oracledb.connect(
                user=user,
                password=password,
                dsn=dsn,
                mode=oracledb.DEFAULT_AUTH,
            )
            conn.clientinfo = "agent_memory_demo"
            return conn
        except Exception as e:
            if attempt < max_retries:
                import time; time.sleep(retry_delay)
            else:
                raise e

vector_conn = connect_to_oracle()

Initialize the Memory Client

client = OracleAgentMemory(conn=vector_conn)

The client automatically creates necessary tables if they don't exist, targeting the VECTOR schema.

Register Users and Agents

The API is idempotent—attempting to add existing entities raises clear errors you can handle:

USER_ID = "dev-guide-user"
AGENT_ID = "dev-guide-agent"

for fn, eid, desc in [
    (client.add_user, USER_ID, "Richmond – AI developer learning the package."),
    (client.add_agent, AGENT_ID, "Tutorial assistant for the AI Agent Package.")
]:
    try:
        fn(eid, desc)
        print(f"Registered {eid}")
    except ValueError as exc:
        if "already exists" in str(exc):
            print(f"(already exists: {eid})")
        else:
            raise

Store Memories with Automatic Embedding

Pass raw text to add_memory(); the SDK calls your configured embedder and stores the vector:

mem_id = client.add_memory(
    "Richmond is evaluating the AI Agent Package for a production RAG pipeline with 50k daily queries.",
    user_id=USER_ID,
    agent_id=AGENT_ID,
)
print(f"Memory stored with ID: {mem_id}")

Search Memories via Vector Similarity

Use search_memories() to retrieve relevant context using HNSW index acceleration:

results = client.search_memories(
    "Who is evaluating the AI Agent Package?",
    top_k=5,
    user_id=USER_ID,
    agent_id=AGENT_ID,
)
for mem in results:
    print(f"⚡ {mem.id}: {mem.content[:80]}…")

Generate Context Cards for LLM Prompts

Build conversation context by aggregating top-k memories into a structured context card:

thread_id = "demo-thread"
card = client.get_context_card(
    thread_id=thread_id,
    user_id=USER_ID,
    agent_id=AGENT_ID,
    top_k=3
)
print("🧩 Context card:")
print(card.text)

Async support: The OracleAgentMemory class exposes async equivalents including add_memory_async(), search_memories_async(), and get_context_card_async() for non-blocking applications.

LLM Integration Options

The oracleagentmemory package supports multiple embedding and generation backends through LiteLLM, enabling you to use OpenAI, Anthropic, or local models. For Oracle Cloud Infrastructure deployments, the package integrates directly with OCI Generative AI.

See notebooks/agent_memory/oracle_agent_memory_developer_guide_oci.ipynb for a complete OCI-native workflow using oracleagentmemory==26.4.0 with OCI extras. This notebook demonstrates configuring the IEmbedder and ILlm interfaces to use OCI's embedding and generation endpoints.

Performance and Benchmarking

For production sizing, refer to notebooks/agent_memory/oracle_agent_memory_benchmarks.ipynb. This notebook contains stress tests measuring insert throughput, vector search latency, and context-card generation performance across different memory pool sizes.

Summary

  • Unified architecture – The oracleagentmemory package combines Oracle AI Database's relational ACID compliance with native vector search, eliminating the need for separate vector stores.
  • Simple Python SDK – The OracleAgentMemory class in oracleagentmemory.core handles connection management, automatic embedding, and CRUD operations for users, agents, and memories.
  • Production-ready primitives – Built-in support for users, agents, memory threads, and context cards enables sophisticated agent workflows with minimal boilerplate.
  • Flexible LLM integration – Works with LiteLLM-compatible providers or OCI Generative AI via configurable embedder interfaces.
  • High-performance search – Leverages Oracle's HNSW indexes for millisecond-level similarity queries across millions of vectors.

Frequently Asked Questions

What is the oracleagentmemory package?

The oracleagentmemory package (OAMP) is a Python SDK that builds a thin abstraction layer on top of Oracle AI Database's vector capabilities. It enables developers to treat the database as a persistent memory store for AI agents, handling embedding generation, vector storage, and similarity search through a clean API.

How does vector search work in this implementation?

Vector search uses Oracle AI Database's native VECTOR column type and HNSW (Hierarchical Navigable Small World) indexes. When you call client.search_memories(), the SDK executes a SQL query using the VECTOR_DISTANCE() function, which computes cosine similarity between the query embedding and stored memory vectors using the optimized HNSW index.

Can I use Oracle Cloud Infrastructure (OCI) Generative AI instead of third-party LLMs?

Yes. The package supports OCI Generative AI through a specific extras install and configuration. The repository includes oracle_agent_memory_developer_guide_oci.ipynb, which demonstrates implementing the IEmbedder and ILlm interfaces to use OCI's embedding and chat models for a fully OCI-native deployment.

Is the agent memory storage ACID-compliant?

Yes. Because memories are stored as rows in Oracle AI Database rather than external vector stores, all operations inherit full ACID properties. This ensures that memory writes are durable, isolated, and consistent with your relational data, preventing data loss or synchronization issues between your agent's memory and business logic.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →