From 9650c36724589c6600a593afc66fc885ded843ce Mon Sep 17 00:00:00 2001 From: Andy Stark Date: Tue, 29 Sep 2026 10:46:59 +0100 Subject: [PATCH] DOC-7121 Consolidate agent-memory Python/TypeScript SDK quickstarts into one TCE page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Python and TypeScript agent-memory quickstarts were near-duplicate prose with only the code fences differing. Merged them into one page (sdk-quickstart.md) using the clients-example tabbed system, with two new pseudo-client keys ("Agent Memory (Python)"/"Agent Memory (TypeScript)") instead of reusing the real Python/Node.js client keys, so the tabs don't misattribute to redis-py/node-redis. Two build-script gaps surfaced adding the TypeScript source file: build/local_examples.py's EXTENSION_TO_LANGUAGE had no .ts entry at all, and build/components/example.py's PREFIXES dict had no 'typescript' comment style either — no .ts file has ever existed under local_examples/ before this. Both needed fixing together or the .ts source silently fails (first as an "unknown extension" skip, then as a None-content crash further down the pipeline once the language is recognized but has no comment prefix). Modeled the footer-hiding on langcache_sdk's page, but its show_footer="false" parameter turned out to be dead code — clients-example.html only ever checks footer="hide" (confirmed back to the commit that introduced it). langcache's live page is therefore not hiding what it thinks it's hiding. Used the parameter that actually works here; did not fix langcache's page (out of scope for this ticket). The tab's visible title is literally the config.toml client key string (only "Node.js"/"ioredis" get a hardcoded display-name override), so the new keys had to be chosen to read well as tab labels directly, not as short internal IDs. Each clients-example step had to become a fully self-contained snippet (imports + client construction repeated per step) rather than the "keep editing one growing file" narrative the original two pages used, because the shortcode slices only the exact STEP_START/STEP_END range with nothing prepended. Learned: .ts support needs EXTENSION_TO_LANGUAGE and PREFIXES kept in sync; langcache_sdk's show_footer param is dead code Constraint: a clients-example tab's display name is its config.toml key verbatim (no Node.js/ioredis-style override exists for new keys) Rejected: show_footer="false" | dead parameter in clients-example.html, only footer="hide" is read Directive: don't add another .ts-based local example without confirming EXTENSION_TO_LANGUAGE (build/local_examples.py) and PREFIXES (build/components/example.py) both still list it Gaps: agent_memory_sdk.py/.ts are hand-written, not harness-verified — no confirmed access to a running Agent Memory backend Ticket: DOC-7121 Co-Authored-By: Claude Sonnet 5 --- build/components/example.py | 1 + build/local_examples.py | 10 + config.toml | 4 +- .../ai/context-engine/agent-memory/_index.md | 18 +- .../agent-memory/developer-guide.md | 7 +- .../agent-memory/rest-api-quickstart.md | 2 +- ...on-sdk-quickstart.md => sdk-quickstart.md} | 199 +++-------- .../agent-memory/typescript-sdk-quickstart.md | 320 ------------------ .../agent-memory/agent_memory_sdk.py | 277 +++++++++++++++ .../agent-memory/agent_memory_sdk.ts | 282 +++++++++++++++ 10 files changed, 635 insertions(+), 485 deletions(-) rename content/develop/ai/context-engine/agent-memory/{python-sdk-quickstart.md => sdk-quickstart.md} (52%) delete mode 100644 content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md create mode 100644 local_examples/agent-memory/agent_memory_sdk.py create mode 100644 local_examples/agent-memory/agent_memory_sdk.ts diff --git a/build/components/example.py b/build/components/example.py index 32e83d020d..8b7199e68e 100644 --- a/build/components/example.py +++ b/build/components/example.py @@ -24,6 +24,7 @@ PREFIXES = { 'python': '#', 'node.js': '//', + 'typescript': '//', 'ioredis': '//', 'java': '//', 'java-sync': '//', diff --git a/build/local_examples.py b/build/local_examples.py index aa539c5765..b688926af4 100644 --- a/build/local_examples.py +++ b/build/local_examples.py @@ -24,6 +24,7 @@ EXTENSION_TO_LANGUAGE = { '.py': 'python', '.js': 'node.js', + '.ts': 'typescript', '.go': 'go', '.c': 'c', '.h': 'c', @@ -101,13 +102,20 @@ def get_client_name_from_language_and_path(language: str, path: str, For Python (.py) files, override based on path substrings: - If 'redisvl' in path -> RedisVL + - If 'agent-memory' in path -> Agent Memory (Python) - Otherwise -> Python + For TypeScript (.ts) files, override based on path substrings: + - If 'agent-memory' in path -> Agent Memory (TypeScript) + Substring checks are case-sensitive and can appear anywhere in the path. """ if language == 'node.js': if 'ioredis' in path: return 'ioredis' + if language == 'typescript': + if 'agent-memory' in path: + return 'Agent Memory (TypeScript)' if language == 'java': if 'lettuce-sync' in path: return 'Lettuce-Sync' @@ -123,6 +131,8 @@ def get_client_name_from_language_and_path(language: str, path: str, if language == 'python': if 'redisvl' in path: return 'RedisVL' + if 'agent-memory' in path: + return 'Agent Memory (Python)' if language == 'c#': variant = 'Async' if 'async' in path else 'Sync' client = 'NRedisStack' if is_nredisstack_example(content) else 'SE.Redis' diff --git a/config.toml b/config.toml index d4365ed220..edc18ab63d 100644 --- a/config.toml +++ b/config.toml @@ -87,7 +87,7 @@ gitHubRepo = "https://github.com/redis/docs" aiSchemaVersion = 2 # Display and sort order for client examples -clientsExamples = ["Python", "Node.js", "ioredis", "Java-Sync", "Lettuce-Sync", "Java-Async", "Java-Reactive", "Go", "C", "C#-Sync (NRedisStack)", "C#-Async (NRedisStack)", "C#-Sync (SE.Redis)", "C#-Async (SE.Redis)", "RedisVL", "PHP", "Ruby", "Rust-Sync", "Rust-Async"] +clientsExamples = ["Python", "Node.js", "ioredis", "Java-Sync", "Lettuce-Sync", "Java-Async", "Java-Reactive", "Go", "C", "C#-Sync (NRedisStack)", "C#-Async (NRedisStack)", "C#-Sync (SE.Redis)", "C#-Async (SE.Redis)", "RedisVL", "PHP", "Ruby", "Rust-Sync", "Rust-Async", "Agent Memory (Python)", "Agent Memory (TypeScript)"] searchService = "/convai/api/search-service" ratingsService = "/docusight/api/rate/docs" @@ -120,6 +120,8 @@ rdi_current_version = "2.0.0" "Ruby"={quickstartSlug="redis-rb", langId="ruby", clientId="redis-rb", clientName="redis-rb", mappingClientId="redis_rb"} "Rust-Sync"={quickstartSlug="rust", langId="rust", clientId="redis-rs", clientName="redis-rs", mappingClientId="redis_rs_sync"} "Rust-Async"={quickstartSlug="rust", langId="rust", clientId="redis-rs", clientName="redis-rs", mappingClientId="redis_rs_async"} +"Agent Memory (Python)"={quickstartSlug="", langId="python", clientId="agent-memory-python", clientName="Agent Memory (Python)", mappingClientId=""} +"Agent Memory (TypeScript)"={quickstartSlug="", langId="typescript", clientId="agent-memory-typescript", clientName="Agent Memory (TypeScript)", mappingClientId=""} # Mount directories for duplicate content [module] diff --git a/content/develop/ai/context-engine/agent-memory/_index.md b/content/develop/ai/context-engine/agent-memory/_index.md index c1eb7eb183..cac480ff6b 100644 --- a/content/develop/ai/context-engine/agent-memory/_index.md +++ b/content/develop/ai/context-engine/agent-memory/_index.md @@ -23,10 +23,9 @@ When enabled, automatic summarization compacts session memory by summarizing old Access Redis Agent Memory through the Python and TypeScript SDKs or its REST API. It works with any agent framework or LLM provider. -
+
{{< tile-card color="bg-blue-300" title="Overview" description="What's the same and what's different if you already know Redis" url="/develop/ai/context-engine/agent-memory/overview" >}} - {{< tile-card color="bg-redis-yellow-500" title="Python SDK" description="Explore Redis Agent Memory with Python" url="/develop/ai/context-engine/agent-memory/python-sdk-quickstart" >}} - {{< tile-card color="bg-redis-yellow-500" title="TypeScript SDK" description="Explore Redis Agent Memory with TypeScript" url="/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart" >}} + {{< tile-card color="bg-redis-yellow-500" title="SDK quickstart" description="Explore Redis Agent Memory with the Python or TypeScript SDK" url="/develop/ai/context-engine/agent-memory/sdk-quickstart" >}} {{< tile-card color="bg-teal-300" title="REST API" description="Explore Redis Agent Memory with curl" url="/develop/ai/context-engine/agent-memory/rest-api-quickstart" >}}
@@ -117,16 +116,11 @@ Get started with Redis Agent Memory on Redis Cloud or join the private preview f After your Redis Agent Memory service is ready, choose a client. Each quickstart follows the same travel planning scenario through session memory, automatic extraction, summarization, custom memory types, and sensitive-data exclusions. -
-
-

