重要提示
你需要是边境预览计划的一部分,才能提前访问 Microsoft Agent 365。 边界将你直接与Microsoft最新的 AI 创新联系起来。 边境预览版受客户协议现有预览条款的约束。 由于这些功能仍在开发中,其可用性和功能可能会随时间而变化。
若要参与代理 365 生态系统,必须将代理 365 可观测性功能添加到代理中。 Agent 365 Observability 基于 OpenTelemetry (OTel)构建, 提供统一的框架,用于在所有代理平台上一致且安全地捕获遥测。 通过实现此必需组件,可以让 IT 管理员监视代理在 Microsoft 管理中心(MAC)中的活动,并允许安全团队使用 Defender 和 Purview 进行合规性和威胁检测。
关键优势
-
端到端可见性:为每个代理调用(包括会话、工具调用和异常)捕获全面的遥测数据,从而提供跨平台的完整可跟踪性。
-
安全性与符合性启用:将统一审核日志馈送到 Defender 和 Purview 中,为代理启用高级安全方案和合规性报告。
-
跨平台灵活性:基于 OTel 标准构建,并支持各种运行时和平台,例如 Copilot Studio、Foundry 和未来的代理框架。
-
管理员的作效率:在 MAC 中提供集中的可观测性,减少故障排除时间,并通过管理代理的 IT 团队的基于角色的访问控制改进治理。
安装
使用这些命令为代理 365 支持的语言安装可观测性模块。
pip install microsoft-agents-a365-observability-core
pip install microsoft-agents-a365-runtime
npm install @microsoft/agents-a365-observability
npm install @microsoft/agents-a365-runtime
dotnet add package Microsoft.Agents.A365.Observability
dotnet add package Microsoft.Agents.A365.Observability.Runtime
配置
可观测性所需的环境变量包括:
| 环境变量 |
Description |
ENABLE_OBSERVABILITY=true |
用于启用/禁用跟踪的标志。 默认情况下:false |
ENABLE_A365_OBSERVABILITY_EXPORTER=true |
True 将日志导出到我们的服务。 否则回退到控制台导出程序 |
from microsoft_agents_a365.observability.core import config
def token_resolver(agent_id: str, tenant_id: str) -> str | None:
# Implement secure token retrieval here
return "Bearer <token>"
config.configure(
service_name="my-agent-service",
service_namespace="my.namespace",
token_resolver=token_resolver,
)
排除令牌解析程序以登录到控制台。
可观测性所需的环境变量包括:
| 环境变量 |
Description |
ENABLE_OBSERVABILITY=true |
用于启用/禁用跟踪的标志。 默认情况下:false |
ENABLE_A365_OBSERVABILITY_EXPORTER=true |
True 将日志导出到我们的服务。 否则回退到控制台导出程序 |
import { ObservabilityManager } from '@microsoft/agents-a365-observability';
const tokenResolver = (agentId, tenantId) => {
// Your token resolution logic here
return "your-token";
};
// Advanced configuration with builder pattern
const builder = ObservabilityManager.configure(builder =>
builder
.withService('my-agent-service', '1.0.0')
.withTokenResolver((agentId, tenantId) => {
return tokenResolver(agentId, tenantId);
})
);
builder.start();
在 appsettings.json 中将 EnableAgent365Exporter 设置为 true。
在 Program.cs中,添加到 Agent365ExporterOptions 服务集合。 此更改配置跟踪导出程序用于检索令牌的委托。
使用 AddA365Tracing(). 添加可观测性相关依赖项。
using Microsoft.Agents.A365.Observability.Runtime;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(sp =>
{
return new Agent365ExporterOptions
{
ClusterCategory = "prod",
TokenResolver = async (agentId, tenantId) =>
{
// It's recommended to implement caching in your token provider for performance.
var token = await tokenProvider.GetObservabilityTokenAsync(agentId, tenantId);
return token;
}
};
});
builder.AddA365Tracing();
行李属性
用于 BaggageBuilder 设置在请求中流经所有范围的上下文信息。
SDK 实现一个 SpanProcessor 副本,将所有无空行李条目复制到新启动的跨度,而无需覆盖现有属性。
from microsoft_agents_a365.observability.core.middleware.baggage_builder import BaggageBuilder
with (
BaggageBuilder()
.tenant_id("tenant-123")
.agent_id("agent-456")
.correlation_id("corr-789")
.build()
):
# Any spans started in this context will receive these as attributes
pass
import { BaggageBuilder } from '@microsoft/agents-a365-observability';
// Create and apply baggage context
using baggageScope = new BaggageBuilder()
// Core identifiers
.tenantId('tenant-123')
.agentId('agent-456')
.correlationId('correlation-789')
.build();
// Execute operations within the baggage context
baggageScope.run(() => {
// All spans created within this context will inherit the baggage values
// Invoke another agent
using agentScope = InvokeAgentScope.start(invokeDetails, agentDetails, tenantDetails);
// ... agent logic
// Execute tools
using toolScope = ExecuteToolScope.start(toolDetails, agentDetails, tenantDetails);
// ... tool logic
});
using var baggageScope = new BaggageBuilder()
.TenantId('tenant-123')
.AgentId('agent-456')
.CorrelationId('correlation-789')
.Build();
// Any spans started in this context will receive them as attributes.
令牌解析程序
使用代理 365 导出程序时,必须提供返回身份验证令牌的令牌解析程序函数。
将 Agent 365 可观测性 SDK 与代理托管框架配合使用时,可以使用代理活动中的令牌生成令牌TurnContext
from microsoft_agents.activity import load_configuration_from_env
from microsoft_agents.authentication.msal import MsalConnectionManager
from microsoft_agents.hosting.aiohttp import CloudAdapter
from microsoft_agents.hosting.core import (
AgentApplication,
Authorization,
MemoryStorage,
TurnContext,
TurnState,
)
from microsoft_agents_a365.runtime.environment_utils import (
get_observability_authentication_scope,
)
agents_sdk_config = load_configuration_from_env(environ)
STORAGE = MemoryStorage()
CONNECTION_MANAGER = MsalConnectionManager(**agents_sdk_config)
ADAPTER = CloudAdapter(connection_manager=CONNECTION_MANAGER)
ADAPTER.use(TranscriptLoggerMiddleware(ConsoleTranscriptLogger()))
AUTHORIZATION = Authorization(STORAGE, CONNECTION_MANAGER, **agents_sdk_config)
AGENT_APP = AgentApplication[TurnState](
storage=STORAGE, adapter=ADAPTER, authorization=AUTHORIZATION, **agents_sdk_config
)
@AGENT_APP.activity("message", auth_handlers=["AGENTIC"])
async def on_message(context: TurnContext, _state: TurnState):
aau_auth_token = await AGENT_APP.auth.exchange_token(
context,
scopes=get_observability_authentication_scope(),
auth_handler_id="AGENTIC",
)
# cache this auth token and return via token resolver
import {
TurnState,
AgentApplication,
MemoryStorage,
TurnContext,
} from '@microsoft/agents-hosting';
import { Activity, ActivityTypes } from '@microsoft/agents-activity';
import { getObservabilityAuthenticationScope } from '@microsoft/agents-a365-runtime';
interface ConversationState {
count: number;
}
type ApplicationTurnState = TurnState<ConversationState>;
const downloader = new AttachmentDownloader();
const storage = new MemoryStorage();
export const agentApplication = new AgentApplication<ApplicationTurnState>({
authorization: {
agentic: { } // We have the type and scopes set in the .env file
},
storage,
});
agentApplication.onActivity(
ActivityTypes.Message,
async (context: TurnContext, state: ApplicationTurnState) => {
const aauAuthToken = await agentApplication.authorization.exchangeToken(context,'agentic', {
scopes: getObservabilityAuthenticationScope()
} )
// cache this auth token and return via token resolver
};
将代理令牌解析程序添加到服务集合。
using Microsoft.Agents.A365.Observability;
builder.Services.AddAgenticTracingExporter();
在代理应用程序中,注册令牌。
using Microsoft.Agents.Builder;
using Microsoft.Agents.Core.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Agents.A365.Observability.Caching;
using System;
using System.Threading.Tasks;
public class MyAgent : AgentApplication
{
private readonly IExporterTokenCache<AgenticTokenStruct> _agentTokenCache;
private readonly ILogger<MyAgent> _logger;
public MyAgent(AgentApplicationOptions options, IExporterTokenCache<AgenticTokenStruct> agentTokenCache, ILogger<MyAgent> logger)
: base(options)
{
_agentTokenCache = agentTokenCache ?? throw new ArgumentNullException(nameof(agentTokenCache));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
protected async Task MessageActivityAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
using var baggageScope = new BaggageBuilder()
.TenantId(turnContext.Activity.Recipient.TenantId)
.AgentId(turnContext.Activity.Recipient.AgenticAppId)
.Build();
try
{
_agentTokenCache.RegisterObservability(
turnContext.Activity.Recipient.AgenticAppId,
turnContext.Activity.Recipient.TenantId,
new AgenticTokenStruct
{
UserAuthorization = UserAuthorization,
TurnContext = turnContext
},
EnvironmentUtils.GetObservabilityAuthenticationScope()
);
}
catch (Exception ex)
{
_logger.LogWarning($"Error registering for observability: {ex.Message}");
}
}
}
自动检测
自动检测会自动侦听代理框架(SDK)现有的跟踪遥测信号,并将其转发到代理 365 可观测性服务。 这样,开发人员就无需手动编写监视代码、简化设置并确保一致的性能跟踪。
跨多个 SDK 和平台支持自动检测:
备注
对自动检测的支持因平台和 SDK 实现而异。
语义内核
自动检测需要使用行李生成器。 使用 BaggageBuilder. 设置代理 ID 和租户 ID。
安装包
pip install microsoft-agents-a365-observability-extensions-semantic-kernel
配置可观测性
from microsoft_agents_a365.observability.core.config import configure
from microsoft_agents_a365.observability.extensions.semantic_kernel import SemanticKernelInstrumentor
# Configure observability
configure(
service_name="my-semantic-kernel-agent",
service_namespace="ai.agents"
)
# Enable auto-instrumentation
instrumentor = SemanticKernelInstrumentor()
instrumentor.instrument()
# Your Semantic Kernel code is now automatically traced
将依赖项添加到服务集合。
using Microsoft.Agents.A365.Observability.Extensions.SemanticKernel;
builder.Services.AddTracing(config => config.WithSemanticKernel());
设置 AgentId 和使用 TenantIdBaggageBuilder。 确保创建 ChatCompletionAgent 与传递给 BaggageBuilder的代理 ID 匹配时使用的 ID。
using Microsoft.Agents.A365.Observability.Extensions.SemanticKernel;
using Microsoft.Agents.A365.Observability.Runtime.Common;
public class MyAgent
{
public async Task<AgentResponse> ProcessUserRequest(string userInput)
{
using var baggageScope = new BaggageBuilder()
.AgentId(<your-agent-id>) // NOTE: This will be the agent ID with which the TokenResolver delegate is invoked.
.TenantId(<your-tenant-id>) // NOTE: This will be the tenant ID with which the TokenResolver delegate is invoked.
.Build();
var chatCompletionAgent = new ChatCompletionAgent
{
// NOTE: This will be the agent ID with which the TokenResolver delegate is invoked. Should match above.
Id = <your-agent-id>,
...
};
}
}
OpenAI
自动检测需要使用行李生成器。 使用 BaggageBuilder. 设置代理 ID 和租户 ID。
安装此包。
pip install microsoft-agents-a365-observability-extensions-openai
配置可观测性
from microsoft_agents_a365.observability.core.config import configure
from microsoft_agents_a365.observability.extensions.openai_agents import OpenAIAgentsTraceInstrumentor
# Configure observability
configure(
service_name="my-openai-agent",
service_namespace="ai.agents"
)
# Enable auto-instrumentation
instrumentor = OpenAIAgentsTraceInstrumentor()
instrumentor.instrument()
# Your OpenAI Agents code is now automatically traced
安装包
npm install @microsoft/agents-a365-observability-extensions-openai
配置可观测性
import { ObservabilityManager } from '@microsoft/agents-a365-observability';
import { OpenAIAgentsTraceInstrumentor } from '@microsoft/agents-a365-observability-extensions-openai';
// Configure observability first
const sdk = ObservabilityManager.configure((builder) =>
builder
.withService('My Agent Service', '1.0.0')
.withConsoleExporter(true)
);
// Create and enable the instrumentor
const instrumentor = new OpenAIAgentsTraceInstrumentor({
enabled: true,
tracerName: 'openai-agents-tracer',
tracerVersion: '1.0.0'
});
sdk.start();
instrumentor.enable();
将依赖项添加到服务集合。
using Microsoft.Agents.A365.Observability.Extensions.OpenAI;
builder.Services.AddTracing(config => config.WithOpenAI());
设置 AgentId 和使用 TenantIdBaggageBuilder。 对于工具调用,请使用 Trace() 实例启动 ChatToolCall 跟踪。
using Microsoft.Agents.A365.Observability.Extensions.OpenAI;
using Microsoft.Agents.A365.Observability.Runtime.Common;
public class MyAgent
{
public async Task<AgentResponse> ProcessUserRequest(string userInput)
{
using var baggageScope = new BaggageBuilder()
.AgentId(<your-agent-id>) // NOTE: This will be the agent ID with which the TokenResolver delegate is invoked.
.TenantId(<your-tenant-id>) // NOTE: This will be the tenant ID with which the TokenResolver delegate is invoked.
.Build();
// NOTE: This will be the agent and tenant ID with which the TokenResolver delegate will be invoked.
using var scope = chatToolCall.Trace(agentId: <your-agent-id>, <your-tenant-id>);
}
}
代理框架
自动检测需要使用行李生成器。 使用 BaggageBuilder 设置代理 ID 和租户 ID。
安装包
pip install microsoft-agents-a365-observability-extensions-agent-framework
配置可观测性
from microsoft_agents_a365.observability.core.config import configure
from microsoft_agents_a365.observability.extensions.agentframework.trace_instrumentor import (
AgentFrameworkInstrumentor,
)
# Configure observability
configure(
service_name="AgentFrameworkTracingWithAzureOpenAI",
service_namespace="AgentFrameworkTesting",
)
# Enable auto-instrumentation
AgentFrameworkInstrumentor().instrument()
将依赖项添加到服务集合。
using Microsoft.Agents.A365.Observability.Extensions.AgentFramework;
builder.Services.AddTracing(config => config.WithAgentFramework());
设置 AgentId 和使用 TenantIdBaggageBuilder。
using Microsoft.Agents.A365.Observability.Runtime.Common;
public class MyAgent : AgentApplication
{
protected async Task MessageActivityAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
using var baggageScope = new BaggageBuilder()
.AgentId(<your-agent-id>) // NOTE: This will be the agent ID with which the TokenResolver delegate is invoked.
.TenantId(<your-tenant-id>) // NOTE: This will be the tenant ID with which the TokenResolver delegate is invoked.
.Build();
}
}
LangChain 框架
自动检测需要使用行李生成器。 使用 BaggageBuilder. 设置代理 ID 和租户 ID。
安装此包。
pip install microsoft-agents-a365-observability-extensions-langchain
配置可观测性
from microsoft_agents_a365.observability.core.config import configure
from microsoft_agents_a365.observability.extensions.langchain import CustomLangChainInstrumentor
# Configure observability
configure(
service_name="my-langchain-agent",
service_namespace="ai.agents"
)
# Enable auto-instrumentation
CustomLangChainInstrumentor()
# Your LangChain code is now automatically traced
手动检测
代理 365 可观测性 SDK 可用于了解代理的内部工作。
SDK 提供三个可以启动的范围: InvokeAgentScope、 ExecuteToolScope和 InferenceScope。
代理调用
应在代理进程开始时使用此范围。 使用调用代理范围,可以捕获正在调用的当前代理、代理用户数据等属性。
from microsoft_agents_a365.observability.core.invoke_agent_scope import InvokeAgentScope
from microsoft_agents_a365.observability.core.invoke_agent_details import InvokeAgentDetails
from microsoft_agents_a365.observability.core.tenant_details import TenantDetails
from microsoft_agents_a365.observability.core.request import Request
invoke_details = InvokeAgentDetails(
details=agent_details, # AgentDetails instance
endpoint=my_endpoint, # Optional endpoint (with hostname/port)
session_id="session-42"
)
tenant_details = TenantDetails(tenant_id="tenant-123")
req = Request(content="User asks a question")
with InvokeAgentScope.start(invoke_details, tenant_details, req):
# Perform agent invocation logic
response = call_agent(...)
import {
InvokeAgentScope,
ExecutionType,
CallerDetails,
EnhancedAgentDetails
} from '@microsoft/agents-a365-observability';
// Basic agent invocation details
const invokeDetails = {
agentId: 'email-agent-123',
agentName: 'Email Assistant',
...
}
};
const tenantDetails = {
tenantId: 'tenant-789'
};
// Optional: Caller details (human user)
const callerDetails: CallerDetails = {};
// Optional: Caller agent details (for agent-to-agent calls)
const callerAgentDetails: EnhancedAgentDetails = {};
// Enhanced invocation with caller context
using scope = InvokeAgentScope.start(
invokeDetails,
tenantDetails,
callerAgentDetails,
callerDetails
);
try {
// Record input messages
scope.recordInputMessages(['Please help me organize my emails', 'Focus on urgent items']);
// Your agent invocation logic here
const response = await invokeAgent(invokeDetails.request.content);
// Record output messages
scope.recordOutputMessages(['I found 15 urgent emails', 'Here is your organized inbox']);
} catch (error) {
scope.recordError(error as Error);
throw error;
}
// Scope automatically disposed at end of using block
using System;
using System.Threading.Tasks;
using Microsoft.Agents.A365.Observability.Runtime.Tracing.Contracts;
using Microsoft.Agents.A365.Observability.Runtime.Tracing.Scopes;
public class MyAgent
{
public async Task<AgentResponse> ProcessUserRequest(string userInput)
{
var agentDetails = new AgentDetails(
agentId: Guid.NewGuid().ToString(),
agentName: "MyAgent",
agentDescription: "Handles user requests.",
tenantId: "tenant-789"
);
var tenantDetails = new TenantDetails(Guid.Parse("11111111-2222-3333-4444-555555555555"));
var request = new Request(
content: userInput,
executionType: ExecutionType.HumanToAgent,
sessionId: "session-abc",
channelMetadata: new ChannelMetadata("webchat", "https://webchat.contoso.com")
);
var callerDetails = new CallerDetails(
callerId: "user-123",
callerName: "Jane Doe",
callerUpn: "jane.doe@contoso.com",
callerUserId: "user-uuid-456",
tenantId: "tenant-789"
);
var endpoint = new Uri("https://myagent.contoso.com");
var invokeAgentDetails = new InvokeAgentDetails(endpoint, agentDetails, sessionId: "session-abc");
var conversationId = "conv-xyz";
// Start the scope
using var scope = InvokeAgentScope.Start(
invokeAgentDetails: invokeAgentDetails,
tenantDetails: tenantDetails,
request: request,
callerAgentDetails: null,
callerDetails: callerDetails,
conversationId: conversationId
);
// Record input messages
scope.RecordInputMessages(new[] { userInput });
// ... your agent logic here ...
// Simulate agent processing and output
var output = $"Processed: {userInput}";
scope.RecordOutputMessages(new[] { output });
// Optionally record a single response
scope.RecordResponse(output);
return new AgentResponse { Content = output };
}
}
public class AgentResponse
{
public string Content { get; set; }
}
以下示例演示如何使用可观测性跟踪检测代理的工具执行,以捕获遥测数据以进行监视和审核。
from microsoft_agents_a365.observability.core.execute_tool_scope import ExecuteToolScope
from microsoft_agents_a365.observability.core.tool_call_details import ToolCallDetails
tool_details = ToolCallDetails(
tool_name="summarize",
tool_type="function",
tool_call_id="tc-001",
arguments="{'text': '...'}",
description="Summarize provided text",
endpoint=None # or endpoint object with hostname/port
)
with ExecuteToolScope.start(tool_details, agent_details, tenant_details):
result = run_tool(tool_details)
import { ExecuteToolScope } from '@microsoft/agents-a365-observability';
const toolDetails = {
toolName: 'email-search',
arguments: JSON.stringify({ query: 'from:boss@company.com', limit: 10 }),
toolCallId: 'tool-call-456',
description: 'Search emails by criteria',
toolType: 'function',
endpoint: {
host: 'tools.contoso.com',
port: 8080, // Will be recorded since not 443
protocol: 'https'
}
};
using scope = ExecuteToolScope.start(toolDetails, agentDetails, tenantDetails);
try {
// Execute the tool
const result = await searchEmails(toolDetails.arguments);
// Record the tool execution result
scope.recordResponse(JSON.stringify(result));
return result;
} catch (error) {
scope.recordError(error as Error);
throw error;
}
using System;
using System.Threading.Tasks;
using Microsoft.Agents.A365.Observability.Runtime.Tracing.Contracts;
using Microsoft.Agents.A365.Observability.Runtime.Tracing.Scopes;
public class MyToolAgent
{
public async Task<ToolResult> ExecuteTool(string toolName, object parameters)
{
var agentDetails = new AgentDetails(
agentId: Guid.NewGuid().ToString(),
agentName: "ToolAgent",
agentDescription: "Executes tools for users.",
agentAUID: "tool-auid-123",
agentUPN: "toolagent@contoso.com",
agentBlueprintId: "tool-blueprint-456",
agentType: AgentType.EntraEmbodied,
tenantId: "tenant-789"
);
var tenantDetails = new TenantDetails(Guid.Parse("11111111-2222-3333-4444-555555555555"));
var endpoint = new Uri("https://toolagent.contoso.com:8443");
var toolCallDetails = new ToolCallDetails(
toolName: toolName,
arguments: System.Text.Json.JsonSerializer.Serialize(parameters),
toolCallId: Guid.NewGuid().ToString(),
description: "Runs a tool operation.",
toolType: "custom-type",
endpoint: endpoint
);
// Start the scope
using var scope = ExecuteToolScope.Start(
toolCallDetails: toolCallDetails,
agentDetails: agentDetails,
tenantDetails: tenantDetails
);
// ... your tool logic here ...
// Record response
var toolOutput = $"Tool '{toolName}' processed with parameters: {System.Text.Json.JsonSerializer.Serialize(parameters)}";
scope.RecordResponse(toolOutput);
return new ToolResult { Output = toolOutput };
}
}
public class ToolResult
{
public string Output { get; set; }
}
推理
以下示例演示如何使用可观测性跟踪检测 AI 模型推理调用,以捕获令牌使用情况、模型详细信息和响应元数据。
from microsoft_agents_a365.observability.core.inference_scope import InferenceScope
from microsoft_agents_a365.observability.core.inference_call_details import InferenceCallDetails
from microsoft_agents_a365.observability.core.request import Request
inference_details = InferenceCallDetails(
operationName=SomeEnumOrValue("chat"),
model="gpt-4o-mini",
providerName="azure-openai",
inputTokens=123,
outputTokens=456,
finishReasons=["stop"],
responseId="resp-987"
)
req = Request(content="Explain quantum computing simply.")
with InferenceScope.start(inference_details, agent_details, tenant_details, req):
completion = call_llm(...)
import { InferenceScope, InferenceOperationType } from '@microsoft/agents-a365-observability';
const inferenceDetails = {
operationName: InferenceOperationType.CHAT,
model: 'gpt-4',
providerName: 'openai',
inputTokens: 150,
outputTokens: 75,
finishReasons: ['stop'],
responseId: 'resp-123456'
};
using scope = InferenceScope.start(inferenceDetails, agentDetails, tenantDetails);
try {
// Record input messages
scope.recordInputMessages(['Summarize the following emails for me...']);
// Call the LLM
const response = await callLLM();
// Record detailed telemetry with granular methods
scope.recordOutputMessages(['Here is your email summary...']);
scope.recordInputTokens(145); // Update if different from constructor
scope.recordOutputTokens(82); // Update if different from constructor
scope.recordResponseId('resp-789123');
scope.recordFinishReasons(['stop', 'max_tokens']);
return response.text;
} catch (error) {
scope.recordError(error as Error);
throw error;
}
using System;
using System.Threading.Tasks;
using Microsoft.Agents.A365.Observability.Runtime.Tracing.Contracts;
using Microsoft.Agents.A365.Observability.Runtime.Tracing.Scopes;
public class MyInferenceAgent
{
public async Task<InferenceResult> RunInference(string input)
{
var agentDetails = new AgentDetails(
agentId: Guid.NewGuid().ToString(),
agentName: "InferenceAgent",
agentDescription: "Performs generative AI inference.",
agentAUID: "inference-auid-123",
agentUPN: "inferenceagent@contoso.com",
agentBlueprintId: "inference-blueprint-456",
agentType: AgentType.EntraEmbodied,
tenantId: "tenant-789"
);
var tenantDetails = new TenantDetails(Guid.Parse("11111111-2222-3333-4444-555555555555"));
var inferenceDetails = new InferenceCallDetails(
operationName: InferenceOperationType.Chat,
model: "gpt-4",
providerName: "OpenAI",
inputTokens: 42,
outputTokens: 84,
finishReasons: new[] { "stop", "length" },
responseId: "response-xyz"
);
// Start the scope
using var scope = InferenceScope.Start(
details: inferenceDetails,
agentDetails: agentDetails,
tenantDetails: tenantDetails
);
// ... your inference logic here ...
// Record input/output messages and other telemetry
scope.RecordInputMessages(new[] { input, "additional context" });
scope.RecordOutputMessages(new[] { "AI response message" });
scope.RecordInputTokens(42);
scope.RecordOutputTokens(84);
scope.RecordResponseId("response-xyz");
scope.RecordFinishReasons(new[] { "stop", "length" });
scope.RecordThoughtProcess("Reasoning step 1; step 2");
return new InferenceResult { Output = "AI response message" };
}
}
public class InferenceResult
{
public string Output { get; set; }
}
在本地验证
将 ENABLE_A365_OBSERVABILITY_EXPORTER 环境变量设置为 false。 此导出范围(跟踪)到控制台。
将 ENABLE_A365_OBSERVABILITY_EXPORTER 环境变量设置为 false。 此导出范围(跟踪)到控制台。
在 appsettings.json 中将 EnableAgent365Exporter 设置为 false。 此导出范围(跟踪)到控制台。
使用可观测性测试代理
在代理中实现可观测性后,测试以确保正确捕获遥测数据。
按照测试指南设置环境,然后主要关注“查看可观测性日志”部分,以验证可观测性实现是否按预期工作。