Long-term memory API

Updated at:

Complete API reference for all long-term memory (new) APIs, including request parameters, responses, and sample code.

This is the complete API reference for the long-term memory (new) feature. For a feature overview and user guide, see long-term memory (new).

Common request information

Parameter

Description

base URL

https://dashscope.aliyuncs.com/api/v2/apps/memory/

Authentication

Add Authorization: Bearer $DASHSCOPE_API_KEY to the request header. To get an API key, see Obtain an API key.

Content-Type

application/json

API overview

ImportantMemory becomes commercially billable at 10:00 (UTC+8) on August 20, 2026. Add and Search calls are differentiated into Pro (Rerank enabled) and Lite (Rerank disabled) versions. For more information, see Memory pricing.

long-term memory provides the following APIs:

API name

HTTP method

Path

Description

AddMemory

POST

/add

Adds a memory fragment.

SearchMemory

POST

/memory_nodes/search

Searches for memory fragments.

ListMemory

GET

/memory_nodes

Lists memory fragments.

DeleteMemory

DELETE

/memory_nodes/{memory_node_id}

Deletes a memory fragment.

UpdateMemory

PATCH

/memory_nodes/{memory_node_id}

Updates a memory fragment.

CreateProfileSchema

POST

/profile_schemas

Creates a profile schema.

ListProfileSchemas

GET

/profile_schemas

Lists profile schemas.

DeleteProfileSchema

DELETE

/profile_schemas/{profile_schema_id}

Deletes a profile schema.

UpdateProfileSchema

PATCH

/profile_schemas/{profile_schema_id}

Updates a profile schema.

GetProfileSchema

GET

/profile_schemas/{profile_schema_id}

Gets a profile schema.

GetUserProfile

GET

/profile_schemas/{profile_schema_id}/user_profile

Gets a user profile.

Usage limits

Throttling (Alibaba Cloud account level):

API

Limit

All APIs

3,000 QPM

memory fragment add API

120 QPM

memory fragment search API

300 QPM

Generated memory fragments and user profiles do not have an expiration date.

Core components

1. AddMemory - Add memory fragment

Stores user conversations as memory fragments and automatically extracts key information. To extract a user profile at the same time, pass profile_schema.

Request body parameters:

Parameter

Type

Required

Description

user_id

string

Yes

The ID of the memory entity's owner. Maximum 64 characters.

messages

array

Yes (mutually exclusive with custom_content; this parameter is ignored if custom_content is provided).

A list of conversation messages. Each message includes a role (user or assistant) and content.

Supports a maximum of 50 messages.

A question-answer pair counts as 2 messages.

messages[0].role

string

-

The message role. Valid values: user (user message) or assistant (assistant response).

messages[0].content

string | array

-

The message content.

custom_content

string

Yes (mutually exclusive with messages; messages is ignored if this parameter is provided).

Custom content. Maximum 512 characters.

profile_schema

string

No

The profile template ID. You can find this ID on the memory library details page. If omitted, no user profile is extracted and only memory fragments are written.

memory_library_id

string

No

The memory library ID. Maximum 32 characters. You can find this ID on the memory library card.

If omitted, the system selects the default memory library ID.

project_id

string

No

The project ID.

meta_data

object

No

User-defined metadata.

Result:

The returned fields include:

  • request_id (string) - The request ID.
  • memory_nodes (array) - A list of the memory nodes that have been changed. The structure is detailed below.

Parameter

Type

Description

memory_node_id

string

The memory node ID.

content

string

The memory node content, extracted from the conversation.

event

string

The event type. Possible values: ADD, UPDATE, or DELETE.

old_content

string

The previous memory node content. This field is populated only when the event is "UPDATE".

Sample code

cURL

# Add memory nodes from a conversation
curl -X POST https://dashscope.aliyuncs.com/api/v2/apps/memory/add \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
    "messages": [{
      "role": "user",
      "content": "Hello"
    }, {
      "role": "assistant",
      "content": "Hello, how can I help you?"
    }, {
      "role": "user",
      "content": "Remind me to order takeout at 11 AM every day."
    }, {
      "role": "assistant",
      "content": "No problem."
    }, {
      "role": "user",
      "content": "Remind me to organize the meeting minutes at 10 AM tomorrow."
     }
    ],
    "user_id": "user_001",
    "memory_library_id": "xxx",
    "meta_data": {
      "location_name": "Beijing",
      "geo_coordinate": "116.481499,39.990475"
    }
  }'

