為你的客服加入背景資訊,讓它能記住使用者偏好、過去的互動或外部知識。
預設情況下,客服將根據底層服務的需求,將聊天歷史儲存在 InMemoryChatHistoryProvider 或底層 AI 服務中。
以下代理使用 OpenAI 聊天完成功能,該功能不支援也不要求服務內聊天歷史儲存,因此會自動建立並使用 InMemoryChatHistoryProvider。
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
.GetChatClient(deploymentName)
.AsAIAgent(instructions: "You are a friendly assistant. Keep your answers brief.", name: "MemoryAgent");
要使用自訂 ChatHistoryProvider,你可以把一個傳給代理選項:
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
AIAgent agent = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
.GetChatClient(deploymentName)
.AsAIAgent(new ChatClientAgentOptions()
{
ChatOptions = new() { Instructions = "You are a helpful assistant." },
ChatHistoryProvider = new CustomChatHistoryProvider()
});
使用階段來跨流程分享上下文:
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync("Hello! What's the square root of 9?", session));
Console.WriteLine(await agent.RunAsync("My name is Alice", session));
Console.WriteLine(await agent.RunAsync("What is my name?", session));
小提示
完整範例可執行檔案請參閱 完整範例 。
定義一個情境提供者,能在會話狀態下儲存使用者資訊並注入個人化指令:
class UserMemoryProvider(BaseContextProvider):
"""A context provider that remembers user info in session state."""
DEFAULT_SOURCE_ID = "user_memory"
async def before_run(
self,
*,
agent: Any,
session: AgentSession | None,
context: SessionContext,
state: dict[str, Any],
) -> None:
"""Inject personalization instructions based on stored user info."""
user_name = state.get("user_name")
if user_name:
context.extend_instructions(
self.source_id,
f"The user's name is {user_name}. Always address them by name.",
)
else:
context.extend_instructions(
self.source_id,
"You don't know the user's name yet. Ask for it politely.",
)
async def after_run(
self,
*,
agent: Any,
session: AgentSession | None,
context: SessionContext,
state: dict[str, Any],
) -> None:
"""Extract and store user info in session state after each call."""
for msg in context.input_messages:
text = msg.text if hasattr(msg, "text") else ""
if isinstance(text, str) and "my name is" in text.lower():
state["user_name"] = text.lower().split("my name is")[-1].strip().split()[0].capitalize()
建立一個包含上下文提供者的代理:
credential = AzureCliCredential()
client = AzureOpenAIResponsesClient(
project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"],
credential=credential,
)
agent = client.as_agent(
name="MemoryAgent",
instructions="You are a friendly assistant.",
context_providers=[UserMemoryProvider()],
)
執行它——客服人員現在可以存取上下文:
session = agent.create_session()
# The provider doesn't know the user yet — it will ask for a name
result = await agent.run("Hello! What's the square root of 9?", session=session)
print(f"Agent: {result}\n")
# Now provide the name — the provider stores it in session state
result = await agent.run("My name is Alice", session=session)
print(f"Agent: {result}\n")
# Subsequent calls are personalized — name persists via session state
result = await agent.run("What is 2 + 2?", session=session)
print(f"Agent: {result}\n")
# Inspect session state to see what the provider stored
provider_state = session.state.get("user_memory", {})
print(f"[Session State] Stored user name: {provider_state.get('user_name')}")
小提示
完整範例可執行檔案請參閱 完整範例 。
備註
在 Python 中,持久性/記憶體由上下文與歷史提供者處理。
BaseHistoryProvider 也是 BaseContextProvider,而 InMemoryHistoryProvider 是內建的本地暨內存實作。
RawAgent 在特定情況下(例如在會話中未設置情境提供程式和服務端存儲器指示器時),可能會自動新增 InMemoryHistoryProvider(),但並非所有情境皆有此保證。
如果你總是想要本地持久化,就明確地加一個 InMemoryHistoryProvider 。 應確保只有一個歷史紀錄提供者有 load_messages=True,以避免在相同的調用中重複執行多組數據。
你也可以在清單 context_providers 末尾加上另一個歷史提供者,並加入 store_context_messages=True審計儲存庫:
from agent_framework import InMemoryHistoryProvider
from agent_framework.mem0 import Mem0ContextProvider
memory_store = InMemoryHistoryProvider(load_messages=True) # add a history provider for persistence across sessions
agent_memory = Mem0ContextProvider("user-memory", api_key=..., agent_id="my-agent") # add Mem0 provider for agent memory
audit_store = InMemoryHistoryProvider(
"audit",
load_messages=False,
store_context_messages=True, # include context added by other providers
)
agent = client.as_agent(
name="MemoryAgent",
instructions="You are a friendly assistant.",
context_providers=[memory_store, agent_memory, audit_store], # audit store last
)
後續步驟
深入探討: