Threads
This page presents the concrete Oracle thread handle together with the developer-facing message helper type.
Oracle Thread
class oracleagentmemory.core.OracleThread
Bases: IThread
Thread backed by an Oracle store.
This implementation embeds and stores both thread messages and manually added memories, then supports similarity search over all stored records.
Notes
- Messages are stored as individual records (one record per message).
- Search can be restricted to the current thread, or allowed to return results from any thread (client-controlled).
Create a new OracleThread instance.
- Parameters:
- store
OracleMemoryStore– Shared store backend used to persist embedded records. - thread_id
str– Thread identifier. If not provided, a UUID is generated. - user_id
str– User identifier associated with the thread. If omitted on a DBSchemaPolicy.NO_CHECKruntime store, the active end-user security context’s username is used. Otherwise, a UUID is generated. - agent_id
str– Agent identifier associated with the thread. If omitted, a UUID is generated. - metadata
dict[str, Any] | None– Optional JSON-like metadata associated with the thread. - persist_messages_in_config
bool– Whether_to_configshould include recent raw message snapshots. Automatically set toFalsefor threads using the DB store to avoid exporting message-table contents through thread config. - llm
ILlm | None– Optional LLM adapter used for memory extraction and context summary updates. When provided,add_messageswill extract relevant memories from each added message and store them as typed memory records ("memory","guideline","fact", or"preference"). - memory_extraction_config
MemoryExtractionConfig– Optional thread-level memory extraction configuration. Use it to control automatic extraction settings such as extraction mode, summary behavior, extraction limits, and whether automatic extraction is enabled at all. Pass either this grouped config or the deprecated inline extraction parameters, not both. When omitted, standaloneOracleThread()uses SDK defaults for the extraction fields and keeps context summaries enabled. An omitted image context isDISABLED. - image_input_limit_config
ImageInputLimitConfig– Optional raw-image and LLM image-request limits for this standalone thread. Omitted fields use SDK defaults. Validation cannot be disabled. -
memory_extraction_window
int–Number of most recent messages (including the newly added one) to provide as context to the LLM during extraction. Set to
-1to extract only once peradd_messagescall using the full batch of newly added messages. Defaults to-1.Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. -
context_summary_update_frequency
int–Number of messages after the latest valid summary before automatically refreshing it. When memory extraction is enabled, the check is after each due extraction, so refresh can occur later. Values less than or equal to
0refresh at every check. Defaults to-1.Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. -
memory_extraction_frequency
int–Number of messages after which the memory extraction is triggered. Set to
-1to extract only once peradd_messagescall using the full batch of newly added messages.Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. -
memory_extraction_token_limit
int–Maximum size, in tokens, of the LLM prompts used for memory extraction and running summary updates. Longer prompts are truncated. If negative or 0, prompt truncation is disabled.
Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. - context_card_token_limit
int– Maximum input token budget for the LLM prompt used to build the summary and topic list included in the context card. Defaults to100_000; values less than or equal to 0 disable prompt truncation. - context_card_type_search_concurrency
int– Maximum number of memory-like record searches to run concurrently when building a context card withmin_relevant_results_by_type. Defaults to5. - max_message_token_length
int– Maximum size, in tokens, of the prompt-time copy of each message used during LLM-backed memory extraction and context-summary updates. Stored message content remains unchanged. If negative or 0, no prompt-time shortening is performed. If an LLM is provided, oversized prompt copies are summarized instead of truncated. - message_shortening_input_token_limit
int– Maximum size, in tokens, of the message excerpt sent to the LLM when shortening oversized prompt copies. Defaults to30_000tokens. If negative or 0, no outbound bound is applied during LLM-based shortening. -
enable_context_summary
bool–Whether to keep a compact summary of the thread. When enabled and an
llmis provided, OAM refreshes it according tocontext_summary_update_frequencyand uses a summary from before the target messages as extraction context. Defaults toTruefor standaloneOracleThread().Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. -
memory_extraction_custom_instructions
str | None–Optional custom instructions appended to the automatic memory extraction system prompt for this thread.
Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. -
memory_extraction_inherit_message_metadata
bool | Sequence[str]–Whether automatically extracted memories inherit metadata from source messages. Pass
Trueto inherit all message metadata, a non-string sequence of top-level message metadata keys to inherit only those keys, orFalseto disable inheritance. Defaults toTrue. If one extraction pass uses multiple source messages, the selected metadata must match across those messages.Deprecated
Deprecated since version 26.6.0: This parameter was deprecated in 26.6.0 and will be removed in 27.1. Please use
memory_extraction_configinstead. - search_config
MemorySearchConfig– Optional search configuration for this thread. When omitted, searches use a fixed top-k search configuration. - client
OracleAgentMemory | None
- store
Examples
from oracleagentmemory.core import MemoryExtractionConfig, OracleAgentMemory
client = OracleAgentMemory(connection=db_pool, embedder=embedder)
thread = client.create_thread(
thread_id="c4",
llm=llm,
memory_extraction_config=MemoryExtractionConfig(enable_context_summary=True),
)
len(thread.add_messages([{"role": "user", "content": "I love pizza."}]))
1
method add_image
Persist one image associated with this thread.
description is stored as the image’s searchable text. When it is
omitted or None, an attached LLM generates a caption. Omitted scope
values inherit this thread’s corresponding user, agent, and thread
identifiers.
- Parameters:
- image
bytes– Raw image bytes to persist. - description
str | None– Optional description or caption. Omit it to generate a caption. - mime_type
ImageMimeType– Optional MIME type used for image persistence and caption generation. When omitted, the SDK detects and validates the type from the image bytes. The supported detected types are PNG, JPEG, and WEBP. - image_id
str– Optional identifier. One is generated when omitted. - user_id
str | None– Optional scope assertions. Omitted values inherit this thread’s scope; provided values must match it exactly. - agent_id
str | None– Optional scope assertions. Omitted values inherit this thread’s scope; provided values must match it exactly. - thread_id
str– Optional scope assertions. Omitted values inherit this thread’s scope; provided values must match it exactly. - metadata
dict[str, Any] | None– Optional metadata stored with the image. - timestamp
str | None– Optional event timestamp to save for this image. Omit this argument or passNoneto store aNULLevent timestamp. When the image is read, its creation time is returned as the effective timestamp. - ttl_days
int | None– Optional expiration settings. - ttl_anchor
TimeToLiveAnchor– Optional expiration settings. - store_kwargs
Any– Additional store-specific options.
- image
- Returns: The persisted image identifier.
- Return type: str
method add_image_async (async)
Persist one image associated with this thread asynchronously.
description is stored as the image’s searchable text. When it is
omitted or None, an attached LLM generates a caption. Omitted scope
values inherit this thread’s corresponding user, agent, and thread
identifiers.
- Parameters:
- image
bytes– Raw image bytes to persist. - description
str | None– Optional description or caption. Omit it to generate a caption. - mime_type
ImageMimeType– Optional MIME type used for image persistence and caption generation. When omitted, the SDK detects and validates the type from the image bytes. The supported detected types are PNG, JPEG, and WEBP. - image_id
str– Optional identifier. One is generated when omitted. - user_id
str | None– Optional scope assertions. Omitted values inherit this thread’s scope; provided values must match it exactly. - agent_id
str | None– Optional scope assertions. Omitted values inherit this thread’s scope; provided values must match it exactly. - thread_id
str– Optional scope assertions. Omitted values inherit this thread’s scope; provided values must match it exactly. - metadata
dict[str, Any] | None– Optional metadata stored with the image. - timestamp
str | None– Optional event timestamp to save for this image. Omit this argument or passNoneto store aNULLevent timestamp. When the image is read, its creation time is returned as the effective timestamp. - ttl_days
int | None– Optional expiration settings. - ttl_anchor
TimeToLiveAnchor– Optional expiration settings. - store_kwargs
Any– Additional store-specific options.
- image
- Returns: The persisted image identifier.
- Return type: str
method add_memory
Add a manual memory entry and index it.
- Parameters:
- content
str– Text content to store as a memory. - memory_type
Literal['memory', 'guideline', 'fact', 'preference'] | ~oracleagentmemory._notset._NotSetMarker– Memory category to store. Supported values are"memory","fact","guideline", and"preference". When omitted, the content is stored as a general"memory". - user_id
str– Optional user identifier override. - agent_id
str– Optional agent identifier override. - thread_id
str– Optional thread identifier override. - memory_id
str– Optional caller-provided stable identifier for this memory row. - metadata
dict[str, Any] | None– Optional metadata to persist with the stored memory. - timestamp
str | None– Optional event timestamp to save for this memory. Omit this argument or passNoneto store aNULLevent timestamp. When the record is read, its creation time is returned as the effective timestamp. Whenttl_anchorisTimeToLiveAnchor.TIMESTAMP, provide a concrete ISO-8601 timestamp value. ISO-8601 timestamps without a timezone are treated as UTC. - ttl_days
int | None– Optional time-to-live duration in days. Omit this argument to use the schema default time-to-live duration. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to store a non-expiring memory when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. - ttl_anchor
TimeToLiveAnchor– Optional time-to-live anchor. UseTimeToLiveAnchor.CREATED_ATfor the database creation time orTimeToLiveAnchor.TIMESTAMPfor the memory timestamp. Timestamp-anchored expiration requires a concrete ISO-8601 timestamp for this memory. ISO-8601 timestamps without a timezone are treated as UTC. - status
RecordStatus– Initial lifecycle status. Omit it to storeRecordStatus.VALID. - autonomous_linking
bool– Whether to create links from this new memory to relevant stored memories using the thread’s LLM. Omitted enables it when an LLM exists; passFalseto skip. Failure leaves the memory stored. - memory_id_to_link
str– Together, create a directed link from the new memory to this existing thread-owned memory. Omitted user, agent, and thread scopes inherit from that target. Omit both to create no explicit link. - link_type
Literal['supersedes', 'contradicts', 'refines', 'supports', 'duplicates'] | ~oracleagentmemory._notset._NotSetMarker– Together, create a directed link from the new memory to this existing thread-owned memory. Omitted user, agent, and thread scopes inherit from that target. Omit both to create no explicit link. - link_id
str– Optional identifier, timestamp, and metadata for the explicit link. - link_timestamp
str | None– Optional identifier, timestamp, and metadata for the explicit link. - link_metadata
dict[str, Any] | None– Optional identifier, timestamp, and metadata for the explicit link. - **store_kwargs (Any) – Store-specific write options forwarded to the backing store.
- content
- Returns: Identifier of the inserted memory record.
- Return type: str
Examples
thread.add_memory("Remember this preference", memory_id="mem-thread-docs")
'mem-thread-docs'
method add_memory_async (async)
Add a manual memory entry and index it asynchronously.
- Parameters:
- content
str– Text content to store as a memory. - memory_type
Literal['memory', 'guideline', 'fact', 'preference'] | ~oracleagentmemory._notset._NotSetMarker– Memory category to store. Supported values are"memory","fact","guideline", and"preference". When omitted, the content is stored as a general"memory". - user_id
str– Optional user identifier override. - agent_id
str– Optional agent identifier override. - thread_id
str– Optional thread identifier override. - memory_id
str– Optional caller-provided stable identifier for this memory row. - metadata
dict[str, Any] | None– Optional metadata to persist with the stored memory. - timestamp
str | None– Optional event timestamp to save for this memory. Omit this argument or passNoneto store aNULLevent timestamp. When the record is read, its creation time is returned as the effective timestamp. Whenttl_anchorisTimeToLiveAnchor.TIMESTAMP, provide a concrete ISO-8601 timestamp value. ISO-8601 timestamps without a timezone are treated as UTC. - ttl_days
int | None– Optional time-to-live duration in days. Omit this argument to use the schema default time-to-live duration. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to store a non-expiring memory when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. - ttl_anchor
TimeToLiveAnchor– Optional time-to-live anchor. UseTimeToLiveAnchor.CREATED_ATfor the database creation time orTimeToLiveAnchor.TIMESTAMPfor the memory timestamp. Timestamp-anchored expiration requires a concrete ISO-8601 timestamp for this memory. ISO-8601 timestamps without a timezone are treated as UTC. - status
RecordStatus– Initial lifecycle status. Omit it to storeRecordStatus.VALID. - autonomous_linking
bool– Whether to create links from this new memory to relevant stored memories using the thread’s LLM. Omitted enables it when an LLM exists; passFalseto skip. Failure leaves the memory stored. - memory_id_to_link
str– Together, create a directed link from the new memory to this existing thread-owned memory. Omitted user, agent, and thread scopes inherit from that target. Omit both to create no explicit link. - link_type
Literal['supersedes', 'contradicts', 'refines', 'supports', 'duplicates'] | ~oracleagentmemory._notset._NotSetMarker– Together, create a directed link from the new memory to this existing thread-owned memory. Omitted user, agent, and thread scopes inherit from that target. Omit both to create no explicit link. - link_id
str– Optional identifier, timestamp, and metadata for the explicit link. - link_timestamp
str | None– Optional identifier, timestamp, and metadata for the explicit link. - link_metadata
dict[str, Any] | None– Optional identifier, timestamp, and metadata for the explicit link. - **store_kwargs (Any) – Store-specific write options forwarded to the backing store.
- content
- Returns: Identifier of the inserted memory record.
- Return type: str
Examples
import asyncio
asyncio.run(thread.add_memory_async(
"Remember this preference", memory_id="mem-thread-docs-async"
))
'mem-thread-docs-async'
method add_messages
Add messages to the thread and index them.
In background extraction mode, this method returns after raw messages are inserted and due background extraction is attempted in the background.
Raw messages are stored before automatic extraction in either mode. If later extraction or derived-memory storage fails, the raw messages remain stored while derived memories or summary updates may be missing.
- Parameters:
- messages
Sequence[Message | ThreadMessageTypedDictT | Mapping[str, str | Sequence[Mapping[str, Any]] | Mapping[str, Any] | None]]– List of messages to append. Messages can beMessageobjects or dictionaries withroleandcontent(and optionalid). - metadata
dict[str, Any] | None | list[dict[str, Any] | None]– Optional shared or per-message metadata to persist. When omitted, metadata embedded in each message is used. - ttl_days
int | None | list[int | None]– Optional time-to-live duration in days for appended messages. Omit this argument to use the schema default time-to-live duration. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to create non-expiring messages when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. Scalar values apply to the full batch. - ttl_anchor
TimeToLiveAnchor | list[TimeToLiveAnchor]– Optional time-to-live anchor. UseTimeToLiveAnchor.CREATED_ATfor database creation time orTimeToLiveAnchor.TIMESTAMPfor each message timestamp. Timestamp-anchored expiration requires a concrete ISO-8601 timestamp for each affected message. When omitted, messages expire relative toTimeToLiveAnchor.CREATED_AT. ISO-8601 timestamps without a timezone are treated as UTC. - **store_kwargs (Any) – Store-specific write options forwarded to the backing store.
- messages
- Returns: Identifiers of inserted message records. In background extraction mode, automatic extraction work may still be running when these identifiers are returned.
- Return type: list[str]
Notes
In MemoryExtractionMode.BACKGROUND, raw messages are persisted
before extracted memories are stored. If background extraction does
not queue, or if a configured queue-capacity wait reaches its
timeout, the inserted raw messages remain stored and the call either
continues without extracted memories or raises TimeoutError,
depending on background_extraction_queue_full_behavior.
Examples
len(thread.add_messages([{"role": "user", "content": "Thread message from docs"}]))
1
method add_messages_async (async)
Asynchronously add messages to the thread and index them.
In background extraction mode, this method returns after raw messages are inserted and due background extraction is attempted in the background.
Raw messages are stored before automatic extraction in either mode. If later extraction or derived-memory storage fails, the raw messages remain stored while derived memories or summary updates may be missing.
In MemoryExtractionMode.BACKGROUND, raw messages are persisted
before extracted memories are stored. If background extraction does
not queue, or if a configured queue-capacity wait reaches its
timeout, the inserted raw messages remain stored and the call either
continues without extracted memories or raises TimeoutError,
depending on background_extraction_queue_full_behavior.
- Parameters:
- messages
Sequence[Message | ThreadMessageTypedDictT | Mapping[str, str | Sequence[Mapping[str, Any]] | Mapping[str, Any] | None]] - metadata
dict[str, Any] | None | list[dict[str, Any] | None] - ttl_days
int | None | list[int | None] - ttl_anchor
TimeToLiveAnchor | list[TimeToLiveAnchor] - store_kwargs
Any
- messages
- Return type: list[str]
method delete_image
Delete one image owned by this thread.
- Parameters:
image_id
str– Identifier of the image to delete. - Returns:
1when deleted, otherwise0when the image does not exist or belongs to another thread. - Return type: int
- Raises: ValueError – If the image is attached to a message. Delete or update the parent message instead.
method delete_image_async (async)
Delete one image owned by this thread asynchronously.
- Parameters:
image_id
str– Identifier of the image to delete. - Returns:
1when deleted, otherwise0when the image does not exist or belongs to another thread. - Return type: int
- Raises: ValueError – If the image is attached to a message. Delete or update the parent message instead.
method delete_memory
Delete a memory-like record (e.g., a memory, fact, preference, or guideline) from this exact thread by identifier.
- Parameters:
memory_id
str– Memory identifier. Only memory-like records (memory,guideline,fact,preference) whose storedthread_idexactly matches this thread are deleted. - Returns:
Number of deleted records (0 or 1). Returns
0when the identifier does not exist or belongs to a different thread. - Return type: int
- Raises: TimeoutError – Raised without deleting the record when earlier accepted background extraction for this thread does not finish within 300 seconds.
Notes
Before deleting the record, this method waits for earlier background extraction accepted for this thread through the attached agent memory component. It does not wait for work accepted after the wait begins or for work started by another component or process.
Examples
thread.delete_memory("456")
0
method delete_memory_async (async)
Delete a memory-like record (e.g., a memory, fact, preference, or guideline) from this exact thread by identifier asynchronously.
- Parameters:
memory_id
str– Memory identifier. Only memory-like records (memory,guideline,fact,preference) whose storedthread_idexactly matches this thread are deleted. - Returns:
Number of deleted records (0 or 1). Returns
0when the identifier does not exist or belongs to a different thread. - Return type: int
- Raises: TimeoutError – Raised without deleting the record when earlier accepted background extraction for this thread does not finish within 300 seconds.
Notes
This method follows the background-extraction wait and concurrency
behavior documented by delete_memory().
Examples
import asyncio
asyncio.run(thread.delete_memory_async("456"))
0
method delete_message
Delete a message record from this exact thread by identifier.
- Parameters:
message_id
str– Message identifier. Only messages whose storedthread_idexactly matches this thread are deleted. - Returns:
Number of deleted message records (0 or 1). Returns
0when the identifier does not exist or belongs to a different thread. - Return type: int
- Raises: TimeoutError – Raised without deleting the message when earlier accepted background extraction for this thread does not finish within 300 seconds.
Notes
Before deleting the message, this method waits for earlier background extraction accepted for this thread through the attached agent memory component. It does not wait for work accepted after the wait begins or for work started by another component or process.
Deleting a message removes only the raw message record. Derived
memories are not deleted because we do not yet track which extracted
memories came from which message, so they may remain searchable or
still affect context-card output. Use
OracleAgentMemory.delete_thread() to delete the thread together
with its associated messages and memories.
Examples
thread.delete_message("123")
0
method delete_message_async (async)
Delete a message record from this exact thread by identifier asynchronously.
- Parameters:
message_id
str– Message identifier. Only messages whose storedthread_idexactly matches this thread are deleted. - Returns:
Number of deleted message records (0 or 1). Returns
0when the identifier does not exist or belongs to a different thread. - Return type: int
- Raises: TimeoutError – Raised without deleting the message when earlier accepted background extraction for this thread does not finish within 300 seconds.
Notes
This method follows the background-extraction wait and concurrency
behavior documented by delete_message().
Deleting a message removes only the raw message record. Derived
memories are not deleted because we do not yet track which extracted
memories came from which message, so they may remain searchable or
still affect context-card output. Use
OracleAgentMemory.delete_thread() to delete the thread together
with its associated messages and memories.
Examples
import asyncio
asyncio.run(thread.delete_message_async("123"))
0
method delete_record_link
Delete a thread-owned relation by ID or complete endpoint tuple.
Endpoint-tuple selectors must use the stored source-to-target orientation.
- Parameters:
- source_record_id
str– Source identifier for an endpoint-tuple selector. - source_record_type
str– Logical source record type for an endpoint-tuple selector. - target_record_id
str– Target identifier for an endpoint-tuple selector. - target_record_type
str– Logical target record type for an endpoint-tuple selector. - relation_type
str– Source-to-target label for an endpoint-tuple selector. - relation_id
str– Relation identifier to select directly. Provide this argument alone.
- source_record_id
- Returns:
Number of deleted relations, either
0or1. - Return type: int
Examples
thread.delete_record_link(relation_id="relation-id")
1
method delete_record_link_async (async)
Asynchronously delete a relation owned by this thread.
- Parameters:
- source_record_id
str - source_record_type
str - target_record_id
str - target_record_type
str - relation_type
str - relation_id
str
- source_record_id
- Return type: int
method get_context_card
Return a context-card object for the thread.
Prefer get_context_card_async when an LLM-backed implementation
may perform remote network I/O.
- Parameters:
- fallback_message_count
int– Number of recent messages to use when deriving the fallback summary text for retrieval and rendering. When omitted, this resolves to5. -
max_relevant_results
int–Maximum number of relevant records (memory-like e.g., fact/preferences, as well as messages) to include in
<relevant_information>section of the context card.- If both this value and
min_relevant_results_by_typeare omitted,max_relevant_resultsresolves to5. - If
min_relevant_results_by_typeis provided,max_relevant_resultsresolves tomax(max_relevant_results, sum(min_relevant_results_by_type.values())).
- If both this value and
- token_budget
int | None– Optional hard limit for the estimated token count of formatted relevant results in the context card. When omitted, the thread search configuration is used. Positive values keep complete results in rank order while their cumulative estimate fits the budget. If the first result does not fit, no relevant results are included. Non-positive values disable the cap. - soft_token_budget
int | None– Optional target for the estimated token count of formatted relevant results. When omitted, the thread search configuration is used. The complete result that reaches or exceeds this target is retained. Non-positive values disable this target. Settoken_budgetto a larger value when the output must also have an absolute limit. - max_recent_messages
int– Maximum number of recent conversation messages to include in the<recent_messages>section of the context card. When omitted,max_recent_messagesresolves to0. -
except_last_messages
int–Number of trailing messages to exclude from the generated summary and relevant-information search included in the context card. This prevents messages supplied separately in LLM prompts from being duplicated in the context card. Use one of these patterns:
-
- External raw tail (recommended for prompt caching):
get_context_card(except_last_messages=N, max_recent_messages=0)The prompt contains the context card followed by the lastNraw messages.
-
- Self-contained context card:
get_context_card(except_last_messages=N, max_recent_messages=N)The context card contains the lastNmessages itself.
When nonzero,
max_recent_messagesmust be0or the same value. -
- min_relevant_results_by_type
Mapping[Literal['message', 'memory', 'guideline', 'fact', 'preference'], int] | None | ~oracleagentmemory._notset._NotSetMarker– Optional per-type minimums for relevant records included in the context card. Requested types are searched first, and remainingmax_relevant_resultsslots are filled from all supported memory-like record types. Supported keys are"memory","fact","guideline","preference", and"message". Message results are limited to the current thread. -
metadata_filter
dict[str, Any] | None–Optional metadata filter mapping used as an additional filter after scope and record-type filtering when searching for memory-like records to include in the context card. Entries in
metadata_filterare combined with AND semantics. Entries whose value is not a field-level operator dictionary use exact-match semantics: the requested key must exist in the stored record metadata. Nested dictionaries match nested metadata objects recursively. Scalar and list values must match exactly; list order and length must also match. Omit this argument, or passNone, to search without metadata filtering. Examples includemetadata_filter={"source": "chat"}for a scalar field,metadata_filter={"travel": {"need": "transit"}}for a nested field, andmetadata_filter={"tags": ["trip", "urgent"]}for an exact list match. Combine conditions to require all of them:metadata_filter={ "source": "chat", "travel": {"need": "transit"}, "tags": ["trip", "urgent"], }To test array membership, use a field-level operator dictionary.
"$array_contains"matches one value, or all values in a list."$array_contains_any"matches at least one value from a list."$not"negates another field-level expression at the same field, including an operator dictionary or raw exact-match value. Negated expressions match when the positive expression would fail, including missing fields; negated array membership also matches non-array fields:metadata_filter={ "source": "chat", "tags": { "$array_contains": "trip", "$not": {"$array_contains": "archived"}, }, } - include_invalid_results
bool– Whether relevant records in the invalid lifecycle status are included in the context card. Omit this argument or passTrueto include them. PassFalseto exclude them. - **kwargs (Any) – Reserved for future context-card options. Unexpected keyword
arguments raise
TypeError.
- fallback_message_count
- Returns:
A context-card object containing a thread context summary based on
the most recent messages. Use
OracleContextCard.contentto access the rendered XML-like text. - Return type: OracleContextCard
Notes
This uses the thread’s default search scope with
exact_thread_match=False, so relevant memories from other
threads for the same user/agent may be included.
Examples
thread.add_memory("User likes pizza", memory_id="mem-context-docs")
'mem-context-docs'
len(thread.add_messages([{"role": "user", "content": "Tell me about pizza"}]))
1
"User likes pizza" in thread.get_context_card().content
True
card = thread.get_context_card(
max_relevant_results=4,
min_relevant_results_by_type={"memory": 1},
)
len(card.relevant_results or []) <= 4
True
method get_context_card_async (async)
Asynchronously return a context-card object for the thread.
- Parameters:
- fallback_message_count
int– Number of recent messages to use when deriving the fallback summary text for retrieval and rendering. When omitted, this resolves to5. -
max_relevant_results
int–Maximum number of relevant records (memory-like e.g., fact/preferences, as well as messages) to include in
<relevant_information>section of the context card.- If both this value and
min_relevant_results_by_typeare omitted,max_relevant_resultsresolves to5. - If
min_relevant_results_by_typeis provided,max_relevant_resultsresolves tomax(max_relevant_results, sum(min_relevant_results_by_type.values())).
- If both this value and
- token_budget
int | None– Optional hard limit for the estimated token count of formatted relevant results in the context card. When omitted, the thread search configuration is used. Positive values keep complete results in rank order while their cumulative estimate fits the budget. If the first result does not fit, no relevant results are included. Non-positive values disable the cap. - soft_token_budget
int | None– Optional target for the estimated token count of formatted relevant results. When omitted, the thread search configuration is used. The complete result that reaches or exceeds this target is retained. Non-positive values disable this target. Settoken_budgetto a larger value when the output must also have an absolute limit. - max_recent_messages
int– Maximum number of recent conversation messages to include in the<recent_messages>section of the context card. When omitted,max_recent_messagesresolves to0. -
except_last_messages
int–Number of trailing messages to exclude from the generated summary and relevant-information search included in the context card. This prevents messages supplied separately in LLM prompts from being duplicated in the context card. Use one of these patterns:
-
- External raw tail (recommended for prompt caching):
get_context_card(except_last_messages=N, max_recent_messages=0)The prompt contains the context card followed by the lastNraw messages.
-
- Self-contained context card:
get_context_card(except_last_messages=N, max_recent_messages=N)The context card contains the lastNmessages itself.
When nonzero,
max_recent_messagesmust be0or the same value. -
- min_relevant_results_by_type
Mapping[Literal['message', 'memory', 'guideline', 'fact', 'preference'], int] | None | ~oracleagentmemory._notset._NotSetMarker– Optional per-type minimums for relevant records included in the context card. Requested types are searched first, and remainingmax_relevant_resultsslots are filled from all supported memory-like record types. Supported keys are"memory","fact","guideline","preference", and"message". Message results are limited to the current thread. -
metadata_filter
dict[str, Any] | None–Optional metadata filter mapping used as an additional filter after scope and record-type filtering when searching for memory-like records to include in the context card. Entries in
metadata_filterare combined with AND semantics. Entries whose value is not a field-level operator dictionary use exact-match semantics: the requested key must exist in the stored record metadata. Nested dictionaries match nested metadata objects recursively. Scalar and list values must match exactly; list order and length must also match. Omit this argument, or passNone, to search without metadata filtering. Examples includemetadata_filter={"source": "chat"}for a scalar field,metadata_filter={"travel": {"need": "transit"}}for a nested field, andmetadata_filter={"tags": ["trip", "urgent"]}for an exact list match. Combine conditions to require all of them:metadata_filter={ "source": "chat", "travel": {"need": "transit"}, "tags": ["trip", "urgent"], }To test array membership, use a field-level operator dictionary.
"$array_contains"matches one value, or all values in a list."$array_contains_any"matches at least one value from a list."$not"negates another field-level expression at the same field, including an operator dictionary or raw exact-match value. Negated expressions match when the positive expression would fail, including missing fields; negated array membership also matches non-array fields:metadata_filter={ "source": "chat", "tags": { "$array_contains": "trip", "$not": {"$array_contains": "archived"}, }, } - include_invalid_results
bool– Whether relevant records in the invalid lifecycle status are included in the context card. Omit this argument or passTrueto include them. PassFalseto exclude them. - **kwargs (Any) – Reserved for future context-card options. Unexpected keyword
arguments raise
TypeError.
- fallback_message_count
- Returns: A context-card object for the thread.
- Return type: OracleContextCard
Examples
import asyncio
card = asyncio.run(thread.get_context_card_async(
min_relevant_results_by_type={"preference": 1, "guideline": 1},
))
len(card.relevant_results or []) <= 5
True
method get_message
Return one message owned by this thread.
Image parts are returned with their identifiers and descriptions by
default. Pass included_image_ids to load bytes for selected image
parts. Unrelated identifiers are ignored.
- Parameters:
- message_id
str– Identifier of the message to retrieve. The message must belong to this thread. - included_image_ids
list[str]– Optional list of attached image identifiers whose bytes should be loaded. Omit this argument or passNoneto return image metadata without loading bytes.
- message_id
- Returns: The requested message, including any attached image parts.
- Return type: Message
- Raises: KeyError – If the message does not exist or belongs to another thread.
method get_message_async (async)
Return one thread-owned message asynchronously.
included_image_ids optionally selects attached image parts whose
bytes should be loaded; omitted or None returns image metadata only.
- Parameters:
- message_id
str– Identifier of the message to retrieve. The message must belong to this thread. - included_image_ids
list[str]– Optional list of attached image identifiers to hydrate.
- message_id
- Returns: The requested message, including any attached image parts.
- Return type: Message
- Raises: KeyError – If the message does not exist or belongs to another thread.
method get_messages
Return stored messages for this thread.
- Parameters:
- start
int | None– Start index (0-based). When omitted together withend, the most recent bounded window is returned. - end
int | None– End index (exclusive). When omitted, a bounded window of most recent messages is returned. PassNoneor-1to explicitly request all messages fromstartonward. - include_image_bytes
bool– Whether to load bytes for image parts attached to the returned messages. Omit this argument or passFalseto return image metadata without loading BLOB values.
- start
- Returns: Messages in chronological order.
- Return type: list[Message]
Examples
len(thread.add_messages([{"role": "user", "content": "Stored message example"}]))
1
messages = thread.get_messages()
messages[-1].content
'Stored message example'
method get_messages_async (async)
Get the unprocessed messages from the thread as added with add_messages
asynchronously.
- Parameters:
- start
int | None– Start index (0-based). When omitted together withend, the most recent bounded window is returned. - end
int | None– End index (exclusive). When omitted, a bounded window of most recent messages is returned. PassNoneor-1to explicitly request all messages fromstartonward. - include_image_bytes
bool– Whether to load bytes for image parts attached to the returned messages. Omit this argument or passFalseto return image metadata without loading BLOB values.
- start
- Returns: Messages in chronological order.
- Return type: list[Message]
Examples
import asyncio
message_ids = asyncio.run(thread.add_messages_async(
[{"role": "user", "content": "Stored message example"}]
))
len(message_ids)
1
messages = asyncio.run(thread.get_messages_async())
messages[-1].content
'Stored message example'
method get_summary
Return a summary of the thread.
A whole-thread request reuses or refreshes the durable summary. A
request with except_last summarizes that prefix without changing
the durable whole-thread summary.
Prefer get_summary_async when an LLM-backed implementation may
perform remote network I/O.
- Parameters:
- except_last
int– Number of most recent messages to exclude from the summary. - token_budget
int– Soft token budget. When omitted, a bounded default is applied. Positive values truncate only when the formatted summary exceeds the budget. Non-positive values disable budget-based truncation; transcript fallbacks remain capped at 4,000 characters. - **kwargs (Any) – Reserved for future summary options. Unexpected keyword arguments
raise
TypeError.
- except_last
- Returns: Summary object containing the synthesized thread summary text.
- Return type: OracleSummary
Examples
len(thread.add_messages([{"role": "assistant", "content": "Summary source message"}]))
1
summary = thread.get_summary()
bool(summary.content)
True
method get_summary_async (async)
Asynchronously return a summary of the thread.
A whole-thread request reuses or refreshes the durable summary. A
request with except_last summarizes that prefix without changing
the durable whole-thread summary.
- Parameters:
- except_last
int– Number of most recent messages to exclude from the summary. - token_budget
int– Soft token budget. When omitted, a bounded default is applied. Positive values truncate only when the formatted summary exceeds the budget. Non-positive values disable budget-based truncation; transcript fallbacks remain capped at 4,000 characters. - **kwargs (Any) – Reserved for future summary options. Unexpected keyword arguments
raise
TypeError.
- except_last
- Returns: Summary object containing the synthesized thread summary text.
- Return type: OracleSummary
method link_records
Create a directed relation between two records owned by this thread.
Currently, both endpoints must be memory-like records: "memory",
"fact", "guideline", or "preference". Built-in relation
types are "supersedes" ("is_superseded_by"),
"contradicts", "refines" ("is_refined_by"),
"supports" ("is_supported_by"), and "duplicates".
"contradicts" and "duplicates" use the same label in reverse.
Both endpoints must belong to this exact thread. Only one orientation
can be stored for an endpoint pair. opposite_relation_type names
the relation when traversing from target to source; for example,
new "supersedes" old becomes old
"is_superseded_by" new in that direction.
- Parameters:
- source_record_id
str– Identifier of the thread-owned source record. - source_record_type
str– Logical type of the source record. - target_record_id
str– Identifier of the thread-owned target record. - target_record_type
str– Logical type of the target record. - relation_type
str– Source-to-target relation label. - opposite_relation_type
str– Optional reverse-traversal label. For a built-in memory relation type, omission uses its predefined reverse label; for a custom relation type, omission uses the same label in both directions. - relation_id
str– Optional stable relation identifier. Omit it to generate one. - timestamp
str | None– Optional timestamp stored on the relation. - metadata
dict[str, Any] | None– Optional relation metadata.
- source_record_id
- Returns: Identifier of the created relation.
- Return type: str
Examples
thread.link_records(
"fact-1", "fact", "memory-1", "memory", "supports"
)
'relation-id'
method link_records_async (async)
Asynchronously create a relation between records owned by this thread.
Currently, both endpoints must be memory-like records: "memory",
"fact", "guideline", or "preference". Built-in relation
types are "supersedes" ("is_superseded_by"),
"contradicts", "refines" ("is_refined_by"),
"supports" ("is_supported_by"), and "duplicates".
"contradicts" and "duplicates" use the same label in reverse.
- Parameters:
- source_record_id
str - source_record_type
str - target_record_id
str - target_record_type
str - relation_type
str - opposite_relation_type
str - relation_id
str - timestamp
str | None - metadata
dict[str, Any] | None
- source_record_id
- Return type: str
method list_images
List image records owned by this thread.
Returned records contain image metadata by default. Raw bytes are
loaded only when include_bytes=True and image_id is provided.
- Parameters:
- image_id
str– Optional identifier used to filter the images. When omitted, no identifier filter is applied. - metadata_filter
dict[str, Any] | None– Optional filter applied to image metadata. - include_bytes
bool– Whether to load raw bytes. This requires animage_id. - limit
int | None– Optional maximum number of records. PassNoneto disable the store’s default limit.
- image_id
- Returns: Matching images in store order.
- Return type: list[ImageRecord]
method list_images_async (async)
List image records owned by this thread asynchronously.
Returned records contain image metadata by default. Raw bytes are
loaded only when include_bytes=True and image_id is provided.
This thread’s scope is applied automatically.
- Parameters:
- image_id
str– Optional identifier used to filter the images. When omitted, no identifier filter is applied. - metadata_filter
dict[str, Any] | None– Optional filter applied to image metadata. - include_bytes
bool– Whether to load raw bytes. This requires animage_id. - limit
int | None– Optional maximum number of records. PassNoneto disable the store’s default limit.
- image_id
- Returns: Matching images in store order.
- Return type: list[ImageRecord]
method search
Search synchronously for records relevant to a query.
- Parameters:
- query
str– Natural-language query string. - user_id
str | None– Optional user scope override. Omitted values inherit the thread’s default user scope. - agent_id
str | None– Optional agent scope override. Omitted values inherit the thread’s default agent scope. - thread_id
str | None– Optional thread scope override. Omitted values inherit the thread’s current thread identifier. - exact_user_match
bool– Whether user matching should be strict. - exact_agent_match
bool– Whether agent matching should be strict. - exact_thread_match
bool– Whether thread matching should be strict. - max_results
int– Optional maximum number of results to return. When provided, it must be at least1. Omitting this argument uses the default value of10. The call may return fewer thanmax_resultswhen fewer non-expired matching records exist. - token_budget
int– Optional hard limit for the estimated token count of the final formatted results. When omitted, the resolved search configuration is used. Positive values keep complete results in rank order while their cumulative estimate fits the budget. If the first result does not fit, no results are returned. Non-positive values disable this output bound. - soft_token_budget
int– Optional target for the estimated token count of the final formatted results. When omitted, the resolved search configuration is used. The complete result that reaches or exceeds this target is retained. Non-positive values disable this target. Settoken_budgetto a larger value when the output must also have an absolute limit. - record_types
list[str]– Optional list of record types to include, such as"memory","message", or"image". -
metadata_filter
dict[str, Any] | None–Optional metadata filter mapping used as an additional filter after scope and record-type filtering. Entries in
metadata_filterare combined with AND semantics. Entries whose value is not a field-level operator dictionary use exact-match semantics: the requested key must exist in the stored record metadata. Nested dictionaries match nested metadata objects recursively. Scalar and list values must match exactly; list order and length must also match. Omit this argument, or passNone, to search without metadata filtering. Examples includemetadata_filter={"source": "chat"}for a scalar field,metadata_filter={"travel": {"need": "transit"}}for a nested field, andmetadata_filter={"tags": ["trip", "urgent"]}for an exact list match. Combine conditions to require all of them:metadata_filter={ "source": "chat", "travel": {"need": "transit"}, "tags": ["trip", "urgent"], }To test array membership, use a field-level operator dictionary.
"$array_contains"matches one value, or all values in a list."$array_contains_any"matches at least one value from a list."$not"negates another field-level expression at the same field, including an operator dictionary or raw exact-match value. Negated expressions match when the positive expression would fail, including missing fields; negated array membership also matches non-array fields:metadata_filter={ "source": "chat", "tags": { "$array_contains": "trip", "$not": {"$array_contains": "archived"}, }, } - include_invalid_results
bool– Whether results include records in the invalid status. Omit this argument or passTrueto include them. PassFalseto exclude them. - num_hops
int– Number of memory-link edges to follow from each direct memory result. Values from0through5are supported; omit for direct results only. Direct message, image, and profile results are retained but are not graph-expanded. - max_linked_results
int– Maximum linked memories across all hops attached to each direct result. Omit for the default of100; pass0to return no linked context. - scope
SearchScope– Optional prebuilt search scope. Provide eitherscopeor the explicit identifier and exact-match arguments, not both.
- query
- Returns: Search results ordered by decreasing relevance.
- Return type: list[SearchResult]
- Raises:
ValueError – If
scopeis combined with explicit identifier or exact-match arguments, ifmax_resultsis less than1, or ifmetadata_filteris neither a dictionary norNone.
Notes
Omitted scope fields inherit this thread’s default search scope:
exact user and agent matching plus this thread’s current
user_id, agent_id, and thread_id. The default thread
search intentionally leaves exact_thread_match=False, so it may
return relevant records from other threads for the same user/agent.
Pass exact_thread_match=True to restrict results to the current
thread. Explicit None scope values still follow the resolved
exact-match rules: exact_*_match=False leaves that dimension
unconstrained, while exact_*_match=True matches only stored
None values.
Explicit max_results values must be at least 1; omitting the
argument uses the default value of 10. This is an upper bound: the
call may return fewer than max_results results when filters are too
restrictive, when fewer matching records exist, or because of
implementation-specific search behavior.
method search_async (async)
Search asynchronously for records relevant to a query.
- Parameters:
- query
str– Natural-language query string. - user_id
str | None– Optional user scope override. Omitted values inherit the thread’s default user scope. - agent_id
str | None– Optional agent scope override. Omitted values inherit the thread’s default agent scope. - thread_id
str | None– Optional thread scope override. Omitted values inherit the thread’s current thread identifier. - exact_user_match
bool– Whether user matching should be strict. - exact_agent_match
bool– Whether agent matching should be strict. - exact_thread_match
bool– Whether thread matching should be strict. - max_results
int– Optional maximum number of results to return. When provided, it must be at least1. Omitting this argument uses the default value of10. - token_budget
int– Optional hard limit for the estimated token count of the final formatted results. When omitted, the resolved search configuration is used. Positive values keep complete results in rank order while their cumulative estimate fits the budget. If the first result does not fit, no results are returned. Non-positive values disable this output bound. - soft_token_budget
int– Optional target for the estimated token count of the final formatted results. When omitted, the resolved search configuration is used. The complete result that reaches or exceeds this target is retained. Non-positive values disable this target. Settoken_budgetto a larger value when the output must also have an absolute limit. - record_types
list[str]– Optional list of record types to include, such as"memory","message", or"image". -
metadata_filter
dict[str, Any] | None–Optional metadata filter mapping used as an additional filter after scope and record-type filtering. Entries in
metadata_filterare combined with AND semantics. Entries whose value is not a field-level operator dictionary use exact-match semantics: the requested key must exist in the stored record metadata. Nested dictionaries match nested metadata objects recursively. Scalar and list values must match exactly; list order and length must also match. Omit this argument, or passNone, to search without metadata filtering. Examples includemetadata_filter={"source": "chat"}for a scalar field,metadata_filter={"travel": {"need": "transit"}}for a nested field, andmetadata_filter={"tags": ["trip", "urgent"]}for an exact list match. Combine conditions to require all of them:metadata_filter={ "source": "chat", "travel": {"need": "transit"}, "tags": ["trip", "urgent"], }To test array membership, use a field-level operator dictionary.
"$array_contains"matches one value, or all values in a list."$array_contains_any"matches at least one value from a list."$not"negates another field-level expression at the same field, including an operator dictionary or raw exact-match value. Negated expressions match when the positive expression would fail, including missing fields; negated array membership also matches non-array fields:metadata_filter={ "source": "chat", "tags": { "$array_contains": "trip", "$not": {"$array_contains": "archived"}, }, } - include_invalid_results
bool– Whether results include records in the invalid status. Omit this argument or passTrueto include them. PassFalseto exclude them. - num_hops
int– Number of memory-link edges to follow from each direct memory result. Values from0through5are supported; omit for direct results only. Direct message, image, and profile results are retained but are not graph-expanded. - max_linked_results
int– Maximum linked memories across all hops attached to each direct result. Omit for the default of100; pass0to return no linked context. - scope
SearchScope– Optional prebuilt search scope. Provide eitherscopeor the explicit identifier and exact-match arguments, not both.
- query
- Returns: Search results ordered by decreasing relevance.
- Return type: list[SearchResult]
- Raises:
ValueError – If
scopeis combined with explicit identifier or exact-match arguments, ifmax_resultsis less than1, or ifmetadata_filteris neither a dictionary norNone.
Notes
Omitted scope fields inherit this thread’s default search scope:
exact user and agent matching plus this thread’s current
user_id, agent_id, and thread_id. The default thread
search intentionally leaves exact_thread_match=False, so it may
return relevant records from other threads for the same user/agent.
Pass exact_thread_match=True to restrict results to the current
thread. Explicit None scope values still follow the resolved
exact-match rules: exact_*_match=False leaves that dimension
unconstrained, while exact_*_match=True matches only stored
None values.
Explicit max_results values must be at least 1; omitting the
argument uses the default value of 10. This is an upper bound: the
call may return fewer than max_results results when filters are too
restrictive, when fewer matching records exist, or because of
implementation-specific search behavior.
method update_image
Update one image owned by this thread.
Omit image to preserve the existing bytes. If image is
provided, mime_type must be provided with it. Omit description
to preserve the existing description. Pass None to generate a new
description with the configured LLM; a non-null description replaces
it directly. Expiration for an image attached to a message must be
changed through update_message().
- Returns: The updated image identifier.
- Return type: str
- Raises: ValueError – If expiration settings are supplied for an image attached to a message.
- Parameters:
- image_id
str - image
bytes - description
str | None - mime_type
ImageMimeType - metadata
dict[str, Any] | None - timestamp
str | None - ttl_days
int | None - ttl_anchor
TimeToLiveAnchor - kwargs
Any
- image_id
method update_image_async (async)
Update one image owned by this thread asynchronously.
Omit image to preserve the existing bytes. If image is
provided, mime_type must be provided with it. Omit description
to preserve the existing description. Pass None to generate a new
description with the configured LLM; a non-null description replaces
it directly. Metadata,
timestamp, and expiration settings are updated when supplied.
Expiration for an image attached to a message must be changed through
update_message_async().
- Returns: The updated image identifier.
- Return type: str
- Raises: ValueError – If expiration settings are supplied for an image attached to a message.
- Parameters:
- image_id
str - image
bytes - description
str | None - mime_type
ImageMimeType - metadata
dict[str, Any] | None - timestamp
str | None - ttl_days
int | None - ttl_anchor
TimeToLiveAnchor - kwargs
Any
- image_id
method update_memory
Update a memory-like record owned by this exact thread.
- Parameters:
- memory_id
str– Memory identifier. Only memory-like records (memory,guideline,fact,preference) whose storedthread_idexactly matches this thread are updated. - content
str– Optional replacement content. Provide a string to replace the stored content. When omitted, the stored content is preserved. Omitcontentto keep the current value, or usedelete_memory()to remove the record. - metadata
dict[str, Any] | None– Optional replacement metadata mapping. When omitted, the stored metadata is preserved. When provided, it replaces the stored metadata object; this API does not deep-merge metadata. - timestamp
str | None– Optional new timestamp for this memory. It represents when the memory was created. When omitted, the stored timestamp is preserved. PassNoneto clear the saved timestamp and use the time the record was created in the store. Whenttl_anchorisTimeToLiveAnchor.TIMESTAMP, replacement timestamps must be ISO-8601 strings. ISO-8601 timestamps without a timezone are treated as UTC. - ttl_days
int | None– Optional expiration refresh in days. Omit this argument to leave the current expiration unchanged unlessttl_anchoris provided. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to clear expiration when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. Expired memories are unavailable to this thread API and cannot be refreshed. - ttl_anchor
TimeToLiveAnchor– Optional time-to-live anchor for an expiration refresh. UseTimeToLiveAnchor.CREATED_ATfor the memory creation time orTimeToLiveAnchor.TIMESTAMPfor the replacementtimestampsupplied in the same update, or the stored event timestamp whentimestampis omitted. Providingttl_anchorwithoutttl_daysuses the schema default time-to-live duration. Whenttl_anchoris omitted during a refresh, the thread usesTimeToLiveAnchor.CREATED_AT. Timestamp-anchored refreshes require either a replacement ISO-8601 timestamp in the same call or an existing stored event timestamp in that format. ISO-8601 timestamps without a timezone are treated as UTC. - status
RecordStatus– Optional replacement lifecycle status for this memory-like record. Omit it to preserve the current status. - **kwargs (Any) – Unexpected keyword arguments are rejected.
- memory_id
- Returns: Identifier of the updated memory-like record.
- Return type: str
method update_memory_async (async)
Update a memory-like record owned by this exact thread asynchronously.
- Parameters:
- memory_id
str– Memory identifier. Only memory-like records (memory,guideline,fact,preference) whose storedthread_idexactly matches this thread are updated. - content
str– Optional replacement content. Provide a string to replace the stored content. When omitted, the stored content is preserved. Omitcontentto keep the current value, or usedelete_memory()to remove the record. - metadata
dict[str, Any] | None– Optional replacement metadata mapping. When omitted, the stored metadata is preserved. When provided, it replaces the stored metadata object; this API does not deep-merge metadata. - timestamp
str | None– Optional new timestamp for this memory. It represents when the memory was created. When omitted, the stored timestamp is preserved. PassNoneto clear the saved timestamp and use the time the record was created in the store. Whenttl_anchorisTimeToLiveAnchor.TIMESTAMP, replacement timestamps must be ISO-8601 strings. ISO-8601 timestamps without a timezone are treated as UTC. - ttl_days
int | None– Optional expiration refresh in days. Omit this argument to leave the current expiration unchanged unlessttl_anchoris provided. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to clear expiration when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. Expired memories are unavailable to this thread API and cannot be refreshed. - ttl_anchor
TimeToLiveAnchor– Optional time-to-live anchor for an expiration refresh. UseTimeToLiveAnchor.CREATED_ATfor the memory creation time orTimeToLiveAnchor.TIMESTAMPfor the replacementtimestampsupplied in the same update, or the stored event timestamp whentimestampis omitted. Providingttl_anchorwithoutttl_daysuses the schema default time-to-live duration. Whenttl_anchoris omitted during a refresh, the thread usesTimeToLiveAnchor.CREATED_AT. Timestamp-anchored refreshes require either a replacement ISO-8601 timestamp in the same call or an existing stored event timestamp in that format. ISO-8601 timestamps without a timezone are treated as UTC. - status
RecordStatus– Optional replacement lifecycle status for this memory-like record. Omit it to preserve the current status. - **kwargs (Any) – Unexpected keyword arguments are rejected.
- memory_id
- Returns: Identifier of the updated memory-like record.
- Return type: str
Examples
import asyncio
memory_id = asyncio.run(thread.add_memory_async("Original memory"))
(
asyncio.run(thread.update_memory_async(
memory_id, content="Updated memory"
))
== memory_id
)
True
method update_message
Update a raw message record owned by this exact thread.
- Parameters:
- message_id
str– Message identifier. Only messages whose storedthread_idexactly matches this thread are updated. - content
str | list[Mapping[str, Any]]– Optional replacement message content. Provide a string to replace the stored content, or an ordered sequence of text and image content parts. When omitted, the stored content is preserved. Use an empty string to replace it with empty text content. - metadata
dict[str, Any] | None– Optional replacement metadata mapping. When omitted, the stored metadata is preserved. When provided, it replaces the stored metadata object; this API does not deep-merge metadata. - ttl_days
int | None– Optional expiration refresh in days. Omit this argument to leave the current expiration unchanged unlessttl_anchoris provided. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to clear expiration when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. Expired messages are unavailable to this thread API and cannot be refreshed. - ttl_anchor
TimeToLiveAnchor– Optional time-to-live anchor for an expiration refresh. UseTimeToLiveAnchor.CREATED_ATfor the message creation time orTimeToLiveAnchor.TIMESTAMPfor the stored event timestamp. Providingttl_anchorwithoutttl_daysuses the schema default time-to-live duration. Whenttl_anchoris omitted during a refresh, the thread usesTimeToLiveAnchor.CREATED_AT. Timestamp-anchored refreshes require an existing stored ISO-8601 message timestamp. ISO-8601 timestamps without a timezone are treated as UTC. - **kwargs (Any) – Unexpected keyword arguments are rejected.
- message_id
- Returns: Identifier of the updated message record.
- Return type: str
Notes
Omitted fields are preserved from the stored record. Stored role and
timestamp remain unchanged. Editing content updates the raw message
history and, when automatic extraction is enabled, can cause the SDK
to re-extract memories from the edited message and earlier history.
In INLINE mode, that extraction completes before this method returns.
In BACKGROUND mode, this method returns after the raw message update
succeeds and background extraction is attempted. This follow-up work does
not affect the normal extraction frequency used by later add_messages()
calls. Existing extracted memories remain in place while newly extracted
memories from the edited content may be added. Because the raw message
update and any later extracted-memory writes do not happen atomically,
extracted memories can still reflect the earlier message content if the
background work does not queue, if a configured queue-capacity wait
reaches its timeout, or if later extraction work fails.
Also, note that existing extracted memories keep their original expiration
when a source message’s TTL changes.
Examples
message_id = thread.add_messages([{"role": "user", "content": "Draft message"}])[0]
thread.update_message(message_id, content="Edited message") == message_id
True
method update_message_async (async)
Update a raw message record owned by this exact thread asynchronously.
- Parameters:
- message_id
str– Message identifier. Only messages whose storedthread_idexactly matches this thread are updated. - content
str | list[Mapping[str, Any]]– Optional replacement message content. Provide a string to replace the stored content, or an ordered sequence of text and image content parts. When omitted, the stored content is preserved. Use an empty string to replace it with empty text content. - metadata
dict[str, Any] | None– Optional replacement metadata mapping. When omitted, the stored metadata is preserved. When provided, it replaces the stored metadata object; this API does not deep-merge metadata. - ttl_days
int | None– Optional expiration refresh in days. Omit this argument to leave the current expiration unchanged unlessttl_anchoris provided. PassNoneto useMemoryRetentionConfig.max_ttl_dayswhen the retention configuration sets one, or to clear expiration when it does not. Values aboveMemoryRetentionConfig.max_ttl_daysare clamped to that maximum with a warning. Expired messages are unavailable to this thread API and cannot be refreshed. - ttl_anchor
TimeToLiveAnchor– Optional time-to-live anchor for an expiration refresh. UseTimeToLiveAnchor.CREATED_ATfor the message creation time orTimeToLiveAnchor.TIMESTAMPfor the stored event timestamp. Providingttl_anchorwithoutttl_daysuses the schema default time-to-live duration. Timestamp-anchored refreshes require an existing stored ISO-8601 message timestamp. ISO-8601 timestamps without a timezone are treated as UTC. - **kwargs (Any) – Unexpected keyword arguments are rejected.
- message_id
- Returns: Identifier of the updated message record.
- Return type: str
Notes
Omitted fields are preserved from the stored record. Stored role and
timestamp remain unchanged. Editing content updates the raw message
history and, when automatic extraction is enabled, can cause the SDK
to re-extract memories from the edited message and earlier history.
In INLINE mode, that extraction completes before this method returns.
In BACKGROUND mode, this method returns after the raw message update
succeeds and background extraction is attempted. This follow-up work does
not affect the normal extraction frequency used by later add_messages()
calls. Existing extracted memories remain in place while newly extracted
memories from the edited content may be added. Because the raw message
update and any later extracted-memory writes do not happen atomically,
extracted memories can still reflect the earlier message content if the
background work does not queue, if a configured queue-capacity wait
reaches its timeout, or if later extraction work fails.
Also, note that existing extracted memories keep their original expiration
when a source message’s TTL changes.
Examples
import asyncio
message_ids = asyncio.run(thread.add_messages_async(
[{"role": "user", "content": "Draft message"}]
))
(
asyncio.run(thread.update_message_async(
message_ids[0], content="Edited message"
))
== message_ids[0]
)
True
method update_record_link
Update a relation whose endpoints are owned by this thread.
Omitted values are preserved. When relation_type changes to a
built-in memory relation type, its fixed reverse label replaces
opposite_relation_type.
- Parameters:
- relation_id
str– Identifier of the thread-owned relation. - relation_type
str– Optional replacement source-to-target label. - opposite_relation_type
str– Optional replacement reverse-traversal label. Omit it to preserve the stored label. - timestamp
str | None– Optional replacement timestamp. PassNoneto clear it. - metadata
dict[str, Any] | None– Optional replacement metadata. It replaces the stored object.
- relation_id
- Returns:
Number of updated relations, either
0or1. - Return type: int
Examples
thread.update_record_link("relation-id", relation_type="supports")
1
method update_record_link_async (async)
Asynchronously update a relation whose endpoints belong to this thread.
- Parameters:
- relation_id
str - relation_type
str - opposite_relation_type
str - timestamp
str | None - metadata
dict[str, Any] | None
- relation_id
- Return type: int
method wait_for_memory_extraction
Wait for earlier background memory extraction for this thread.
This method waits for background extraction started by earlier
add_messages(), add_messages_async(), update_message(), or
update_message_async() calls on this thread through the same agent
memory component. If one of those calls is already finishing, this
method includes the extraction it starts before waiting.
The method does not wait for extraction started after this wait begins, for extraction started by a different agent memory component, or for extraction running in another process. Extraction failures count as finished for this wait.
- Parameters:
timeout
float | None– Optional maximum number of seconds to wait. Defaults to300. PassNoneto wait until pending extraction for this thread has finished. - Raises: TimeoutError – Raised when the timeout expires before the earlier background extraction finishes.
- Return type: None
Examples
thread.wait_for_memory_extraction(timeout=10)
method wait_for_memory_extraction_async (async)
Asynchronously wait for earlier background memory extraction.
This method follows the same behavior as
wait_for_memory_extraction().
- Parameters:
timeout
float | None– Optional maximum number of seconds to wait. Defaults to300. PassNoneto wait indefinitely. - Raises: TimeoutError – Raised when the timeout expires before the earlier background extraction finishes.
- Return type: None
Examples
import asyncio
asyncio.run(thread.wait_for_memory_extraction_async(timeout=10))
Note: delete_message() deletes only the raw message row. Derived memories may
still be searchable or appear in context cards. Use
OracleAgentMemory.delete_thread() to delete the
thread together with its associated messages and memories. Message and
memory deletion through a thread handle waits for earlier background
extraction already accepted by the attached client for that thread. This is
not a global concurrency barrier for other client instances, processes, or
work accepted after the wait begins.
Messages and message contents
class oracleagentmemory.apis.message.Message
Bases: object
The in-memory message shared by threads and LLM adapters.
- Parameters:
- role
str– The message role. Custom role names are allowed for thread messages. - content
str | collections.abc.Sequence[oracleagentmemory.apis.message.MessageContent]– The message text or an ordered sequence of TextContent and ImageContent parts. A content sequence must not be empty and is stored as an immutable tuple. - timestamp
str | None– Optional timestamp associated with the message. - metadata
dict[str, Any] | None– Optional JSON-compatible metadata associated with the message. - id
str | None– Optional stable message identifier. Stores generate one when the message is added without an identifier.
- role
class oracleagentmemory.apis.message.MessageContent
Bases: ABC
Base class for structured message content.
- Parameters:
- id
str– Stable identifier for this content part. Generated automatically when omitted. - timestamp
str | None– Optional timestamp associated with this content part.
- id
class oracleagentmemory.apis.message.TextContent
Bases: MessageContent
A text part in a multimodal message.
- Parameters:
- text
str– Text carried by this content part. - id
str– Stable identifier inherited from MessageContent. Generated automatically when omitted. - timestamp
str | None– Optional timestamp inherited from MessageContent.
- text
class oracleagentmemory.apis.message.ImageContent
Bases: MessageContent
An image part in a multimodal message.
- Parameters:
- bytes
bytes | None– The image data when available.Noneis allowed when a message contains image metadata without loading the image bytes. - mime_type
oracleagentmemory.apis.message.ImageMimeType– The image MIME type. - description
str | None– Optional text describing the image. WhenNone, high-level image and message APIs may generate a description using their configured LLM. - id
str– Stable identifier inherited from MessageContent. Generated automatically when omitted. - timestamp
str | None– Optional timestamp inherited from MessageContent.
- bytes
class oracleagentmemory.apis.message.ImageMimeType
Bases: str, Enum
MIME types supported for image content.
Animated PNG and WebP are not supported.
JPEG = ‘image/jpeg’
PNG = ‘image/png’
WEBP = ‘image/webp’
Context Cards
class oracleagentmemory.apis.contextcard.ContextCard
Bases: ABC
Abstract context-card object returned by thread APIs.
property content (abstract)
- Return Type: str
- Description: Return the rendered context-card text.
class oracleagentmemory.core.contextcard.OracleContextCard
Bases: ContextCard
Context card returned by an Oracle thread.
- Parameters:
- summary
str– Summary text embedded in the card. - topics
Sequence[str] | None– Optional retrieval topics associated with the thread. - relevant_results
Sequence[SearchResult] | None– Optional retrieved durable records included in the card. - recent_messages
Sequence[Message] | None– Optional recent raw messages rendered into the card. - message_format
str– Internal template used when renderingrecent_messages.
- summary
property content
- Return Type: str
-
Description: Return the rendered context-card text.
- Returns: XML-like rendered context-card text suitable for prompt assembly.
- Return type: str
Examples
card = OracleContextCard(summary="ctx")
"<summary>" in card.content and "ctx" in card.content
True
property formatted_content
- Return Type: str
-
Description: Return the rendered context-card text used in prompt-building flows.
- Returns: XML-like rendered context-card text.
- Return type: str
Examples
OracleContextCard(summary="").formatted_content
''
card = OracleContextCard(summary="ctx", topics=["travel"])
"<topics>" in card.formatted_content
True
Summaries
class oracleagentmemory.apis.summary.Summary
Bases: ABC
Abstract thread-summary object returned by thread APIs.
property content (abstract)
- Return Type: str
- Description: Return the synthesized summary text.
class oracleagentmemory.core.summary.OracleSummary
Bases: Summary
Summary returned by an Oracle thread.
- Parameters:
content
str– Summary text synthesized from the thread transcript.
Examples
summary = OracleSummary(content="Plan the Rome itinerary.")
summary.content
'Plan the Rome itinerary.'
str(summary)
'Plan the Rome itinerary.'
property content
- Return Type: str
-
Description: Return the synthesized summary text.
- Returns: Summary text for the thread.
- Return type: str
Examples
OracleSummary(content="Keep the tea preference in mind.").content
'Keep the tea preference in mind.'
property formatted_content
- Return Type: str
-
Description: Return the rendered summary text used in prompt-building flows.
- Returns: Rendered summary text.
- Return type: str
Examples
OracleSummary(content="Thread recap").formatted_content
'Thread recap'