# response
{
  "memory_nodes": [{
    "content": "The user asks to be reminded to order takeout every day at 11 AM.",
    "event": "ADD",
    "memory_node_id": "50b46e9751504556a1a49a11b7639b3d"
  }, {
    "content": "The user asks to be reminded at 10 AM tomorrow to organize the meeting minutes.",
    "event": "ADD",
    "memory_node_id": "381cc694e4144dffbd546059189ce498"
  }],
  "request_id": "bec69131-627c-4636-a2ff-e71c0c8a5c53"
}

# Add a memory node (with custom content)
curl -X POST https://dashscope.aliyuncs.com/api/v2/apps/memory/add \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "custom_content": "The user is going to Shanghai for the WAIC this weekend.",
    "user_id": "user_001",
    "meta_data": {
      "custom_key": "custom_value"
    }
  }'

Python

NoteThe agentscope-runtime package is required. Install it with the following command: pip install agentscope-runtime>=1.1.5

from agentscope_runtime.tools.modelstudio_memory import (
    AddMemory, Message, AddMemoryInput,
)
import asyncio

async def add_memory_example():
    add_memory = AddMemory()
    try:
        result = await add_memory.arun(AddMemoryInput(
            user_id="user_001",
            messages=[
                Message(role="user", content="Remind me to drink water at 9 AM every day."),
                Message(role="assistant", content="Okay, noted."),
            ],
            meta_data={"category": "Reminder", "priority": "Medium"}
        ))
        print(f"Created {len(result.memory_nodes)} memory nodes")
    finally:
        await add_memory.close()

asyncio.run(add_memory_example())

2. SearchMemory - Search memory fragments

Finds relevant memory fragments using semantic similarity.

Request body parameters:

Parameter

Type

Required

Description

user_id

string

Yes

The memory entity ID, which identifies the owning object, must be 64 characters or fewer.

messages

array

Yes

An array of message objects representing the conversation history.

messages[0].role

string

-

The message role. Valid values: user (user message) or assistant (assistant reply).

messages[0].content

string | array

-

The message content.

memory_library_id

string

No

The memory library ID, up to 32 characters long. This ID can be found on the memory library card.

If this parameter is omitted, the default memory library ID is used.

project_ids

list

No

An array of memory fragment rule IDs. Pass multiple rule IDs to perform a hybrid search.

If this parameter is omitted, the default memory fragment rule for the specified memory library is used.

top_k

integer

No

The maximum recall count. Must be an integer from 1 to 100. Default: 10.

min_score

double

No

The minimum similarity score threshold. Range: [0.0, 1.0]. Default: 0.3.

enable_rerank

boolean

No

Specifies whether to enable reranking for search results. Defaults to false.

plan_version

string

No

The plan version. Valid values: pro (default, Rerank enabled) or lite (Rerank disabled). Case-insensitive. Takes precedence over enable_rerank: if plan_version is specified, enable_rerank is ignored. Pro: ¥0.001 per call. Lite: ¥0.00002 per call.

enable_judge

boolean

No

Specifies whether to enable the intent recognition callback. Defaults to false.

enable_rewrite

boolean

No

Specifies whether to enable query rewriting. Defaults to false.

Result:

The response contains the following fields:

  • request_id (string) - The request ID.
  • memory_nodes (array) - A list of memory nodes, each containing the following fields:

Parameter

Type

Description

memory_node_id

string

The ID of the memory node.

content

string

The content of the memory node, extracted from the conversation.

created_at

long

The creation time, as a Unix timestamp in seconds.

updated_at

long

The last update time, as a Unix timestamp in seconds.

Sample code:

cURL

