你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
重要
Foundry Agent Service 中的 Memory(预览版)和 Memory Store API(预览版)作为 Azure 订阅的一部分向你授予许可,并受 Microsoft 产品条款、Microsoft 产品和服务数据保护附录 以及 Microsoft Azure 预览版补充使用条款 中适用于“预览版”的条款约束。
最新预览版提供新功能和增强功能,包括:
- 用于创建、读取、更新、列出和删除单个内存记录的内存项操作。
- 存储级别的默认保留控制,包括新创建的内存存储的默认 TTL。
- 直接控制“记住”或“忘记”同步记忆命令的行为。
Foundry 代理服务中的内存是托管的长期内存解决方案。 它支持跨会话、设备和工作流的代理连续性。 通过创建和管理内存存储,可以生成代理来保留用户首选项、维护聊天历史记录并提供个性化体验。
内存存储充当持久性存储,定义与每个代理相关的信息类型。 使用 scope 参数控制访问,该参数将内存分段到各个用户,以确保安全且隔离的体验。
本文介绍如何创建、管理和使用内存存储。 有关概念性信息,请参阅 Foundry 智能体服务中的记忆。
对于第一个端到端成功,请遵循以下路径:
- 为代理创建内存存储 。
- 将内存搜索工具附加到 代理。
- 创建对话、发送首选项并等待配置的更新延迟,以便服务可以记住它。
- 在同一示例中启动一个新对话,并询问一个相关问题,以确认代理记得该偏好设置。
根据你需要直接控制内存的程度选择工作流:
| 情景 | 从采购 | 使用它来 |
|---|---|---|
| 管理 | 创建内存存储 | 配置、更新、列出或删除存储和保留设置。 |
| 命令 | 应用直接的“记住或遗忘”行为 | 遵循显式用户请求,立即记住或忘记信息。 |
| 项 | 管理内存项 | 直接创建、检查、更新或删除单个记录。 |
示例覆盖率
复选标记意味着本文包含该语言的示例。 短划线表示当前不包含示例;它不指示 SDK 是否支持该操作。
| 能力 | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API |
|---|---|---|---|---|---|
| 创建、更新、列出和删除内存存储 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| 将内存附加到提示智能体 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| 更新和搜索记忆 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| 执行直接“记住”或“忘记”命令 | ✔️ | — | ✔️ | ✔️ | ✔️ |
| 创建、读取、更新、列出和删除内存项 | ✔️ | — | ✔️ | ✔️ | ✔️ |
先决条件
- 一个 Azure 订阅。 免费创建一个。
- Microsoft Foundry 项目配置了授权和权限。
- 在项目中,部署聊天模型,例如
gpt-5.2。 - 在项目中部署嵌入模型,例如
text-embedding-3-small。 - 配置了具有所需包和环境变量的 本地环境 。
授权和权限
对生产部署使用 基于角色的访问控制 。 如果角色不可行,请跳过本部分,改用基于密钥的身份验证。
配置基于角色的访问权限:
登录到 Azure 门户。
在您的项目中:
- 在左窗格中,选择 “资源管理>标识”。
- 使用切换按钮启用系统分配的托管标识。
在包含您项目的资源中:
在左窗格中,选择“访问控制”(IAM)。
选择 添加>角色分配。
将 Foundry 用户分配给项目的托管标识。
重要
Foundry RBAC 角色最近已更名。 Foundry 用户、Foundry 所有者、Foundry 帐户所有者和 Foundry 项目经理之前的名称分别为“Azure AI 用户”、“Azure AI 所有者”、“Azure AI 帐户所有者”和“Azure AI 项目经理”。 在重命名推出时,你仍可能会在某些位置看到以前的名称。重命名后,角色 ID 和核心权限保持不变。
设置环境
安装所需的包:
pip install "azure-ai-projects>=2.3.0"
安装所需的包:
dotnet add package Azure.AI.Projects --version 2.1.0-beta.4
dotnet add package Azure.AI.Projects.Agents --version 2.1.0-beta.4
dotnet add package Azure.AI.Extensions.OpenAI --version 2.1.0-beta.4
dotnet add package Azure.Identity
安装所需的包:
npm install @azure/ai-projects @azure/identity
将 Node.js 22 或更高版本与 @azure/ai-projects 2.8.0 配合使用。
安装所需的包:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
</dependency>
为项目终结点和模型部署名称设置环境变量:
export FOUNDRY_PROJECT_ENDPOINT="https://{your-ai-services-account}.services.ai.azure.com/api/projects/{project-name}"
export MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME="<chat-model-deployment-name>"
export MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME="<embedding-model-deployment-name>"
为项目终结点、模型部署、API 版本和访问令牌设置环境变量:
FOUNDRY_PROJECT_ENDPOINT="https://{your-ai-services-account}.services.ai.azure.com/api/projects/{project-name}"
MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME="<chat-model-deployment-name>" # For example, gpt-5.2
MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME="<embedding-model-deployment-name>" # For example, text-embedding-3-small
API_VERSION="2025-11-15-preview"
# Get a short-lived access token using Azure CLI
ACCESS_TOKEN="$(az account get-access-token --resource https://ai.azure.com/ --query accessToken -o tsv)"
了解范围
参数 scope 控制内存的分区方式。 内存存储中的每个范围都保留一个独立内存项集合。 例如,如果创建具有内存的客户支持代理,则每个客户都应有自己的单个内存。
作为开发人员,可以选择用于存储和检索内存项的密钥。 正确的方法取决于访问内存的方式。
通过内存搜索工具
将内存搜索工具附加到代理时,设置为scope{{$userId}}启用每用户内存隔离,而无需硬编码标识符。 系统会自动解析来自以下两个源之一的每个响应调用的最终用户标识:
x-memory-user-id请求标头: 如果存在,标头值将用作用户 ID。 在代理或后端方案中使用此方案,服务代表最终用户调用 API。Microsoft Entra 身份验证令牌:如果未设置标头,系统会回退到调用方的租户 ID 和对象 ID。 这是前端方案中的默认方案,即用户直接使用 Microsoft Entra 进行身份验证。
如果不需要每个用户隔离,请改用静态 scope 值。
通过低级别内存 API
直接调用 内存 API 时,请在每个请求中显式指定 scope 。 可以从系统传递静态值,例如通用唯一标识符(UUID)或其他稳定标识符。 这些操作不支持自动标识提取。
创建内存存储
为每个代理创建专用内存存储,为内存访问和优化建立明确的边界。 创建内存存储时,请指定处理内存内容的聊天模型和嵌入模型的部署。
使用内存存储选项来控制提取行为和保留默认值。 在最新的预览版中,可以启用过程内存,并为新创建的内存条目设置默认的 TTL(秒)。
import os
from datetime import timedelta
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions
from azure.identity import DefaultAzureCredential
project_client = AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
memory_store_name = "my_memory_store"
# Specify memory store options
options = MemoryStoreDefaultOptions(
chat_summary_enabled=True,
user_profile_enabled=True,
procedural_memory_enabled=True,
default_ttl_seconds=timedelta(days=30),
user_profile_details="Avoid irrelevant or sensitive data, such as age, financials, precise location, and credentials"
)
# Create memory store
chat_model = os.environ["MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME"]
embedding_model = os.environ["MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME"]
definition = MemoryStoreDefaultDefinition(
chat_model=chat_model,
embedding_model=embedding_model,
options=options
)
memory_store = project_client.beta.memory_stores.create(
name=memory_store_name,
definition=definition,
description="Memory store with procedural memory and 30-day default TTL",
)
print(f"Created memory store: {memory_store.name}")
using System;
using Azure.AI.Projects;
using Azure.AI.Projects.Memory;
using Azure.Identity;
#pragma warning disable AAIP001
var projectEndpoint = Environment.GetEnvironmentVariable(
"FOUNDRY_PROJECT_ENDPOINT");
var chatModel = Environment.GetEnvironmentVariable(
"MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME");
var embeddingModel = Environment.GetEnvironmentVariable(
"MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME");
AIProjectClient projectClient = new(
new Uri(projectEndpoint),
new DefaultAzureCredential());
var memoryStoreName = "my_memory_store";
// Specify memory store options
MemoryStoreDefaultDefinition memoryStoreDefinition = new(
chatModel: chatModel,
embeddingModel: embeddingModel
);
memoryStoreDefinition.Options = new(
isUserProfileEnabled: true,
isChatSummaryEnabled: true);
memoryStoreDefinition.Options.UserProfileDetails =
"Avoid irrelevant or sensitive data, such as age, "
+ "financials, precise location, and credentials";
// Create memory store
MemoryStore memoryStore = projectClient.MemoryStores.CreateMemoryStore(
name: memoryStoreName,
definition: memoryStoreDefinition,
description: "Memory store for customer support agent"
);
Console.WriteLine($"Created memory store: {memoryStore.Name}");
import { DefaultAzureCredential } from "@azure/identity";
import type {
MemoryStoreDefaultDefinition,
MemoryStoreDefaultOptions,
} from "@azure/ai-projects";
import { AIProjectClient } from "@azure/ai-projects";
const projectEndpoint =
process.env["FOUNDRY_PROJECT_ENDPOINT"] ||
"<project endpoint>";
const chatModelDeployment =
process.env["MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME"] ||
"<chat model deployment name>";
const embeddingModelDeployment =
process.env["MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME"] ||
"<embedding model deployment name>";
const memoryStoreName = "my_memory_store";
const project = new AIProjectClient(
projectEndpoint,
new DefaultAzureCredential(),
);
const memoryOptions: MemoryStoreDefaultOptions = {
user_profile_enabled: true,
chat_summary_enabled: true,
procedural_memory_enabled: true,
default_ttl_seconds: 30 * 24 * 60 * 60,
user_profile_details:
"Avoid irrelevant or sensitive data, such as age, " +
"financials, precise location, and credentials",
};
const definition: MemoryStoreDefaultDefinition = {
kind: "default",
chat_model: chatModelDeployment,
embedding_model: embeddingModelDeployment,
options: memoryOptions,
};
const memoryStore = await project.beta.memoryStores.create(
memoryStoreName,
definition,
{
description: "Memory store with procedural memory and 30-day default TTL",
},
);
console.log(
`Created memory store: ${memoryStore.name} (${memoryStore.id})`,
);
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.BetaMemoryStoresClient;
import com.azure.ai.agents.models.MemoryStoreDefaultDefinition;
import com.azure.ai.agents.models.MemoryStoreDefaultOptions;
import com.azure.ai.agents.models.MemoryStoreDetails;
import com.azure.identity.DefaultAzureCredentialBuilder;
String projectEndpoint = System.getenv("FOUNDRY_PROJECT_ENDPOINT");
String chatModel = System.getenv("MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME");
String embeddingModel =
System.getenv("MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME");
BetaMemoryStoresClient memoryStoresClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.beta()
.buildBetaMemoryStoresClient();
String memoryStoreName = "my_memory_store";
MemoryStoreDefaultDefinition definition =
new MemoryStoreDefaultDefinition(chatModel, embeddingModel)
.setOptions(new MemoryStoreDefaultOptions(true, true));
MemoryStoreDetails memoryStore = memoryStoresClient.createMemoryStore(
memoryStoreName,
definition,
"Memory store for customer support agent",
null);
System.out.println("Created memory store: " + memoryStore.getName());
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "my_memory_store",
"description": "Memory store with procedural memory and 30-day default TTL",
"definition": {
"kind": "default",
"chat_model": "'"${MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME}"'",
"embedding_model": "'"${MEMORY_STORE_EMBEDDING_MODEL_DEPLOYMENT_NAME}"'",
"options": {
"chat_summary_enabled": true,
"user_profile_enabled": true,
"procedural_memory_enabled": true,
"default_ttl_seconds": 2592000,
"user_profile_details": "Avoid irrelevant or sensitive data, such as age, financials, precise location, and credentials"
}
}
}'
提示
其余Python、C#、TypeScript 和Java代码片段在创建内存存储中定义的客户端和变量上生成。 如果独立运行这些代码片段,请包含本节中的导入代码和客户端初始化代码。
本文中的 C# 代码片段使用同步方法。 有关异步用法,请参阅 memory 搜索工具和 memory store 示例。
自定义内存
自定义代理存储的信息,以保持内存使用高效、信息相关以及尊重隐私。 使用 user_profile_details 参数指定对代理函数至关重要的数据类型。
例如,将user_profile_details设置为优先考虑“航班航空公司首选项和饮食限制”以供旅行社使用。 这种重点方法可帮助记忆系统了解应该提取、汇总哪些详细信息,并将其提交到长期记忆中。
还可以使用此参数排除某些类型的数据,使内存保持精简且符合隐私要求。 例如,设置为 user_profile_details “避免不相关或敏感数据,例如年龄、财务、精确位置和凭据”。
配置 TTL 和保留策略
TTL 适用于所有内存,无论是从直接内存命令、提取和合并,还是项级 CRUD 操作。 如果内存已更新并合并,服务将重置其上次更新的时间。
TTL 仅适用于引入 TTL 支持后创建的内存存储。 它不会影响现有内存存储。
default_ttl_seconds 的 0 值指示无过期。 选择符合合规性和用户数据生命周期要求的保留期。
更新内存存储
更新内存存储属性(例如 description 或 metadata)以更好地管理内存存储。
# Update memory store properties
updated_store = project_client.beta.memory_stores.update(
name=memory_store_name,
description="Updated description"
)
print(f"Updated: {updated_store.description}")
// Update memory store properties
MemoryStore updatedStore = projectClient.MemoryStores.UpdateMemoryStore(
name: memoryStoreName,
description: "Updated description"
);
Console.WriteLine($"Updated: {updatedStore.Description}");
const updatedStore = await project.beta.memoryStores.update(
memoryStoreName,
{
description: "Updated description",
},
);
console.log(`Updated: ${updatedStore.description}`);
import com.azure.ai.agents.models.MemoryStoreDetails;
MemoryStoreDetails updatedStore = memoryStoresClient.updateMemoryStore(
memoryStoreName,
"Updated description",
null);
System.out.println("Updated: " + updatedStore.getDescription());
MEMORY_STORE_NAME="my_memory_store"
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/${MEMORY_STORE_NAME}?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"description": "Updated description"
}'
列出内存存储器
检索项目中内存存储的列表,以管理和监视内存基础结构。
# List all memory stores
stores_list = list(project_client.beta.memory_stores.list())
print(f"Found {len(stores_list)} memory stores")
for store in stores_list:
print(f"- {store.name} ({store.description})")
// List all memory stores
foreach (MemoryStore store in projectClient.MemoryStores.GetMemoryStores())
{
Console.WriteLine(
$"Memory store: {store.Name} ({store.Description})");
}
const storeList = project.beta.memoryStores.list();
console.log("Listing all memory stores...");
for await (const store of storeList) {
console.log(` - Memory Store: ${store.name} (${store.id})`);
}
import com.azure.ai.agents.models.MemoryStoreDetails;
System.out.println("Listing all memory stores...");
for (MemoryStoreDetails store : memoryStoresClient.listMemoryStores()) {
System.out.println(
" - Memory Store: " + store.getName() + " (" + store.getId() + ")");
}
curl -X GET "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}"
通过代理工具使用内存
创建内存存储后,可以将内存搜索工具附加到提示代理。 此工具使代理能够在会话期间读取和写入内存存储。 使用 scope 和 update_delay 来配置该工具,以控制内存更新的方式和时间。
提示
若要将内存范围限定为单个最终用户,请将其设置为scope"{{$userId}}"工具定义中,并在每个响应调用中作为标头传递x-memory-user-id: <user-id>。 系统将作用域解析为该用户的身份。 如果没有标头,范围将回退到调用方的 Microsoft Entra 标识(TID 和 OID)。 有关详细信息,请参阅 “了解范围”。
from azure.ai.projects.models import MemorySearchPreviewTool, PromptAgentDefinition
# Set scope to associate the memories with
scope = "user_123"
openai_client = project_client.get_openai_client()
# Create memory search tool
tool = MemorySearchPreviewTool(
memory_store_name=memory_store_name,
scope=scope,
update_delay=1, # Wait 1 second of inactivity before updating memories
# In a real application, set this to a higher value like 300 (5 minutes, default)
)
# Create a prompt agent with memory search tool
agent = project_client.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model=os.environ["MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant that answers general questions",
tools=[tool],
)
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
using Azure.AI.Projects.Agents;
using Azure.AI.Extensions.OpenAI;
using OpenAI.Responses;
#pragma warning disable OPENAI001
// Set scope to associate the memories with
string scope = "user_123";
// Create a prompt agent with memory search tool
DeclarativeAgentDefinition agentDefinition = new(model: chatModel)
{
Instructions = "You are a helpful assistant that answers "
+ "general questions",
};
agentDefinition.Tools.Add(new MemorySearchPreviewTool(
memoryStoreName: memoryStore.Name,
scope: scope)
{
UpdateDelayInSecs = 1, // Wait 1 second of inactivity before updating memories
// In a real application, set this to a higher value
// like 300 (5 minutes, default)
});
ProjectsAgentVersion agent =
projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "MyAgent",
options: new(agentDefinition));
Console.WriteLine(
$"Agent created (id: {agent.Id}, name: {agent.Name}, "
+ $"version: {agent.Version})");
// Set scope to associate the memories with
const scope = "user_123";
const agent = await project.agents.createVersion(
"memory-search-agent",
{
kind: "prompt",
model: chatModelDeployment,
instructions:
"You are a helpful assistant that retrieves relevant " +
"information from the user's memory store to answer their questions.",
tools: [
{
type: "memory_search_preview",
memory_store_name: memoryStoreName,
scope: scope,
update_delay: 1,
},
],
},
);
console.log(
`Created agent with memory search tool, agent ID: ${agent.id}, ` +
`name: ${agent.name}, version: ${agent.version}`,
);
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.MemorySearchPreviewTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
String scope = "user_123";
AgentsClient agentsClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildAgentsClient();
MemorySearchPreviewTool memoryTool = new MemorySearchPreviewTool(
memoryStoreName,
scope).setUpdateDelaySeconds(1);
PromptAgentDefinition agentDefinition = new PromptAgentDefinition(chatModel)
.setInstructions("You are a helpful assistant that answers general questions")
.setTools(java.util.Collections.singletonList(memoryTool));
AgentVersionDetails agent =
agentsClient.createAgentVersion("MyAgent", agentDefinition);
System.out.println(
"Agent created (id: " + agent.getId() + ", name: " + agent.getName()
+ ", version: " + agent.getVersion() + ")");
# The agents API uses api-version=v1, which differs from the memory store API version
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/agents?api-version=v1" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"name": "MyAgent",
"definition": {
"kind": "prompt",
"model": "gpt-5.2",
"instructions": "You are a helpful assistant that answers general questions",
"tools": [
{
"type": "memory_search_preview",
"memory_store_name": "my_memory_store",
"scope": "user_123",
"update_delay": 1
}
]
}
}'
创建对话
现在可以创建对话和请求代理响应。 在每个会话开始时,将注入静态内存,以便代理具有即时的持久上下文。 上下文记忆会在每一轮根据最新消息进行检索,以辅助生成每个响应。
每次代理响应后,服务都会在内部调用 update_memories。 但是,对长期记忆的实际写入会受到 update_delay 设置的去抖控制。 更新是计划执行的,只有在配置的非活动时间段结束后才会完成。
注释
在更新的预览架构中,内存搜索工具输出使用 memories 集合而不是旧 results 字段。 如果您处理原始输出载荷,请相应更新解析器。
import time
# Create a conversation with the agent with memory tool enabled
conversation = openai_client.conversations.create()
print(f"Created conversation (id: {conversation.id})")
# Create an agent response to initial user message
response = openai_client.responses.create(
input="I prefer dark roast coffee",
conversation=conversation.id,
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
# To scope memories to an end user, uncomment:
# extra_headers={"x-memory-user-id": "<user-id>"},
)
print(f"Response output: {response.output_text}")
# After an inactivity in the conversation, memories will be extracted from the conversation and stored
print("Waiting for memories to be stored...")
time.sleep(65)
# Create a new conversation
new_conversation = openai_client.conversations.create()
print(f"Created new conversation (id: {new_conversation.id})")
# Create an agent response with stored memories
new_response = openai_client.responses.create(
input="Please order my usual coffee",
conversation=new_conversation.id,
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response output: {new_response.output_text}")
using System.Threading;
#pragma warning disable OPENAI001
// Get a response client scoped to the agent
ProjectResponsesClient responseClient =
projectClient.ProjectOpenAIClient
.GetProjectResponsesClientForAgent(agent.Name);
// Create an agent response to initial user message
ResponseItem request = ResponseItem.CreateUserMessageItem(
"I prefer dark roast coffee");
ResponseResult response = responseClient.CreateResponse([request]);
// To scope memories to an end user, uncomment:
// var options = new CreateResponseOptions();
// options.InputItems.Add(request);
// var requestOptions = new RequestOptions();
// requestOptions.AddHeader("x-memory-user-id", "<user-id>");
// ClientResult result = responseClient.CreateResponse(
// BinaryContent.Create(options), requestOptions);
// ResponseResult response = ModelReaderWriter.Read<ResponseResult>(
// result.GetRawResponse().Content);
Console.WriteLine($"Response output: {response.GetOutputText()}");
// After inactivity, memories are extracted and stored
Console.WriteLine("Waiting for memories to be stored...");
Thread.Sleep(65_000);
// Create a new response to demonstrate cross-session recall
ResponseItem newRequest = ResponseItem.CreateUserMessageItem(
"Please order my usual coffee");
ResponseResult newResponse = responseClient.CreateResponse(
[newRequest]);
Console.WriteLine(
$"Response output: {newResponse.GetOutputText()}");
import { setTimeout } from "timers/promises";
const openai = project.getOpenAIClient();
// Create a conversation with the agent with memory tool enabled
const conversation = await openai.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Create an agent response to initial user message
const response = await openai.responses.create(
{
conversation: conversation.id,
input: "I prefer dark roast coffee",
},
{
body: {
agent_reference: { name: agent.name, type: "agent_reference" },
},
// To scope memories to an end user, uncomment:
// headers: { "x-memory-user-id": "<user-id>" },
},
);
console.log(`Response output: ${response.output_text}`);
// After inactivity, memories are extracted and stored
console.log("Waiting for memories to be stored...");
await setTimeout(65_000);
// Create a new conversation to demonstrate cross-session recall
const newConversation = await openai.conversations.create();
console.log(`Created new conversation (id: ${newConversation.id})`);
// Create an agent response with stored memories
const newResponse = await openai.responses.create(
{
conversation: newConversation.id,
input: "Please order my usual coffee",
},
{
body: {
agent_reference: { name: agent.name, type: "agent_reference" },
},
},
);
console.log(`Response output: ${newResponse.output_text}`);
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
ResponsesClient responsesClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildResponsesClient();
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("I prefer dark roast coffee"));
System.out.println("Response output: " + response.output());
System.out.println("Waiting for memories to be stored...");
Thread.sleep(65_000);
Response newResponse = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Please order my usual coffee"));
System.out.println("Response output: " + newResponse.output());
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/openai/v1/conversations" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{}'
# Copy the "id" field from the previous response
# To scope memories to an end user, add -H "x-memory-user-id: <user-id>" to the following request
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"input": "I prefer dark roast coffee",
"conversation": "{conversation-id}",
"agent_reference": {
"type": "agent_reference",
"name": "MyAgent"
}
}'
采用直接记住或忘记机制
当用户显式要求代理记住或忘记信息时,数组中的 tools 内存搜索工具会立即应用该操作,并将结果作为响应输出中的内存命令项返回。 无需其他工具配置。
注释
直接内存命令不会覆盖内存 TTL。 如果内存存储已配置 TTL,内存项仍可能过期,即使内存项是通过记住命令添加的。
openai_client = project_client.get_openai_client()
# Configure the memory search tool
tools = [
{
"type": "memory_search_preview",
"memory_store_name": memory_store_name,
"scope": scope,
}
]
# Ask the agent to remember information
remember_response = openai_client.responses.create(
model=os.environ["MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME"],
tools=tools,
input="Remember that my preferred seat is aisle.",
)
for item in remember_response.output:
if getattr(item, "type", None) == "memory_command_call":
print(item.type) # memory_command_call
print(item.arguments) # {"action": "remember", "content": "..."}
print(item.status) # completed
# Ask the agent to forget information
forget_response = openai_client.responses.create(
model=os.environ["MEMORY_STORE_CHAT_MODEL_DEPLOYMENT_NAME"],
tools=tools,
input="Forget my preferred seat.",
)
for item in forget_response.output:
if getattr(item, "type", None) == "memory_command_call":
print(item.type)
print(item.arguments) # {"action": "forget", "content": "..."}
print(item.status)
此示例重复使用在创建对话中创建的 responseClient。
using Azure.AI.Extensions.OpenAI;
using OpenAI.Responses;
#pragma warning disable AAIP001
#pragma warning disable OPENAI001
static void PrintMemoryCommands(ResponseResult response)
{
foreach (ResponseItem item in response.OutputItems)
{
switch (item.AsAgentResponseItem())
{
case MemoryCommandToolCall command:
Console.WriteLine($"Arguments: {command.Arguments}");
Console.WriteLine($"Status: {command.Status}");
break;
case MemoryCommandToolCallOutput output:
Console.WriteLine($"Status: {output.Status}");
break;
}
}
}
// Ask the agent to remember information
ResponseResult rememberResponse = responseClient.CreateResponse(
[ResponseItem.CreateUserMessageItem(
"Remember that my preferred seat is aisle.")]);
PrintMemoryCommands(rememberResponse);
// Ask the agent to forget information
ResponseResult forgetResponse = responseClient.CreateResponse(
[ResponseItem.CreateUserMessageItem(
"Forget my preferred seat.")]);
PrintMemoryCommands(forgetResponse);
const openai = project.getOpenAIClient();
// Configure the memory search tool
const tools = [
{
type: "memory_search_preview",
memory_store_name: memoryStoreName,
scope: scope,
},
];
// Ask the agent to remember information
const rememberResponse = await openai.responses.create({
model: chatModelDeployment,
input: "Remember that my preferred seat is aisle.",
tools: tools as any,
});
for (const item of rememberResponse.output) {
const outputItem = item as Record<string, unknown>;
if (outputItem["type"] === "memory_command_call") {
console.log(outputItem["type"]); // memory_command_call
console.log(outputItem["arguments"]);
// {"action": "remember", "content": "..."}
console.log(outputItem["status"]); // completed
}
}
// Ask the agent to forget information
const forgetResponse = await openai.responses.create({
model: chatModelDeployment,
input: "Forget my preferred seat.",
tools: tools as any,
});
for (const item of forgetResponse.output) {
const outputItem = item as Record<string, unknown>;
if (outputItem["type"] === "memory_command_call") {
console.log(outputItem["type"]);
console.log(outputItem["arguments"]);
// {"action": "forget", "content": "..."}
console.log(outputItem["status"]);
}
}
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
Response rememberResponse = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Remember that my preferred seat is aisle."));
System.out.println(rememberResponse.output());
Response forgetResponse = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Forget my preferred seat."));
System.out.println(forgetResponse.output());
# Reuse the {conversation-id} from the previous section
# To scope memories to an end user, set x-memory-user-id in each request
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-H "x-memory-user-id: <user-id>" \
-d '{
"input": "Remember that my preferred seat is aisle.",
"conversation": "{conversation-id}",
"agent_reference": {
"type": "agent_reference",
"name": "MyAgent"
}
}'
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/openai/v1/responses" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-H "x-memory-user-id: <user-id>" \
-d '{
"input": "Forget my preferred seat.",
"conversation": "{conversation-id}",
"agent_reference": {
"type": "agent_reference",
"name": "MyAgent"
}
}'
通过 API 使用存储
可以使用内存存储 API 直接与内存存储进行交互。 首先,将对话内容中的记忆添加到内存存储,然后搜索相关记忆,以提供代理交互的上下文。
将记忆添加到存储库
通过向内存存储提供对话内容来添加记忆。 系统预处理和后处理数据(包括内存提取和合并)以优化代理的内存。 此长时间运行的操作可能需要大约一分钟。
通过指定 scope 参数来确定如何跨用户分段内存。 可以将内存范围限定为特定的最终用户、团队或其他标识符。
可以使用多个会话轮次的内容更新内存存储,或者使用以前的更新操作 ID 在每个轮次和链更新后更新。
# Set scope to associate the memories with
scope = "user_123"
user_message = {
"role": "user",
"content": "I prefer dark roast coffee and usually drink it in the morning",
"type": "message"
}
update_poller = project_client.beta.memory_stores.begin_update_memories(
name=memory_store_name,
scope=scope,
items=[user_message], # Pass conversation items that you want to add to memory
update_delay=0, # Trigger update immediately without waiting for inactivity
)
# Wait for the update operation to complete, but can also fire and forget
update_result = update_poller.result()
print(f"Updated with {len(update_result.memory_operations)} memory operations")
for operation in update_result.memory_operations:
print(
f" - Operation: {operation.kind}, Memory ID: {operation.memory_item.memory_id}, Content: {operation.memory_item.content}"
)
# Extend the previous update with another update and more messages
new_message = {
"role":"user",
"content":"I also like cappuccinos in the afternoon",
"type":"message"}
new_update_poller = project_client.beta.memory_stores.begin_update_memories(
name=memory_store_name,
scope=scope,
items=[new_message],
previous_update_id=update_poller.update_id, # Extend from previous update ID
update_delay=0, # Trigger update immediately without waiting for inactivity
)
new_update_result = new_update_poller.result()
for operation in new_update_result.memory_operations:
print(
f" - Operation: {operation.kind}, Memory ID: {operation.memory_item.memory_id}, Content: {operation.memory_item.content}"
)
#pragma warning disable OPENAI001
// Set scope to associate the memories with
string scope = "user_123";
MemoryUpdateOptions memoryOptions = new(scope)
{
UpdateDelay = 0, // Trigger update immediately without waiting for inactivity
};
memoryOptions.Items.Add(ResponseItem.CreateUserMessageItem(
"I prefer dark roast coffee and usually drink it "
+ "in the morning"));
// Wait for the update operation to complete
MemoryUpdateResult updateResult =
projectClient.MemoryStores.WaitForMemoriesUpdate(
memoryStoreName: memoryStore.Name,
options: memoryOptions,
pollingInterval: 500);
if (updateResult.Status == MemoryStoreUpdateStatus.Failed)
{
throw new InvalidOperationException(
updateResult.ErrorDetails);
}
Console.WriteLine(
$"Updated with {updateResult.Details.MemoryOperations.Count} "
+ "memory operations");
foreach (var operation in updateResult.Details.MemoryOperations)
{
Console.WriteLine(
$" - Operation: {operation.Kind}, "
+ $"Memory ID: {operation.MemoryItem.MemoryId}, "
+ $"Content: {operation.MemoryItem.Content}");
}
// Extend the previous update with another message
MemoryUpdateOptions newMemoryOptions = new(scope)
{
PreviousUpdateId = updateResult.UpdateId,
UpdateDelay = 0, // Trigger update immediately without waiting for inactivity
};
newMemoryOptions.Items.Add(ResponseItem.CreateUserMessageItem(
"I also like cappuccinos in the afternoon"));
MemoryUpdateResult newUpdateResult =
projectClient.MemoryStores.WaitForMemoriesUpdate(
memoryStoreName: memoryStore.Name,
options: newMemoryOptions,
pollingInterval: 500);
if (newUpdateResult.Status == MemoryStoreUpdateStatus.Failed)
{
throw new InvalidOperationException(
newUpdateResult.ErrorDetails);
}
foreach (var operation in newUpdateResult.Details.MemoryOperations)
{
Console.WriteLine(
$" - Operation: {operation.Kind}, "
+ $"Memory ID: {operation.MemoryItem.MemoryId}, "
+ $"Content: {operation.MemoryItem.Content}");
}
const scope = "user_123";
const userMessage: Record<string, unknown> = {
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "I prefer dark roast coffee and usually drink it in the morning",
},
],
};
console.log("\nSubmitting memory update request...");
const updatePoller = project.beta.memoryStores.updateMemories(
memoryStoreName,
scope,
{
items: [userMessage],
updateDelayInSecs: 0,
},
);
const updateResult = await updatePoller.pollUntilDone();
console.log(
`Updated with ${updateResult.memory_operations.length} ` +
`memory operation(s)`,
);
for (const operation of updateResult.memory_operations) {
console.log(
` - Operation: ${operation.kind}, ` +
`Memory ID: ${operation.memory_item.memory_id}, ` +
`Content: ${operation.memory_item.content}`,
);
}
// Extend the previous update with another message
const newMessage = {
role: "user",
content: "I also like cappuccinos in the afternoon",
type: "message",
};
const newUpdatePoller = project.beta.memoryStores.updateMemories(
memoryStoreName,
scope,
{
items: [newMessage],
updateDelayInSecs: 0,
},
);
const newUpdateResult = await newUpdatePoller.pollUntilDone();
console.log(
`Updated with ${newUpdateResult.memory_operations.length} ` +
`memory operation(s)`,
);
for (const operation of newUpdateResult.memory_operations) {
console.log(
` - Operation: ${operation.kind}, ` +
`Memory ID: ${operation.memory_item.memory_id}, ` +
`Content: ${operation.memory_item.content}`,
);
}
import com.azure.ai.agents.models.MemoryStoreUpdateCompletedResult;
import com.azure.ai.agents.models.MemoryStoreUpdateResponse;
import com.azure.core.util.polling.SyncPoller;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseInputItem;
import java.util.Arrays;
ResponseInputItem userMessage = ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("I prefer dark roast coffee and usually drink it in the morning")
.build());
SyncPoller<MemoryStoreUpdateResponse, MemoryStoreUpdateCompletedResult> updatePoller =
memoryStoresClient.beginUpdateMemories(
memoryStoreName,
scope,
Arrays.asList(userMessage),
null,
0);
updatePoller.waitForCompletion();
MemoryStoreUpdateCompletedResult updateResult = updatePoller.getFinalResult();
System.out.println(
"Updated with " + updateResult.getMemoryOperations().size()
+ " memory operation(s)");
for (var operation : updateResult.getMemoryOperations()) {
System.out.println(
" - Operation: " + operation.getKind() + ", Memory ID: "
+ operation.getMemoryItem().getMemoryId() + ", Content: "
+ operation.getMemoryItem().getContent());
}
ResponseInputItem newMessage = ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("I also like cappuccinos in the afternoon")
.build());
// Pass null for previousUpdateId to start a fresh independent update.
// To chain from the previous update, pass the update ID from the
// intermediate poller response instead.
SyncPoller<MemoryStoreUpdateResponse, MemoryStoreUpdateCompletedResult> newUpdatePoller =
memoryStoresClient.beginUpdateMemories(
memoryStoreName,
scope,
Arrays.asList(newMessage),
null,
0);
newUpdatePoller.waitForCompletion();
MemoryStoreUpdateCompletedResult newUpdateResult = newUpdatePoller.getFinalResult();
for (var newOperation : newUpdateResult.getMemoryOperations()) {
System.out.println(
" - Operation: " + newOperation.getKind() + ", Memory ID: "
+ newOperation.getMemoryItem().getMemoryId() + ", Content: "
+ newOperation.getMemoryItem().getContent());
}
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store:update_memories?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"scope": "user_123",
"items": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "I prefer dark roast coffee and usually drink it in the morning"
}
]
}
],
"update_delay": 0
}'
# Get add memory status by polling the update_id
# Use the "update_id" from previous response
UPDATE_ID=<your_update_id>
curl -X GET "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store/updates/${UPDATE_ID}?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}"
在记忆存储库中搜索记忆
搜索存储器以检索代理程序交互的相关上下文。 指定内存存储名称和范围以缩小搜索范围。
from azure.ai.projects.models import MemorySearchOptions
# Search memories by a query
query_message = {"role": "user", "content": "What are my coffee preferences?", "type": "message"}
search_response = project_client.beta.memory_stores.search_memories(
name=memory_store_name,
scope=scope,
items=[query_message],
options=MemorySearchOptions(max_memories=5)
)
print(f"Found {len(search_response.memories)} memories")
for memory in search_response.memories:
print(f" - Memory ID: {memory.memory_item.memory_id}, Content: {memory.memory_item.content}")
#pragma warning disable OPENAI001
// Search memories by a query
MemorySearchOptions searchOptions = new(scope)
{
Items =
{
ResponseItem.CreateUserMessageItem(
"What are my coffee preferences?")
},
ResultOptions = new() { MaxMemories = 5 },
};
MemoryStoreSearchResponse searchResponse =
projectClient.MemoryStores.SearchMemories(
memoryStoreName: memoryStore.Name,
options: searchOptions);
Console.WriteLine(
$"Found {searchResponse.Memories.Count} memories");
foreach (MemorySearchItem item in searchResponse.Memories)
{
Console.WriteLine(
$" - Content: {item.MemoryItem.Content}");
}
const queryMessage: Record<string, unknown> = {
type: "message",
role: "user",
content: [
{ type: "input_text", text: "What are my coffee preferences?" },
],
};
console.log("\nSearching memories for stored preferences...");
const searchResponse =
await project.beta.memoryStores.searchMemories(
memoryStoreName,
scope,
{
items: [queryMessage],
options: { max_memories: 5 },
},
);
console.log(`Found ${searchResponse.memories.length} memory item(s)`);
for (const memory of searchResponse.memories) {
console.log(
` - Memory ID: ${memory.memory_item.memory_id}, ` +
`Content: ${memory.memory_item.content}`,
);
}
import com.azure.ai.agents.models.MemorySearchItem;
import com.azure.ai.agents.models.MemorySearchOptions;
import com.azure.ai.agents.models.MemoryStoreSearchResponse;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseInputItem;
import java.util.Arrays;
ResponseInputItem queryMessage = ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("What are my coffee preferences?")
.build());
MemorySearchOptions searchOptions = new MemorySearchOptions()
.setMaxMemories(5);
MemoryStoreSearchResponse searchResponse = memoryStoresClient.searchMemories(
memoryStoreName,
scope,
Arrays.asList(queryMessage),
null,
searchOptions);
System.out.println("Found " + searchResponse.getMemories().size() + " memories");
for (MemorySearchItem item : searchResponse.getMemories()) {
System.out.println(
" - Memory ID: " + item.getMemoryItem().getMemoryId() + ", Content: "
+ item.getMemoryItem().getContent());
}
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store:search_memories?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"scope": "user_123",
"items": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What are my coffee preferences?"
}
]
}
],
"options": {
"max_memories": 5
}
}'
检索静态或上下文内存
通常,你无法根据用户消息的语义相似度来检索用户配置文件记忆。 将静态记忆注入每个会话的开头,并使用上下文记忆生成每个代理响应。
要检索静态内存,请使用
search_memories并包含scope,但不含items或previous_search_id。 这会返回与范围关联的用户资料记录。若要检索上下文记忆,请调用
search_memories,并将items设置为最新消息。 这可以返回与给定项目最相关的用户配置文件和聊天摘要记忆。
有关用户配置文件和聊天摘要记忆的详细信息,请参阅 内存类型。
管理内存项
使用项级操作直接创建、检查、更新和删除单个内存记录。 有关范围级别或存储级删除,请参阅 “删除记忆”。
创建内存项
# Create a memory item directly
created = project_client.beta.memory_stores.create_memory(
name=memory_store_name,
scope="defaultUser",
content="User prefers concise changelogs with impact-first summaries.",
kind="user_profile",
)
print(f"Memory ID: {created.memory_id}")
print(f"Content: {created.content}")
print(f"Kind: {created.kind}")
using Azure.AI.Projects.Memory;
#pragma warning disable AAIP001
// Create a memory item directly
MemoryItem created = projectClient.MemoryStores.CreateMemory(
name: memoryStoreName,
scope: "defaultUser",
content: "User prefers concise changelogs with impact-first summaries.",
kind: MemoryItemKind.UserProfile);
Console.WriteLine($"Memory ID: {created.MemoryId}");
Console.WriteLine($"Content: {created.Content}");
Console.WriteLine($"Scope: {created.Scope}");
// Create a memory item directly
const created = await project.beta.memoryStores.createMemory(
memoryStoreName,
"defaultUser",
"User prefers concise changelogs with impact-first summaries.",
"user_profile",
);
console.log(`Memory ID: ${created.memory_id}`);
console.log(`Content: ${created.content}`);
console.log(`Kind: ${created.kind}`);
import com.azure.ai.agents.models.MemoryItem;
import com.azure.ai.agents.models.MemoryItemKind;
MemoryItem created = memoryStoresClient.createMemory(
memoryStoreName,
"defaultUser",
"User prefers concise changelogs with impact-first summaries.",
MemoryItemKind.USER_PROFILE);
System.out.println("Memory ID: " + created.getMemoryId());
System.out.println("Content: " + created.getContent());
System.out.println("Kind: " + created.getKind());
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store/items?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"scope": "defaultUser",
"content": "User prefers concise changelogs with impact-first summaries.",
"kind": "user_profile"
}'
获取内存项
# Retrieve a memory item by ID
item = project_client.beta.memory_stores.get_memory(
name=memory_store_name,
memory_id="<memory-item-id>",
)
print(f"Memory ID: {item.memory_id}")
print(f"Content: {item.content}")
print(f"Kind: {item.kind}")
using Azure.AI.Projects.Memory;
#pragma warning disable AAIP001
// Retrieve a memory item by ID
MemoryItem item = projectClient.MemoryStores.GetMemory(
name: memoryStoreName,
memoryId: "<memory-item-id>");
Console.WriteLine($"Memory ID: {item.MemoryId}");
Console.WriteLine($"Content: {item.Content}");
Console.WriteLine($"Scope: {item.Scope}");
// Retrieve a memory item by ID
const item = await project.beta.memoryStores.getMemory(
memoryStoreName,
"<memory-item-id>",
);
console.log(`Memory ID: ${item.memory_id}`);
console.log(`Content: ${item.content}`);
console.log(`Kind: ${item.kind}`);
import com.azure.ai.agents.models.MemoryItem;
MemoryItem memItem = memoryStoresClient.getMemory(
memoryStoreName,
"<memory-item-id>");
System.out.println("Memory ID: " + memItem.getMemoryId());
System.out.println("Content: " + memItem.getContent());
System.out.println("Kind: " + memItem.getKind());
curl -X GET "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store/items/<memory-item-id>?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}"
列出内存项
# List all memory items in the store
memories = project_client.beta.memory_stores.list_memories(
name=memory_store_name,
scope="defaultUser",
)
count = 0
for item in memories:
count += 1
print(f"- {item.memory_id} [{item.kind}]: {item.content}")
print(f"Total memories: {count}")
using Azure.AI.Projects.Memory;
#pragma warning disable AAIP001
// List all memory items in the store
int count = 0;
foreach (MemoryItem item in projectClient.MemoryStores.GetMemories(
name: memoryStoreName,
scope: "defaultUser"))
{
count++;
Console.WriteLine(
$"- {item.MemoryId} [{item.Scope}]: {item.Content}");
}
Console.WriteLine($"Total memories: {count}");
// List all memory items in the store
const memoriesList = project.beta.memoryStores.listMemories(
memoryStoreName,
"defaultUser",
);
let count = 0;
for await (const item of memoriesList) {
count += 1;
console.log(`- ${item.memory_id} [${item.kind}]: ${item.content}`);
}
console.log(`Total memories: ${count}`);
import com.azure.ai.agents.models.ListMemoriesOptions;
import com.azure.ai.agents.models.MemoryItem;
ListMemoriesOptions options = new ListMemoriesOptions(
memoryStoreName,
"defaultUser");
int count = 0;
for (MemoryItem memoryEntry : memoryStoresClient.listMemories(options)) {
count++;
System.out.println(
"- " + memoryEntry.getMemoryId() + " [" + memoryEntry.getKind() + "]: "
+ memoryEntry.getContent());
}
System.out.println("Total memories: " + count);
curl -X GET "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store/items:list?scope=user_123&api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}"
更新内存项
# Update a memory item by ID
updated = project_client.beta.memory_stores.update_memory(
name=memory_store_name,
memory_id="<memory-item-id>",
content="User prefers detailed technical explanations with examples.",
)
print(f"Updated: {updated.content}")
using Azure.AI.Projects.Memory;
#pragma warning disable AAIP001
// Update a memory item by ID
MemoryItem updated = projectClient.MemoryStores.UpdateMemory(
name: memoryStoreName,
memoryId: "<memory-item-id>",
content: "User prefers detailed technical explanations with examples.");
Console.WriteLine($"Updated: {updated.Content}");
// Update a memory item by ID
const updated = await project.beta.memoryStores.updateMemory(
memoryStoreName,
"<memory-item-id>",
"User prefers detailed technical explanations with examples.",
);
console.log(`Updated: ${updated.content}`);
import com.azure.ai.agents.models.MemoryItem;
MemoryItem updated = memoryStoresClient.updateMemory(
memoryStoreName,
"<memory-item-id>",
"User prefers detailed technical explanations with examples.");
System.out.println("Updated: " + updated.getContent());
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store/items/<memory-item-id>?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{"content": "User prefers detailed technical explanations with examples."}'
删除内存项
# Delete a memory item by ID
project_client.beta.memory_stores.delete_memory(
name=memory_store_name,
memory_id="<memory-item-id>",
)
print("Memory item deleted successfully")
using Azure.AI.Projects.Memory;
#pragma warning disable AAIP001
// Delete a memory item by ID
MemoryDeletionResult result = projectClient.MemoryStores.DeleteMemory(
name: memoryStoreName,
memoryId: "<memory-item-id>");
Console.WriteLine(
$"Memory item {result.MemoryId} deleted: {result.Deleted}");
// Delete a memory item by ID
await project.beta.memoryStores.deleteMemory(
memoryStoreName,
"<memory-item-id>",
);
console.log("Memory item deleted successfully");
memoryStoresClient.deleteMemory(memoryStoreName, "<memory-item-id>");
System.out.println("Memory item deleted successfully");
curl -X DELETE "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store/items/<memory-item-id>?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}"
删除内存
警告
在删除内存存储之前,请考虑对依赖代理的影响。 具有附加内存存储的代理可能会失去对历史上下文的访问权限。
内存会在存储器中按范围进行组织。 可以删除特定范围的内存以删除特定于用户的数据,也可以删除整个内存存储,以删除所有范围内的所有内存。
按范围删除记忆
在保留内存存储结构的同时,删除与特定用户或组范围关联的所有内存。 使用此操作可处理特定用户的用户数据删除请求或重置内存。
# Delete memories for a specific scope
project_client.beta.memory_stores.delete_scope(
name=memory_store_name,
scope="user_123"
)
print(f"Deleted memories for scope: user_123")
// Delete memories for a specific scope
MemoryStoreDeleteScopeResponse deleteScopeResponse =
projectClient.MemoryStores.DeleteScope(
name: memoryStore.Name,
scope: "user_123");
Console.WriteLine(
$"Deleted scope: {deleteScopeResponse.Name}, "
+ $"success: {deleteScopeResponse.IsDeleted}");
console.log("\nDeleting memories for scope...");
await project.beta.memoryStores.deleteScope(memoryStoreName, scope);
memoryStoresClient.deleteScope(memoryStoreName, "user_123");
System.out.println("Deleted memories for scope: user_123");
curl -X POST "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store:delete_scope?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"scope": "user_123"
}'
删除内存存储
删除所有作用域中的整个内存库和所有关联的内存。 此操作不可逆。
# Delete the entire memory store
delete_response = project_client.beta.memory_stores.delete(memory_store_name)
print(f"Deleted memory store: {delete_response.deleted}")
// Delete the entire memory store
DeleteMemoryStoreResponse deleteResponse =
projectClient.MemoryStores.DeleteMemoryStore(
name: memoryStore.Name);
Console.WriteLine(
$"Deleted memory store: {deleteResponse.Name}, "
+ $"success: {deleteResponse.IsDeleted}");
console.log("Deleting memory store...");
await project.beta.memoryStores.delete(memoryStoreName);
memoryStoresClient.deleteMemoryStore(memoryStoreName);
System.out.println("Deleted memory store: " + memoryStoreName);
curl -X DELETE "${FOUNDRY_PROJECT_ENDPOINT}/memory_stores/my_memory_store?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${ACCESS_TOKEN}"
最佳做法
实现每用户访问控制: 避免向代理授予对所有用户共享的内存的访问权限。
scope使用属性按用户对内存存储进行分区。 在用户之间共享scope时,用于user_profile_details指示内存系统不存储个人信息。将范围映射到最终用户:使用内存搜索工具时,请在工具定义中设置为
scope{{$userId}}。 系统从x-memory-user-id请求标头(如果存在)解析用户标识。 否则,会回退到调用方的 Microsoft Entra 令牌 ({tid}_{oid})。最小化和保护敏感数据: 仅存储用例所需的内容。 如果必须存储敏感数据(如个人数据、运行状况数据或机密业务输入),请编辑或删除可用于追溯到个人的其他内容。
支持隐私和合规性: 为用户提供透明度,包括访问和删除其数据的选项。 在防篡改审核日志中记录所有删除。 确保系统遵守本地合规性要求和法规标准。
分段数据并隔离内存: 在多代理系统中,以逻辑方式和操作方式分段内存。 允许客户定义、隔离、检查和删除其自己的内存占用情况。
监视内存使用情况: 跟踪令牌使用情况和内存操作,以了解成本和优化性能。
公开面向用户的内存控件: 提供项级编辑和删除操作以支持信任和数据权限工作流。
设置显式保留默认值: 使用与策略要求匹配的 TTL 设置。 产品 UX 中的文档保留行为。
故障 排除
| 问题 | 原因 | 分辨率 |
|---|---|---|
| 请求失败并出现身份验证或授权错误。 | 你的标识或项目托管标识没有所需的角色。 | 验证 授权和权限中的角色。 对于 REST 调用,请生成新的访问令牌并重试。 |
| 对话后不会出现记忆。 | 内存更新已去抖或仍在处理。 | 增加等待时间,或将 update_delay 设置为 0 并调用更新 API 立即触发处理。 |
| 内存搜索不返回任何结果。 | 该值 scope 与存储内存时使用的作用域不匹配。 |
使用相同的范围进行更新和搜索。 如果将范围映射到用户,请使用稳定的用户标识符。 |
| 代理响应不使用存储的内存。 | 代理未使用内存搜索工具进行配置,或者内存存储名称不正确。 | 确认代理定义包括工具memory_search_preview并指向正确的内存存储名称。 |
| 更新后,过程内存或默认 TTL 设置未生效。 | 在最新的预览版中,只能在内存存储创建时设置默认选项。 | 使用所需的默认值重新创建内存存储,或检查 API 版本是否支持创建后选项更新。 |
| 显式记住或忘记请求未在响应中返回内存命令项。 | 内存工具未正确配置,或者输入未识别为“记住”或“忘记”命令。 | 确认记忆工具的配置,并使用直接的“记住”或“忘记”表述进行测试。 |