Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
In diesem Lernprogramm wird die erste Phase der Microsoft Foundry-Entwicklerreise behandelt: von einer ersten Idee bis hin zu einem funktionierenden Prototyp. Sie erstellen einen modernen Arbeitsplatz-Assistenten , der interne Unternehmenskenntnisse mit externen technischen Anleitungen mithilfe des Microsoft Foundry SDK kombiniert.
Geschäftsszenario: Erstellen Sie einen KI-Assistenten, der Mitarbeitern hilft, indem Sie Folgendes kombinieren:
- Unternehmensrichtlinien (aus SharePoint-Dokumenten)
- Anleitung zur technischen Implementierung (von Microsoft Learn über MCP)
- Komplettlösungen (Kombinieren beider Quellen für die Unternehmensimplementierung)
- Stapelbewertung zur Validierung der Leistung des Agenten in realistischen Geschäftssituationen
Lernprogrammergebnis: Am Ende haben Sie einen ausgeführten Assistenten für moderne Arbeitsplätze, der Richtlinien, technische und kombinierte Implementierungsfragen beantworten kann; ein wiederholbares Batchauswertungsskript; und klare Erweiterungspunkte (andere Tools, Multi-Agent-Muster, umfangreichere Auswertung).
Sie werden:
- Erstellen Sie einen Assistenten für moderne Arbeitsplätze mit der SharePoint- und MCP-Integration.
- Veranschaulichen Sie reale Geschäftsszenarien, die interne und externe Kenntnisse kombinieren.
- Setzen Sie eine robuste Fehlerbehandlung und eine sanfte Degradierung um.
- Erstellen Sie Evaluierungsframework für unternehmensorientierte Tests.
- Vorbereitung der Grundlage für Governance und Produktionsbereitstellung.
In diesem minimalen Beispiel werden unternehmensfähige Muster mit realistischen Geschäftsszenarien veranschaulicht.
Von Bedeutung
Der Code in diesem Artikel verwendet Pakete, die sich derzeit in der Vorschau befinden. Diese Vorschauversion wird ohne Vereinbarung zum Servicelevel bereitgestellt und sollte nicht für Produktionsworkloads verwendet werden. Manche Features werden möglicherweise nicht unterstützt oder sind nur eingeschränkt verwendbar. Weitere Informationen finden Sie unter Zusätzliche Nutzungsbestimmungen für Microsoft Azure-Vorschauen.
Voraussetzungen
Azure-Abonnement und CLI-Authentifizierung (
az login)Azure CLI 2.67.0 oder höher (Überprüfen mit
az version)Ein Foundry-Projekt mit einem bereitgestellten Modell (z. B.
gpt-4o-mini). Wenn Sie über keins verfügen: Erstellen Sie ein Projekt , und stellen Sie dann ein Modell bereit (siehe Modellübersicht: Modellkatalog).Python 3.10 oder höher
In Ihrem Projekt konfigurierte SharePoint-Verbindung (SharePoint-Tooldokumentation)
Hinweis
Informationen zum Konfigurieren Ihres Foundry-Projekts für die SharePoint-Konnektivität finden Sie in der SharePoint-Tooldokumentation.
(Optional) Git zum Klonen des Beispiel-Repositorys installiert
Schritt 1: Abrufen des Beispielcodes
Statt in einer großen Repositorystruktur zu navigieren, sollten Sie einen der folgenden Ansätze verwenden:
Option A (gesamtes Beispiel-Repository klonen)
Tipp
Code verwendet die Foundry-Projekt-API (neu) (Vorschau) und ist nicht kompatibel mit der Foundry-Projekt-API (klassisch).
git clone --depth 1 https://github.com/azure-ai-foundry/foundry-samples.git
cd foundry-samples/samples/python/enterprise-agent-tutorial/1-idea-to-prototype
Option B (sparsamer Check-Out, nur dieses Tutorial – reduzierter Download)
git clone --no-checkout https://github.com/azure-ai-foundry/foundry-samples.git
cd foundry-samples
git sparse-checkout init --cone
git sparse-checkout set samples/python/enterprise-agent-tutorial/1-idea-to-prototype
git checkout
cd samples/python/enterprise-agent-tutorial/1-idea-to-prototype
Wiederholen Sie den Pfad für csharp oder java Varianten nach Bedarf.
Option C (DOWNLOAD ZIP des Repositorys)
Laden Sie das Repository-ZIP herunter, und extrahieren Sie es in Ihre lokale Umgebung, und wechseln Sie zum Tutorial-Ordner.
Von Bedeutung
Verwenden Sie für die Produktionsakzeptanz ein eigenständiges Repository. In diesem Lernprogramm wird das freigegebene Beispiel-Repository verwendet. Der sparsame Check-Out minimiert lokales Rauschen.
Die minimale Struktur enthält nur wesentliche Dateien:
enterprise-agent-tutorial/
└── 1-idea-to-prototype/
├── main.py # Modern Workplace Assistant
├── evaluate.py # Business evaluation framework
├── questions.jsonl # Business test scenarios (4 questions)
├── requirements.txt # Python dependencies
├── .env.template # Environment variables template
├── README.md # Complete setup instructions
├── MCP_SERVERS.md # MCP server configuration guide
├── sharepoint-sample-data # Sample business documents for SharePoint
└── collaboration-standards.docx # Sample content for policies
└── remote-work-policy.docx # Sample content for policies
└── security-guidelines.docx # Sample content for policies
└── data-governance-policy.docx # Sample content for policies
Schritt 2: Das Beispiel sofort ausführen
Beginnen Sie, indem Sie den Agent ausführen, damit Sie die Funktionsfähigkeit sehen, bevor Sie sich mit den Implementierungsdetails beschäftigen.
Umgebungseinrichtung und virtuelle Umgebung
Installieren Sie die erforderlichen Sprachlaufzeiten, globalen Tools und VS-Codeerweiterungen, wie unter "Vorbereiten Der Entwicklungsumgebung" beschrieben.
Abhängigkeiten installieren von
requirements.txt:pip install -r requirements.txt-
Kopieren Sie Ihren Endpunkt vom Willkommensbildschirm. Sie verwenden es im nächsten Schritt.
Konfigurieren
.env.Kopieren
.env.templatein.envund Konfigurieren:# Foundry Configuration PROJECT_ENDPOINT=https://<your-project>.aiservices.azure.com MODEL_DEPLOYMENT_NAME=gpt-4o-mini AI_FOUNDRY_TENANT_ID=<your-tenant-id> # The Microsoft Learn MCP Server (public authoritative Microsoft docs index) MCP_SERVER_URL=https://learn.microsoft.com/api/mcp # SharePoint Integration (Optional - requires connection setup) SHAREPOINT_RESOURCE_NAME=your-sharepoint-connection SHAREPOINT_SITE_URL=https://<your-company>.sharepoint.com/teams/your-siteTipp
Um Ihre Mandanten-ID zu erhalten, führen Sie Folgendes aus:
# Get tenant ID az account show --query tenantId -o tsvUm Ihren Projektendpunkt abzurufen, öffnen Sie Ihr Projekt im Foundry-Portal , und kopieren Sie den dort angezeigten Wert.
Ausführen von Agent und Auswertung
python main.py
python evaluate.py
Erwartete Ausgabe (erste Agent-Ausführung)
Erfolgreiche Ausführung mit SharePoint:
🤖 Creating Modern Workplace Assistant...
✅ SharePoint connected: YourConnection
✅ Agent created: asst_abc123
Sanfter Abbau ohne SharePoint
⚠️ SharePoint connection not found: Connection 'YourConnection' not found
✅ Agent created: asst_abc123
Nachdem Sie nun über einen Funktionierenden Agent verfügen, erläutern die nächsten Abschnitte, wie es funktioniert. Sie müssen beim Lesen dieser Abschnitte keine Aktion ausführen – sie sind zur Erläuterung.
Schritt 3: Einrichten von SharePoint-Beispiel-Geschäftsdokumenten
- Wechseln Sie zu Ihrer SharePoint-Website (in der Verbindung konfiguriert).
- Erstellen Sie die Dokumentbibliothek "Unternehmensrichtlinien" (oder verwenden Sie vorhandene "Dokumente").
- Laden Sie die vier Word-Musterdokumente hoch, die im Ordner
sharepoint-sample-databereitgestellt werden:remote-work-policy.docxsecurity-guidelines.docxcollaboration-standards.docxdata-governance-policy.docx
Beispielstruktur
📁 Company Policies/
├── remote-work-policy.docx # VPN, MFA, device requirements
├── security-guidelines.docx # Azure security standards
├── collaboration-standards.docx # Teams, SharePoint usage
└── data-governance-policy.docx # Data classification, retention
Schritt 4: Die Implementierung des Assistant verstehen
In diesem Abschnitt wird der Hauptcode in main.py erklärt. Sie haben den Agent bereits ausgeführt; Dieser Abschnitt ist konzeptuell und erfordert keine Änderungen. Nach dem Lesen haben Sie folgende Möglichkeiten:
- Fügen Sie neue interne und externe Datentools hinzu.
- Erweitern Sie dynamische Anweisungen.
- Führen Sie die Multi-Agent-Orchestrierung ein.
- Verbessern Sie die Überwachbarkeit und Diagnose.
Der Code unterteilt sich in die folgenden Hauptabschnitte, sortiert, wie sie im vollständigen Beispielcode angezeigt werden:
- Konfigurieren von Importen und Authentifizierung
- Konfigurieren der Authentifizierung für Azure
- Konfigurieren des SharePoint-Tools
- Konfigurieren des MCP-Tools
- Erstellen des Agents und Verbinden der Tools
- Mit dem Agenten sprechen
Von Bedeutung
Der Code in diesem Artikel verwendet Pakete, die sich derzeit in der Vorschau befinden. Diese Vorschauversion wird ohne Vereinbarung zum Servicelevel bereitgestellt und sollte nicht für Produktionsworkloads verwendet werden. Manche Features werden möglicherweise nicht unterstützt oder sind nur eingeschränkt verwendbar. Weitere Informationen finden Sie unter Zusätzliche Nutzungsbestimmungen für Microsoft Azure-Vorschauen.
Importe und Authentifizierungseinrichtung
Der Code verwendet mehrere Clientbibliotheken aus dem Microsoft Foundry SDK, um einen robusten Enterprise-Agent zu erstellen.
import os
import time
from azure.ai.agents import AgentsClient
from azure.ai.agents.models import (
SharepointTool,
SharepointGroundingToolParameters,
McpTool,
RunHandler,
ToolApproval
)
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv
# Import for connection resolution
try:
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import ConnectionType
HAS_PROJECT_CLIENT = True
except ImportError:
HAS_PROJECT_CLIENT = False
Konfigurieren der Authentifizierung in Azure
Bevor Sie Ihren Agent erstellen, richten Sie die Authentifizierung für die Gießerei ein.
# Support default Azure credentials
credential = DefaultAzureCredential()
agents_client = AgentsClient(
endpoint=os.environ["PROJECT_ENDPOINT"],
credential=credential,
)
print(f"✅ Connected to Azure AI Foundry: {os.environ['PROJECT_ENDPOINT']}")
Erstellen des SharePoint-Tools für den Agent
Der Agent verwendet SharePoint und kann auf dort gespeicherte Unternehmensrichtlinien- und Prozedurdokumente zugreifen. Richten Sie die Verbindung mit SharePoint in Ihrem Code ein.
# Create SharePoint tool with the full ARM resource ID
sharepoint_tool = SharepointTool(connection_id=connection_id)
print(f"✅ SharePoint tool configured successfully")
Erstellen des MCP-Tools für den Agent
# MCP (Model Context Protocol) enables agents to access external data sources
# like Microsoft Learn documentation. The approval flow is handled automatically
# in the chat_with_assistant function.
from azure.ai.agents.models import McpTool
mcp_server_url = os.environ.get("MCP_SERVER_URL")
mcp_tool = None
if mcp_server_url:
print(f"📚 Configuring Microsoft Learn MCP integration...")
print(f" Server URL: {mcp_server_url}")
try:
# Create MCP tool for Microsoft Learn documentation access
# server_label must match pattern: ^[a-zA-Z0-9_]+$ (alphanumeric and underscores only)
mcp_tool = McpTool(
server_url=mcp_server_url,
server_label="Microsoft_Learn_Documentation"
)
print(f"✅ MCP tool configured successfully")
except Exception as e:
print(f"⚠️ MCP tool unavailable: {e}")
print(f" Agent will operate without Microsoft Learn access")
mcp_tool = None
else:
print(f"📚 MCP integration skipped (MCP_SERVER_URL not set)")
Erstellen des Agents und Verbinden der Tools
Erstellen Sie nun den Agent, und verbinden Sie die SharePoint- und MCP-Tools.
# Create the agent using Agent SDK v2 with available tools
print(f"🛠️ Creating agent with model: {os.environ['MODEL_DEPLOYMENT_NAME']}")
# Build tools list with proper serialization
tools = []
# Add SharePoint tool using .definitions property
if sharepoint_tool:
tools.extend(sharepoint_tool.definitions)
print(f" ✓ SharePoint tool added")
# Add MCP tool using .definitions property
if mcp_tool:
tools.extend(mcp_tool.definitions)
print(f" ✓ MCP tool added")
print(f" Total tools: {len(tools)}")
# Create agent with or without tools
if tools:
agent = agents_client.create_agent(
model=os.environ["MODEL_DEPLOYMENT_NAME"],
name="Modern Workplace Assistant",
instructions=instructions,
tools=tools
)
else:
agent = agents_client.create_agent(
model=os.environ["MODEL_DEPLOYMENT_NAME"],
name="Modern Workplace Assistant",
instructions=instructions,
)
print(f"✅ Agent created successfully: {agent.id}")
return agent
Mit dem Agenten sprechen
Implementieren Sie schließlich eine interaktive Schleife, um mit dem Agent zu sprechen.
# Get response from the agent
print("🤖 ASSISTANT RESPONSE:")
response, status = chat_with_assistant(agent.id, scenario['question'])
Erwartete Ausgabe aus Agent-Beispielcode (main.py)
Wenn Sie den Agent ausführen, wird die Ausgabe ähnlich wie im folgenden Beispiel angezeigt. Die Ausgabe zeigt erfolgreiche Toolkonfigurations- und Agentantworten auf Geschäftsszenarien:
$ python main.py
✅ Connected to Foundry
🚀 Foundry - Modern Workplace Assistant
Tutorial 1: Building Enterprise Agents with Agent SDK v2
======================================================================
🤖 Creating Modern Workplace Assistant...
📁 Configuring SharePoint integration...
Connection name: ContosoCorpPoliciesProcedures
🔍 Resolving connection name to ARM resource ID...
✅ Resolved
✅ SharePoint tool configured successfully
📚 Configuring Microsoft Learn MCP integration...
Server URL: https://learn.microsoft.com/api/mcp
✅ MCP tool configured successfully
🛠️ Creating agent with model: gpt-4o-mini
✓ SharePoint tool added
✓ MCP tool added
Total tools: 2
✅ Agent created successfully
======================================================================
🏢 MODERN WORKPLACE ASSISTANT - BUSINESS SCENARIO DEMONSTRATION
======================================================================
This demonstration shows how AI agents solve real business problems
using the Azure AI Agents SDK v2.
======================================================================
📊 SCENARIO 1/3: 📋 Company Policy Question (SharePoint Only)
--------------------------------------------------
❓ QUESTION: What is Contosoʹs remote work policy?
🎯 BUSINESS CONTEXT: Employee needs to understand company-specific remote work requirements
🎓 LEARNING POINT: SharePoint tool retrieves internal company policies
--------------------------------------------------
🤖 ASSISTANT RESPONSE:
✅ SUCCESS: Contosoʹs remote work policy, effective January 2024, outlines the following key points:
### Overview
Contoso Corp supports flexible work arrangements, including remote work, to enhance employee productivity and work-life balance.
### Eligibility
- **Full-time Employees**: Must have completed a 90...
📏 Full response: 1530 characters
📈 STATUS: completed
--------------------------------------------------
📊 SCENARIO 2/3: 📚 Technical Documentation Question (MCP Only)
--------------------------------------------------
❓ QUESTION: According to Microsoft Learn, what is the correct way to implement Azure AD Conditional Access policies? Please include reference links to the official documentation.
🎯 BUSINESS CONTEXT: IT administrator needs authoritative Microsoft technical guidance
🎓 LEARNING POINT: MCP tool accesses Microsoft Learn for official documentation with links
--------------------------------------------------
🤖 ASSISTANT RESPONSE:
✅ SUCCESS: To implement Azure AD Conditional Access policies correctly, follow these key steps outlined in the Microsoft Learn documentation:
### 1. Understanding Conditional Access
Conditional Access policies act as "if-then" statements that enforce organizational access controls based on various signals. Th...
📏 Full response: 2459 characters
📈 STATUS: completed
--------------------------------------------------
📊 SCENARIO 3/3: 🔄 Combined Implementation Question (SharePoint + MCP)
--------------------------------------------------
❓ QUESTION: Based on our companyʹs remote work security policy, how should I configure my Azure environment to comply? Please include links to Microsoft documentation showing how to implement each requirement.
🎯 BUSINESS CONTEXT: Need to map company policy to technical implementation with official guidance
🎓 LEARNING POINT: Both tools work together: SharePoint for policy + MCP for implementation docs
--------------------------------------------------
🤖 ASSISTANT RESPONSE:
✅ SUCCESS: To configure your Azure environment in compliance with Contoso Corpʹs remote work security policy, you need to focus on several key areas, including enabling Multi-Factor Authentication (MFA), utilizing Azure Security Center, and implementing proper access management. Below are specific steps and li...
📏 Full response: 3436 characters
📈 STATUS: completed
--------------------------------------------------
✅ DEMONSTRATION COMPLETED!
🎓 Key Learning Outcomes:
• Agent SDK v2 usage for enterprise AI
• Proper thread and message management
• Real business value through AI assistance
• Foundation for governance and monitoring (Tutorials 2-3)
🎯 Try interactive mode? (y/n): n
🎉 Sample completed successfully!
📚 This foundation supports Tutorial 2 (Governance) and Tutorial 3 (Production)
🔗 Next: Add evaluation metrics, monitoring, and production deployment
Schritt 5: Auswerten des Assistenten in einem Batch
Der Evaluierungsframeworkcode testet realistische Geschäftsszenarien, die SharePoint-Richtlinien mit technischen Anleitungen von Microsoft Learn kombinieren. Dieser Ansatz veranschaulicht Batchauswertungsfunktionen für die Überprüfung der Agentleistung in mehreren Testfällen. Die Auswertung verwendet einen schlüsselwortbasierten Ansatz, um zu beurteilen, ob der Agent relevante Antworten bereitstellt, die die erwarteten Informationsquellen enthalten.
Dieses Evaluierungsframework testet:
- SharePoint-Integration für Fragen zur Unternehmensrichtlinie
- MCP-Integration für Fragen zur technischen Anleitung
- Kombinierte Szenarien , die sowohl interne als auch externe Kenntnisse erfordern
- Antwortqualität mithilfe der Schlüsselwortabgleichs- und Längenanalyse
Der Code unterteilt sich in die folgenden Hauptabschnitte:
- Laden von Auswertungsdaten.
- Führen Sie die Batchauswertung aus.
- Kompilieren der Auswertungsergebnisse.
Laden von Auswertungsdaten
In diesem Abschnitt lädt das Evaluierungsframework Testfragen von questions.jsonl. Die Datei enthält Geschäftsszenarien, die verschiedene Aspekte des Agents testen:
{"question": "What is Contoso's remote work policy?", "expected_source": "sharepoint", "test_type": "sharepoint_only", "explanation": "Forces SharePoint tool usage - answer must contain Contoso-specific policy details", "validation": "check_for_contoso_specifics"}
{"question": "What are Contoso's security protocols for remote employees?", "expected_source": "sharepoint", "test_type": "sharepoint_only", "explanation": "Forces SharePoint tool usage - must retrieve specific security protocols from company policies", "validation": "check_for_contoso_specifics"}
{"question": "How does Contoso classify confidential business documents according to our data governance policy?", "expected_source": "sharepoint", "test_type": "sharepoint_only", "explanation": "Forces SharePoint tool usage - must retrieve data classification from governance policy", "validation": "check_for_contoso_specifics"}
{"question": "What collaboration tools are approved for internal use at Contoso?", "expected_source": "sharepoint", "test_type": "sharepoint_only", "explanation": "Forces SharePoint tool usage - must list specific tools from collaboration standards", "validation": "check_for_contoso_specifics"}
{"question": "According to Microsoft Learn documentation, what is the correct way to set up Azure Active Directory for remote workers? Include reference links.", "expected_source": "mcp", "test_type": "mcp_only", "explanation": "Forces MCP tool usage - must provide Microsoft Learn documentation with links", "validation": "check_for_microsoft_learn_links"}
{"question": "What does Microsoft Learn say about configuring Azure Security Center monitoring? Please provide the official documentation links.", "expected_source": "mcp", "test_type": "mcp_only", "explanation": "Forces MCP tool usage - must access Microsoft Learn for Security Center guidance with links", "validation": "check_for_microsoft_learn_links"}
{"question": "How do I implement data loss prevention in Microsoft 365 according to Microsoft's official documentation? Include links to the relevant Microsoft Learn articles.", "expected_source": "mcp", "test_type": "mcp_only", "explanation": "Forces MCP tool usage - must provide DLP implementation steps with documentation links", "validation": "check_for_microsoft_learn_links"}
{"question": "What are the steps to configure conditional access policies in Azure AD according to Microsoft Learn? Provide documentation links.", "expected_source": "mcp", "test_type": "mcp_only", "explanation": "Forces MCP tool usage - must provide conditional access guidance with Microsoft Learn links", "validation": "check_for_microsoft_learn_links"}
{"question": "Based on Contoso's remote work policy requirements, how should I implement Azure VPN Gateway? Include links to Microsoft documentation for each step.", "expected_source": "both", "test_type": "hybrid", "explanation": "Forces both tools - must combine Contoso policy requirements with Azure VPN implementation guidance and links", "validation": "check_for_both_sources"}
{"question": "What Azure services do I need to configure to meet Contoso's data governance requirements? Provide Microsoft Learn links for implementing each service.", "expected_source": "both", "test_type": "hybrid", "explanation": "Forces both tools - must map Contoso governance policy to specific Azure services with documentation links", "validation": "check_for_both_sources"}
{"question": "How do I configure Microsoft Teams to comply with Contoso's collaboration standards? Include Microsoft documentation links for the setup.", "expected_source": "both", "test_type": "hybrid", "explanation": "Forces both tools - must combine Contoso collaboration standards with Teams configuration guidance and links", "validation": "check_for_both_sources"}
{"question": "What Azure security services should I implement to align with Contoso's incident response procedures? Provide links to Microsoft Learn for each service.", "expected_source": "both", "test_type": "hybrid", "explanation": "Forces both tools - must connect Contoso security policy to Azure security services with documentation links", "validation": "check_for_both_sources"}
# NOTE: This code is a non-runnable snippet of the larger sample code from which it is taken.
def load_test_questions(filepath="questions.jsonl"):
"""Load test questions from JSONL file"""
questions = []
with open(filepath, 'r') as f:
for line in f:
questions.append(json.loads(line.strip()))
return questions
Batchauswertung starten
def run_evaluation(agent_id):
"""
Run evaluation with test questions using Agent SDK v2.
Args:
agent_id: The ID of the agent to evaluate
Returns:
list: Evaluation results for each question
"""
questions = load_test_questions()
results = []
print(f"🧪 Running evaluation with {len(questions)} test questions...")
print("="*70)
# Track results by test type
stats = {
"sharepoint_only": {"passed": 0, "total": 0},
"mcp_only": {"passed": 0, "total": 0},
"hybrid": {"passed": 0, "total": 0}
}
for i, q in enumerate(questions, 1):
test_type = q.get("test_type", "unknown")
expected_source = q.get("expected_source", "unknown")
validation_type = q.get("validation", "default")
print(f"\n📝 Question {i}/{len(questions)} [{test_type.upper()}]")
print(f" {q['question'][:80]}...")
response, status = chat_with_assistant(agent_id, q["question"])
# Validate response using source-specific checks
passed, validation_details = validate_response(response, validation_type, expected_source)
result = {
"question": q["question"],
"response": response,
"status": status,
"passed": passed,
"validation_details": validation_details,
"test_type": test_type,
"expected_source": expected_source,
"explanation": q.get("explanation", "")
}
results.append(result)
# Update stats
if test_type in stats:
stats[test_type]["total"] += 1
if passed:
stats[test_type]["passed"] += 1
status_icon = "✅" if passed else "⚠️"
print(f"{status_icon} Status: {status} | Tool check: {validation_details}")
print("\n" + "="*70)
print("📊 EVALUATION SUMMARY BY TEST TYPE:")
print("="*70)
for test_type, data in stats.items():
if data["total"] > 0:
pass_rate = (data["passed"] / data["total"]) * 100
icon = "✅" if pass_rate >= 75 else "⚠️" if pass_rate >= 50 else "❌"
print(f"{icon} {test_type.upper()}: {data['passed']}/{data['total']} passed ({pass_rate:.1f}%)")
return results
Kompilieren von Auswertungsergebnissen
def calculate_and_save_results(results):
"""Calculate pass rate and save results"""
# Calculate pass rate
passed = sum(1 for r in results if r.get("passed", False))
total = len(results)
pass_rate = (passed / total * 100) if total > 0 else 0
print(f"\n📊 Overall Evaluation Results: {passed}/{total} questions passed ({pass_rate:.1f}%)")
# Save results
with open("evaluation_results.json", "w") as f:
json.dump(results, f, indent=2)
print(f"💾 Results saved to evaluation_results.json")
# Print summary of failures
failures = [r for r in results if not r.get("passed", False)]
if failures:
print(f"\n⚠️ Failed Questions ({len(failures)}):")
for r in failures:
print(f" - [{r['test_type']}] {r['question'][:60]}...")
print(f" Reason: {r['validation_details']}")
Erwartete Ausgabe aus Auswertungsbeispielcode (evaluate.py)
Wenn Sie das Auswertungsskript ausführen, wird die Ausgabe ähnlich wie im folgenden Beispiel angezeigt. Die Ausgabe zeigt die erfolgreiche Ausführung von Geschäftstestszenarien und die Generierung von Auswertungsmetriken:
python evaluate.py
✅ Connected to Foundry
🧪 Modern Workplace Assistant - Evaluation (Agent SDK v2)
======================================================================
🤖 Creating Modern Workplace Assistant...
📁 Configuring SharePoint integration...
Connection name: ContosoCorpPoliciesProcedures
🔍 Resolving connection name to ARM resource ID...
✅ Resolved
✅ SharePoint tool configured successfully
📚 Configuring Microsoft Learn MCP integration...
Server URL: https://learn.microsoft.com/api/mcp
✅ MCP tool configured successfully
🛠️ Creating agent with model: gpt-4o-mini
✓ SharePoint tool added
✓ MCP tool added
Total tools: 2
✅ Agent created successfully
Model: gpt-4o-mini
Name: Modern Workplace Assistant
======================================================================
🧪 Running evaluation with 12 test questions...
======================================================================
📝 Question 1/12 [SHAREPOINT_ONLY]
What is Contosoʹs remote work policy?...
✅ Status: completed | Tool check: Contoso-specific content: True
...
📝 Question 5/12 [MCP_ONLY]
According to Microsoft Learn documentation, what is the correct way to set up Az...
✅ Status: completed | Tool check: Microsoft Learn links: True
...
📝 Question 12/12 [HYBRID]
What Azure security services should I implement to align with Contosoʹs incident...
✅ Status: completed | Tool check: Contoso content: True, Learn links: True
======================================================================
📊 EVALUATION SUMMARY BY TEST TYPE:
======================================================================
✅ SHAREPOINT_ONLY: 4/4 passed (100.0%)
✅ MCP_ONLY: 4/4 passed (100.0%)
✅ HYBRID: 4/4 passed (100.0%)
📊 Overall Evaluation Results: 12/12 questions passed (100.0%)
💾 Results saved to evaluation_results.json
Zusätzliche Auswertungsressourcen
Die Auswertung generiert evaluation_results.json mit Metriken für jede Frage (Schlüsselworttreffer, Längenheuristik). Sie können diese Datei auf Folgendes erweitern:
- Verwenden Sie modellbasierte Bewertungsaufforderungen.
- Einführung einer strukturierten Ausgabeüberprüfung.
- Aufzeichnungsverzögerung und Tokenverwendung.
Hier ist ein Beispiel für die JSON-Ausgabestruktur:
[
{
"question": "What is Contoso's remote work policy?",
"response": "Contoso's remote work policy includes the following key components: <...>",
"status": "completed",
"passed": true,
"validation_details": "Contoso-specific content: True",
"test_type": "sharepoint_only",
"expected_source": "sharepoint",
"explanation": "Forces SharePoint tool usage - answer must contain Contoso-specific policy details"
},
{
"question": "What are Contoso's security protocols for remote employees?",
"response": ...
...
}
]
Zusammenfassung
Sie haben jetzt Folgendes:
- Ein funktionierender Einzelagent-Prototyp, der in internem und externem Wissen geerdet ist.
- Ein wiederholbares Auswertungsskript, das Enterprise-Validierungsmuster veranschaulicht.
- Klarer Upgradepfad: weitere Tools, Multi-Agent-Orchestrierung, umfangreichere Auswertung, Bereitstellung.
Diese Muster reduzieren die Reibung von Prototypen zu Produktion: Sie können Datenquellen hinzufügen, Governance erzwingen und Überwachung integrieren, ohne die Kernlogik neu zu schreiben.
Nächste Schritte
In diesem Lernprogramm wird Phase 1 der Entwicklerreise veranschaulicht – von der Idee zum Prototyp. Dieses minimale Beispiel bietet die Grundlage für die KI-Entwicklung für Unternehmensanwendungen. Um Ihre Reise fortzusetzen, erkunden Sie die nächsten Phasen:
Vorgeschlagene zusätzliche Verbesserungen
- Fügen Sie weitere Datenquellen hinzu (Azure AI Search, andere Quellen).
- Implementieren erweiterter Auswertungsmethoden (KI-unterstützte Auswertung).
- Erstellen Sie benutzerdefinierte Tools für geschäftsspezifische Vorgänge.
- Fügen Sie Gesprächsspeicher und Personalisierung hinzu.
Phase 2: Prototyp zur Produktion
- Implementieren Sie die Sicherheitsbewertung mit Red-Team-Tests.
- Erstellen Sie umfassende Auswertungsdatensätze mit Qualitätsmetriken.
- Wenden Sie organisationsweite Governancerichtlinien und Modellvergleiche an.
- Konfigurieren Sie Flottenüberwachungs-, CI/CD-Integrations- und Produktionsbereitstellungsendpunkte.
Phase 3: Von Produktion zur Einführung
- Sammeln Sie Tracing-Daten und Benutzerfeedback aus Produktionsumgebungen.
- Optimieren Sie Modelle und generieren Sie Auswertungserkenntnisse zur kontinuierlichen Verbesserung.
- Integrieren Sie das Azure-API-Verwaltungsgateway in eine kontinuierliche Qualitätsüberwachung.
- Implementieren Sie Flottengovernance, Compliancekontrollen und Kostenoptimierung.