# Search memory nodes
curl -X POST https://dashscope.aliyuncs.com/api/v2/apps/memory/memory_nodes/search \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "user_id": "user_001",
    "memory_library_id": "xxx",
    "messages": [{
      "role": "user",
      "content": "Hello"
    }, {
      "role": "assistant",
      "content": "Hello"
    }, {
      "role": "user",
      "content": "What is on my schedule at 11 AM tomorrow?"
    }],
    "top_k": 100,
    "min_score": 0
  }'

# response
{
  "memory_nodes": [{
    "updated_at": 1752941349,
    "created_at": 1752941349,
    "memory_node_id": "cce2393d894b477f8b207ba4d3aa70da",
    "content": "- The user wants a reminder to drink water at 3 PM every day.\n- The user is currently preparing for an exam and has reported low study efficiency."
  }, {
    "updated_at": 1752941151,
    "created_at": 1752941151,
    "memory_node_id": "e9af5fbb696748d6b0133429e8c68b47",
    "content": "- The user asked for a daily reminder to drink water at 3 PM.\n- The user is preparing for an exam, experiencing low study efficiency, and needs advice."
  }],
  "request_id": "cd6b32ef-a1ba-9ce1-af64-37f61e30e814"
}

Python

NoteInstall agentscope-runtime by running the following command: pip install agentscope-runtime>=1.1.5

from agentscope_runtime.tools.modelstudio_memory import (
    SearchMemory, Message, SearchMemoryInput,
)
import asyncio

async def search_memory_example():
    search_memory = SearchMemory()
    try:
        result = await search_memory.arun(SearchMemoryInput(
            user_id="user_001",
            memory_library_id="xxx",
            messages=[Message(role="user", content="What do I need to do?")],
            top_k=5,
            min_score=0.5
        ))
        for node in result.memory_nodes:
            print(f"memory_node: {node.content}")
    finally:
        await search_memory.close()

asyncio.run(search_memory_example())

3. ListMemory

Displays a paginated list of a user's memory fragments.

Query parameters

Parameter

Type

Required

Description

user_id

string

Yes

The memory entity ID that identifies the owner. Maximum length: 64 characters.

memory_library_id

string

No

The ID of the memory library. You can find this ID on the memory library card. Maximum length: 32 characters.

If you omit this parameter, the system automatically uses the default memory library ID.

project_id

string

No

The project ID.

If you omit this parameter, the system uses a default project ID.

page_num

integer

No

The page number (starts from 1, default: 1).

page_size

integer

No

The number of items to return per page. Default: 10.

Result:

The returned fields are:

  • request_id (string) - A unique identifier for the request.
  • memory_nodes (array) - A list of memory nodes, each with the following fields:

Parameter

Type

Description

memory_node_id

string

The memory node ID.

content

string

The content of the memory node, extracted from the conversation.

created_at

long

The creation time, as a Unix timestamp in seconds.

updated_at

long

The update time, as a Unix timestamp in seconds.

meta_data

object

User-defined metadata.

Pagination:

  • total (integer) - The total number of entries.
  • page_size (integer) - The number of entries per page.
  • page_num (integer) - The page number.
Sample code:

cURL

# List memory nodes
curl --location --request GET 'https://dashscope.aliyuncs.com/api/v2/apps/memory/memory_nodes?user_id=user_001&page_size=10&page_num=1' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{}'

# response
{
  "memory_nodes": [{
    "updated_at": 1752941349,
    "created_at": 1752941349,
    "memory_node_id": "cce2393d894b477f8b207ba4d3aa70da",
    "content": "- The user wants a reminder to drink water at 3 PM every day.\n- The user is currently preparing for an exam and is experiencing low study efficiency."
  }, {
    "updated_at": 1752941151,
    "created_at": 1752941151,
    "memory_node_id": "e9af5fbb696748d6b0133429e8c68b47",
    "content": "- The user asked for a daily reminder to drink water at 3 PM.\n- The user is preparing for an exam, experiencing low study efficiency, and needs advice."
  }],
  "page_size": 10,
  "page_num": 1,
  "total": 100,
  "request_id": "cc2690f9f2b3485a93013e5705c91241"
}

Python

NoteInstall agentscope-runtime: pip install agentscope-runtime>=1.1.5

from agentscope_runtime.tools.modelstudio_memory import (
    ListMemory, ListMemoryInput,
)
import asyncio

