Semantic Kernel & Azure AI Semantic Kernel & Azure AI
Tiefenreferenz für Kernel-Architektur, Plugins, Connectoren, Memory, Agents, Planner, Prompt Engineering, Azure OpenAI, Azure AI Services und Responsible AI. Deep reference for kernel architecture, plugins, connectors, memory, agents, planners, prompt engineering, Azure OpenAI, Azure AI Services, and responsible AI.
Der Mehrwert liegt in klaren Funktionsverträgen, robustem Prompting, Memory-Design, Agentensteuerung und verantwortungsvoller Integration in Azure-AI-Dienste. The value lies in clear function contracts, robust prompting, memory design, agent steering, and responsible integration with Azure AI services.
Kernel, Plugins, Filters, Memory Kernel, plugins, filters, memory
Native, Prompt, OpenAPI Native, prompt, OpenAPI
Azure OpenAI, OpenAI, Ollama, Gemini Azure OpenAI, OpenAI, Ollama, Gemini
AI Search, Qdrant, Pinecone, Redis, Chroma AI Search, Qdrant, Pinecone, Redis, Chroma
ChatCompletionAgent, Assistant, Handlebars ChatCompletionAgent, assistant, Handlebars
Templates, Variablen, Few-Shot, Grounding Templates, variables, few-shot, grounding
Modelle, Deployments, PTU, Search, Vision Models, deployments, PTU, search, vision
Content Safety, Prompt Shields, Groundedness Content Safety, prompt shields, groundedness
Semantic-Kernel-Architektur: Kernel, Plugins, Memory und Filter Semantic Kernel architecture: kernel, plugins, memory, and filters
Semantic Kernel strukturiert LLM-Anwendungen entlang klarer Bausteine: der Kernel verwaltet Dienste, Plugins kapseln Fähigkeiten, Memory liefert Kontext, und Filter erzwingen Governance an Ein- und Ausgängen. Semantic Kernel structures LLM applications around clear building blocks: the kernel manages services, plugins encapsulate capabilities, memory provides context, and filters enforce governance at inputs and outputs.
Diese Trennung ist essenziell für Enterprise-Anwendungen, weil sich Modelle, Prompts, Wissensspeicher und Sicherheitskontrollen unabhängig voneinander weiterentwickeln können. That separation is essential for enterprise applications because models, prompts, knowledge stores, and security controls can evolve independently.
| Baustein Building block | Rolle Role | Designhinweis Design guidance |
|---|---|---|
| Kernel Kernel | Registriert AI-Services, Plugins, Execution Settings und Filter. Registers AI services, plugins, execution settings, and filters. | Der Kernel bleibt leichtgewichtig; Geschäftslogik gehört in Plugins und Services. Keep the kernel lightweight; business logic belongs in plugins and services. |
| Plugins Plugins | Fassen Funktionen zusammen, die das Modell aufrufen kann. Bundle functions that the model can call. | Gute Beschreibungen sind wichtiger als eine hohe Funktionszahl. Good descriptions are more important than a large function count. |
| Memory / Context Memory / context | Stellt Abrufe aus Vektorspeichern, Chat-Verlauf oder Faktenquellen bereit. Provides retrieval from vector stores, chat history, or fact stores. | Kurzlebigen Konversationskontext von langfristigem Wissensspeicher trennen. Separate short-lived conversation context from long-lived knowledge memory. |
| Filters Filters | Greifen vor und nach Funktions- oder Promptausführung ein. Hook before and after function or prompt execution. | Ideal für Logging, Policy-Prüfung, Maskierung und Genehmigungstore. Ideal for logging, policy checks, masking, and approval gates. |
| Execution Settings Execution settings | Steuern Temperatur, Top-P, Funktionsaufrufe und Streaming. Control temperature, top-p, function calling, and streaming. | Settings pro Aufgabe definieren statt global für alle Anwendungsfälle. Define settings per task instead of globally for every use case. |
| Agents Agents | Kapseln Ziel, Verlauf, Tools und Interaktionsmuster. Encapsulate goal, history, tools, and interaction patterns. | Agents auf klare Rollen beschränken, damit Multi-Agent-Systeme beherrschbar bleiben. Constrain agents to clear roles so multi-agent systems remain manageable. |
- Kernel-Instanzen pro Request oder pro Session bewusst planen. Deliberately plan kernel instances per request or per session.
- Function- und Prompt-Filter für Audit und Guardrails zentralisieren. Centralize function and prompt filters for audit and guardrails.
- Memory nicht als Datenhalde nutzen; nur autoritativen Kontext einspeisen. Do not use memory as a data dump; feed only authoritative context.
- Modellwechsel entkoppeln, indem Connectors und Prompting sauber abstrahiert werden. Decouple model changes by abstracting connectors and prompting cleanly.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
deploymentName: "gpt-4o-prod",
endpoint: "https://aoai-contoso.openai.azure.com/",
apiKey: Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!);
Kernel kernel = builder.Build();
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
kernel = Kernel()
kernel.add_service(
AzureChatCompletion(
deployment_name="gpt-4o-prod",
endpoint="https://aoai-contoso.openai.azure.com/",
api_key="<key>",
)
)
Plugins: Native Functions, Prompt Functions und OpenAPI Plugins: native functions, prompt functions, and OpenAPI
Plugins sind die Domänenschnittstelle des Kernels. Native Functions kapseln Code, Prompt Functions kapseln wiederverwendbare Anweisungen, und OpenAPI-Importe öffnen bestehende APIs für Tool-Nutzung. Plugins are the domain interface of the kernel. Native functions encapsulate code, prompt functions encapsulate reusable instructions, and OpenAPI imports expose existing APIs for tool use.
Die wichtigste Qualitätsregel lautet: Kleine, klar benannte Funktionen mit eindeutigen Eingaben, deterministischem Verhalten und verständlichen Beschreibungen schlagen große generische Mega-Plugins. The most important quality rule is: small, clearly named functions with explicit inputs, deterministic behavior, and understandable descriptions beat large generic mega-plugins.
| Plugin-Typ Plugin type | Stärken Strengths | Grenzen Limits |
|---|---|---|
| Native Plugin Native plugin | Volle Typisierung, Business-Logik, Validierung und Testbarkeit. Full typing, business logic, validation, and testability. | Braucht Deployments und klassische Entwicklungsdisziplin. Requires deployments and classical engineering discipline. |
| Prompt Function Prompt function | Sehr schnell für Texttransformation, Klassifikation und Zusammenfassung. Very fast for transformation, classification, and summarization. | Nicht geeignet für dauerhafte Zustandsänderung oder komplexe Fachlogik. Not suitable for durable state changes or complex business logic. |
| OpenAPI Plugin OpenAPI plugin | Bindet vorhandene REST-APIs ohne viel Adaptercode ein. Connects existing REST APIs with minimal adapter code. | Nur brauchbar, wenn die Spezifikation sauber und klein genug ist. Useful only when the specification is clean and small enough. |
| Description Metadata Description metadata | Lenkt Tool-Auswahl und Parameterinterpretation. Guides tool selection and parameter interpretation. | Beschreibungen gehören zur Sicherheitsoberfläche des Systems. Descriptions are part of the security surface of the system. |
| Schema-Validierung Schema validation | Reduziert Halluzinationen bei Parametern und Rückgaben. Reduces hallucinations on parameters and return values. | Immer nutzen, wenn externe APIs aufgerufen werden. Always use it when external APIs are called. |
| Versionierung Versioning | Erlaubt evolutionäre Änderungen ohne Prompt-Brüche. Enables evolutionary changes without prompt breakage. | Versioniere Plugins wie jede andere öffentliche API. Version plugins like any other public API. |
- Funktionsnamen verbenbasiert und fachlich verständlich wählen. Choose verb-based function names that are understandable to the business.
- Jede schreibende Funktion mit Validierung und Autorisierungsprüfung schützen. Protect every write function with validation and authorization checks.
- OpenAPI-Spezifikationen vor Import entschlacken. Trim OpenAPI specifications before import.
- Prompt Functions als austauschbare Bausteine statt als ganze Applikation behandeln. Treat prompt functions as replaceable building blocks, not the whole application.
using Microsoft.SemanticKernel;
public class TimePlugin
{
[KernelFunction]
public string GetUtcNow() => DateTime.UtcNow.ToString("O");
}
kernel.ImportPluginFromObject(new TimePlugin(), "time");
prompt = """
You summarize incidents for operations teams.
Input: {{$incident}}
Return: 3 bullet points and one recommended action.
"""
kernel.add_function(
plugin_name="ops",
function_name="summarize_incident",
prompt=prompt,
)
AI-Connectoren: Azure OpenAI, OpenAI, Ollama und Gemini AI connectors: Azure OpenAI, OpenAI, Ollama, and Gemini
Semantic Kernel abstrahiert die Modellanbindung, sodass Teams je nach Datenschutz, Kosten, Latenz und Funktionsumfang zwischen mehreren Providern wechseln können. Semantic Kernel abstracts model connectivity so teams can switch between providers based on privacy, cost, latency, and feature coverage.
Trotz dieser Abstraktion bleiben Modellprofile unterschiedlich: Azure OpenAI liefert Enterprise-Governance, OpenAI deckt viele Features früh ab, Ollama erlaubt lokale Läufe, und Gemini kann für multimodale oder alternative Workflows interessant sein. Despite that abstraction, model profiles differ: Azure OpenAI delivers enterprise governance, OpenAI often exposes features early, Ollama enables local runs, and Gemini may be attractive for multimodal or alternative workflows.
| Connector Connector | Wann sinnvoll When it fits | Beobachtung Observation |
|---|---|---|
| Azure OpenAI Azure OpenAI | Unternehmensdaten, Entra-integrierte Governance, regionale Bereitstellung. Enterprise data, Entra-integrated governance, regional deployment. | Standardwahl für Azure-zentrierte Produktionssysteme. Default choice for Azure-centric production systems. |
| OpenAI OpenAI | Schneller Zugang zu neuen Features oder nicht in Azure verfügbaren Optionen. Fast access to new features or options not yet available in Azure. | Vor Nutzung Datenschutz- und Datenstandortfragen prüfen. Validate privacy and data residency before use. |
| Ollama Ollama | Lokale Entwicklung, Air-Gap-nahe Prototypen, Kostenkontrolle. Local development, near-air-gapped prototyping, cost control. | Modellqualität und Tool-Kompatibilität stark modellabhängig. Model quality and tool compatibility are strongly model-dependent. |
| Gemini Gemini | Alternative Modelle und multimodale Flows. Alternative models and multimodal flows. | Vor allem sinnvoll, wenn Governance und Vertragssituation geklärt sind. Most useful when governance and contractual posture are clear. |
| Embeddings Connector Embeddings connector | Erzeugt Vektoren für Retrieval, Similarity und Clustering. Creates vectors for retrieval, similarity, and clustering. | Embedding-Modell, Sprache und Chunking müssen zusammenpassen. Embedding model, language, and chunking must align. |
| Retry / Telemetry Layer Retry and telemetry layer | Erfasst Fehler, Delays, Tokenverbrauch und Providerwechsel. Captures failures, delays, token consumption, and provider switching. | Unverzichtbar für Kostenkontrolle und Incident Response. Essential for cost control and incident response. |
- Providerwechsel nur über zentrale Konfiguration und nicht über verstreute Prompts steuern. Control provider switching through central configuration, not scattered prompts.
- Modelle je Anwendungsfall testen: Klassifikation, Tool-Calling, RAG, Reasoning. Test models per workload: classification, tool calling, RAG, reasoning.
- Lokale Modelle in derselben Evaluationspipeline wie Cloudmodelle messen. Measure local models in the same evaluation pipeline as cloud models.
- Telemetry pro Connector und Deployment erfassen. Capture telemetry per connector and deployment.
using Microsoft.SemanticKernel.Connectors.OpenAI;
builder.AddOpenAIChatCompletion(
modelId: "gpt-4.1",
apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")!);
from semantic_kernel.connectors.ai.ollama import OllamaChatCompletion
kernel.add_service(
OllamaChatCompletion(
service_id="local",
host="http://localhost:11434",
ai_model_id="llama3.1"
)
)
Memory, Vector Stores, Agents und Planner Memory, vector stores, agents, and planners
Memory in Semantic Kernel sollte als Retrieval-Schicht verstanden werden, nicht als magischer Langzeitspeicher. Relevanz entsteht durch sauberes Chunking, Metadaten, Filterbarkeit und eindeutige Herkunft. Memory in Semantic Kernel should be understood as a retrieval layer, not a magical long-term memory. Relevance comes from clean chunking, metadata, filterability, and clear provenance.
Agents bündeln Ziel, Anweisungen, Tools und Verlauf. Planner entstehen heute oft aus Function Calling oder Handlebars-gesteuerten Schritten statt aus einer separaten magischen Komponente. Agents bundle goal, instructions, tools, and history. Planners today often emerge from function calling or Handlebars-driven steps rather than a separate magical component.
| Konzept Concept | Nutzen Benefit | Warnhinweis Caution |
|---|---|---|
| Azure AI Search Azure AI Search | Semantische, Vektor- und Hybrid-Suche mit Filtern und Security-Trimming. Semantic, vector, and hybrid retrieval with filters and security trimming. | Der Standard-Partnerdienst für Enterprise-RAG in Azure. The standard partner service for enterprise RAG in Azure. |
| Qdrant / Pinecone / Redis / Chroma Qdrant / Pinecone / Redis / Chroma | Alternativen mit unterschiedlichen Betriebs- und Skalierungsprofilen. Alternatives with different operating and scaling profiles. | Store-Auswahl an Latenz, Compliance und Plattformkompetenz koppeln. Tie store selection to latency, compliance, and platform capability. |
| ChatCompletionAgent ChatCompletionAgent | Leichtgewichtiger Agent für chatbasierte Aufgaben mit Tool-Nutzung. Lightweight agent for chat-based tasks with tool usage. | Ideal für klar umrissene Rollen wie Analyst oder Retriever. Ideal for clearly scoped roles like analyst or retriever. |
| OpenAIAssistantAgent OpenAIAssistantAgent | Assistentenähnliche Erfahrungen mit persistenterem Thread-Modell. Assistant-like experiences with a more persistent thread model. | Thread-Persistenz separat unter Datenschutzgesichtspunkten prüfen. Assess thread persistence separately from a privacy perspective. |
| Function Calling Function calling | Erlaubt planbares Aufrufen von Plugins und APIs. Enables predictable invocation of plugins and APIs. | Besser steuerbar als freie Textplanung. More controllable than free-text planning. |
| Handlebars Planner Handlebars planner | Erzeugt strukturierte Schritte mit Variablenersetzung. Produces structured steps with variable substitution. | Gut für standardisierte Planmuster und Approval Gates. Good for standardized plan patterns and approval gates. |
- Metadaten wie Quelle, Sprache, Sensitivität und Gültigkeit konsequent speichern. Persist metadata such as source, language, sensitivity, and validity consistently.
- Multi-Agent-Systeme mit Telemetrie pro Rolle instrumentieren. Instrument multi-agent systems with per-role telemetry.
- Plan-Ausgaben validieren, bevor Folgeaktionen freigegeben werden. Validate plan outputs before releasing follow-up actions.
- RAG ohne Zitate und Herkunftstracking nicht produktiv setzen. Do not put RAG into production without citations and provenance tracking.
using Microsoft.SemanticKernel.Memory;
var memory = new VolatileMemoryStore();
await memory.UpsertAsync(
collectionName: "kb",
record: MemoryRecord.LocalRecord(
id: "doc-001",
text: "Azure AI Search supports semantic, vector, and hybrid search.",
description: "AI Search note",
additionalMetadata: "source=architecture-guide"));
from semantic_kernel.memory.volatile_memory_store import VolatileMemoryStore
memory = VolatileMemoryStore()
await memory.upsert(
collection_name="kb",
record={
"id": "doc-001",
"text": "Qdrant is useful for containerized vector search workloads.",
"description": "vector note"
}
)
using Microsoft.SemanticKernel.Agents;
var agent = new ChatCompletionAgent
{
Name = "support-analyst",
Instructions = "Review incidents, call tools only when needed, and cite retrieved facts."
};
from semantic_kernel.agents import ChatCompletionAgent
agent = ChatCompletionAgent(
service_id="default",
name="risk-reviewer",
instructions="Review proposed actions, flag policy violations, and request approval if needed."
)
Prompt Engineering, Azure OpenAI Service und Azure AI Services Prompt engineering, Azure OpenAI Service, and Azure AI Services
Prompt Engineering in Semantic Kernel sollte wiederholbar und versionierbar sein. Templates beschreiben Rollen, Variablen liefern Kontext, Few-Shot-Beispiele stabilisieren das Ausgabeformat und Grounding begrenzt Halluzinationen. Prompt engineering in Semantic Kernel should be repeatable and versionable. Templates describe roles, variables provide context, few-shot examples stabilize output format, and grounding limits hallucinations.
Azure OpenAI ergänzt diese Ebene mit Modell-Deployments, Content Filtering, PTU, Fine-Tuning und Embeddings. Azure AI Search, Vision, Language, Speech und Document Intelligence liefern die Fachsignale für RAG, multimodale und sprachbasierte Szenarien. Azure OpenAI complements that layer with model deployments, content filtering, PTU, fine-tuning, and embeddings. Azure AI Search, Vision, Language, Speech, and Document Intelligence provide the domain signals for RAG, multimodal, and speech-driven scenarios.
| Dienst / Technik Service / technique | Rolle Role | Architekturhinweis Architecture note |
|---|---|---|
| Templates & Variables Templates and variables | Machen Prompts versionierbar, testbar und kontextfähig. Make prompts versionable, testable, and context-aware. | Prompts wie Code reviewen und releasen. Review and release prompts like code. |
| Few-Shot Few-shot | Stabilisiert Stil, Struktur und Tool-Auswahl. Stabilizes style, structure, and tool selection. | Beispiele klein halten und mit realen Fehlbildern pflegen. Keep examples small and maintain them against real failure cases. |
| GPT-4o / GPT-4.1 GPT-4o / GPT-4.1 | Starke Generalisten für Chat, Tool-Use und multimodale Aufgaben. Strong generalists for chat, tool use, and multimodal work. | Oft erste Wahl für Produktions-Chats und Agenten. Often the first choice for production chats and agents. |
| o1 / o3 / o4-mini o1 / o3 / o4-mini | Reasoning-lastige Modelle für komplexere Analysepfade. Reasoning-oriented models for more complex analysis paths. | Mit Kosten, Latenz und Tooling-Bedarf abgleichen. Balance against cost, latency, and tooling needs. |
| Embeddings, Fine-Tuning, PTU Embeddings, fine-tuning, PTU | Unterstützen RAG, Spezialisierung und planbare Kapazität. Support RAG, specialization, and predictable capacity. | Fine-Tuning erst nach Retrieval- und Prompt-Optimierung prüfen. Consider fine-tuning only after retrieval and prompt optimization. |
| Vision / Language / Speech / Document Intelligence Vision / Language / Speech / Document Intelligence | Erweitern Text-LLMs um Bilder, Sprache, NER und Dokumentextraktion. Extend text LLMs with images, speech, NER, and document extraction. | Signalpfade getrennt absichern und bepreisen. Secure and cost-manage those signal paths separately. |
| Azure AI Search Azure AI Search | Bietet semantische, Vektor- und Hybrid-Suche für RAG. Provides semantic, vector, and hybrid retrieval for RAG. | Für die meisten Wissensszenarien robuster als reine Vektorsuche. More robust than pure vector search for most knowledge scenarios. |
| Content Filtering Content filtering | Setzt Sicherheits- und Missbrauchsgrenzen auf Plattformebene. Sets safety and abuse boundaries at the platform level. | Mit App-seitigen Regeln, Logging und Human Approval kombinieren. Combine with app-side rules, logging, and human approval. |
- Modelle pro Fähigkeit statt per Marketingname evaluieren. Evaluate models by capability, not marketing name alone.
- Deployments, Filter und PTU-Entscheidungen als Plattformprodukt behandeln. Treat deployments, filters, and PTU choices as a platform product.
- Grounding-Fehler gesondert von Modellfehlern messen. Measure grounding failures separately from model failures.
- Output-Formate streng validieren, bevor Automatisierung folgt. Strictly validate output formats before automation follows.
string template = """
You are an enterprise assistant.
Question: {{$question}}
Context: {{$context}}
Return JSON with fields answer, citations, confidence.
""";
var result = await kernel.InvokePromptAsync(template, new() {
["question"] = "How do I enable hybrid search?",
["context"] = "Azure AI Search supports vector, semantic, and hybrid retrieval."
});
template = """
You are a procurement copilot.
User request: {{$request}}
Approved vendors: {{$vendors}}
Return YAML with recommendation and justification.
"""
result = await kernel.invoke_prompt(
prompt=template,
arguments={
"request": "Need a speech-to-text service for German meetings.",
"vendors": "Azure AI Speech, Contoso Voice Archive"
}
)
Responsible AI: Content Safety, Prompt Shields und Groundedness Responsible AI: content safety, prompt shields, and groundedness
Responsible AI ist kein nachgelagerter Freigabeschritt, sondern Teil der Laufzeitarchitektur. Sicherheitsfilter, Prompt Shields, Groundedness-Prüfungen, Evaluationssuiten und Human-in-the-Loop müssen zusammenwirken. Responsible AI is not a downstream approval step, but part of runtime architecture. Safety filters, prompt shields, groundedness checks, evaluation suites, and human-in-the-loop controls need to work together.
Gerade Agentensysteme mit Tool-Zugriff benötigen zusätzliche Kontrollen: Welche Prompts werden übernommen, welche Daten dürfen das Modell sehen, welche Aktionen dürfen ohne Bestätigung laufen und wie wird Missbrauch erkannt. Especially agent systems with tool access need additional controls: which prompts are accepted, which data the model may see, which actions may run without confirmation, and how abuse is detected.
| Kontrolle Control | Ziel Goal | Empfehlung Recommendation |
|---|---|---|
| Content Safety Content safety | Erkennt und begrenzt schädliche, missbräuchliche oder riskante Inhalte. Detects and limits harmful, abusive, or risky content. | Plattformfilter und app-spezifische Regeln kombinieren. Combine platform filters with app-specific rules. |
| Prompt Shields Prompt shields | Reduziert Prompt Injection und bösartige Instruktionsübernahme. Reduces prompt injection and hostile instruction takeover. | Besonders wichtig bei RAG, Browser- oder Mail-Inhalten. Especially important for RAG, browser, or email content. |
| Groundedness Checks Groundedness checks | Bewerten, ob Antworten auf bereitgestellte Quellen zurückführbar sind. Assess whether answers can be traced back to provided sources. | Mit Zitationspflicht und Retrieval-Metriken koppeln. Tie them to mandatory citations and retrieval metrics. |
| Human Approval Human approval | Unterbricht riskante Aktionen vor Ausführung. Interrupts risky actions before execution. | Pflicht für Finanz-, HR-, Sicherheits- und Rechtsprozesse. Mandatory for finance, HR, security, and legal flows. |
| Evaluations Evaluations | Messen Halluzination, Relevanz, Bias, Tool-Fehler und Robustheit. Measure hallucination, relevance, bias, tool errors, and robustness. | Vor jedem Modell- oder Promptwechsel Regressionen fahren. Run regressions before every model or prompt change. |
| Logging und Auditing Logging and auditing | Schafft Nachvollziehbarkeit für Sicherheit, Betrieb und Compliance. Creates traceability for security, operations, and compliance. | Prompts, Tool-Calls, Quellen und Entscheidungen revisionsfähig speichern. Store prompts, tool calls, sources, and decisions in an auditable way. |
- Keine Tool-Ausführung ohne klare Autorisierung, Schema und Ergebnisprüfung. Do not execute tools without clear authorization, schema, and result validation.
- Groundedness und Content Safety als eigene KPIs etablieren. Establish groundedness and content safety as separate KPIs.
- Prompt-Injection-Tests in CI/CD und Abnahmeprozesse aufnehmen. Include prompt injection tests in CI/CD and release sign-off.
- Fallback-Antworten definieren, wenn Unsicherheit, Safety oder Toolfehler auftreten. Define fallback responses for uncertainty, safety, or tool failures.
var ragPrompt = """
Answer only from the supplied passages.
Question: {{$question}}
Passages: {{$passages}}
Return citations with each claim.
""";
embeddings_model = {
"deployment": "text-embedding-3-large",
"usage": "semantic and vector retrieval for multilingual knowledge bases"
}