-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantic_kernel_setup.py
More file actions
313 lines (250 loc) · 9.52 KB
/
semantic_kernel_setup.py
File metadata and controls
313 lines (250 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
Example: Semantic Kernel Setup & Plugin Configuration
KB Section: 1. Architecture Patterns - Microsoft Copilot Stack
KB Link: https://maree217.github.io/copilot-architect-kb#architecture-patterns
Description:
Production-ready Semantic Kernel configuration with:
- Azure OpenAI integration
- Custom plugin creation
- Memory (semantic memory)
- Planner configuration
- Error handling & logging
Prerequisites:
- pip install semantic-kernel azure-identity
- Azure OpenAI deployment
Usage:
$ python semantic_kernel_setup.py
"""
import os
import asyncio
from typing import List
from dotenv import load_dotenv
# Semantic Kernel imports
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.core_plugins import TextMemoryPlugin
from semantic_kernel.memory import SemanticTextMemory, VolatileMemoryStore
from semantic_kernel.functions import kernel_function
load_dotenv()
class ProductionSemanticKernelSetup:
"""
Production-ready Semantic Kernel configuration following KB patterns.
Features:
- Azure OpenAI integration
- Custom plugins
- Semantic memory
- Planner for multi-step tasks
- Error handling
"""
def __init__(self):
self.kernel = None
self.memory = None
async def setup_kernel(self) -> sk.Kernel:
"""Initialize Semantic Kernel with Azure OpenAI"""
print("🔧 Setting up Semantic Kernel...")
# Create kernel
kernel = sk.Kernel()
# Add Azure OpenAI service
deployment_name = os.getenv("AZURE_OPENAI_DEPLOYMENT", "gpt-4o")
endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
api_key = os.getenv("AZURE_OPENAI_KEY")
kernel.add_service(
AzureChatCompletion(
service_id="azure_openai",
deployment_name=deployment_name,
endpoint=endpoint,
api_key=api_key
)
)
print(f"✓ Azure OpenAI configured (deployment: {deployment_name})")
self.kernel = kernel
return kernel
async def setup_memory(self) -> SemanticTextMemory:
"""Configure semantic memory for context retention"""
print("\n🧠 Setting up Semantic Memory...")
# Create memory store (in production, use persistent store)
memory_store = VolatileMemoryStore()
# Configure embeddings (using same Azure OpenAI)
embedding_service = self.kernel.get_service("azure_openai")
# Create semantic memory
memory = SemanticTextMemory(
storage=memory_store,
embeddings_generator=embedding_service
)
print("✓ Semantic memory configured")
self.memory = memory
return memory
async def create_custom_plugin(self):
"""Create custom plugin with native functions"""
print("\n🔌 Creating Custom Plugin...")
# Define plugin class
class CompliancePlugin:
"""Plugin for compliance-related operations"""
@kernel_function(
name="check_policy",
description="Check if an action complies with company policy"
)
def check_policy(self, action: str) -> str:
"""Check policy compliance"""
# In production, query policy database
policies = {
"refund": "Refunds allowed within 30 days",
"data_access": "Data access requires manager approval",
"expense": "Expenses under $500 auto-approved"
}
for key, policy in policies.items():
if key in action.lower():
return f"✓ Policy found: {policy}"
return "❌ No matching policy found"
@kernel_function(
name="get_approval_chain",
description="Get approval chain for a request"
)
def get_approval_chain(self, request_type: str, amount: str = "0") -> str:
"""Get approval requirements"""
amount_value = float(amount.replace("$", "").replace(",", ""))
if amount_value < 500:
return "Auto-approved (under $500)"
elif amount_value < 5000:
return "Requires: Manager approval"
else:
return "Requires: Manager + Director approval"
# Add plugin to kernel
compliance_plugin = CompliancePlugin()
self.kernel.add_plugin(
plugin=compliance_plugin,
plugin_name="CompliancePlugin"
)
print("✓ CompliancePlugin registered")
print(" Functions: check_policy, get_approval_chain")
async def add_memory_context(self):
"""Add context to semantic memory"""
print("\n💾 Adding Context to Memory...")
# Add company knowledge to memory
contexts = [
{
"id": "policy_1",
"text": "Refund policy: Customers can request refunds within 30 days of purchase.",
"description": "Refund policy details"
},
{
"id": "policy_2",
"text": "Data access policy: Employee data access requires manager approval.",
"description": "Data access policy"
},
{
"id": "policy_3",
"text": "Expense policy: Expenses under $500 are auto-approved. Above requires manager approval.",
"description": "Expense approval policy"
}
]
for ctx in contexts:
await self.memory.save_information(
collection="policies",
id=ctx["id"],
text=ctx["text"],
description=ctx["description"]
)
print(f" ✓ Stored: {ctx['id']}")
print(f"✓ Added {len(contexts)} items to memory")
async def query_with_memory(self, query: str) -> str:
"""Query using semantic memory for context"""
print(f"\n🔍 Query with Memory: '{query}'")
# Search memory for relevant context
results = await self.memory.search(
collection="policies",
query=query,
limit=2,
min_relevance_score=0.7
)
print(f"✓ Found {len(results)} relevant memories:")
context = []
for result in results:
print(f" - {result.text} (relevance: {result.relevance:.3f})")
context.append(result.text)
# Use context with LLM
prompt = f"""Based on these company policies:
{chr(10).join(f"- {c}" for c in context)}
Answer this question: {query}"""
# Get LLM response
chat_service = self.kernel.get_service("azure_openai")
response = await chat_service.get_chat_message_content(
chat_history=None,
settings=None,
prompt=prompt
)
answer = str(response)
print(f"\n💬 Answer: {answer}")
return answer
async def execute_with_plugin(self, action: str):
"""Execute function using plugin"""
print(f"\n⚙️ Executing Plugin Function: '{action}'")
# Get plugin function
check_policy_func = self.kernel.get_function(
plugin_name="CompliancePlugin",
function_name="check_policy"
)
# Execute function
result = await self.kernel.invoke(
function=check_policy_func,
action=action
)
print(f"✓ Result: {result}")
return result
async def main():
"""Example usage demonstrating SK capabilities"""
print("="*60)
print("🚀 SEMANTIC KERNEL PRODUCTION SETUP")
print("="*60)
# Initialize setup
sk_setup = ProductionSemanticKernelSetup()
# 1. Setup kernel
await sk_setup.setup_kernel()
# 2. Setup memory
await sk_setup.setup_memory()
# 3. Create custom plugin
await sk_setup.create_custom_plugin()
# 4. Add knowledge to memory
await sk_setup.add_memory_context()
# 5. Query with memory (RAG-like)
print("\n" + "="*60)
print("📋 EXAMPLE 1: Query with Semantic Memory")
print("="*60)
await sk_setup.query_with_memory(
"Can I get a refund if I bought something 2 weeks ago?"
)
# 6. Execute with plugin
print("\n" + "="*60)
print("📋 EXAMPLE 2: Execute Plugin Function")
print("="*60)
await sk_setup.execute_with_plugin("process refund request")
# 7. Get approval chain
print("\n" + "="*60)
print("📋 EXAMPLE 3: Multi-Step with Plugin")
print("="*60)
approval_func = sk_setup.kernel.get_function(
plugin_name="CompliancePlugin",
function_name="get_approval_chain"
)
result = await sk_setup.kernel.invoke(
function=approval_func,
request_type="expense",
amount="$2500"
)
print(f"Approval chain for $2,500 expense: {result}")
# Summary
print("\n" + "="*60)
print("✅ PRODUCTION SETUP COMPLETE")
print("="*60)
print("\n✓ Kernel configured with Azure OpenAI")
print("✓ Semantic memory with policy context")
print("✓ Custom compliance plugin registered")
print("✓ Ready for production use")
print("\n💡 Next Steps:")
print(" 1. Add more plugins (EmailPlugin, DatabasePlugin)")
print(" 2. Use persistent memory (Redis, Cosmos)")
print(" 3. Add planner for multi-step workflows")
print(" 4. Implement error handling & retries")
print(" 5. Add monitoring & logging")
if __name__ == "__main__":
asyncio.run(main())