async def list_memory_example():
    list_memory = ListMemory()
    try:
        result = await list_memory.arun(ListMemoryInput(
            user_id="user_001",
            page_num=1,
            page_size=10
        ))
        for node in result.memory_nodes:
            print(f"memory node ID: {node.memory_node_id}, content: {node.content}")
    finally:
        await list_memory.close()

asyncio.run(list_memory_example())

4. DeleteMemory

Deletes the specified memory fragment.

path parameter: memory_node_id - The ID of the memory segment.

Query parameters:

Parameter

Type

Required

Description

memory_library_id

string

No

The memory library ID (maximum 32 characters). Get this ID from the memory library card.

If omitted, the system uses the default memory library.

Sample code:

cURL

# Delete a memory node
curl --location --request DELETE 'https://dashscope.aliyuncs.com/api/v2/apps/memory/memory_nodes/{memory_node_id}' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{}'

# response
{
  "request_id": "cc2690f9f2b3485a93013e5705c91241"
}

Python

NoteTo use this tool, install agentscope-runtime by running the following command: pip install agentscope-runtime>=1.1.5

from agentscope_runtime.tools.modelstudio_memory import (
    DeleteMemory, DeleteMemoryInput,
)
import asyncio

async def delete_memory_example():
    delete_memory = DeleteMemory()
    try:
        result = await delete_memory.arun(DeleteMemoryInput(
            user_id="user_001",
            memory_node_id="node_abc123"
        ))
        print(f"Successfully deleted. request_id: {result.request_id}")
    finally:
        await delete_memory.close()

asyncio.run(delete_memory_example())

5. UpdateMemory - Update a memory

Update memory chunk content.

path parameter: memory_node_id - The ID of the memory node.

Request body parameters

Parameter

Type

Required

Description

custom_content

string

Yes

The content of the memory fragment to update. Maximum length: 512 characters.

user_id

string

Yes

The ID of the owning user. The maximum length is 64 characters.

memory_library_id

string

No

The memory library ID, with a maximum length of 32 characters. You can obtain this ID from the memory library card.

If not provided, the default memory library is used.

timestamp

long

No

The Unix timestamp in seconds for the event corresponding to the memory fragment. Defaults to the current time if omitted.

meta_data

object

No

Metadata to be merged with existing metadata.

Response: request_id (string) - A unique ID for tracking the request.

Sample code:

cURL

# Update a memory node
curl --location --request PATCH 'https://dashscope.aliyuncs.com/api/v2/apps/memory/memory_nodes/{memory_node_id}' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "user_id": "user_001",
    "memory_library_id": "xxx",
    "custom_content": "{new_memory_custom_content}",
    "timestamp": 1747278460,
    "meta_data": {
      "custom_key": "custom_value"
    }
  }'

# response
{
  "request_id": "23d4f8bf-5e39-43ef-925a-82cf7757ec70"
}

Python

NoteThe Python SDK does not currently wrap this API. The following example calls the API directly using the requests library. Install it with: pip install requests

import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")
memory_node_id = "MEMORY_NODE_ID"

response = requests.patch(
    f"https://dashscope.aliyuncs.com/api/v2/apps/memory/memory_nodes/{memory_node_id}",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json={
        "user_id": "user_001",
        "memory_library_id": "xxx",
        "custom_content": "{new_memory_custom_content}",
        "timestamp": 1747278460,
        "meta_data": {"custom_key": "custom_value"},
    },
)
print(response.json())

6. CreateProfileSchema

Request body parameters:

Parameter

Type

Required

Description

memory_library_id

string

No

The memory library ID. Maximum length: 32 characters. You can obtain this ID from the Memory Library Card.

If this parameter is not provided, the system uses the default memory library ID.

name

string

Yes

The template name. Maximum length: 32 characters.

description

string

No

The template description. Maximum length: 128 characters.

plan_version

string

No

The plan version. Valid values: pro (default) or lite. Pro: ¥0.03 per call. Lite: ¥0.025 per call.

attributes

array

Yes

An array of template attributes.

attributes[0].name

string

Yes

