Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Penting
Memori (pratinjau) di Foundry Agent Service dan Memory Store API (pratinjau) dilisensikan untuk Anda sebagai bagian dari langganan Azure Anda dan tunduk pada ketentuan yang berlaku untuk "Pratinjau" dalam Ketentuan Produk Microsoft, Adendum Perlindungan Data Produk dan Layanan Microsoft, dan Ketentuan Penggunaan Tambahan untuk Pratinjau Microsoft Azure.
Pratinjau terbaru menawarkan fitur dan peningkatan baru, termasuk:
- Operasi item memori untuk membuat, membaca, memperbarui, mencantumkan, dan menghapus rekaman memori individual.
- Kontrol retensi bawaan pada tingkat store, termasuk TTL bawaan untuk store memori yang baru dibuat.
- Atur langsung perilaku perintah memori tersinkronisasi untuk mengingat atau melupakan.
Memori di Foundry Agent Service adalah solusi memori jangka panjang terkelola. Ini memungkinkan kelangsungan agen di seluruh sesi, perangkat, dan alur kerja. Dengan membuat dan mengelola penyimpanan memori, Anda dapat membangun agen yang mempertahankan preferensi pengguna, mempertahankan riwayat percakapan, dan memberikan pengalaman yang dipersonalisasi.
Penyimpanan memori bertindak sebagai penyimpanan persisten, menentukan jenis informasi mana yang relevan dengan setiap agen. Anda mengontrol akses menggunakan scope parameter, yang menyegmentasi memori antar pengguna untuk memastikan pengalaman yang aman dan terisolasi.
Artikel ini menjelaskan cara membuat, mengelola, dan menggunakan penyimpanan memori. Untuk informasi konseptual, lihat Memori di Foundry Agent Service.
Untuk keberhasilan end-to-end pertama, ikuti jalur ini:
- Buat penyimpanan memori untuk agen.
- Lampirkan alat pencarian memori ke agen.
- Buat percakapan, kirim preferensi, dan tunggu penundaan pembaruan yang dikonfigurasi sehingga layanan dapat mengingatnya.
- Mulai percakapan baru dalam contoh yang sama dan ajukan pertanyaan terkait untuk mengonfirmasi bahwa agen memanggil kembali preferensi.
Pilih alur kerja berdasarkan seberapa langsung Anda perlu mengontrol memori:
| Scenario | Mulai dengan | Gunakan untuk |
|---|---|---|
| Administrasi | Membuat penyimpanan memori | Mengonfigurasi, memperbarui, mencantumkan, atau menghapus pengaturan penyimpanan dan retensi. |
| Perintah | Menerapkan perilaku ingat atau lupa langsung | Hormati permintaan pengguna eksplisit untuk segera mengingat atau melupakan informasi. |
| Items | Mengelola item memori | Membuat, memeriksa, memperbarui, atau menghapus rekaman individual secara langsung. |
Contoh cakupan
Tanda centang berarti artikel ini menyertakan contoh untuk bahasa tersebut. Tanda hubung berarti contoh saat ini tidak disertakan; ini tidak menunjukkan apakah SDK mendukung operasi.
| Kemampuan | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API |
|---|---|---|---|---|---|
| Membuat, memperbarui, mencantumkan, dan menghapus penyimpanan memori | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| Melampirkan memori ke agen perintah | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| Memperbarui dan mencari memori | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
| Menerapkan perintah ingat atau lupa langsung | ✔️ | — | ✔️ | ✔️ | ✔️ |
| Membuat, membaca, memperbarui, mencantumkan, dan menghapus item memori | ✔️ | — | ✔️ | ✔️ | ✔️ |
Prasyarat
- Langganan Azure. Buat satu secara gratis.
- Proyek Microsoft Foundry dengan otorisasi dan izin yang sudah dikonfigurasi.
-
Penyebaran model percakapan, seperti
gpt-5.2, dalam proyek Anda. -
Penerapan model embedding, seperti
text-embedding-3-small, dalam proyek Anda. - Lingkungan lokal yang dikonfigurasi dengan paket dan variabel lingkungan yang diperlukan.
Otorisasi dan izin
Gunakan kontrol akses berbasis peran untuk penyebaran produksi. Jika peran tidak memungkinkan, lewati bagian ini dan gunakan autentikasi berbasis kunci sebagai gantinya.
Untuk mengonfigurasi akses berbasis peran:
Masuk ke portal Azure.
Pada proyek Anda:
- Dari panel kiri, pilihIdentitas> Sumber Daya.
- Gunakan tombol untuk mengaktifkan identitas terkelola yang ditetapkan sistem.
Pada sumber daya yang berisi proyek Anda:
Dari panel kiri, pilih Kontrol akses (IAM).
Pilih Tambahkan>penetapan peran.
Tetapkan Pengguna Foundry pada identitas terkelola proyek Anda.
Penting
Peran Foundry RBAC baru-baru ini diubah namanya. Pengguna Foundry, Pemilik Foundry, Pemilik Akun Foundry, dan Manajer Proyek Foundry sebelumnya bernama Pengguna Azure AI, Pemilik Azure AI, Pemilik Akun Azure AI, dan Manajer Proyek Azure AI. Anda mungkin masih melihat nama sebelumnya di beberapa tempat saat penggantian nama diluncurkan. ID peran dan izin inti tidak berubah oleh penggantian nama.
Menyiapkan lingkungan Anda
Instal paket yang diperlukan:
pip install "azure-ai-projects>=2.3.0" azure-identity
Instal paket yang diperlukan:
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
Instal paket yang diperlukan:
npm install @azure/ai-projects @azure/identity
Gunakan Node.js 22 atau yang lebih baru dengan @azure/ai-projects 2.4.0.
Instal paket yang diperlukan:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
</dependency>
Atur variabel lingkungan untuk titik akhir proyek dan nama penyebaran model Anda:
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>"
Atur variabel lingkungan untuk titik akhir proyek, penyebaran model, versi API, dan token akses Anda:
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)"
Memahami cakupan
Parameter scope mengontrol bagaimana memori dipartisi. Setiap cakupan di penyimpanan memori menyimpan kumpulan item memori yang terisolasi. Misalnya, jika Anda membuat agen dukungan pelanggan dengan memori, setiap pelanggan harus memiliki memori individual mereka sendiri.
Sebagai pengembang, Anda memilih kunci yang digunakan untuk menyimpan dan mengambil item memori. Pendekatan yang tepat tergantung pada cara Anda mengakses memori.
Melalui alat pencarian memori
Saat Anda menghubungkan alat analisis memori ke agen, atur scope ke {{$userId}} untuk mengaktifkan isolasi memori untuk setiap pengguna tanpa pengidentifikasi hard-coding. Sistem secara otomatis menyelesaikan identitas pengguna akhir pada setiap panggilan respons dari salah satu dari dua sumber:
x-memory-user-idheader permintaan: Jika ada, nilai header digunakan sebagai ID pengguna. Gunakan ini dalam skenario proksi atau backend di mana layanan Anda memanggil API atas nama pengguna akhir.Microsoft Entra authentication token: Jika header tidak diatur, sistem akan mengacu kembali ke ID penyewa (TID) dan ID objek (OID) pemanggil. Ini adalah default dalam skenario frontend di mana pengguna mengautentikasi langsung dengan Microsoft Entra.
Jika Anda tidak memerlukan isolasi per pengguna, gunakan nilai statis scope sebagai gantinya.
Melalui API memori tingkat rendah
Saat Anda memanggil API memori secara langsung, tentukan scope secara eksplisit di setiap permintaan. Anda dapat meneruskan nilai statis, seperti pengidentifikasi unik universal (UUID) atau pengidentifikasi stabil lainnya dari sistem Anda. Ekstraksi identitas otomatis tidak didukung untuk operasi ini.
Membuat penyimpanan memori
Buat penyimpanan memori khusus untuk setiap agen untuk menetapkan batas yang jelas untuk akses dan pengoptimalan memori. Saat Anda membuat penyimpanan memori, tentukan model obrolan dan model penyematan yang memproses konten memori Anda.
Gunakan opsi penyimpanan memori untuk mengontrol perilaku ekstraksi dan default retensi. Dalam pratinjau terbaru, Anda dapat mengaktifkan memori prosedural dan mengatur TTL default (detik) untuk entri memori yang baru dibuat.
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"
}
}
}'
Tips
Cuplikan Python, C#, TypeScript, dan Java lainnya menggunakan klien dan variabel yang didefinisikan dalam Membuat penyimpanan memori. Jika Anda menjalankan cuplikan kode tersebut secara independen, sertakan kode inisialisasi impor dan klien dari bagian ini.
Cuplikan C# dalam artikel ini menggunakan metode sinkron. Untuk penggunaan asinkron, lihat contoh alat pencarian memori dan penyimpanan memori.
Menyesuaikan memori
Sesuaikan informasi apa yang disimpan agen untuk menjaga memori tetap efisien, relevan, dan menghormati privasi.
user_profile_details Gunakan parameter untuk menentukan jenis data yang penting untuk fungsi agen.
Misalnya, atur user_profile_details untuk memprioritaskan "preferensi operator penerbangan dan pembatasan diet" untuk agen perjalanan. Pendekatan yang berfokus ini membantu sistem memori mengetahui detail mana yang akan diekstrak, dirangkum, dan berkomitmen pada memori jangka panjang.
Anda juga dapat menggunakan parameter ini untuk mengecualikan jenis data tertentu, menjaga memori tetap ramping dan mematuhi persyaratan privasi. Misalnya, atur user_profile_details ke "hindari data yang tidak relevan atau sensitif, seperti usia, keuangan, lokasi yang tepat, dan kredensial."
Mengonfigurasi kebijakan TTL dan retensi
TTL berlaku untuk semua memori, baik dari perintah memori langsung, ekstraksi dan konsolidasi, atau operasi CRUD tingkat item. Jika memori diperbarui dan dikonsolidasikan, layanan akan mengatur ulang waktu terakhir yang diperbarui.
TTL hanya berlaku untuk penyimpanan memori yang dibuat setelah dukungan TTL diperkenalkan. Ini tidak memengaruhi penyimpanan memori yang ada.
Nilai default_ttl_seconds0 menunjukkan tidak ada kedaluwarsa. Pilih periode retensi yang sesuai dengan persyaratan kepatuhan dan siklus hidup data pengguna Anda.
Memperbarui penyimpanan memori
Perbarui properti penyimpanan memori, seperti description atau metadata, untuk mengelola penyimpanan memori dengan lebih baik.
# 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"
}'
Mencantumkan penyimpanan memori
Ambil daftar penyimpanan memori di proyek Anda untuk mengelola dan memantau infrastruktur memori Anda.
# 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}"
Menggunakan memori melalui alat agen
Setelah membuat penyimpanan memori, Anda dapat melampirkan alat pencarian memori ke agen prompt. Alat ini memungkinkan agen membaca dari dan menulis ke penyimpanan memori Anda selama percakapan. Konfigurasikan alat dengan yang sesuai scope dan update_delay untuk mengontrol bagaimana dan kapan memori diperbarui.
Tips
Untuk membatasi memori ke pengguna akhir individual, atur scope ke "{{$userId}}" dalam definisi alat dan sampaikan x-memory-user-id: <user-id> sebagai header pada setiap panggilan respons. Sistem mengaitkan cakupan dengan identitas pengguna tersebut. Tanpa header, ruang lingkup akan beralih kembali ke identitas Microsoft Entra pemanggil (TID dan OID). Untuk informasi selengkapnya, lihat Memahami cakupan.
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
}
]
}
}'
Membuat percakapan
Sekarang Anda dapat membuat percakapan dan meminta respons agen. Pada awal setiap percakapan, memori statis disuntikkan sehingga agen memiliki konteks persisten secara langsung. Memori kontekstual diambil per giliran berdasarkan pesan terbaru untuk menginformasikan setiap respons.
Setelah setiap respons agen, layanan secara internal memanggil update_memories. Namun, penulisan aktual ke memori jangka panjang diredam oleh pengaturan update_delay. Pembaruan dijadwalkan dan hanya selesai setelah periode tidak aktif yang dikonfigurasi.
Note
Dalam skema pratinjau yang diperbarui, output dari alat penelusuran memori menggunakan koleksi memories alih-alih kolom lama results. Jika Anda memproses payload keluaran mentah, perbarui parser Anda sesuai.
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"
}
}'
Terapkan mekanisme ingat atau lupakan secara langsung
Ketika pengguna secara eksplisit meminta agen untuk mengingat atau melupakan informasi, alat pencarian memori dalam tools array segera menerapkan operasi dan mengembalikan hasilnya sebagai item perintah memori dalam output respons. Tidak diperlukan konfigurasi alat tambahan.
Note
Perintah memori langsung tidak mengambil alih TTL memori. Jika penyimpanan memori memiliki TTL yang dikonfigurasi, item memori masih dapat kedaluwarsa, bahkan jika ditambahkan oleh perintah ingat.
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)
Contoh ini menggunakan kembali yang responseClient dibuat di Membuat percakapan.
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"
}
}'
Menggunakan memori melalui API
Anda dapat berinteraksi dengan penyimpanan memori secara langsung menggunakan API penyimpanan memori. Mulailah dengan menambahkan memori dari konten percakapan ke penyimpanan memori, lalu cari memori yang relevan untuk memberikan konteks interaksi agen.
Menambahkan memori ke penyimpanan memori
Tambahkan memori dengan menyediakan konten percakapan ke penyimpanan memori. Sistem melakukan praproses dan pascaproses data, termasuk ekstraksi memori dan konsolidasi, untuk mengoptimalkan memori agen. Operasi jangka panjang ini mungkin memakan waktu sekitar satu menit.
Tentukan cara mensegmentasi memori di seluruh pengguna dengan menentukan scope parameter . Anda dapat membatasi memori ke pengguna akhir, tim, atau pengidentifikasi lain.
Anda dapat memperbarui penyimpanan memori dengan konten dari beberapa giliran percakapan, atau memperbarui setelah setiap giliran dan pembaruan rantai menggunakan ID operasi pembaruan sebelumnya.
# 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}"
Mencari memori di toko memori
Mencari memori untuk mengambil konteks yang relevan bagi interaksi agen. Tentukan nama dan cakupan penyimpanan memori untuk mempersempit pencarian.
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
}
}'
Mengambil memori statis atau kontekstual
Seringkali, Anda tidak dapat mengambil memori profil pengguna berdasarkan kesamaan semantik dengan pesan pengguna. Masukkan memori statis ke awal setiap percakapan, dan gunakan memori kontekstual untuk menghasilkan setiap respons agen.
Untuk mengambil memori statis, panggil
search_memoriesdenganscopetetapi tanpaitemsatauprevious_search_id. Ini mengembalikan memori profil pengguna yang terkait dengan cakupan.Untuk mengambil ingatan kontekstual, panggil
search_memoriesdenganitemsdisetel ke pesan terbaru. Ini dapat mengembalikan memori profil pengguna dan ringkasan obrolan yang paling relevan dengan item yang diberikan.
Untuk informasi selengkapnya tentang profil pengguna dan memori ringkasan obrolan, lihat Jenis memori.
Mengelola item di memori
Gunakan operasi tingkat item untuk langsung membuat, memeriksa, memperbarui, dan menghapus catatan memori individual. Untuk penghapusan tingkat cakupan atau tingkat penyimpanan, lihat Menghapus memori.
Buat item memori
# 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"
}'
Dapatkan item memori
# 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}"
Daftar item memori
# 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}"
Memperbarui item memori
# 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."}'
Menghapus item memori
# 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}"
Menghapus memori
Peringatan
Sebelum Anda menghapus penyimpanan memori, pertimbangkan dampaknya pada agen dependen. Agen dengan penyimpanan memori terlampir mungkin kehilangan akses ke konteks historis.
Memori diatur berdasarkan cakupan dalam penyimpanan memori. Anda dapat menghapus memori untuk cakupan tertentu untuk menghapus data khusus pengguna, atau Anda dapat menghapus seluruh penyimpanan memori untuk menghapus semua memori di semua cakupan.
Menghapus memori berdasarkan ruang lingkup
Hapus semua memori yang terkait dengan cakupan pengguna atau grup tertentu sambil mempertahankan struktur penyimpanan memori. Gunakan operasi ini untuk menangani permintaan penghapusan data pengguna atau mengatur ulang memori untuk pengguna tertentu.
# 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"
}'
Menghapus penyimpanan memori
Hapus seluruh penyimpanan memori dan semua memori terkait di semua lingkup. Operasi ini tidak dapat dibatalkan.
# 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}"
Praktik terbaik
Terapkan kontrol akses per pengguna: Hindari memberi agen akses ke memori yang dibagikan di semua pengguna.
scopeGunakan properti untuk mempartisi penyimpanan memori oleh pengguna. Saat Anda berbagiscopedi seluruh pengguna, gunakanuser_profile_detailsuntuk menginstruksikan sistem memori untuk tidak menyimpan informasi pribadi.Petakan cakupan ke pengguna akhir: Saat Anda menggunakan alat pencarian memori, atur
scopeke{{$userId}}dalam definisi alat. Sistem menentukan identitas pengguna dari header permintaanx-memory-user-id, jika ada. Jika tidak, itu jatuh kembali ke token Microsoft Entra pemanggil ({tid}_{oid}).Minimalkan dan lindungi data sensitif: Simpan hanya apa yang diperlukan untuk kasus penggunaan Anda. Jika Anda harus menyimpan data sensitif, seperti data pribadi, data kesehatan, atau input bisnis rahasia, redaksi atau hapus konten lain yang dapat digunakan untuk melacak kembali ke individu.
Mendukung privasi dan kepatuhan: Berikan transparansi kepada pengguna, termasuk opsi untuk mengakses dan menghapus data mereka. Rekam semua penghapusan dalam jejak audit yang menunjukkan bukti perusakan. Pastikan sistem mematuhi persyaratan kepatuhan lokal dan standar peraturan.
Segmentasi data dan isolasi memori: Dalam sistem multi-agen, segmentasikan memori secara logis dan operasional. Izinkan pelanggan untuk menentukan, mengisolasi, memeriksa, dan menghapus jejak memori mereka sendiri.
Memantau penggunaan memori: Lacak penggunaan token dan operasi memori untuk memahami biaya dan mengoptimalkan performa.
Tampilkan kontrol memori yang dapat dilihat pengguna: Sediakan opsi edit dan hapus untuk setiap item guna mendukung alur kerja kepercayaan pengguna dan hak data.
Atur default retensi eksplisit: Gunakan pengaturan TTL yang cocok dengan persyaratan kebijakan. Perilaku retensi dokumen di UX produk Anda.
Pemecahan masalah
| Masalah | Menyebabkan | Resolusi |
|---|---|---|
| Permintaan gagal dengan kesalahan autentikasi atau otorisasi. | Identitas Anda atau identitas terkelola proyek tidak memiliki peran yang diperlukan. | Verifikasi peran dalam Otorisasi dan izin. Untuk panggilan REST, buat token akses baru dan coba lagi. |
| Memori tidak muncul setelah percakapan. | Pembaruan memori dibatasi atau sedang diproses. | Tingkatkan waktu tunggu atau panggil API pembaruan dengan update_delay diatur ke 0 untuk segera memicu pemrosesan. |
| Pencarian memori tidak mengembalikan hasil. | Nilai scope tidak cocok dengan cakupan yang digunakan saat memori disimpan. |
Gunakan cakupan yang sama untuk pembaruan dan pencarian. Jika Anda memetakan cakupan ke pengguna, gunakan pengidentifikasi pengguna yang stabil. |
| Respons agen tidak menggunakan memori tersimpan. | Agen tidak dikonfigurasi dengan alat pencarian memori, atau nama penyimpanan memori salah. | Pastikan definisi agen menyertakan memory_search_preview alat dan mereferensikan nama penyimpanan memori yang benar. |
| Memori prosedural atau pengaturan TTL default tidak berlaku setelah pembaruan. | Dalam pratinjau terbaru, Anda hanya dapat mengatur opsi default pada waktu pembuatan penyimpanan memori. | Buat ulang penyimpanan memori dengan default yang diinginkan atau periksa apakah versi API Anda mendukung pembaruan opsi pasca-buat. |
| Permintaan ingat atau lupa eksplisit tidak mengembalikan item perintah memori dalam respons. | Alat memori tidak dikonfigurasi dengan benar, atau input tidak dikenali sebagai perintah ingat atau lupakan. | Pastikan konfigurasi alat memori dan uji dengan frasa langsung seperti “ingat” atau “lupakan”. |