Python SDK

-

Explore the Redis Agent Memory workflow with the Python SDK.

-

}}">Open the Python quickstart

-
+
-

TypeScript SDK

-

Explore the Redis Agent Memory workflow with the TypeScript SDK.

-

}}">Open the TypeScript quickstart

+

Python or TypeScript SDK

+

Explore the Redis Agent Memory workflow with the Python or TypeScript SDK.

+

}}">Open the SDK quickstart

REST API

diff --git a/content/develop/ai/context-engine/agent-memory/developer-guide.md b/content/develop/ai/context-engine/agent-memory/developer-guide.md index f0520ec30d..3f31b0d703 100644 --- a/content/develop/ai/context-engine/agent-memory/developer-guide.md +++ b/content/develop/ai/context-engine/agent-memory/developer-guide.md @@ -26,8 +26,8 @@ Redis Agent Memory can automatically summarize older session events and extract | Client | Use it when | Package and quickstart | |:-------|:------------|:-----------------------| -| Python SDK | Your application or agent uses Python. | Install [`redis-agent-memory`](https://pypi.org/project/redis-agent-memory/) and follow the [Python SDK quickstart](/content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md). | -| TypeScript SDK | Your application or agent uses JavaScript or TypeScript. | Install [`@redis-iris/agent-memory`](https://www.npmjs.com/package/@redis-iris/agent-memory) and follow the [TypeScript SDK quickstart](/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md). | +| Python SDK | Your application or agent uses Python. | Install [`redis-agent-memory`](https://pypi.org/project/redis-agent-memory/) and follow the [SDK quickstart](/content/develop/ai/context-engine/agent-memory/sdk-quickstart.md). | +| TypeScript SDK | Your application or agent uses JavaScript or TypeScript. | Install [`@redis-iris/agent-memory`](https://www.npmjs.com/package/@redis-iris/agent-memory) and follow the [SDK quickstart](/content/develop/ai/context-engine/agent-memory/sdk-quickstart.md). | | REST API | You need language-independent HTTP access or don't want an SDK dependency. | No package required. Follow the [REST API quickstart](/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md). | ## Connect to a Redis Agent Memory service @@ -173,8 +173,7 @@ Follow any of the client quickstarts to create and search long-term memory. For ## References -* [Python SDK quickstart](/content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md) -* [TypeScript SDK quickstart](/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md) +* [SDK quickstart](/content/develop/ai/context-engine/agent-memory/sdk-quickstart.md) * [Python SDK reference](https://pypi.org/project/redis-agent-memory/) * [TypeScript SDK reference](https://www.npmjs.com/package/@redis-iris/agent-memory) * [REST API quickstart](/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md) diff --git a/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md b/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md index 9a5d00feab..519a8330e3 100644 --- a/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md +++ b/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md @@ -250,6 +250,6 @@ See [sensitive-data exclusions](/content/operate/iris/agent-memory/create-servic ## Next steps -* Follow the [Python SDK quickstart](/content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md) or [TypeScript SDK quickstart](/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md). +* Follow the [SDK quickstart](/content/develop/ai/context-engine/agent-memory/sdk-quickstart.md). * Learn when to [create long term memories directly](/content/develop/ai/context-engine/agent-memory/developer-guide.md#create-long-term-memories). * Use the [Redis Agent Memory API reference](/content/develop/ai/context-engine/agent-memory/api-reference.md) for endpoint and schema details. diff --git a/content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md b/content/develop/ai/context-engine/agent-memory/sdk-quickstart.md similarity index 52% rename from content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md rename to content/develop/ai/context-engine/agent-memory/sdk-quickstart.md index f98b5534ee..2aad46eb60 100644 --- a/content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md +++ b/content/develop/ai/context-engine/agent-memory/sdk-quickstart.md @@ -4,11 +4,14 @@ categories: - docs - develop - ai -description: Explore session memory, automatic extraction, summarization, custom memory types, and sensitive-data exclusions with the Redis Agent Memory Python SDK. +description: Explore session memory, automatic extraction, summarization, custom memory types, and sensitive-data exclusions with the Redis Agent Memory Python and TypeScript SDKs. hideListLinks: true -linktitle: Python SDK quickstart -title: Redis Agent Memory Python SDK quickstart +linktitle: SDK quickstart +title: Redis Agent Memory SDK quickstart weight: 6 +aliases: +- /develop/ai/context-engine/agent-memory/python-sdk-quickstart/ +- /develop/ai/context-engine/agent-memory/typescript-sdk-quickstart/ --- Use this quickstart to follow a travel planning conversation through Redis Agent Memory. You will retrieve the conversation from session memory, recall information extracted in the background, inspect an automatically generated session summary, extract structured travel information, and guide extraction away from sensitive data. @@ -19,7 +22,7 @@ To complete this quickstart, you need: {{< embed-md "rc-agent-memory-quickstart-prerequisites.md" >}} -You also need Python 3.10 or later. +You also need Python 3.10 or later, or Node.js and npm. ## Create a Redis Agent Memory service @@ -39,115 +42,75 @@ Keep the API key out of source control, application logs, and other unsecured lo ## Install the SDK +{{< multitabs id="agent-memory-install" + tab1="Python" + tab2="TypeScript" >}} + ```sh python -m pip install redis-agent-memory ``` -## Create the client and check the service health - -Create `quickstart.py` with the following code. Replace `` and `` with the values from Redis Cloud. The endpoint must include `https://`. - -```python -import os -from datetime import datetime, timezone +-tab-sep- -from redis_agent_memory import AgentMemory, models - - -ENDPOINT = "" -STORE_ID = "" -SESSION_ID = "travel-planning-session" -USER_ID = "quickstart-user" +```sh +mkdir agent-memory-quickstart +cd agent-memory-quickstart +npm init -y +npm install @redis-iris/agent-memory +npm install --save-dev tsx +``` +{{< /multitabs >}} -def show(label, response): - print(f"{label}:") - print(response.model_dump_json(by_alias=True, indent=2)) +## Create the client and check the service health +Create `quickstart.py` or `quickstart.ts` with the following code. Replace `` and `` with the values from Redis Cloud. The endpoint must include `https://`. -def main(): - with AgentMemory( - ENDPOINT, - store_id=STORE_ID, - api_key=os.environ["API_KEY"], - ) as agent_memory: - health = agent_memory.health() - show("Service health", health) +{{< clients-example set="agent_memory_sdk" step="connect_health_check" footer="hide" description="Construct the client and check that Redis Agent Memory is reachable" difficulty="beginner" >}}{{< /clients-example >}} +Run the file: -if __name__ == "__main__": - main() +```sh +python quickstart.py ``` -Run the file: +or: ```sh -python quickstart.py +npx tsx quickstart.ts ``` A healthy response confirms that the client can reach Redis Agent Memory and authenticate with the API key. The first store request validates the Store ID. ## 1. Build conversation context with session memory -Session memory stores a conversation as an ordered sequence of events. Add the following code after the health check, inside the `with` block: - -```python - event = agent_memory.add_session_event( - session_id=SESSION_ID, - actor_id=USER_ID, - role=models.MessageRole.USER, - content=[models.Text( - text=( - "I am visiting Tokyo and Kyoto next month. " - "I am vegetarian and prefer spicy food." - ), - )], - created_at=datetime.now(timezone.utc), - ) - show("Created event", event) - - session = agent_memory.get_session_memory( - session_id=SESSION_ID, - ) - show("Session memory", session) -``` +Session memory stores a conversation as an ordered sequence of events. -Run the file again. The session response contains the stored message, its role, actor, and timestamps. An application can retrieve this session before the next agent turn and add the events to the model's context. +{{< clients-example set="agent_memory_sdk" step="add_session_event" footer="hide" description="Add a session event, then retrieve the session" difficulty="beginner" >}}{{< /clients-example >}} + +Run the example. The session response contains the stored message, its role, actor, and timestamps. An application can retrieve this session before the next agent turn and add the events to the model's context. > [!NOTE] > **What to expect:** The `events` array contains the travel message. Redis Agent Memory adds an `eventId` and `systemTimestamp`, showing that the application can recover the complete event later using only the session ID. -After the event is stored, comment out the call to `add_session_event` before subsequent runs to avoid adding the same message again. +Run this example only once. Running it again adds the same message a second time. ## 2. Recall automatically extracted information Redis Agent Memory processes session events in the background and creates long term memories for information that may be useful in later conversations. You configured the extraction cadence to one minute when you created the service. You do not need to call a memory creation method. -Wait at least one minute, then add this search after the session retrieval: - -```python - results = agent_memory.search_long_term_memory( - request={ - "text": "What dietary requirements and food preferences does the user have?", - "filter_": { - "owner_id": { - "eq": USER_ID, - } - }, - "limit": 5, - }, - ) - show("Automatically extracted memories", results) -``` +Wait at least one minute after completing the previous step, then run this search: -Run the file. The `items` array should contain memories derived from the conversation, such as the vegetarian requirement or preference for spicy food. Extraction is asynchronous, so run the search again if the array is empty. +{{< clients-example set="agent_memory_sdk" step="search_long_term_memory_basic" footer="hide" description="Search long-term memory for automatically extracted information" difficulty="beginner" >}}{{< /clients-example >}} + +The `items` array should contain memories derived from the conversation, such as the vegetarian requirement or preference for spicy food. Extraction is asynchronous, so run the search again if the array is empty. > [!NOTE] > **What to expect:** Results similar to `User is a vegetarian` and `User prefers spicy food`. Your application did not create these memories directly. Redis Agent Memory derived them from the session event. The exact text and memory types can vary. The extracted memory remains searchable after the session expires, subject to the long term memory TTL. You can change the extraction cadence and both TTLs in the [Redis Agent Memory service configuration](/content/operate/iris/agent-memory/create-service.md#memory-configuration). -The Python SDK uses snake case for method arguments and request fields. Serialized API requests and responses use camel case. +The Python SDK uses snake case for method arguments and request fields. The TypeScript SDK uses camel case. Serialized API requests and responses always use camel case. ## 3. Keep long conversations concise with automatic summarization @@ -157,40 +120,17 @@ You enabled automatic summarization when you created the service. When the sessi ### Add conversation turns -Add this code after the first session event to continue the conversation past the configured threshold: - -```python - turns = [ - (models.MessageRole.ASSISTANT, "What dates are you traveling?"), - (models.MessageRole.USER, "I arrive on October 10 and leave on October 18."), - (models.MessageRole.ASSISTANT, "Would you like formal or casual restaurants?"), - (models.MessageRole.USER, "Mostly casual places near public transit."), - (models.MessageRole.ASSISTANT, "Do you have a preferred budget?"), - (models.MessageRole.USER, "About 40 euros per person."), - ] - - for role, text in turns: - agent_memory.add_session_event( - session_id=SESSION_ID, - actor_id=USER_ID if role == models.MessageRole.USER else "travel-agent", - role=role, - content=[models.Text(text=text)], - created_at=datetime.now(timezone.utc), - ) -``` +Continue the conversation past the configured threshold: + +{{< clients-example set="agent_memory_sdk" step="add_conversation_turns" footer="hide" description="Add several more session events to trigger summarization" difficulty="beginner" >}}{{< /clients-example >}} -Run the code once, then comment out the loop to avoid adding the same turns again. Summarization runs in the background. +Run this example only once. Summarization runs in the background. ### Retrieve the summarized session After a short wait, retrieve the session again: -```python - compacted_session = agent_memory.get_session_memory( - session_id=SESSION_ID, - ) - show("Compacted session memory", compacted_session) -``` +{{< clients-example set="agent_memory_sdk" step="retrieve_session_summary" footer="hide" description="Retrieve the session after it has been summarized" difficulty="beginner" >}}{{< /clients-example >}} Run the retrieval again after a short wait if `summary` is not present. Compare `summary.text` with the recent events. The summary should preserve earlier trip decisions while recent turns remain available in full. @@ -205,19 +145,7 @@ Built in memories preserve generally useful information. Custom memory types let Search for the structured memory: -```python - custom_results = agent_memory.search_long_term_memory( - request={ - "text": "What are the requirements for the user's trip?", - "filter_": { - "owner_id": {"eq": USER_ID}, - "memory_type": {"eq": "trip_preference"}, - }, - "limit": 5, - }, - ) - show("Trip preference memories", custom_results) -``` +{{< clients-example set="agent_memory_sdk" step="search_long_term_memory_custom_type" footer="hide" description="Search long-term memory filtered to a custom memory type" difficulty="intermediate" >}}{{< /clients-example >}} The result uses `trip_preference` as its `memoryType` and contains travel information extracted from the conversation. The exact text and returned fields depend on the conversation, extraction model, and client. @@ -230,42 +158,19 @@ See [custom memory types](/content/operate/iris/agent-memory/create-service.md#c The semantic exclusion prompt tells Redis Agent Memory which information should not be kept in long-term memory. Add an event containing a fictional booking code and information that is safe to retain: -```python - sensitive_event = agent_memory.add_session_event( - session_id=SESSION_ID, - actor_id=USER_ID, - role=models.MessageRole.USER, - content=[models.Text( - text=( - "I booked Hotel Sakura in Tokyo. For this example, " - "the fictional booking confirmation code is DEMO-7QX9." - ), - )], - created_at=datetime.now(timezone.utc), - ) - show("Event with excluded information", sensitive_event) -``` +{{< clients-example set="agent_memory_sdk" step="add_session_event_sensitive" footer="hide" description="Add a session event containing a fictional sensitive booking code" difficulty="intermediate" >}}{{< /clients-example >}} -Run the code once, then comment out the call to `add_session_event`. Wait at least one minute and search for the safe hotel information: - -```python - exclusion_results = agent_memory.search_long_term_memory( - request={ - "text": "Where is the user staying in Tokyo?", - "filter_": { - "owner_id": {"eq": USER_ID}, - }, - "limit": 5, - }, - ) - show("Memories after semantic exclusion", exclusion_results) -``` +Run this example only once. Wait at least one minute, then search for the safe hotel information: + +{{< clients-example set="agent_memory_sdk" step="search_long_term_memory_exclusion" footer="hide" description="Search long-term memory to confirm the sensitive value was excluded" difficulty="intermediate" >}}{{< /clients-example >}} Inspect the returned memories. They can retain the hotel name, but should not contain `DEMO-7QX9` because the exclusion prompt covers booking confirmation codes. > [!NOTE] > **What to expect:** A memory similar to `User booked Hotel Sakura in Tokyo` without the fictional confirmation code. If the code appears, refine the exclusion prompt and test again. Exclusions remain advisory. +  + > [!WARNING] > Semantic exclusions are advisory and do not guarantee that sensitive information is excluded. Session content still reaches the extraction model provider. Do not use real sensitive data in this exercise. Exclusions do not apply to directly created long-term memories. @@ -273,6 +178,6 @@ See [sensitive-data exclusions](/content/operate/iris/agent-memory/create-servic ## Next steps -* Review the [Python SDK package and reference](https://pypi.org/project/redis-agent-memory/). -* Try the [TypeScript SDK quickstart](/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md) or [REST API quickstart](/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md). +* Review the [Python SDK package and reference](https://pypi.org/project/redis-agent-memory/) or the [TypeScript SDK package and reference](https://www.npmjs.com/package/@redis-iris/agent-memory). +* Try the [REST API quickstart](/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md). * Learn when to [create long term memories directly](/content/develop/ai/context-engine/agent-memory/developer-guide.md#create-long-term-memories). diff --git a/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md b/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md deleted file mode 100644 index e4e513a8d1..0000000000 --- a/content/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart.md +++ /dev/null @@ -1,320 +0,0 @@ ---- -alwaysopen: false -categories: -- docs -- develop -- ai -description: Explore session memory, automatic extraction, summarization, custom memory types, and sensitive-data exclusions with the Redis Agent Memory TypeScript SDK. -hideListLinks: true -linktitle: TypeScript SDK quickstart -title: Redis Agent Memory TypeScript SDK quickstart -weight: 7 ---- - -Use this quickstart to follow a travel planning conversation through Redis Agent Memory. You will retrieve the conversation from session memory, recall information extracted in the background, inspect an automatically generated session summary, extract structured travel information, and guide extraction away from sensitive data. - -## Before you begin - -To complete this quickstart, you need: - -{{< embed-md "rc-agent-memory-quickstart-prerequisites.md" >}} - -You also need Node.js and npm. - -## Create a Redis Agent Memory service - -1. Sign in to the [Redis Cloud console](https://cloud.redis.io/). -1. Select **Agent Memory** from the navigation menu. -1. If Redis Cloud displays the public preview terms, review and accept them. -1. Select **Create custom service**. -1. Enter a service name, select an eligible database, and select its `default` user. -1. Under **Memory configuration**, enter these values: - - | Setting | Value | What it controls | - |:--------|:------|:-----------------| - | **Short-term TTL** | `1` day | How long session memory is retained. | - | **Long-term TTL** | `365` days | How long long-term memories are retained. | - | **Extraction cadence** | `1` minute | How often session events are processed for extraction. One minute is for this quickstart; use a longer production interval unless you need rapid extraction. | - | **Automatic summarization** | Enabled | Whether older session events are condensed into a summary. | - | **Summarize after (messages)** | `6` | The event count that triggers summarization. Six is for this quickstart; use a higher production threshold. | - | **Keep most recent (messages)** | `2` | How many recent events remain in full. Two is for this quickstart; retain more in production when recent turns are needed. | - -1. Under **Memory types & extraction**, select **Add type** and configure this custom memory type: - - | Setting | Value | What it controls | - |:--------|:------|:-----------------| - | **Name** | `trip_preference` | The identifier stored in `memoryType` and used in search filters. | - | **Description** | `Structured requirements for a planned trip` | The purpose of the custom memory type. | - | **Extraction prompt** | `Extract trip requirements only when the user states a destination or travel plan. Preserve explicit dietary requirements and food preferences.` | When to create the memory and which information to capture. | - | **Enabled** | Enabled | Whether new memories of this type are extracted. | - -1. Add these custom fields: - - | Field | Type | Description | - |:------|:-----|:------------| - | `destinations` | `list[str]` | Cities or countries the user plans to visit. | - | `travel_period` | `str` | When the user plans to travel. | - | `dietary_requirements` | `list[str]` | Dietary requirements that affect recommendations. | - | `food_preferences` | `list[str]` | Cuisines, flavors, or dining preferences stated by the user. | - -1. Under **Sensitive-data exclusions**, enable **Semantic exclusions** and enter this exclusion prompt: - - ```text - Do not keep passwords, access tokens, recovery codes, payment card information, or booking confirmation codes in long-term memory. - ``` - -1. Select **Create**. -1. Copy the Redis Agent Memory API key and store it securely. - -> [!WARNING] -> Redis Cloud displays the Redis Agent Memory API key only once. If you lose it, [generate a new API key](/content/operate/iris/agent-memory/view-service.md#replace-service-api-key). - -These settings keep the background stages short enough to observe during the quickstart. For screenshots and configuration details, see [create a Redis Agent Memory service](/content/operate/iris/agent-memory/create-service.md). - -> [!WARNING] -> Sensitive-data exclusions guide the extraction model but do not guarantee exclusion. Sensitive session content still reaches the model provider. Exclusions do not apply when an application creates long-term memories directly. - -## Save the connection values - -1. Open the Redis Agent Memory service in the Redis Cloud console. -1. On the **Configuration** tab, copy the **Endpoint** and **Store ID**. -1. Export the API key in your shell: - - ```sh - export API_KEY='' - ``` - -Keep the API key out of source control, application logs, and other unsecured locations. - -## Install the SDK - -```sh -mkdir agent-memory-quickstart -cd agent-memory-quickstart -npm init -y -npm install @redis-iris/agent-memory -npm install --save-dev tsx -``` - -## Create the client and check the service health - -Create `quickstart.ts` with the following code. Replace `` and `` with the values from Redis Cloud. The endpoint must include `https://`. - -```typescript -import { AgentMemory } from "@redis-iris/agent-memory"; - -const apiKey = process.env.API_KEY; -if (!apiKey) { - throw new Error("Set the API_KEY environment variable."); -} - -const serverURL = ""; -const storeId = ""; -const sessionId = "travel-planning-session"; -const userId = "quickstart-user"; - -const agentMemory = new AgentMemory({ - serverURL, - storeId, - apiKey, -}); - -async function run() { - const health = await agentMemory.health(); - console.log("Service health:"); - console.dir(health, { depth: null }); -} - -run().catch((error) => { - console.error(error); - process.exitCode = 1; -}); -``` - -Run the file: - -```sh -npx tsx quickstart.ts -``` - -A healthy response confirms that the client can reach Redis Agent Memory and authenticate with the API key. The first store request validates the Store ID. - -## 1. Build conversation context with session memory - -Session memory stores a conversation as an ordered sequence of events. Add the following code after the health check, inside `run`: - -```typescript - const event = await agentMemory.addSessionEvent({ - sessionId, - actorId: userId, - role: "USER", - content: [{ - text: "I am visiting Tokyo and Kyoto next month. I am vegetarian and prefer spicy food.", - }], - createdAt: new Date(), - }); - console.log("Created event:"); - console.dir(event, { depth: null }); - - const session = await agentMemory.getSessionMemory(sessionId); - console.log("Session memory:"); - console.dir(session, { depth: null }); -``` - -Run the file again. The session response contains the stored message, its role, actor, and timestamps. An application can retrieve this session before the next agent turn and add the events to the model's context. - -> [!NOTE] -> **What to expect:** The `events` array contains the travel message. Redis Agent Memory adds an `eventId` and `systemTimestamp`, showing that the application can recover the complete event later using only the session ID. - -After the event is stored, comment out the call to `addSessionEvent` before subsequent runs to avoid adding the same message again. - -## 2. Recall automatically extracted information - -Redis Agent Memory processes session events in the background and creates long term memories for information that may be useful in later conversations. You configured the extraction cadence to one minute when you created the service. You do not need to call a memory creation method. - -Wait at least one minute, then add this search after the session retrieval: - -```typescript - const results = await agentMemory.searchLongTermMemory({ - text: "What dietary requirements and food preferences does the user have?", - filter: { - ownerId: { - eq: userId, - }, - }, - limit: 5, - }); - console.log("Automatically extracted memories:"); - console.dir(results, { depth: null }); -``` - -Run the file. The `items` array should contain memories derived from the conversation, such as the vegetarian requirement or preference for spicy food. Extraction is asynchronous, so run the search again if the array is empty. - -> [!NOTE] -> **What to expect:** Results similar to `User is a vegetarian` and `User prefers spicy food`. Your application did not create these memories directly. Redis Agent Memory derived them from the session event. The exact text and memory types can vary. - -The extracted memory remains searchable after the session expires, subject to the long term memory TTL. You can change the extraction cadence and both TTLs in the [Redis Agent Memory service configuration](/content/operate/iris/agent-memory/create-service.md#memory-configuration). - -## 3. Keep long conversations concise with automatic summarization - -Automatic summarization condenses older events and retains the most recent events in full. The retrieved session then contains a `summary` object and the recent `events` array, so the application can provide useful history without filling the model's context window with every original message. - -You enabled automatic summarization when you created the service. When the session reaches six events, Redis Agent Memory summarizes the older events and retains the two most recent events in full. - -### Add conversation turns - -Add this code after the first session event to continue the conversation past the configured threshold: - -```typescript - const turns = [ - { role: "ASSISTANT", actorId: "travel-agent", text: "What dates are you traveling?" }, - { role: "USER", actorId: userId, text: "I arrive on October 10 and leave on October 18." }, - { role: "ASSISTANT", actorId: "travel-agent", text: "Would you like formal or casual restaurants?" }, - { role: "USER", actorId: userId, text: "Mostly casual places near public transit." }, - { role: "ASSISTANT", actorId: "travel-agent", text: "Do you have a preferred budget?" }, - { role: "USER", actorId: userId, text: "About 40 euros per person." }, - ] as const; - - for (const turn of turns) { - await agentMemory.addSessionEvent({ - sessionId, - actorId: turn.actorId, - role: turn.role, - content: [{ text: turn.text }], - createdAt: new Date(), - }); - } -``` - -Run the code once, then comment out the loop to avoid adding the same turns again. Summarization runs in the background. - -### Retrieve the summarized session - -After a short wait, retrieve the session again: - -```typescript - const compactedSession = await agentMemory.getSessionMemory(sessionId); - console.log("Compacted session memory:"); - console.dir(compactedSession, { depth: null }); -``` - -Run the retrieval again after a short wait if `summary` is not present. Compare `summary.text` with the recent events. The summary should preserve earlier trip decisions while recent turns remain available in full. - -> [!NOTE] -> **What to expect:** A `summary` object that preserves details such as Tokyo, Kyoto, the travel dates, and food preferences. `summarizedUpToEventId` identifies the last event covered by the summary, while `events` contains the newer turns that remain in full. The exact summary text can vary. - -See [automatic summarization configuration](/content/operate/iris/agent-memory/create-service.md#automatic-summarization) for details. - -## 4. Extract business specific data with a custom memory type - -Built in memories preserve generally useful information. Custom memory types let an application extract structured information for its business domain. You configured `trip_preference` when you created the service, so it processed the same travel planning event independently. - -Search for the structured memory: - -```typescript - const customResults = await agentMemory.searchLongTermMemory({ - text: "What are the requirements for the user's trip?", - filter: { - ownerId: { eq: userId }, - memoryType: { eq: "trip_preference" }, - }, - limit: 5, - }); - console.log("Trip preference memories:"); - console.dir(customResults, { depth: null }); -``` - -The result uses `trip_preference` as its `memoryType` and contains travel information extracted from the conversation. The exact text and returned fields depend on the conversation, extraction model, and client. - -> [!NOTE] -> **What to expect:** A result with `memoryType` set to `trip_preference` that combines the destinations, travel period, and dietary preferences. This shows that the custom type processed the same conversation independently from the built-in memory types. - -See [custom memory types](/content/operate/iris/agent-memory/create-service.md#custom-memory-types) for configuration requirements and limits. - -## 5. Guide extraction away from sensitive data - -The semantic exclusion prompt tells Redis Agent Memory which information should not be kept in long-term memory. Add an event containing a fictional booking code and information that is safe to retain: - -```typescript - const sensitiveEvent = await agentMemory.addSessionEvent({ - sessionId, - actorId: userId, - role: "USER", - content: [{ - text: "I booked Hotel Sakura in Tokyo. For this example, the fictional booking confirmation code is DEMO-7QX9.", - }], - createdAt: new Date(), - }); - console.log("Event with excluded information:"); - console.dir(sensitiveEvent, { depth: null }); -``` - -Run the code once, then comment out the call to `addSessionEvent`. Wait at least one minute and search for the safe hotel information: - -```typescript - const exclusionResults = await agentMemory.searchLongTermMemory({ - text: "Where is the user staying in Tokyo?", - filter: { - ownerId: { eq: userId }, - }, - limit: 5, - }); - console.log("Memories after semantic exclusion:"); - console.dir(exclusionResults, { depth: null }); -``` - -Inspect the returned memories. They can retain the hotel name, but should not contain `DEMO-7QX9` because the exclusion prompt covers booking confirmation codes. - -> [!NOTE] -> **What to expect:** A memory similar to `User booked Hotel Sakura in Tokyo` without the fictional confirmation code. If the code appears, refine the exclusion prompt and test again. Exclusions remain advisory. - -> [!WARNING] -> Semantic exclusions are advisory and do not guarantee that sensitive information is excluded. Session content still reaches the extraction model provider. Do not use real sensitive data in this exercise. Exclusions do not apply to directly created long-term memories. - -See [sensitive-data exclusions](/content/operate/iris/agent-memory/create-service.md#sensitive-data-exclusions) for configuration details. - -## Next steps - -* Review the [TypeScript SDK package and reference](https://www.npmjs.com/package/@redis-iris/agent-memory). -* Try the [Python SDK quickstart](/content/develop/ai/context-engine/agent-memory/python-sdk-quickstart.md) or [REST API quickstart](/content/develop/ai/context-engine/agent-memory/rest-api-quickstart.md). -* Learn when to [create long term memories directly](/content/develop/ai/context-engine/agent-memory/developer-guide.md#create-long-term-memories). diff --git a/local_examples/agent-memory/agent_memory_sdk.py b/local_examples/agent-memory/agent_memory_sdk.py new file mode 100644 index 0000000000..4f635d1a6f --- /dev/null +++ b/local_examples/agent-memory/agent_memory_sdk.py @@ -0,0 +1,277 @@ +# EXAMPLE: agent_memory_sdk + +# STEP_START connect_health_check +import os + +from redis_agent_memory import AgentMemory + +ENDPOINT = "" +STORE_ID = "" + + +def check_health(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + health = agent_memory.health() + print("Service health:") + print(health.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + check_health() +# STEP_END + +# STEP_START add_session_event +import os +from datetime import datetime, timezone + +from redis_agent_memory import AgentMemory, models + +ENDPOINT = "" +STORE_ID = "" +SESSION_ID = "travel-planning-session" +USER_ID = "quickstart-user" + + +def build_conversation_context(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + event = agent_memory.add_session_event( + session_id=SESSION_ID, + actor_id=USER_ID, + role=models.MessageRole.USER, + content=[models.Text( + text=( + "I am visiting Tokyo and Kyoto next month. " + "I am vegetarian and prefer spicy food." + ), + )], + created_at=datetime.now(timezone.utc), + ) + print("Created event:") + print(event.model_dump_json(by_alias=True, indent=2)) + + session = agent_memory.get_session_memory( + session_id=SESSION_ID, + ) + print("Session memory:") + print(session.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + build_conversation_context() +# STEP_END + +# STEP_START search_long_term_memory_basic +import os + +from redis_agent_memory import AgentMemory + +ENDPOINT = "" +STORE_ID = "" +USER_ID = "quickstart-user" + + +def recall_extracted_memory(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + results = agent_memory.search_long_term_memory( + request={ + "text": "What dietary requirements and food preferences does the user have?", + "filter_": { + "owner_id": { + "eq": USER_ID, + } + }, + "limit": 5, + }, + ) + print("Automatically extracted memories:") + print(results.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + recall_extracted_memory() +# STEP_END + +# STEP_START add_conversation_turns +import os +from datetime import datetime, timezone + +from redis_agent_memory import AgentMemory, models + +ENDPOINT = "" +STORE_ID = "" +SESSION_ID = "travel-planning-session" +USER_ID = "quickstart-user" + + +def add_conversation_turns(): + turns = [ + (models.MessageRole.ASSISTANT, "What dates are you traveling?"), + (models.MessageRole.USER, "I arrive on October 10 and leave on October 18."), + (models.MessageRole.ASSISTANT, "Would you like formal or casual restaurants?"), + (models.MessageRole.USER, "Mostly casual places near public transit."), + (models.MessageRole.ASSISTANT, "Do you have a preferred budget?"), + (models.MessageRole.USER, "About 40 euros per person."), + ] + + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + for role, text in turns: + agent_memory.add_session_event( + session_id=SESSION_ID, + actor_id=USER_ID if role == models.MessageRole.USER else "travel-agent", + role=role, + content=[models.Text(text=text)], + created_at=datetime.now(timezone.utc), + ) + + +if __name__ == "__main__": + add_conversation_turns() +# STEP_END + +# STEP_START retrieve_session_summary +import os + +from redis_agent_memory import AgentMemory + +ENDPOINT = "" +STORE_ID = "" +SESSION_ID = "travel-planning-session" + + +def retrieve_session_summary(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + compacted_session = agent_memory.get_session_memory( + session_id=SESSION_ID, + ) + print("Compacted session memory:") + print(compacted_session.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + retrieve_session_summary() +# STEP_END + +# STEP_START search_long_term_memory_custom_type +import os + +from redis_agent_memory import AgentMemory + +ENDPOINT = "" +STORE_ID = "" +USER_ID = "quickstart-user" + + +def search_custom_memory_type(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + custom_results = agent_memory.search_long_term_memory( + request={ + "text": "What are the requirements for the user's trip?", + "filter_": { + "owner_id": {"eq": USER_ID}, + "memory_type": {"eq": "trip_preference"}, + }, + "limit": 5, + }, + ) + print("Trip preference memories:") + print(custom_results.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + search_custom_memory_type() +# STEP_END + +# STEP_START add_session_event_sensitive +import os +from datetime import datetime, timezone + +from redis_agent_memory import AgentMemory, models + +ENDPOINT = "" +STORE_ID = "" +SESSION_ID = "travel-planning-session" +USER_ID = "quickstart-user" + + +def add_sensitive_event(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + sensitive_event = agent_memory.add_session_event( + session_id=SESSION_ID, + actor_id=USER_ID, + role=models.MessageRole.USER, + content=[models.Text( + text=( + "I booked Hotel Sakura in Tokyo. For this example, " + "the fictional booking confirmation code is DEMO-7QX9." + ), + )], + created_at=datetime.now(timezone.utc), + ) + print("Event with excluded information:") + print(sensitive_event.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + add_sensitive_event() +# STEP_END + +# STEP_START search_long_term_memory_exclusion +import os + +from redis_agent_memory import AgentMemory + +ENDPOINT = "" +STORE_ID = "" +USER_ID = "quickstart-user" + + +def search_with_exclusion(): + with AgentMemory( + ENDPOINT, + store_id=STORE_ID, + api_key=os.environ["API_KEY"], + ) as agent_memory: + exclusion_results = agent_memory.search_long_term_memory( + request={ + "text": "Where is the user staying in Tokyo?", + "filter_": { + "owner_id": {"eq": USER_ID}, + }, + "limit": 5, + }, + ) + print("Memories after semantic exclusion:") + print(exclusion_results.model_dump_json(by_alias=True, indent=2)) + + +if __name__ == "__main__": + search_with_exclusion() +# STEP_END diff --git a/local_examples/agent-memory/agent_memory_sdk.ts b/local_examples/agent-memory/agent_memory_sdk.ts new file mode 100644 index 0000000000..e285f8aa0c --- /dev/null +++ b/local_examples/agent-memory/agent_memory_sdk.ts @@ -0,0 +1,282 @@ +// EXAMPLE: agent_memory_sdk + +// STEP_START connect_health_check +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function checkHealth() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const health = await agentMemory.health(); + console.log("Service health:"); + console.dir(health, { depth: null }); +} + +checkHealth().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START add_session_event +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function buildConversationContext() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const sessionId = "travel-planning-session"; + const userId = "quickstart-user"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const event = await agentMemory.addSessionEvent({ + sessionId, + actorId: userId, + role: "USER", + content: [{ + text: "I am visiting Tokyo and Kyoto next month. I am vegetarian and prefer spicy food.", + }], + createdAt: new Date(), + }); + console.log("Created event:"); + console.dir(event, { depth: null }); + + const session = await agentMemory.getSessionMemory(sessionId); + console.log("Session memory:"); + console.dir(session, { depth: null }); +} + +buildConversationContext().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START search_long_term_memory_basic +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function recallExtractedMemory() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const userId = "quickstart-user"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const results = await agentMemory.searchLongTermMemory({ + text: "What dietary requirements and food preferences does the user have?", + filter: { + ownerId: { + eq: userId, + }, + }, + limit: 5, + }); + console.log("Automatically extracted memories:"); + console.dir(results, { depth: null }); +} + +recallExtractedMemory().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START add_conversation_turns +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function addConversationTurns() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const sessionId = "travel-planning-session"; + const userId = "quickstart-user"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const turns = [ + { role: "ASSISTANT", actorId: "travel-agent", text: "What dates are you traveling?" }, + { role: "USER", actorId: userId, text: "I arrive on October 10 and leave on October 18." }, + { role: "ASSISTANT", actorId: "travel-agent", text: "Would you like formal or casual restaurants?" }, + { role: "USER", actorId: userId, text: "Mostly casual places near public transit." }, + { role: "ASSISTANT", actorId: "travel-agent", text: "Do you have a preferred budget?" }, + { role: "USER", actorId: userId, text: "About 40 euros per person." }, + ] as const; + + for (const turn of turns) { + await agentMemory.addSessionEvent({ + sessionId, + actorId: turn.actorId, + role: turn.role, + content: [{ text: turn.text }], + createdAt: new Date(), + }); + } +} + +addConversationTurns().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START retrieve_session_summary +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function retrieveSessionSummary() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const sessionId = "travel-planning-session"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const compactedSession = await agentMemory.getSessionMemory(sessionId); + console.log("Compacted session memory:"); + console.dir(compactedSession, { depth: null }); +} + +retrieveSessionSummary().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START search_long_term_memory_custom_type +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function searchCustomMemoryType() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const userId = "quickstart-user"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const customResults = await agentMemory.searchLongTermMemory({ + text: "What are the requirements for the user's trip?", + filter: { + ownerId: { eq: userId }, + memoryType: { eq: "trip_preference" }, + }, + limit: 5, + }); + console.log("Trip preference memories:"); + console.dir(customResults, { depth: null }); +} + +searchCustomMemoryType().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START add_session_event_sensitive +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function addSensitiveEvent() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const sessionId = "travel-planning-session"; + const userId = "quickstart-user"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const sensitiveEvent = await agentMemory.addSessionEvent({ + sessionId, + actorId: userId, + role: "USER", + content: [{ + text: "I booked Hotel Sakura in Tokyo. For this example, the fictional booking confirmation code is DEMO-7QX9.", + }], + createdAt: new Date(), + }); + console.log("Event with excluded information:"); + console.dir(sensitiveEvent, { depth: null }); +} + +addSensitiveEvent().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END + +// STEP_START search_long_term_memory_exclusion +import { AgentMemory } from "@redis-iris/agent-memory"; + +async function searchWithExclusion() { + const apiKey = process.env.API_KEY; + if (!apiKey) { + throw new Error("Set the API_KEY environment variable."); + } + + const userId = "quickstart-user"; + + const agentMemory = new AgentMemory({ + serverURL: "", + storeId: "", + apiKey, + }); + + const exclusionResults = await agentMemory.searchLongTermMemory({ + text: "Where is the user staying in Tokyo?", + filter: { + ownerId: { eq: userId }, + }, + limit: 5, + }); + console.log("Memories after semantic exclusion:"); + console.dir(exclusionResults, { depth: null }); +} + +searchWithExclusion().catch((error) => { + console.error(error); + process.exitCode = 1; +}); +// STEP_END