The attribute name. Maximum length: 32 characters. To ensure optimal extraction performance, each attribute name should be semantically unique. Using semantically similar names, such as ["Full Name", "Name", "Given Name"] or ["Age", "Years Old"], in the same template can degrade extraction performance.

attributes[0].description

string

No

The attribute description. Maximum length: 128 characters.

attributes[0].default_value

string

No

The default value for the attribute. Maximum length: 128 characters.

Result:
  • request_id (string) — The request ID.
  • profile_schema_id (string) — The profile schema ID.
Sample code:

cURL

# Create a profile schema
curl --location "https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas" \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "name": "{your_profile_schema_name}",
    "description": "{schema_description}",
    "attributes": [
      {"name": "Age", "description": "The user's age.", "default_value": "18"},
      {"name": "Age Group", "description": "The user's age group (e.g., elementary school student, middle school student, high school student, college student, young adult, middle-aged, or elderly)."},
      {"name": "Ethnicity", "description": "The user's ethnic background."},
      {"name": "Gender", "description": "The user's gender identity or self-expression."},
      {"name": "Family Members", "description": "Mentioned family members and their relationships (e.g., parents, siblings, children)."},
      {"name": "Place of Residence", "description": "The city, region, or country where the user currently lives."},
      {"name": "Dietary Habits", "description": "The user's dietary preferences or restrictions (e.g., vegetarian, food avoidances, dieting, or preferences for sour, sweet, bitter, spicy, or salty flavors)."},
      {"name": "Hobbies", "description": "The user's hobbies, interests, and leisure activities."},
      {"name": "Platforms Used", "description": "The social media platforms, content platforms, or operating systems the user frequently uses."},
      {"name": "Content Preferences", "description": "The types of content the user enjoys reading or watching (e.g., news, entertainment, technology, anime)."},
      {"name": "Pets", "description": "Whether the user owns pets, and if so, their type and number."},
      {"name": "Religious Restrictions", "description": "The user's religious beliefs and any associated taboos or codes of conduct."},
      {"name": "Childhood Experience", "description": "The user's childhood memories, upbringing, or related experiences."},
      {"name": "Life Events", "description": "Significant life milestones the user has experienced (e.g., starting a new school, graduation, employment, moving)."},
      {"name": "Collectibles / Possessions", "description": "Valuable items, collectibles, or possessions owned by the user."},
      {"name": "Games", "description": "The types of games the user plays, their preferences, or achievements."},
      {"name": "Negative Emotions", "description": "The user's feelings of anxiety, stress, dissatisfaction, or distress."},
      {"name": "Source of Happiness", "description": "Things or experiences that bring the user happiness or satisfaction."},
      {"name": "Family Relationships", "description": "The quality of the user's relationships with family members (e.g., close, distant, conflicting)."},
      {"name": "Life Goals / Ambitions", "description": "The user's long-term goals, dreams, or life plans."},
      {"name": "Social Circle / Relationships", "description": "The user's circle of friends, social habits, or significant social connections."},
      {"name": "Recent Activities", "description": "The user's recent activities or behaviors."}
    ]
  }'

# response
{
  "profile_schema_id": "d148aac7f4ff42f598e3fcbc6eae4de3",
  "request_id": "23d4f8bf-5e39-43ef-925a-82cf7757ec70"
}

Python

NoteInstall agentscope-runtime by running the following command: pip install agentscope-runtime>=1.1.5

from agentscope_runtime.tools.modelstudio_memory import (
    CreateProfileSchema, ProfileAttribute, CreateProfileSchemaInput,
)
import asyncio

async def create_schema_example():
    create_schema = CreateProfileSchema()
    try:
        result = await create_schema.arun(CreateProfileSchemaInput(
            name="Basic User Profile",
            description="User information including age, hobbies, and occupation.",
            attributes=[
                ProfileAttribute(name="Age", description="The user's age."),
                ProfileAttribute(name="Hobbies", description="The user's hobbies and interests."),
                ProfileAttribute(name="Occupation", description="The user's occupation."),
            ]
        ))
        print(f"Created profile schema ID: {result.profile_schema_id}")
    finally:
        await create_schema.close()

asyncio.run(create_schema_example())

7. ListProfileSchemas

Gets a paginated list of all user profile templates.

