중요
Foundry Agent Service의 메모리(미리 보기) 및 Memory Store API(미리 보기)는 Azure 구독의 일부로 사용자에게 라이선스가 부여되며, Microsoft 제품 약관, Microsoft 제품 및 서비스 데이터 보호 부록 및 Microsoft Azure 미리 보기에 대한 추가 사용 약관에서 "Previews"에 적용되는 약관의 적용을 받습니다.
최신 미리 보기는 다음을 비롯한 새로운 기능과 향상된 기능을 제공합니다.
- 개별 메모리 레코드를 만들고, 읽고, 업데이트하고, 나열하고, 삭제하는 메모리 항목 작업입니다.
- 새로 만든 메모리 저장소에 대한 기본 TTL을 포함하여 저장소 수준 기본 보존 컨트롤입니다.
- 동기화된 메모리 명령 동작을 직접 기억하거나 잊어버리세요.
Foundry 에이전트 서비스의 메모리는 관리되는 장기 메모리 솔루션입니다. 이를 통해 세션, 디바이스 및 워크플로에서 에이전트 연속성을 사용할 수 있습니다. 메모리 저장소를 만들고 관리하면 사용자 기본 설정을 유지하고 대화 기록을 유지하며 개인 설정된 환경을 제공하는 에이전트를 빌드할 수 있습니다.
메모리 저장소는 영구적 스토리지 역할을 하며 각 에이전트와 관련된 정보 유형을 정의합니다. 보안 및 격리된 환경을 보장하기 위해 사용자 간에 메모리를 분할하는 매개 변수를 사용하여 scope 액세스를 제어합니다.
이 문서에서는 메모리 저장소를 만들고 관리하고 사용하는 방법을 설명합니다. 개념 정보는 Foundry 에이전트 서비스에서의 메모리를 참조하세요.
사용량 지원
| 기능 | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API |
|---|---|---|---|---|---|
| 메모리 저장소 만들기, 업데이트, 나열 및 삭제 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| 프롬프트 에이전트에 메모리 연결 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| 메모리 업데이트 및 검색 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| 메모리 항목 만들기, 읽기, 업데이트, 나열 및 삭제 | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
필수 구성 요소
- Azure 구독입니다. 무료로 만듭니다.
- Microsoft Foundry 프로젝트로서 권한 부여 및 인증이 구성됨.
- 프로젝트에서 채팅 모델 배포(예:
gpt-5.2)입니다. - 프로젝트에 임베딩 모델 배포(예:
text-embedding-3-small) - 필수 패키지 및 환경 변수가 있는 구성된 로컬 환경입니다.
인증 및 권한
프로덕션 배포에 대한 역할 기반 액세스 제어 를 권장합니다. 역할이 적합하지 않은 경우 이 섹션을 건너뛰고 대신 키 기반 인증을 사용합니다.
역할 기반 액세스를 구성하려면 다음을 수행합니다.
Azure 포털 로그인합니다.
프로젝트에서:
- 왼쪽 창에서 리소스 관리>ID를 선택합니다.
- 토글을 사용하여 시스템 할당 관리 ID를 사용하도록 설정합니다.
프로젝트가 포함된 리소스에서 다음을 수행합니다.
왼쪽 창에서 액세스 제어(IAM)를 선택합니다.
역할 할당 추가를> 선택합니다.
Foundry 사용자를 프로젝트의 관리 ID에 할당합니다.
중요
Foundry RBAC 역할의 이름이 최근에 바뀌었습니다. Foundry User, Foundry OwnerFoundry 계정 소유자 및 Foundry Project Manager는 이전에 Azure AI 사용자, Azure AI 소유자, Azure AI 계정 소유자 및 Azure AI Project Manager로 이름이 지정되었습니다. 이름 바꾸기가 롤아웃되는 동안 일부 위치에서는 이전 이름이 계속 표시될 수 있습니다. 역할 ID 및 핵심 권한은 이름 바꾸기에 의해 변경되지 않습니다.
환경 설정
필요한 패키지를 설치합니다.
pip install "azure-ai-projects>=2.0.0" azure-identity
필요한 패키지를 설치합니다.
dotnet add package Azure.AI.Projects
dotnet add package Azure.AI.Projects.Agents
dotnet add package Azure.AI.Extensions.OpenAI
dotnet add package Azure.Identity
필요한 패키지를 설치합니다.
npm install @azure/ai-projects@2 @azure/identity
필요한 패키지를 설치합니다.
<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}}. 시스템은 다음 두 소스 중 하나의 각 응답 호출에서 최종 사용자의 ID를 자동으로 확인합니다.
x-memory-user-id요청 헤더: 있는 경우 헤더 값이 사용자 ID로 사용됩니다. 서비스가 최종 사용자를 대신하여 API를 호출하는 프록시 또는 백 엔드 시나리오에서 사용합니다.Microsoft Entra 인증 토큰: 헤더가 설정되지 않으면 시스템은 호출자의 TID(테넌트 ID) 및 OID(개체 ID)로 대체됩니다. 이는 사용자가 Microsoft Entra 직접 인증하는 프런트 엔드 시나리오의 기본값입니다.
사용자별 격리가 필요하지 않은 경우 정적 scope 값을 대신 사용합니다.
낮은 수준의 메모리 API를 통해
메모리 API를 직접 호출할 때 각 요청에 명시적으로 지정 scope 합니다. 시스템에서 UUID(범용 고유 식별자) 또는 다른 안정적인 식별자와 같은 정적 값을 전달할 수 있습니다. 이러한 작업에는 자동 ID 추출이 지원되지 않습니다.
메모리 저장소 만들기
각 에이전트에 대한 전용 메모리 저장소를 만들어 메모리 액세스 및 최적화에 대한 명확한 경계를 설정합니다. 메모리 저장소를 만들 때는 채팅 모델을 지정하고 메모리 콘텐츠를 처리하는 모델 배포를 포함합니다.
메모리 저장소 옵션을 사용하여 추출 동작 및 보존 기본값을 제어합니다. 최신 미리 보기에서는 절차적 메모리를 사용하도록 설정하고 새로 만든 메모리 항목에 대한 기본 TTL(초)을 설정할 수 있습니다.
import os
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=30 * 24 * 60 * 60,
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.MemoryStoresClient;
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");
MemoryStoresClient memoryStoresClient = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint)
.buildMemoryStoresClient();
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>를 헤더로 전달합니다. 시스템은 해당 사용자의 ID로 범위를 확인합니다. 헤더가 없으면 범위는 호출자의 Microsoft Entra ID(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 openaiClient = project.getOpenAIClient();
// Create a conversation with the agent with memory tool enabled
const conversation = await openaiClient.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Create an agent response to initial user message
const response = await openaiClient.responses.create(
{
conversation: conversation.id,
input: "I prefer dark roast coffee",
},
{
body: {
agent: { 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 openaiClient.conversations.create();
console.log(`Created new conversation (id: ${newConversation.id})`);
// Create an agent response with stored memories
const newResponse = await openaiClient.responses.create(
{
conversation: newConversation.id,
input: "Please order my usual coffee",
},
{
body: {
agent: { 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이 구성된 경우 메모리 항목이 remember 명령에 의해 추가된 경우에도 계속 만료할 수 있습니다.
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)
// This code snippet is currently unavailable.
const openaiClient = 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 openaiClient.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 openaiClient.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를 사용하여 메모리 저장소와 직접 상호 작용할 수 있습니다. 먼저 대화 콘텐츠의 추억을 메모리 저장소에 추가한 다음 관련 추억을 검색하여 에이전트 상호 작용에 대한 컨텍스트를 제공합니다.
메모리 저장소에 추억 추가
메모리 저장소에 대화 콘텐츠를 제공하여 추억을 추가합니다. 시스템은 메모리 추출 및 통합을 포함하여 데이터를 전처리하고 후처리하여 에이전트의 메모리를 최적화합니다. 이 장기 실행 작업은 약 1분 정도 걸릴 수 있습니다.
매개 변수를 지정하여 사용자 간에 메모리를 분할하는 방법을 결정합니다 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_memoriesitems합니다. 이렇게 하면 지정된 항목과 가장 관련성이 큰 사용자 프로필 및 채팅 요약 추억을 모두 반환할 수 있습니다.
사용자 프로필 및 채팅 요약 메모리에 대한 자세한 내용은 메모리 유형을 참조하세요.
메모리 항목 관리
항목 수준 작업을 사용하여 개별 메모리 레코드를 직접 만들고, 검사하고, 업데이트하고, 삭제합니다. 범위 수준 또는 저장소 수준 삭제는 메모리 삭제를 참조하세요.
메모리 항목 만들기
# 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}")
// This code snippet is currently unavailable.
// 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}")
// This code snippet is currently unavailable.
// 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}")
// This code snippet is currently unavailable.
// 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}")
// This code snippet is currently unavailable.
// 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")
// This code snippet is currently unavailable.
// 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으로 설정하십시오. 시스템은x-memory-user-id요청 헤더에서 사용자 ID를 해결합니다, (있다면). 그렇지 않으면 호출자의 Microsoft Entra 토큰({tid}_{oid})으로 대체됩니다.중요한 데이터 최소화 및 보호: 사용 사례에 필요한 것만 저장합니다. 개인 데이터, 건강 데이터 또는 기밀 비즈니스 입력과 같은 중요한 데이터를 저장해야 하는 경우 개인에게 다시 추적하는 데 사용할 수 있는 다른 콘텐츠를 수정하거나 제거합니다.
개인 정보 보호 및 규정 준수 지원: 사용자에게 데이터에 액세스하고 삭제하는 옵션을 포함하여 투명도를 제공합니다. 모든 삭제를 변조 방지 감사 내역에 기록합니다. 시스템이 로컬 규정 준수 요구 사항 및 규정 표준을 준수하는지 확인합니다.
데이터를 분할하고 메모리를 격리합니다 . 다중 에이전트 시스템에서 메모리를 논리적 및 운영적으로 분할합니다. 고객이 자신의 메모리 공간을 정의, 격리, 검사 및 삭제할 수 있습니다.
메모리 사용량 모니터링: 토큰 사용량 및 메모리 작업을 추적하여 비용을 이해하고 성능을 최적화합니다.
사용자 연결 메모리 컨트롤 노출: 항목 수준 편집 및 삭제 작업을 제공하여 신뢰 및 데이터 권한 워크플로를 지원합니다.
명시적 보존 기본값을 설정합니다. 정책 요구 사항과 일치하는 TTL 설정을 사용합니다. 제품 UX의 문서 보존 동작입니다.
문제 해결
| 문제 | 원인 | 해상도 |
|---|---|---|
| 인증 또는 권한 부여 오류로 요청이 실패합니다. | 사용자 ID 또는 프로젝트 관리 ID에 필요한 역할이 부여되어 있지 않습니다. | 인증 및 권한에서의 역할을 확인합니다. REST 호출의 경우 새 액세스 토큰을 생성하고 다시 시도합니다. |
| 대화 후에는 기억이 나타나지 않습니다. | 메모리 업데이트가 디버그되거나 여전히 처리 중입니다. | 대기 시간을 늘리거나 즉시 처리를 트리거하도록 설정된 업데이트 API update_delay 를 0 호출합니다. |
| 메모리 검색은 결과를 반환하지 않습니다. | 이 값은 scope 메모리가 저장되었을 때 사용되는 범위와 일치하지 않습니다. |
업데이트 및 검색에 동일한 범위를 사용합니다. 사용자에게 범위를 매핑하는 경우 안정적인 사용자 식별자를 사용합니다. |
| 에이전트 응답은 저장된 메모리를 사용하지 않습니다. | 에이전트가 메모리 검색 도구로 구성되지 않았거나 메모리 저장소 이름이 잘못되었습니다. | 에이전트 정의에 도구가 memory_search_preview 포함되어 있고 올바른 메모리 저장소 이름을 참조했는지 확인합니다. |
| 업데이트 후 절차 메모리 또는 기본 TTL 설정이 적용되지 않았습니다. | 최신 미리 보기에서는 메모리 저장소를 만들 때만 기본 옵션을 설정할 수 있습니다. | 원하는 기본값으로 메모리 저장소를 다시 만들거나 API 버전이 사후 만들기 옵션 업데이트를 지원하는지 확인합니다. |
| 명시적 기억 또는 잊어버리기 요청은 응답에서 메모리 명령 항목을 반환하지 않았습니다. | 메모리 도구가 올바르게 구성되지 않았거나 입력이 기억 또는 잊어버리기 명령으로 인식되지 않았습니다. | 메모리 도구 구성을 확인하고 직접 기억 또는 잊어버리기 구문을 사용하여 테스트합니다. |