Loading...
// Program.cs - Enterprise Semantic Kernel Application
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
public class EnterpriseAIApplication
{
private readonly Kernel _kernel;
private readonly SecretClient _secretClient;
public EnterpriseAIApplication()
{
// Initialize Azure Key Vault for secure credential management
var keyVaultUrl = new Uri("https://your-keyvault.vault.azure.net/");
_secretClient = new SecretClient(keyVaultUrl, new DefaultAzureCredential());
// Build Semantic Kernel with Azure OpenAI
var builder = Kernel.CreateBuilder();
// Add Azure OpenAI Chat Completion
var apiKey = _secretClient.GetSecret("AzureOpenAI-ApiKey").Value.Value;
builder.AddAzureOpenAIChatCompletion(
deploymentName: "gpt-4",
endpoint: "https://your-resource.openai.azure.com/",
apiKey: apiKey
);
// Add plugins
builder.Plugins.AddFromType<EmailPlugin>("EmailPlugin");
builder.Plugins.AddFromType<DatabasePlugin>("DatabasePlugin");
builder.Plugins.AddFromType<DocumentPlugin>("DocumentPlugin");
// Add logging and telemetry
builder.Services.AddLogging(config =>
{
config.AddConsole();
config.AddApplicationInsights();
});
_kernel = builder.Build();
}
public async Task<string> ExecuteWorkflowAsync(string userRequest)
{
var chatService = _kernel.GetRequiredService<IChatCompletionService>();
var chatHistory = new ChatHistory();
// System prompt with enterprise context
chatHistory.AddSystemMessage(@"
You are an enterprise AI assistant with access to:
- Email system for notifications
- Database for data queries
- Document management for file operations
Follow company policies:
- Never expose sensitive data
- Log all actions for audit
- Require approval for critical operations
");
chatHistory.AddUserMessage(userRequest);
// Execute with automatic function calling
var settings = new OpenAIPromptExecutionSettings
{
ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};
var result = await chatService.GetChatMessageContentAsync(
chatHistory,
executionSettings: settings,
kernel: _kernel
);
return result.Content;
}
}
// Enterprise Plugin with Governance
public class EmailPlugin
{
private readonly IEmailService _emailService;
private readonly IAuditLogger _auditLogger;
public EmailPlugin(IEmailService emailService, IAuditLogger auditLogger)
{
_emailService = emailService;
_auditLogger = auditLogger;
}
[KernelFunction("send_email")]
[Description("Send an email to specified recipient")]
public async Task<string> SendEmailAsync(
[Description("Recipient email address")] string to,
[Description("Email subject")] string subject,
[Description("Email body")] string body)
{
// Validate recipient against allowed domains
if (!IsAllowedDomain(to))
{
await _auditLogger.LogSecurityEventAsync(
"Attempted to send email to unauthorized domain",
new { To = to, Subject = subject }
);
return "Error: Recipient domain not authorized";
}
// Log for audit trail
await _auditLogger.LogActionAsync(
"EmailSent",
new { To = to, Subject = subject, Timestamp = DateTime.UtcNow }
);
// Send email
await _emailService.SendAsync(to, subject, body);
return $"Email sent successfully to {to}";
}
private bool IsAllowedDomain(string email)
{
var allowedDomains = new[] { "company.com", "partner.com" };
var domain = email.Split('@').LastOrDefault();
return allowedDomains.Contains(domain);
}
}
// Database Plugin with Row-Level Security
public class DatabasePlugin
{
private readonly IDbConnection _connection;
private readonly IUserContext _userContext;
[KernelFunction("query_customers")]
[Description("Query customer data with proper access controls")]
public async Task<string> QueryCustomersAsync(
[Description("SQL WHERE clause")] string whereClause)
{
// Apply row-level security based on user context
var userId = _userContext.GetCurrentUserId();
var userPermissions = await GetUserPermissions(userId);
if (!userPermissions.CanAccessCustomerData)
{
return "Error: Insufficient permissions to access customer data";
}
// Build secure query with parameterization
var query = $@"
SELECT CustomerID, Name, Email, Region
FROM Customers
WHERE TenantID = @TenantId
AND {whereClause}
";
var results = await _connection.QueryAsync(query, new
{
TenantId = userPermissions.TenantId
});
return JsonSerializer.Serialize(results);
}
}# semantic_kernel_app.py
import asyncio
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.functions import kernel_function
from semantic_kernel.connectors.memory.azure_cognitive_search import AzureCognitiveSearchMemoryStore
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
import logging
class EnterpriseSemanticKernel:
def __init__(self):
self.kernel = Kernel()
self._setup_azure_services()
self._register_plugins()
self._configure_logging()
def _setup_azure_services(self):
"""Configure Azure AI services with managed identity"""
# Retrieve secrets from Azure Key Vault
credential = DefaultAzureCredential()
key_vault_url = "https://your-keyvault.vault.azure.net/"
secret_client = SecretClient(vault_url=key_vault_url, credential=credential)
api_key = secret_client.get_secret("AzureOpenAI-ApiKey").value
# Add Azure OpenAI service
self.kernel.add_service(
AzureChatCompletion(
service_id="azure_gpt4",
deployment_name="gpt-4",
endpoint="https://your-resource.openai.azure.com/",
api_key=api_key
)
)
# Add Azure Cognitive Search for memory
search_endpoint = secret_client.get_secret("CognitiveSearch-Endpoint").value
search_key = secret_client.get_secret("CognitiveSearch-Key").value
memory_store = AzureCognitiveSearchMemoryStore(
search_endpoint=search_endpoint,
admin_key=search_key
)
self.kernel.register_memory_store(memory_store)
def _register_plugins(self):
"""Register enterprise plugins with governance"""
self.kernel.add_plugin(
EnterpriseDataPlugin(),
plugin_name="DataPlugin"
)
self.kernel.add_plugin(
CompliancePlugin(),
plugin_name="CompliancePlugin"
)
def _configure_logging(self):
"""Configure Application Insights logging"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Add Azure Application Insights handler
# Implementation here
async def execute_with_planning(self, goal: str) -> str:
"""Execute goal with automatic planning"""
from semantic_kernel.planners import SequentialPlanner
planner = SequentialPlanner(self.kernel)
# Create plan
plan = await planner.create_plan(goal)
# Log plan for audit
logging.info(f"Executing plan: {plan}")
# Execute plan
result = await plan.invoke(self.kernel)
return str(result)
class EnterpriseDataPlugin:
"""Enterprise data access plugin with security controls"""
@kernel_function(
name="get_financial_data",
description="Retrieve financial data with proper authorization"
)
async def get_financial_data(self, query: str, user_id: str) -> str:
"""Get financial data with access controls"""
# Check user permissions
if not await self._has_financial_access(user_id):
return "Error: User not authorized for financial data"
# Apply data masking for sensitive fields
results = await self._query_database(query)
masked_results = self._mask_sensitive_data(results)
# Audit log
await self._log_access(
user_id=user_id,
action="financial_data_access",
query=query
)
return masked_results
async def _has_financial_access(self, user_id: str) -> bool:
"""Check if user has financial data access"""
# Implementation here
return True
def _mask_sensitive_data(self, data: dict) -> str:
"""Mask sensitive fields like SSN, account numbers"""
# Implementation here
return str(data)
class CompliancePlugin:
"""Compliance and governance plugin"""
@kernel_function(
name="check_compliance",
description="Verify action complies with company policies"
)
async def check_compliance(
self,
action: str,
resource_type: str
) -> str:
"""Check if action complies with policies"""
policies = await self._load_policies(resource_type)
violations = []
for policy in policies:
if not policy.allows(action):
violations.append(policy.name)
if violations:
return f"Compliance violation: {', '.join(violations)}"
return "Action approved"
@kernel_function(
name="generate_audit_report",
description="Generate compliance audit report"
)
async def generate_audit_report(
self,
start_date: str,
end_date: str
) -> str:
"""Generate audit report for date range"""
# Query audit logs from Azure Monitor
logs = await self._fetch_audit_logs(start_date, end_date)
report = {
'period': f'{start_date} to {end_date}',
'total_actions': len(logs),
'violations': [log for log in logs if log.get('violation')],
'high_risk_actions': [log for log in logs if log.get('risk_level') == 'high']
}
return str(report)// SemanticKernelConfig.java
import com.microsoft.semantickernel.Kernel;
import com.microsoft.semantickernel.aiservices.openai.chatcompletion.OpenAIChatCompletion;
import com.microsoft.semantickernel.plugin.KernelPlugin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SemanticKernelConfig {
@Bean
public Kernel kernel(
AzureKeyVaultService keyVaultService,
List<KernelPlugin> plugins
) {
// Retrieve API key from Key Vault
String apiKey = keyVaultService.getSecret("AzureOpenAI-ApiKey");
// Build kernel
var chatCompletion = OpenAIChatCompletion.builder()
.withModelId("gpt-4")
.withApiKey(apiKey)
.withEndpoint("https://your-resource.openai.azure.com/")
.build();
var kernel = Kernel.builder()
.withAIService(OpenAIChatCompletion.class, chatCompletion)
.build();
// Register plugins
for (KernelPlugin plugin : plugins) {
kernel.importPlugin(plugin, plugin.getName());
}
return kernel;
}
}
// EnterprisePlugin.java
import com.microsoft.semantickernel.semanticfunctions.annotations.DefineKernelFunction;
import com.microsoft.semantickernel.semanticfunctions.annotations.KernelFunctionParameter;
import org.springframework.stereotype.Component;
@Component
public class EnterpriseDataPlugin implements KernelPlugin {
private final DataAccessService dataService;
private final AuditLogger auditLogger;
@DefineKernelFunction(
name = "queryCustomerData",
description = "Query customer data with authorization checks"
)
public String queryCustomerData(
@KernelFunctionParameter(description = "SQL query") String query,
@KernelFunctionParameter(description = "User ID") String userId
) {
// Authorization check
if (!authService.hasPermission(userId, "READ_CUSTOMER_DATA")) {
auditLogger.logUnauthorizedAccess(userId, "queryCustomerData");
return "Error: Insufficient permissions";
}
// Execute query with tenant isolation
String tenantId = userService.getTenantId(userId);
List<Customer> results = dataService.queryWithTenantFilter(query, tenantId);
// Audit log
auditLogger.logDataAccess(userId, "queryCustomerData", query);
return objectMapper.writeValueAsString(results);
}
@Override
public String getName() {
return "EnterpriseDataPlugin";
}
}# azure-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: semantic-kernel-agent
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: sk-agent
template:
metadata:
labels:
app: sk-agent
spec:
serviceAccountName: sk-agent-sa
containers:
- name: agent
image: yourregistry.azurecr.io/sk-agent:latest
env:
- name: AZURE_CLIENT_ID
valueFrom:
secretKeyRef:
name: azure-identity
key: client-id
- name: AZURE_TENANT_ID
valueFrom:
secretKeyRef:
name: azure-identity
key: tenant-id
- name: KEY_VAULT_URL
value: "https://your-keyvault.vault.azure.net/"
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: sk-agent-service
spec:
selector:
app: sk-agent
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: LoadBalancer{
"maxTokens": 4000,
"temperature": 0.2,
"systemPrompt": "You are a Microsoft Semantic Kernel enterprise specialist focused on Azure-native AI applications with governance and security"
}Azure OpenAI rate limit 429 errors during high-volume requests
Built-in retry with exponential backoff (3 attempts). Add Microsoft.Extensions.Http.Resilience for custom retry. Increase TPM quota in Azure Portal or implement request queue.
Plugin functions not being auto-invoked by AI model
Set FunctionChoiceBehavior.Auto() in PromptExecutionSettings. Verify plugin with kernel.Plugins.Add(). Use clear function descriptions. Ensure model supports tools (gpt-4, not gpt-3.5-turbo-instruct).
KeyError when invoking plugin or function name not recognized
Verify plugin/function names match exactly (case-sensitive). Run: pip install --upgrade semantic-kernel. Check kernel.plugins property. Use [KernelFunction] attribute for C# registration.
Resource not found 404 error connecting to Azure OpenAI endpoint
Verify deployment name matches Azure Portal exactly. Check endpoint format: https://RESOURCE.openai.azure.com/. Confirm API key from correct resource. Test with: az cognitiveservices account show.
High token usage with large plugin datasets or function schemas
Minimize function descriptions. Paginate dataset responses. Enable semantic caching with Azure Redis. Use summary functions vs full retrieval. Monitor: ChatHistory.Count property.
Loading reviews...
AutoGen v0.4 conversation agent specialist using actor model architecture for building multi-turn dialogue systems with cross-language messaging and real-time tool invocation
Multi-cloud infrastructure specialist focused on AWS, GCP, and Azure architecture, cost optimization, disaster recovery, high availability, and cloud-native design patterns
Expert code reviewer that provides thorough, constructive feedback on code quality, security, performance, and best practices
Growing community of AI engineers actively building with Claude
Live in 5 minutes • Growing community