Query parameters

Parameter

Type

Required

Description

memory_library_id

string

No

The memory library ID. Maximum length: 32 characters. You can get this ID from the memory library card.

If omitted, the default memory library ID is used.

page_size

integer

No

The number of entries to return on each page. Default: 10.

page_num

integer

No

The page number. Page numbering starts at 1. Default: 1.

Result:
  • request_id (string) - The request ID.
  • profile_schemas (array) - A list of profile schema objects. Each object includes:
  • name (string) - The profile schema name.
  • description (string) - The profile schema description.
  • profile_schema_id (string) - The profile schema ID.
  • total (integer) - The number of profile schemas.
Sample code:

cURL

# List profile schemas
curl --location --request GET 'https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas?page_size=10&page_num=1' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{}'

# response
{
  "profile_schemas": [
    {
      "name": "{your_profile_schema_name}",
      "description": "{schema_description}",
      "profile_schema_id": "2dd5b7961ac44630949db7533f796b18"
    },
    {
      "description": "Test description",
      "name": "Test profile schema",
      "profile_schema_id": "fa06b80b08e1445bb128d2ea8373aef3"
    }
  ],
  "request_id": "25b10053-194d-48e2-9189-3e3d868afcf2",
  "total": 2
}

Python

NoteThe Python SDK does not currently wrap this API. The following example calls the API directly using the requests library. Install it with: pip install requests

import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")

response = requests.get(
    "https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    params={"page_size": 10, "page_num": 1},
)
result = response.json()
for schema in result.get("profile_schemas", []):
    print(f"Schema: {schema['name']} (ID: {schema['profile_schema_id']})")
print(f"Total: {result.get('total')}")

8. DeleteProfileSchema

Deletes the specified profile template.

path parameter: profile_schema_id - The profile schema ID.

Query parameter: memory_library_id. Maximum length: 32 characters. You can find this ID on the memory library card.

NoteIf omitted, the default translation memory ID is used.

request_id (string) - The request ID.

Sample code:

cURL

# Delete a profile schema
curl --location --request DELETE 'https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{}'

# response
{
  "request_id": "23d4f8bf-5e39-43ef-925a-82cf7757ec70"
}

Python

NoteThe Python SDK does not yet have a wrapper for this API. The following example shows how to call the API directly using the requests library. To install it, run: pip install requests

import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")
profile_schema_id = "PROFILE_SCHEMA_ID"

response = requests.delete(
    f"https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json={},
)
print(response.json())

9. UpdateProfileSchema

Update the name, description, and attributes of a profile template.

path parameter: profile_schema_id - The ID of the profile schema.

Request body parameters:

Parameter

Type

Required

Description

memory_library_id

string

No

The memory library ID. Maximum length: 32 characters. Get this ID from the memory library card.

If omitted, the default memory library ID is used.

name

string

No

The template name. Maximum length: 32 characters.

description

string

No

The template description. Maximum length: 128 characters.

attributes_operations

array

No

A list of attribute operations.

attributes_operations[0].op

string

Yes

The operation type. Valid values: add (adds an attribute), update (updates an attribute), and delete (deletes an attribute).

attributes_operations[0].attribute_id

string

No

The attribute ID to operate on (required when the operation type is UPDATE or DELETE).

attributes_operations[0].name

string

No

attribute name, maximum 32 characters (Required if the operation type is Add)

attributes_operations[0].description

string

No

The attribute description. Maximum length: 128 characters.

attributes_operations[0].default_value

string

No

The default value. Maximum length: 128 characters.

Response: request_id (string) - The request ID.

Sample code:

cURL

# Update a profile schema
curl --location --request PATCH 'https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "name": "New Schema Name",
    "description": "New schema description",
    "attributes_operations": [
      {
        "op": "add",
        "name": "plan",
        "description": "User subscription plan",
        "default_value": "free"
      },
      {
        "op": "update",
        "attribute_id": "attr_1",
        "name": "plan_v2",
        "description": "Updated description",
        "default_value": null
      },
      {
        "op": "delete",
        "attribute_id": "attr_2"
      }
    ]
  }'

# response
{
  "request_id": "733715b5-23b1-4bf5-87b7-076f72e7181f"
}

