{
  "schema_version": 1,
  "id": "develop/ai/context-engine/agent-memory/python-sdk-quickstart",
  "title": "Redis Agent Memory Python SDK quickstart",
  "url": "https://redis.io/docs/latest/develop/ai/context-engine/agent-memory/python-sdk-quickstart/",
  "summary": "Explore session memory, automatic extraction, summarization, custom memory types, and sensitive-data exclusions with the Redis Agent Memory Python SDK.",
  "tags": [
    "docs",
    "develop",
    "ai"
  ],
  "last_updated": "2026-08-07T08:57:54-07:00",
  "page_type": "content",
  "content_hash": "1f8d4fa36edfea81a91b597dc4808cd51cc1bd1806e7a25a45a0bc643938c853",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "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."
    },
    {
      "id": "before-you-begin",
      "title": "Before you begin",
      "role": "content",
      "text": "To complete this quickstart, you need:\n\n* A Redis Cloud account that can create Redis Agent Memory services.\n* An eligible Redis Cloud database, or permission to create one.\n\nThe database must be active, run a supported Redis version, and use a Pro or Essentials plan. It must also have a public endpoint, Redis Search, and the default user enabled.\n\nRedis Agent Memory doesn't support Flex, Active-Active, or AWS PrivateLink databases during public preview.\n\nFor the complete list, see [prerequisites and limitations](https://redis.io/docs/latest/operate/iris/agent-memory/create-service#prerequisites-and-limitations).\n\n\nYou also need Python 3.10 or later."
    },
    {
      "id": "create-a-redis-agent-memory-service",
      "title": "Create a Redis Agent Memory service",
      "role": "content",
      "text": "1. Sign in to the [Redis Cloud console](https://cloud.redis.io/).\n1. Select **Agent Memory** from the navigation menu.\n1. If Redis Cloud displays the public preview terms, review and accept them.\n1. Select **Create custom service**.\n1. Enter a service name, select an eligible database, and select its `default` user.\n1. Under **Memory configuration**, enter these values:\n\n    | Setting | Value | What it controls |\n    |:--------|:------|:-----------------|\n    | **Short-term TTL** | `1` day | How long session memory is retained. |\n    | **Long-term TTL** | `365` days | How long long-term memories are retained. |\n    | **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. |\n    | **Automatic summarization** | Enabled | Whether older session events are condensed into a summary. |\n    | **Summarize after (messages)** | `6` | The event count that triggers summarization. Six is for this quickstart; use a higher production threshold. |\n    | **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. |\n\n1. Under **Memory types & extraction**, select **Add type** and configure this custom memory type:\n\n    | Setting | Value | What it controls |\n    |:--------|:------|:-----------------|\n    | **Name** | `trip_preference` | The identifier stored in `memoryType` and used in search filters. |\n    | **Description** | `Structured requirements for a planned trip` | The purpose of the custom memory type. |\n    | **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. |\n    | **Enabled** | Enabled | Whether new memories of this type are extracted. |\n\n1. Add these custom fields:\n\n    | Field | Type | Description |\n    |:------|:-----|:------------|\n    | `destinations` | `list[str]` | Cities or countries the user plans to visit. |\n    | `travel_period` | `str` | When the user plans to travel. |\n    | `dietary_requirements` | `list[str]` | Dietary requirements that affect recommendations. |\n    | `food_preferences` | `list[str]` | Cuisines, flavors, or dining preferences stated by the user. |\n\n1. Under **Sensitive-data exclusions**, enable **Semantic exclusions** and enter this exclusion prompt:\n\n    [code example]\n\n1. Select **Create**.\n1. Copy the Redis Agent Memory API key and store it securely.\n\n\nRedis Cloud displays the Redis Agent Memory API key only once. If you lose it, [generate a new API key](https://redis.io/docs/latest/operate/iris/agent-memory/view-service#replace-service-api-key).\n\n\nThese settings keep the background stages short enough to observe during the quickstart. For screenshots and configuration details, see [create a Redis Agent Memory service](https://redis.io/docs/latest/operate/iris/agent-memory/create-service).\n\n\nSensitive-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."
    },
    {
      "id": "save-the-connection-values",
      "title": "Save the connection values",
      "role": "content",
      "text": "1. Open the Redis Agent Memory service in the Redis Cloud console.\n1. On the **Configuration** tab, copy the **Endpoint** and **Store ID**.\n1. Export the API key in your shell:\n\n    [code example]\n\nKeep the API key out of source control, application logs, and other unsecured locations."
    },
    {
      "id": "install-the-sdk",
      "title": "Install the SDK",
      "role": "setup",
      "text": "[code example]"
    },
    {
      "id": "create-the-client-and-check-the-service-health",
      "title": "Create the client and check the service health",
      "role": "content",
      "text": "Create `quickstart.py` with the following code. Replace `<ENDPOINT>` and `<STORE_ID>` with the values from Redis Cloud. The endpoint must include `https://`.\n\n[code example]\n\nRun the file:\n\n[code example]\n\nA 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."
    },
    {
      "id": "1-build-conversation-context-with-session-memory",
      "title": "1. Build conversation context with session memory",
      "role": "content",
      "text": "Session memory stores a conversation as an ordered sequence of events. Add the following code after the health check, inside the `with` block:\n\n[code example]\n\nRun 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.\n\n\n**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.\n\n\nAfter the event is stored, comment out the call to `add_session_event` before subsequent runs to avoid adding the same message again."
    },
    {
      "id": "2-recall-automatically-extracted-information",
      "title": "2. Recall automatically extracted information",
      "role": "content",
      "text": "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.\n\nWait at least one minute, then add this search after the session retrieval:\n\n[code example]\n\nRun 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.\n\n\n**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.\n\n\nThe 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](https://redis.io/docs/latest/operate/iris/agent-memory/create-service#memory-configuration).\n\nThe Python SDK uses snake case for method arguments and request fields. Serialized API requests and responses use camel case."
    },
    {
      "id": "3-keep-long-conversations-concise-with-automatic-summarization",
      "title": "3. Keep long conversations concise with automatic summarization",
      "role": "content",
      "text": "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.\n\nYou 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."
    },
    {
      "id": "add-conversation-turns",
      "title": "Add conversation turns",
      "role": "content",
      "text": "Add this code after the first session event to continue the conversation past the configured threshold:\n\n[code example]\n\nRun the code once, then comment out the loop to avoid adding the same turns again. Summarization runs in the background."
    },
    {
      "id": "retrieve-the-summarized-session",
      "title": "Retrieve the summarized session",
      "role": "content",
      "text": "After a short wait, retrieve the session again:\n\n[code example]\n\nRun 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.\n\n\n**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.\n\n\nSee [automatic summarization configuration](https://redis.io/docs/latest/operate/iris/agent-memory/create-service#automatic-summarization) for details."
    },
    {
      "id": "4-extract-business-specific-data-with-a-custom-memory-type",
      "title": "4. Extract business specific data with a custom memory type",
      "role": "content",
      "text": "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.\n\nSearch for the structured memory:\n\n[code example]\n\nThe 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.\n\n\n**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.\n\n\nSee [custom memory types](https://redis.io/docs/latest/operate/iris/agent-memory/create-service#custom-memory-types) for configuration requirements and limits."
    },
    {
      "id": "5-guide-extraction-away-from-sensitive-data",
      "title": "5. Guide extraction away from sensitive data",
      "role": "content",
      "text": "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:\n\n[code example]\n\nRun the code once, then comment out the call to `add_session_event`. Wait at least one minute and search for the safe hotel information:\n\n[code example]\n\nInspect the returned memories. They can retain the hotel name, but should not contain `DEMO-7QX9` because the exclusion prompt covers booking confirmation codes.\n\n\n**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.\n\n\n\nSemantic 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.\n\n\nSee [sensitive-data exclusions](https://redis.io/docs/latest/operate/iris/agent-memory/create-service#sensitive-data-exclusions) for configuration details."
    },
    {
      "id": "next-steps",
      "title": "Next steps",
      "role": "content",
      "text": "* Review the [Python SDK package and reference](https://pypi.org/project/redis-agent-memory/).\n* Try the [TypeScript SDK quickstart](https://redis.io/docs/latest/develop/ai/context-engine/agent-memory/typescript-sdk-quickstart) or [REST API quickstart](https://redis.io/docs/latest/develop/ai/context-engine/agent-memory/rest-api-quickstart).\n* Learn when to [create long term memories directly](https://redis.io/docs/latest/develop/ai/context-engine/agent-memory/developer-guide#create-long-term-memories)."
    }
  ],
  "examples": [
    {
      "id": "create-a-redis-agent-memory-service-ex0",
      "language": "text",
      "code": "Do not keep passwords, access tokens, recovery codes, payment card information, or booking confirmation codes in long-term memory.",
      "section_id": "create-a-redis-agent-memory-service"
    },
    {
      "id": "save-the-connection-values-ex0",
      "language": "sh",
      "code": "export API_KEY='<API_KEY>'",
      "section_id": "save-the-connection-values"
    },
    {
      "id": "install-the-sdk-ex0",
      "language": "sh",
      "code": "python -m pip install redis-agent-memory",
      "section_id": "install-the-sdk"
    },
    {
      "id": "create-the-client-and-check-the-service-health-ex0",
      "language": "python",
      "code": "import os\nfrom datetime import datetime, timezone\n\nfrom redis_agent_memory import AgentMemory, models\n\n\nENDPOINT = \"<ENDPOINT>\"\nSTORE_ID = \"<STORE_ID>\"\nSESSION_ID = \"travel-planning-session\"\nUSER_ID = \"quickstart-user\"\n\n\ndef show(label, response):\n    print(f\"{label}:\")\n    print(response.model_dump_json(by_alias=True, indent=2))\n\n\ndef main():\n    with AgentMemory(\n        ENDPOINT,\n        store_id=STORE_ID,\n        api_key=os.environ[\"API_KEY\"],\n    ) as agent_memory:\n        health = agent_memory.health()\n        show(\"Service health\", health)\n\n\nif __name__ == \"__main__\":\n    main()",
      "section_id": "create-the-client-and-check-the-service-health"
    },
    {
      "id": "create-the-client-and-check-the-service-health-ex1",
      "language": "sh",
      "code": "python quickstart.py",
      "section_id": "create-the-client-and-check-the-service-health"
    },
    {
      "id": "1-build-conversation-context-with-session-memory-ex0",
      "language": "python",
      "code": "event = agent_memory.add_session_event(\n            session_id=SESSION_ID,\n            actor_id=USER_ID,\n            role=models.MessageRole.USER,\n            content=[models.Text(\n                text=(\n                    \"I am visiting Tokyo and Kyoto next month. \"\n                    \"I am vegetarian and prefer spicy food.\"\n                ),\n            )],\n            created_at=datetime.now(timezone.utc),\n        )\n        show(\"Created event\", event)\n\n        session = agent_memory.get_session_memory(\n            session_id=SESSION_ID,\n        )\n        show(\"Session memory\", session)",
      "section_id": "1-build-conversation-context-with-session-memory"
    },
    {
      "id": "2-recall-automatically-extracted-information-ex0",
      "language": "python",
      "code": "results = agent_memory.search_long_term_memory(\n            request={\n                \"text\": \"What dietary requirements and food preferences does the user have?\",\n                \"filter_\": {\n                    \"owner_id\": {\n                        \"eq\": USER_ID,\n                    }\n                },\n                \"limit\": 5,\n            },\n        )\n        show(\"Automatically extracted memories\", results)",
      "section_id": "2-recall-automatically-extracted-information"
    },
    {
      "id": "add-conversation-turns-ex0",
      "language": "python",
      "code": "turns = [\n            (models.MessageRole.ASSISTANT, \"What dates are you traveling?\"),\n            (models.MessageRole.USER, \"I arrive on October 10 and leave on October 18.\"),\n            (models.MessageRole.ASSISTANT, \"Would you like formal or casual restaurants?\"),\n            (models.MessageRole.USER, \"Mostly casual places near public transit.\"),\n            (models.MessageRole.ASSISTANT, \"Do you have a preferred budget?\"),\n            (models.MessageRole.USER, \"About 40 euros per person.\"),\n        ]\n\n        for role, text in turns:\n            agent_memory.add_session_event(\n                session_id=SESSION_ID,\n                actor_id=USER_ID if role == models.MessageRole.USER else \"travel-agent\",\n                role=role,\n                content=[models.Text(text=text)],\n                created_at=datetime.now(timezone.utc),\n            )",
      "section_id": "add-conversation-turns"
    },
    {
      "id": "retrieve-the-summarized-session-ex0",
      "language": "python",
      "code": "compacted_session = agent_memory.get_session_memory(\n            session_id=SESSION_ID,\n        )\n        show(\"Compacted session memory\", compacted_session)",
      "section_id": "retrieve-the-summarized-session"
    },
    {
      "id": "4-extract-business-specific-data-with-a-custom-memory-type-ex0",
      "language": "python",
      "code": "custom_results = agent_memory.search_long_term_memory(\n            request={\n                \"text\": \"What are the requirements for the user's trip?\",\n                \"filter_\": {\n                    \"owner_id\": {\"eq\": USER_ID},\n                    \"memory_type\": {\"eq\": \"trip_preference\"},\n                },\n                \"limit\": 5,\n            },\n        )\n        show(\"Trip preference memories\", custom_results)",
      "section_id": "4-extract-business-specific-data-with-a-custom-memory-type"
    },
    {
      "id": "5-guide-extraction-away-from-sensitive-data-ex0",
      "language": "python",
      "code": "sensitive_event = agent_memory.add_session_event(\n            session_id=SESSION_ID,\n            actor_id=USER_ID,\n            role=models.MessageRole.USER,\n            content=[models.Text(\n                text=(\n                    \"I booked Hotel Sakura in Tokyo. For this example, \"\n                    \"the fictional booking confirmation code is DEMO-7QX9.\"\n                ),\n            )],\n            created_at=datetime.now(timezone.utc),\n        )\n        show(\"Event with excluded information\", sensitive_event)",
      "section_id": "5-guide-extraction-away-from-sensitive-data"
    },
    {
      "id": "5-guide-extraction-away-from-sensitive-data-ex1",
      "language": "python",
      "code": "exclusion_results = agent_memory.search_long_term_memory(\n            request={\n                \"text\": \"Where is the user staying in Tokyo?\",\n                \"filter_\": {\n                    \"owner_id\": {\"eq\": USER_ID},\n                },\n                \"limit\": 5,\n            },\n        )\n        show(\"Memories after semantic exclusion\", exclusion_results)",
      "section_id": "5-guide-extraction-away-from-sensitive-data"
    }
  ]
}
