הערה
הגישה לדף זה מחייבת הרשאה. באפשרותך לנסות להיכנס או לשנות מדריכי כתובות.
הגישה לדף זה מחייבת הרשאה. באפשרותך לנסות לשנות מדריכי כתובות.
Microsoft Purview provides enterprise-grade data security, compliance, and governance capabilities for AI applications. By integrating Purview APIs within the Agent Framework SDK, developers can build intelligent agents that are secure by design, while ensuring sensitive data in prompts and responses are protected and compliant with organizational policies.
Why integrate Purview with Agent Framework?
- Prevent sensitive data leaks: Inline blocking of sensitive content based on Data Loss Prevention (DLP) policies.
- Enable governance: Log AI interactions in Purview for Audit, Communication Compliance, Insider Risk Management, eDiscovery, and Data Lifecycle Management.
- Accelerate adoption: Enterprise customers require compliance for AI apps. Purview integration unblocks deployment.
Prerequisites
Before you begin, ensure you have:
- Microsoft Azure subscription with Microsoft Purview configured.
- Microsoft 365 subscription with an E5 license and pay-as-you-go billing setup.
- For testing, you can use a Microsoft 365 Developer Program tenant. For more information, see Join the Microsoft 365 Developer Program.
- Agent Framework SDK: To install the Agent Framework SDK:
- Python: Run
pip install agent-framework. - .NET: Install from NuGet.
- Python: Run
How to integrate Microsoft Purview into your agent
In your agent's workflow middleware pipeline, you can add Microsoft Purview policy middleware to intercept prompts and responses to determine if they meet the policies set up in Microsoft Purview. The Agent Framework SDK is capable of intercepting agent-to-agent or end-user chat client prompts and responses.
The following code sample demonstrates how to add the Microsoft Purview policy middleware to your agent code. If you're new to Agent Framework, see Create and run an agent with Agent Framework.
using Azure.AI.Projects;
using Azure.Core;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Purview;
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
string purviewClientAppId = Environment.GetEnvironmentVariable("PURVIEW_CLIENT_APP_ID") ?? throw new InvalidOperationException("PURVIEW_CLIENT_APP_ID is not set.");
TokenCredential browserCredential = new InteractiveBrowserCredential(
new InteractiveBrowserCredentialOptions
{
ClientId = purviewClientAppId
});
AIAgent agent = new AIProjectClient(
new Uri(endpoint),
new DefaultAzureCredential())
.AsAIAgent(
model: deploymentName,
instructions: "You are a secure assistant.")
.AsBuilder()
.WithPurview(browserCredential, new PurviewSettings("My Secure Agent"))
.Build();
AgentResponse response = await agent.RunAsync("Summarize zero trust in one sentence.").ConfigureAwait(false);
Console.WriteLine(response);
Warning
DefaultAzureCredential is convenient for development but requires careful consideration in production. In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
import asyncio
import os
from agent_framework import Agent, Message
from agent_framework.openai import OpenAIChatCompletionClient
from agent_framework.microsoft import PurviewPolicyMiddleware, PurviewSettings
from azure.identity import AzureCliCredential, InteractiveBrowserCredential
# Set default environment variables if not already set
os.environ.setdefault("AZURE_OPENAI_ENDPOINT", "<azureOpenAIEndpoint>")
os.environ.setdefault("AZURE_OPENAI_CHAT_COMPLETION_MODEL", "<azureOpenAIChatDeploymentName>")
async def main():
chat_client = OpenAIChatCompletionClient(
model=os.environ["AZURE_OPENAI_CHAT_COMPLETION_MODEL"],
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
credential=AzureCliCredential(),
)
purview_middleware = PurviewPolicyMiddleware(
credential=InteractiveBrowserCredential(
client_id="<clientId>",
),
settings=PurviewSettings(app_name="My Secure Agent")
)
agent = Agent(
client=chat_client,
instructions="You are a secure assistant.",
middleware=[purview_middleware]
)
response = await agent.run(Message(role='user', contents=["Summarize zero trust in one sentence."]))
print(response)
if __name__ == "__main__":
asyncio.run(main())
Python content evaluation and enforcement
The middleware evaluates every non-empty message content item, not only plain text. Text and reasoning text are
evaluated as text. Base64 data URI payloads are evaluated as binary content. Non-base64 data, URI content, function
calls, function results, and other structured content are serialized as text so they aren't skipped. Only empty
content and usage content are omitted.
Policy evaluation fails closed when the middleware can't resolve a user ID, tenant, or application location. Derive
identity from a validated server-side token rather than caller-controlled message fields. Set ignore_exceptions only
when you deliberately prefer availability over enforcement; this setting bypasses enforcement for every error.
Choose Python middleware placement
PurviewPolicyMiddleware and PurviewChatPolicyMiddleware enforce the same policies at different pipeline boundaries:
| Behavior | Agent middleware | Chat middleware |
|---|---|---|
| Evaluation scope | Evaluates the caller's input and final response once per agent run. | Evaluates the prepared request and response on every model call. |
| Tool and context data | Doesn't evaluate context-provider output or a model tool call before the tool runs. | Evaluates context-provider output, replayed history, and model tool calls before execution. Tool results are evaluated on the next model call. |
| Blocked response history | The original response might already be stored before the middleware replaces it for the caller. | The replacement is available before Agent Framework stores the turn. Provider-managed storage might still retain the original response. |
Use PurviewChatPolicyMiddleware for data loss prevention when policy must cover the complete model request. Use
PurviewPolicyMiddleware when a single check at the agent run boundary is sufficient. In either middleware list,
place the Purview middleware last so that later middleware can't replace content after Purview evaluates it.
Both middleware types buffer a streamed response in full and evaluate it before releasing any update. Streaming therefore doesn't deliver content incrementally while Purview middleware is attached.
Next steps
Now that you added the above code to your agent, perform the following steps to test the integration of Microsoft Purview into your code:
- Entra registration: Register your agent and add the required Microsoft Graph permissions (ProtectionScopes.Compute.All, ContentActivity.Write, Content.Process.All) to the Service Principal. For more information, see Register an application in Microsoft Entra ID and dataSecurityAndGovernance resource type. You'll need the Microsoft Entra app ID in the next step.
- Purview policies: Configure Purview policies using the Microsoft Entra app ID to enable agent communications data to flow into Purview. For more information, see Configure Microsoft Purview.
Resources
- Nuget: Microsoft.Agents.AI.Purview
- Github: Microsoft.Agents.AI.Purview
- Sample: AgentWithPurview
Note
Go support for this feature is coming soon. See the Agent Framework Go repository for the latest status.