Python

NoteThe Python SDK does not currently include a wrapper for this API. This example uses the requests library to call the API directly. Install it with: pip install requests

import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")
profile_schema_id = "PROFILE_SCHEMA_ID"

response = requests.patch(
    f"https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json={
        "name": "New Schema Name",
        "description": "New schema description",
        "attributes_operations": [
            {
                "op": "add",
                "name": "plan",
                "description": "User subscription plan",
                "default_value": "free",
            },
            {
                "op": "update",
                "attribute_id": "attr_1",
                "name": "plan_v2",
                "description": "Updated description",
                "default_value": None,
            },
            {
                "op": "delete",
                "attribute_id": "attr_2",
            },
        ],
    },
)
print(response.json())

10. GetProfileSchema

Retrieves the details of a user profile template.

path parameter: profile_schema_id - The unique identifier of the profile schema.

Query parameter: memory_library_id: The memory library ID. Maximum length: 32 characters. Obtainable from the Memory Library card.

NoteIf this parameter is omitted, the default translation memory ID is used.

Response
  • request_id (string) - The request ID.
  • name (string) - The name of the profile template.
  • description (string) - The description of the profile template.
  • attributes (array) - A list of attributes. Each attribute includes the following fields:
  • attribute_id (string) - The attribute ID.
  • name (string) - The attribute name.
  • description (string) - The attribute description.
  • default_value (string) - The default value of the attribute.
Example code:

cURL

# Get profile schema details
curl --location --request GET 'https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{}'

# response
{
  "attributes": [
    {
      "attribute_id": "0050023926374ef397b9cf06542a287c",
      "default_value": "updated_default_value",
      "description": "updated_attribute",
      "name": "updated_attribute"
    },
    {
      "attribute_id": "0270aff7e631425c91595455ff8a65cf",
      "description": "The user's long-term goals, dreams, or life plans.",
      "name": "Life Goals/Ambitions"
    },
    {
      "attribute_id": "092fc04dd42241f5842dedb1ec6d9575",
      "description": "Mentioned family members and their relationships (e.g., parents, siblings, children).",
      "name": "Family Members"
    }
  ],
  "name": "{your_profile_schema_name}",
  "description": "{schema_description}",
  "request_id": "22e73019-c24d-4885-9cbd-89e6cb7ca801"
}

Python

NoteThe Python SDK does not yet wrap this API. The following example calls the API directly using the requests library. Installation command: pip install requests

import os
import requests

api_key = os.getenv("DASHSCOPE_API_KEY")
profile_schema_id = "PROFILE_SCHEMA_ID"

response = requests.get(
    f"https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
)
result = response.json()
print(f"Schema name: {result.get('name')}")
print(f"Schema description: {result.get('description')}")
for attr in result.get("attributes", []):
    print(f"  Attribute: {attr['name']} - {attr.get('description', '')}")

11. GetUserProfile

Retrieves the extracted user profile. Profile attributes are extracted only when AddMemory is called with profile_schema. If all returned attribute values are empty, verify that AddMemory was called with the same profile template ID.

path parameter: profile_schema_id - The profile template ID.

Query parameters:
  • user_id - The memory entity ID that identifies the owning object. Maximum length: 64 characters.

  • memory_library_id: The ID of the memory library. Maximum length: 32 characters. You can find this ID on the memory library card.

    NoteIf you omit this parameter, the system uses the default memory library ID.

Result:

The returned fields are:

  • request_id (string) - The request ID.
  • profile (object) - The user profile, which contains the following fields:

Parameter

Type

Description

schema_name

string

The name of the profile template.

schema_description

string

The description of the profile template.

attributes

array

An array of attributes, where each attribute contains the following fields:

Attributes

Parameter

Type

Description

id

string

The property ID.

name

string

The property name.

value

string

The extracted property value. This field is returned only when a value is extracted.

Sample code:

cURL

# Get user profile
curl --location --request GET 'https://dashscope.aliyuncs.com/api/v2/apps/memory/profile_schemas/{profile_schema_id}/user_profile?user_id={user_id}' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{}'

