為你的客服加入背景資訊,讓它能記住使用者偏好、過去的互動或外部知識。
預設情況下,客服將根據底層服務的需求,將聊天歷史儲存在 InMemoryChatHistoryProvider 或底層 AI 服務中。
以下代理使用 OpenAI 聊天完成功能,該功能不支援也不要求服務內聊天歷史儲存,因此會自動建立並使用 InMemoryChatHistoryProvider。
using System;
using Azure.AI.Projects;
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 AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
.AsAIAgent(
model: deploymentName,
instructions: "You are a friendly assistant. Keep your answers brief.",
name: "MemoryAgent");
Warning
DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。
若要使用自訂 ChatHistoryProvider,您可以將一個傳遞給代理程式選項:
using System;
using Azure.AI.Projects;
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 AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
.AsAIAgent(model: deploymentName, options: 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));
Tip
請見 此 處的完整可執行範例應用。
完整範例定義了一個情境提供者,將其加入代理,並使用一個會話來維持個人化狀態:
import asyncio
from typing import Any
from agent_framework import Agent, AgentSession, ContextProvider, SessionContext
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
class UserMemoryProvider(ContextProvider):
def __init__(self) -> None:
super().__init__("user_memory")
async def before_run(
self,
*,
agent: Any,
session: AgentSession | None,
context: SessionContext,
state: dict[str, Any],
) -> None:
user_name = state.get("user_name")
instructions = (
f"The user's name is {user_name}. Address them by name." if user_name else "Ask for the user's name."
)
context.extend_instructions(self.source_id, instructions)
async def after_run(
self,
*,
agent: Any,
session: AgentSession | None,
context: SessionContext,
state: dict[str, Any],
) -> None:
for message in context.input_messages:
text = message.text
if not isinstance(text, str):
continue
_, marker, name = text.lower().partition("my name is")
if marker and name.strip():
state["user_name"] = name.split()[0].capitalize()
async def main() -> None:
agent = Agent(
client=FoundryChatClient(
project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
model="gpt-6-luna",
credential=AzureCliCredential(),
),
instructions="You are a friendly assistant.",
context_providers=[UserMemoryProvider()],
)
session = agent.create_session()
print(await agent.run("Hello! What's the square root of 9?", session=session))
print(await agent.run("My name is Alice", session=session))
print(await agent.run("What is 2 + 2?", session=session))
if __name__ == "__main__":
asyncio.run(main())
Tip
完整範例可執行檔案請參閱 完整範例 。
備註
在 Python 中,持久化/記憶體的處理由 ContextProvider 和 HistoryProvider 的實作來完成。
InMemoryHistoryProvider 是內建的本地記憶體歷史提供者。
RawAgent 在特定情況下(例如在會話中未設置情境提供程式和服務端存儲器指示器時),可能會自動新增 InMemoryHistoryProvider(),但並非所有情境皆有此保證。
如果你總是想要本地持久化,就明確地加一個 InMemoryHistoryProvider 。 此外,請確定只有一個歷程記錄提供者擁有 load_messages=True,這樣您就不會將多個存放區重新執行到同一個叫用中。
依照 Microsoft Foundry 管理語意記憶建立專案客戶端與記憶體儲存。 接著結合本地逐字紀錄、受管理記憶體和審計儲存庫:
from agent_framework import InMemoryHistoryProvider
from agent_framework.foundry import FoundryMemoryProvider
history = InMemoryHistoryProvider(load_messages=True)
memory = FoundryMemoryProvider(
project_client=project_client,
memory_store_name="user-memory",
scope="user-123",
)
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=[history, memory, audit_store], # audit store last
)
預設情況下,代理會根據提供者與會話使用本地記憶體歷史或服務管理歷史。
以下 Foundry 代理程式採用專案支援的模型部署。 當你想要超出對話紀錄的應用程式專用記憶或個人化狀態時,可以新增情境提供者。
a := foundryprovider.NewAgent(
endpoint,
token,
foundryprovider.ModelDeployment(model),
foundryprovider.AgentConfig{
Instructions: "You are a friendly assistant. Keep your answers brief.",
Config: agent.Config{
Name: "MemoryAgent",
},
},
)
定義一個情境提供者,能在會話狀態下儲存使用者資訊並注入個人化指令:
import (
"context"
"fmt"
"strings"
"github.com/microsoft/agent-framework-go/agent"
"github.com/microsoft/agent-framework-go/message"
)
const userMemorySourceID = "user_memory"
type providerState struct {
UserName string `json:"user_name,omitempty"`
}
func newUserMemoryProvider() agent.ContextProvider {
return agent.NewContextProvider(agent.ContextProviderConfig{
SourceID: userMemorySourceID,
Provide: provideUserMemory,
Store: storeUserMemory,
})
}
func provideUserMemory(ctx context.Context, invoking agent.InvokingContext) ([]*message.Message, []agent.Option, error) {
session, _ := agent.GetOption(invoking.Options, agent.WithSession)
var state providerState
_, _ = session.Get(userMemorySourceID, &state)
instructions := "You don't know the user's name yet. Ask for it politely."
if state.UserName != "" {
instructions = fmt.Sprintf("The user's name is %s. Always address them by name.", state.UserName)
}
return nil, []agent.Option{agent.WithInstructions(instructions)}, nil
}
func storeUserMemory(ctx context.Context, invoked agent.InvokedContext) error {
session, _ := agent.GetOption(invoked.Options, agent.WithSession)
var state providerState
_, _ = session.Get(userMemorySourceID, &state)
for _, msg := range invoked.RequestMessages {
text := strings.TrimSpace(msg.Contents.Text())
lower := strings.ToLower(text)
if idx := strings.Index(lower, "my name is"); idx >= 0 {
parts := strings.Fields(text[idx+len("my name is"):])
if len(parts) == 0 {
continue
}
state.UserName = strings.Trim(parts[0], ".,!?")
session.Set(userMemorySourceID, state)
break
}
}
return nil
}
建立一個包含內容提供者的代理程式:
a := foundryprovider.NewAgent(
endpoint,
token,
foundryprovider.ModelDeployment(model),
foundryprovider.AgentConfig{
Instructions: "You are a friendly assistant.",
Config: agent.Config{
Name: "MemoryAgent",
ContextProviders: []agent.ContextProvider{newUserMemoryProvider()},
},
},
)
執行它——客服人員現在可以存取上下文:
ctx := context.Background()
session, err := a.CreateSession(ctx)
if err != nil {
panic(err)
}
// The provider doesn't know the user yet.
resp, err := a.RunText(ctx, "Hello, what is the square root of 9?", agent.WithSession(session)).Collect()
fmt.Println(resp, err)
// Teach the provider the user's name.
resp, err = a.RunText(ctx, "My name is Alice", agent.WithSession(session)).Collect()
fmt.Println(resp, err)
// Subsequent calls are personalized using session state.
resp, err = a.RunText(ctx, "What is 2 + 2?", agent.WithSession(session)).Collect()
fmt.Println(resp, err)
Tip
完整範例可執行檔案請參閱 完整範例 。
下一步
深入探討: