重要
你需要參加 Frontier 預覽計畫 ,才能搶 先取得 Microsoft Agent 365 的使用權。 Frontier 直接連結你與 Microsoft 最新的 AI 創新。 Frontier 預覽受限於您現有的客戶協議預覽條款。 由於這些功能仍在開發中,其可用性與功能可能會隨時間改變。
要參與 Agent 365 生態系統,您必須在您的代理中新增 Agent 365 可觀察性功能。 Agent 365 可觀察性建立在 OpenTelemetry(OTel) 之上,提供統一框架,能在所有代理平台上一致且安全地捕捉遙測資料。 透過實作此必要元件,您可以讓 IT 管理員監控 Microsoft 管理中心(MAC)中代理的活動,並允許資安團隊使用 Defender 與 Purview 進行合規與威脅偵測。
重點優勢
-
端對端可視性:為每次代理呼叫擷取完整的遙測數據,包括會話、工具呼叫及例外,提供跨平台的完整追蹤性。
-
安全與合規啟用:將統一稽核日誌輸入 Defender 與 Purview,讓您的客服人員能進行進階的安全情境與合規報告。
-
跨平台彈性:建立在 OTel 標準之上,支援多元的執行環境與平台,如 Copilot Studio、Foundry 及未來代理框架。
-
管理員的營運效率:在 MAC 中提供集中可觀察性,縮短故障排除時間,並透過基於角色的存取控制改善治理,幫助管理您的代理的 IT 團隊。
安裝
使用這些指令安裝 Agent 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,
)
排除 token 解析器以登入主控台。
可觀察所需的環境變數包括:
| 環境變數 |
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.
令牌解析器
使用 Agent 365 匯出器時,必須提供一個憑證解析函式來回傳認證憑證。
當使用 Agent 365 Observability SDK 搭配 Agent Hosting 框架時,你可以使用 TurnContext from agent 活動產生權杖
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)現有的遙測訊號以進行追蹤,並將其轉發給 Agent 365 可觀察性服務。 這消除了開發人員手動撰寫監控程式碼的需求,簡化設定並確保績效追蹤的一致性。
自動儀器化支援多個 SDK 與平台:
注意
自動儀器化的支援因平台與 SDK 實作而異。
語意核心
汽車儀表需要使用行李製造器。 請用 BaggageBuilder。
Install the package
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 並 TenantId 使用 BaggageBuilder。 確保建立 a ChatCompletionAgent 時使用的 ID 與傳入 BaggageBuilder的代理 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。
安裝 套件。
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
Install the package
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 並 TenantId 使用 BaggageBuilder。 對於工具呼叫,請在實ChatToolCall例上開始追蹤Trace()。
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。
Install the package
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()
JavaScript 不支援 Agent Framework。
將相依性加入服務集合。
using Microsoft.Agents.A365.Observability.Extensions.AgentFramework;
builder.Services.AddTracing(config => config.WithAgentFramework());
集合 AgentId 並 TenantId 使用 BaggageBuilder。
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。
安裝 套件。
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
手動檢測
可以使用 Agent 365 可觀察性 SDK 來理解代理的內部運作。
SDK 提供三個可啟動的範圍:InvokeAgentScope、、 ExecuteToolScopeInferenceScope和 。
代理人召喚
此範圍應在您代理人申請流程的開始時使用。 使用 Invoke agent 範圍時,你可以擷取像是目前被調用的代理、代理使用者資料等屬性。
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。 這會將跨度(traces)匯出到主控台。
將 ENABLE_A365_OBSERVABILITY_EXPORTER 環境變數設定為 false。 這會將跨度(traces)匯出到主控台。
在 appsettings.json 中將 EnableAgent365Exporter 設為 false: 這會將跨度(traces)匯出到主控台。
用可觀察性測試你的代理
在你的代理程式中實作可觀察性後,測試是否正確捕捉遙測資料。 依照 測試指南 設定環境,然後主要 專注於檢視可觀察性日誌 區塊,以驗證你的可觀察性實作是否如預期運作。