# response
{
  "profile": {
    "attributes": [
      {
        "id": "00484806d4a343198d61abe8a0d8ae84",
        "name": "Family relationships"
      },
      {
        "id": "05fa398b8386454999a685d246bb2f91",
        "name": "Platforms used"
      },
      {
        "id": "09100265f3d341a79e2916fa623b9ffc",
        "name": "Religious restrictions"
      },
      {
        "id": "14bb432a07c64dad82033e2613db7a9c",
        "name": "Life events",
        "value": "27th birthday"
      },
      {
        "id": "15c3d7da69584e7c8b9b51c62afc121b",
        "name": "Games"
      },
      {
        "id": "2f4d4a48125a45beb22f45f7578b167e",
        "name": "Content preferences"
      },
      {
        "id": "4d4a765760c749d082d82eb81029bd44",
        "name": "Hobbies"
      },
      {
        "id": "614991ce106b4e27a369c04204cd4412",
        "name": "Ethnicity"
      },
      {
        "id": "6cc071fb3e764128a2313443bff7eb70",
        "name": "Negative emotions"
      },
      {
        "id": "8afa889cbe504ff69551d729a1a0df53",
        "name": "Collectibles / possessions"
      },
      {
        "id": "8f73380e494b4b0fab6da1ed64b27eee",
        "name": "Gender",
        "value": "Male"
      },
      {
        "id": "8fb150e4acf8421cb2825c382e695ea2",
        "name": "Family members"
      },
      {
        "id": "93d5d2cb8b8b4b3bbfdea44a69b63642",
        "name": "Recent activities",
        "value": "Organizing meeting minutes"
      },
      {
        "id": "a118ec78a5874251b1892e148eef76d7",
        "name": "Pets",
        "value": "A puppy named Ian"
      },
      {
        "id": "a7a1023d69b74e23852165ffe1a7d249",
        "name": "Age group",
        "value": "Young adult"
      },
      {
        "id": "aeb1c823222f4cdd849859403b2a9ff5",
        "name": "Age",
        "value": "27"
      },
      {
        "id": "dca26843674945c59d7b822ae51c8f33",
        "name": "Source of happiness"
      },
      {
        "id": "e11e8a29dd3b4c71b26bbd9b4283f65e",
        "name": "Dietary habits"
      },
      {
        "id": "f040cf561d8d461693d9d768ddcaa86c",
        "name": "Life goals / ambitions"
      },
      {
        "id": "f0c6744a65e44c2991e6b04864f05d6c",
        "name": "Place of residence"
      },
      {
        "id": "fe1be71415c6436f849064aeb781d7c3",
        "name": "Social circle"
      },
      {
        "id": "ff87d78ca1e24018985d80157d1dc266",
        "name": "Childhood experience"
      }
    ],
    "schema_description": "Description of user profile 001",
    "schema_name": "user profile 001"
  },
  "request_id": "e5986fe3-6f2b-4381-892b-01528443790e"
}

Python

NoteThis example requires the agentscope-runtime package. To install it, run: pip install agentscope-runtime>=1.1.5

from agentscope_runtime.tools.modelstudio_memory import (
    GetUserProfile, GetUserProfileInput,
)
import asyncio

async def get_profile_example():
    get_profile = GetUserProfile()
    try:
        result = await get_profile.arun(GetUserProfileInput(
            schema_id="schema_abc123",
            user_id="user_001"
        ))
        for attr in result.profile.attributes:
            print(f"{attr.name}: {attr.value or 'Not extracted'}")
    finally:
        await get_profile.close()

asyncio.run(get_profile_example())

Error handling

You may encounter the following common errors when calling the memory APIs.

Error code

HTTP status code

Description

Recommended action

InvalidApiKey

401

The API key is invalid or not configured.

Verify that the DASHSCOPE_API_KEY environment variable is configured correctly.

UserNotFound

404

The specified user_id does not exist.

Verify that the user_id is correct, or call AddMemory first to add a memory snippet.

TooManyRequests

429

The request rate exceeds the limit.

Reduce your request rate. Wait at least 1 second between requests.

InternalError

500

An internal server error occurred.

Retry the request after a short delay. If the error persists, contact technical support.

For more information about error codes, see Error Messages.