-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathsemantic_kernel_loader.py
More file actions
2088 lines (1886 loc) · 109 KB
/
semantic_kernel_loader.py
File metadata and controls
2088 lines (1886 loc) · 109 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# semantic_kernel_loader.py
"""
Loader for Semantic Kernel plugins/actions from app settings.
- Loads plugin/action manifests from settings (CosmosDB)
- Registers plugins with the Semantic Kernel instance
"""
import logging
import builtins
from agent_orchestrator_groupchat import OrchestratorAgent, SCGroupChatManager
from semantic_kernel import Kernel
from semantic_kernel.agents import Agent
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.core_plugins import TimePlugin, HttpPlugin
from semantic_kernel.core_plugins.wait_plugin import WaitPlugin
from semantic_kernel_plugins.math_plugin import MathPlugin
from semantic_kernel_plugins.text_plugin import TextPlugin
from semantic_kernel.functions.kernel_plugin import KernelPlugin
from semantic_kernel_plugins.embedding_model_plugin import EmbeddingModelPlugin
from semantic_kernel_plugins.fact_memory_plugin import FactMemoryPlugin
from functions_settings import get_settings, get_user_settings
from foundry_agent_runtime import AzureAIFoundryChatCompletionAgent
from functions_appinsights import log_event, get_appinsights_logger
from functions_authentication import get_current_user_id
from semantic_kernel_plugins.plugin_health_checker import PluginHealthChecker, PluginErrorRecovery
from semantic_kernel_plugins.logged_plugin_loader import create_logged_plugin_loader
from semantic_kernel_plugins.plugin_invocation_logger import get_plugin_logger
from semantic_kernel_plugins.smart_http_plugin import SmartHttpPlugin
from functions_debug import debug_print
from flask import g
from functions_keyvault import validate_secret_name_dynamic, retrieve_secret_from_key_vault, retrieve_secret_from_key_vault_by_full_name, SecretReturnType
from functions_global_actions import get_global_actions
from functions_global_agents import get_global_agents
from functions_group_agents import get_group_agent, get_group_agents
from functions_group_actions import get_group_actions
from functions_group import require_active_group
from functions_personal_actions import get_personal_actions, ensure_migration_complete as ensure_actions_migration_complete
from functions_personal_agents import get_personal_agents, ensure_migration_complete as ensure_agents_migration_complete
from semantic_kernel_plugins.plugin_loader import discover_plugins
from semantic_kernel_plugins.openapi_plugin_factory import OpenApiPluginFactory
import app_settings_cache
try:
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
except ImportError:
DefaultAzureCredential = None
get_bearer_token_provider = None
# Agent and Azure OpenAI chat service imports
log_event("[SK Loader] Starting loader imports")
try:
from semantic_kernel.agents import ChatCompletionAgent
from agent_logging_chat_completion import LoggingChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
except ImportError:
ChatCompletionAgent = None
AzureChatCompletion = None
log_event(
"[SK Loader] ChatCompletionAgent or AzureChatCompletion not available. Ensure you have the correct Semantic Kernel version.",
level=logging.ERROR,
exceptionTraceback=True
)
log_event("[SK Loader] Completed imports")
# Define supported chat types in a single place
orchestration_types = [
{
"value": "default_agent",
"label": "Selected Agent",
"agent_mode": "single",
"description": "Single-agent chat with the selected agent."
}
]
"""
{
"value": "group_chat",
"label": "Group Chat",
"agent_mode": "multi",
"description": "Multi-agent group chat orchestration."
},
{
"value": "magnetic",
"label": "Magnetic",
"agent_mode": "multi",
"description": "Multi-agent magnetic orchestration."
}
"""
def get_agent_orchestration_types():
"""Returns the supported chat orchestration types (full metadata)."""
return orchestration_types
def get_agent_orchestration_type_values():
"""Returns just the allowed values for validation/settings."""
return [t["value"] for t in orchestration_types]
def get_agent_orchestration_types_by_mode(mode):
"""Filter orchestration types by agent_mode ('single' or 'multi')."""
return [t for t in orchestration_types if t["agent_mode"] == mode]
def first_if_comma(val):
if isinstance(val, str) and "," in val:
return val.split(",")[0].strip()
return val
def resolve_agent_config(agent, settings):
debug_print(f"[SK Loader] resolve_agent_config called for agent: {agent.get('name')}")
debug_print(f"[SK Loader] Agent config: {agent}")
debug_print(f"[SK Loader] Agent is_global flag: {agent.get('is_global')}")
debug_print(f"[SK Loader] Agent is_group flag: {agent.get('is_group')}")
agent_type = (agent.get('agent_type') or 'local').lower()
agent['agent_type'] = agent_type
other_settings = agent.get("other_settings", {}) or {}
gpt_model_obj = settings.get('gpt_model', {})
selected_model = gpt_model_obj.get('selected', [{}])[0] if gpt_model_obj.get('selected') else {}
debug_print(f"[SK Loader] Global selected_model: {selected_model}")
debug_print(f"[SK Loader] Global selected_model deploymentName: {selected_model.get('deploymentName')}")
# User APIM enabled if agent has enable_agent_gpt_apim True (or 1, or 'true')
user_apim_enabled = agent.get("enable_agent_gpt_apim") in [True, 1, "true", "True"]
global_apim_enabled = settings.get("enable_gpt_apim", False)
per_user_enabled = settings.get('per_user_semantic_kernel', False)
allow_user_custom_agent_endpoints = settings.get('allow_user_custom_agent_endpoints', False)
allow_group_custom_agent_endpoints = settings.get('allow_group_custom_agent_endpoints', False)
is_group_agent = agent.get("is_group", False)
is_global_agent = agent.get("is_global", False)
if is_group_agent:
allow_custom_agent_endpoints = allow_group_custom_agent_endpoints
elif is_global_agent:
allow_custom_agent_endpoints = False
else:
allow_custom_agent_endpoints = allow_user_custom_agent_endpoints
debug_print(f"[SK Loader] user_apim_enabled: {user_apim_enabled}, global_apim_enabled: {global_apim_enabled}, per_user_enabled: {per_user_enabled}")
debug_print(f"[SK Loader] allow_user_custom_agent_endpoints: {allow_user_custom_agent_endpoints}, allow_group_custom_agent_endpoints: {allow_group_custom_agent_endpoints}, allow_custom_agent_endpoints_resolved: {allow_custom_agent_endpoints}")
debug_print(f"[SK Loader] Max completion tokens from agent: {agent.get('max_completion_tokens')}")
def resolve_secret_value_if_needed(value, scope_value, source, scope):
if validate_secret_name_dynamic(value):
return retrieve_secret_from_key_vault(value, scope_value, scope, source)
return value
def any_filled(*fields):
return any(bool(f) for f in fields)
def all_filled(*fields):
return all(bool(f) for f in fields)
def get_user_apim():
endpoint = agent.get("azure_apim_gpt_endpoint")
key = agent.get("azure_apim_gpt_subscription_key")
deployment = agent.get("azure_apim_gpt_deployment")
api_version = agent.get("azure_apim_gpt_api_version")
# Check if key vault secret storage is enabled in settings
if settings.get("enable_key_vault_secret_storage", False) and settings.get("key_vault_name") and key:
try:
if validate_secret_name_dynamic(key):
# Try to retrieve the secret from Key Vault
resolved_key = retrieve_secret_from_key_vault_by_full_name(key)
if resolved_key:
# Update the agent dict with the resolved key for this session
agent["azure_apim_gpt_subscription_key"] = resolved_key
key = resolved_key
except Exception as e:
log_event(f"[SK Loader] Failed to resolve Key Vault secret for agent '{agent.get('name')}' in get_user_apim: {e}", level=logging.ERROR, exceptionTraceback=True)
# Fallback to using the value as-is
return (endpoint, key, deployment, api_version)
def get_global_apim():
endpoint = settings.get("azure_apim_gpt_endpoint")
key = settings.get("azure_apim_gpt_subscription_key")
deployment = first_if_comma(settings.get("azure_apim_gpt_deployment"))
api_version = settings.get("azure_apim_gpt_api_version")
# Check if key vault secret storage is enabled in settings
if settings.get("enable_key_vault_secret_storage", False) and settings.get("key_vault_name") and key:
try:
if validate_secret_name_dynamic(key):
# Try to retrieve the secret from Key Vault
resolved_key = retrieve_secret_from_key_vault_by_full_name(key)
if resolved_key:
# Update the settings dict with the resolved key for this session
settings["azure_apim_gpt_subscription_key"] = resolved_key
key = resolved_key
except Exception as e:
log_event(f"[SK Loader] Failed to resolve Key Vault secret in get_global_apim: {e}", level=logging.ERROR, exceptionTraceback=True)
# Fallback to using the value as-is
return (endpoint, key, deployment, api_version)
def get_user_gpt():
endpoint = agent.get("azure_openai_gpt_endpoint")
key = agent.get("azure_openai_gpt_key")
deployment = agent.get("azure_openai_gpt_deployment")
api_version = agent.get("azure_openai_gpt_api_version")
# Check if key vault secret storage is enabled in settings
if settings.get("enable_key_vault_secret_storage", False) and settings.get("key_vault_name") and key:
try:
if validate_secret_name_dynamic(key):
# Try to retrieve the secret from Key Vault
resolved_key = retrieve_secret_from_key_vault_by_full_name(key)
if resolved_key:
# Update the agent dict with the resolved key for this session
agent["azure_openai_gpt_key"] = resolved_key
key = resolved_key
except Exception as e:
log_event(f"[SK Loader] Failed to resolve Key Vault secret for agent '{agent.get('name')}' in get_user_gpt: {e}", level=logging.ERROR, exceptionTraceback=True)
# Fallback to using the value as-is
return (endpoint, key, deployment, api_version)
def get_global_gpt():
endpoint = settings.get("azure_openai_gpt_endpoint") or selected_model.get("endpoint")
key = settings.get("azure_openai_gpt_key") or selected_model.get("key")
deployment = settings.get("azure_openai_gpt_deployment") or selected_model.get("deploymentName")
api_version = settings.get("azure_openai_gpt_api_version") or selected_model.get("api_version")
# Check if key vault secret storage is enabled in settings
if settings.get("enable_key_vault_secret_storage", False) and settings.get("key_vault_name") and key:
try:
if validate_secret_name_dynamic(key):
# Try to retrieve the secret from Key Vault
resolved_key = retrieve_secret_from_key_vault_by_full_name(key)
if resolved_key:
# Update the settings dict with the resolved key for this session
settings["azure_openai_gpt_key"] = resolved_key
key = resolved_key
except Exception as e:
log_event(f"[SK Loader] Failed to resolve Key Vault secret in get_global_gpt: {e}", level=logging.ERROR, exceptionTraceback=True)
# Fallback to using the value as-is
return (endpoint, key, deployment, api_version)
def merge_fields(primary, fallback):
return tuple(p if p not in [None, ""] else f for p, f in zip(primary, fallback))
# If per-user mode is not enabled, ignore all user/agent-specific config fields
if agent_type == "aifoundry":
return {
"name": agent.get("name"),
"display_name": agent.get("display_name", agent.get("name")),
"description": agent.get("description", ""),
"id": agent.get("id", ""),
"default_agent": agent.get("default_agent", False),
"is_global": agent.get("is_global", False),
"is_group": agent.get("is_group", False),
"group_id": agent.get("group_id"),
"group_name": agent.get("group_name"),
"agent_type": "aifoundry",
"other_settings": other_settings,
"max_completion_tokens": agent.get("max_completion_tokens", -1),
}
if not per_user_enabled:
try:
if global_apim_enabled:
g_apim = get_global_apim()
endpoint, key, deployment, api_version = g_apim
else:
g_gpt = get_global_gpt()
endpoint, key, deployment, api_version = g_gpt
return {
"endpoint": endpoint,
"key": key,
"deployment": deployment,
"api_version": api_version,
"instructions": agent.get("instructions", ""),
"actions_to_load": agent.get("actions_to_load", []),
"additional_settings": agent.get("additional_settings", {}),
"name": agent.get("name"),
"display_name": agent.get("display_name", agent.get("name")),
"description": agent.get("description", ""),
"id": agent.get("id", ""),
"default_agent": agent.get("default_agent", False),
"is_global": agent.get("is_global", False),
"is_group": agent.get("is_group", False),
"group_id": agent.get("group_id"),
"group_name": agent.get("group_name"),
"enable_agent_gpt_apim": agent.get("enable_agent_gpt_apim", False),
"max_completion_tokens": agent.get("max_completion_tokens", -1),
"agent_type": agent_type or "local",
"other_settings": other_settings,
}
except Exception as e:
log_event(f"[SK Loader] Error resolving agent config: {e}", level=logging.ERROR, exceptionTraceback=True)
# --- PATCHED DECISION TREE ---
u_apim = get_user_apim()
g_apim = get_global_apim()
u_gpt = get_user_gpt()
g_gpt = get_global_gpt()
can_use_agent_endpoints = allow_custom_agent_endpoints
user_apim_allowed = user_apim_enabled and can_use_agent_endpoints
# 1. User APIM enabled and any user APIM values set: use user APIM (merge with global APIM if needed)
if user_apim_allowed and any_filled(*u_apim):
debug_print(f"[SK Loader] Using user APIM with global fallback")
merged = merge_fields(u_apim, g_apim if global_apim_enabled and any_filled(*g_apim) else (None, None, None, None))
endpoint, key, deployment, api_version = merged
endpoint_is_user_supplied = True
# 2. User APIM enabled but no user APIM values, and global APIM enabled and present: use global APIM
elif user_apim_enabled and global_apim_enabled and any_filled(*g_apim):
debug_print(f"[SK Loader] Using global APIM (user APIM enabled but not present)")
endpoint, key, deployment, api_version = g_apim
endpoint_is_user_supplied = False
# 3. User GPT config is FULLY filled: use user GPT (all fields filled)
elif all_filled(*u_gpt) and can_use_agent_endpoints:
debug_print(f"[SK Loader] Using agent GPT config (all fields filled)")
endpoint, key, deployment, api_version = u_gpt
endpoint_is_user_supplied = True
# 4. User GPT config is PARTIALLY filled, global APIM is NOT enabled: merge user GPT with global GPT
elif any_filled(*u_gpt) and not global_apim_enabled and can_use_agent_endpoints:
debug_print(f"[SK Loader] Using agent GPT config (partially filled, merging with global GPT, global APIM not enabled)")
endpoint, key, deployment, api_version = merge_fields(u_gpt, g_gpt)
# Only treat as user-supplied if the agent itself provided an endpoint.
# If the endpoint was filled in via global fallback (agent's own endpoint is empty),
# it is the system-controlled global endpoint and managed identity remains safe to use.
endpoint_is_user_supplied = bool(u_gpt[0])
# 5. Global APIM enabled and present: use global APIM
elif global_apim_enabled and any_filled(*g_apim):
debug_print(f"[SK Loader] Using global APIM (fallback)")
endpoint, key, deployment, api_version = g_apim
endpoint_is_user_supplied = False
# 6. Fallback to global GPT config
else:
debug_print(f"[SK Loader] Using global GPT config (fallback)")
endpoint, key, deployment, api_version = g_gpt
endpoint_is_user_supplied = False
result = {
"endpoint": endpoint,
"key": key,
"deployment": deployment,
"api_version": api_version,
"instructions": agent.get("instructions", ""),
"actions_to_load": agent.get("actions_to_load", []),
"additional_settings": agent.get("additional_settings", {}),
"name": agent.get("name"),
"display_name": agent.get("display_name", agent.get("name")),
"description": agent.get("description", ""),
"id": agent.get("id", ""),
"default_agent": agent.get("default_agent", False), # [Deprecated, use 'selected_agent' or 'global_selected_agent' in agent config]
"is_global": agent.get("is_global", False), # Ensure we have this field
"is_group": agent.get("is_group", False),
"group_id": agent.get("group_id"),
"group_name": agent.get("group_name"),
"enable_agent_gpt_apim": agent.get("enable_agent_gpt_apim", False), # Use this to check if APIM is enabled for the agent
"max_completion_tokens": agent.get("max_completion_tokens", -1), # -1 meant use model default determined by the service, 35-trubo is 4096, 4o is 16384, 4.1 is at least 32768
"agent_type": agent_type or "local",
"other_settings": other_settings,
# Security: track whether the endpoint was user/agent-supplied vs system-controlled.
# Managed identity must NOT be used with user-supplied endpoints to prevent token theft.
"endpoint_is_user_supplied": endpoint_is_user_supplied,
}
print(f"[SK Loader] Final resolved config for {agent.get('name')}: endpoint={bool(endpoint)}, key={bool(key)}, deployment={deployment}")
return result
def load_time_plugin(kernel: Kernel):
kernel.add_plugin(
TimePlugin(),
plugin_name="time",
description="Provides time-related functions."
)
def load_http_plugin(kernel: Kernel):
try:
# Use smart HTTP plugin with 75k character limit (≈50k tokens)
smart_plugin = SmartHttpPlugin(max_content_size=75000, extract_text_only=True)
kernel.add_plugin(
smart_plugin,
plugin_name="http",
description="Provides HTTP request functions with intelligent content size management for web scraping."
)
log_event("[SK Loader] Loaded Smart HTTP plugin with content size limits.", level=logging.INFO)
except ImportError as e:
log_event(f"[SK Loader] Smart HTTP plugin not available, falling back to standard HttpPlugin: {e}", level=logging.WARNING)
# Fallback to standard HTTP plugin
kernel.add_plugin(
HttpPlugin(),
plugin_name="http",
description="Provides HTTP request functions for making API calls."
)
def load_wait_plugin(kernel: Kernel):
kernel.add_plugin(
WaitPlugin(),
plugin_name="wait",
description="Provides wait functions for delaying execution."
)
def load_math_plugin(kernel: Kernel):
kernel.add_plugin(
MathPlugin(),
plugin_name="math",
description="Provides mathematical calculation functions."
)
def load_text_plugin(kernel: Kernel):
kernel.add_plugin(
TextPlugin(),
plugin_name="text",
description="Provides text manipulation functions."
)
def load_fact_memory_plugin(kernel: Kernel):
kernel.add_plugin(
FactMemoryPlugin(),
plugin_name="fact_memory",
description="Provides functions for managing persistent facts."
)
def load_embedding_model_plugin(kernel: Kernel, settings):
embedding_endpoint = settings.get('azure_openai_embedding_endpoint')
embedding_key = settings.get('azure_openai_embedding_key')
embedding_model = settings.get('embedding_model', {}).get('selected', [None])[0]
if embedding_endpoint and embedding_key and embedding_model:
plugin = EmbeddingModelPlugin()
kernel.add_plugin(
plugin,
plugin_name="embedding_model",
description="Provides text embedding functions using the configured embedding model."
)
def load_core_plugins_only(kernel: Kernel, settings):
"""Load only core plugins for model-only conversations without agents."""
debug_print(f"[SK Loader] Loading core plugins only for model-only mode...")
log_event("[SK Loader] Loading core plugins only for model-only mode...", level=logging.INFO)
if settings.get('enable_time_plugin', True):
load_time_plugin(kernel)
log_event("[SK Loader] Loaded Time plugin.", level=logging.INFO)
if settings.get('enable_fact_memory_plugin', True):
load_fact_memory_plugin(kernel)
log_event("[SK Loader] Loaded Fact Memory plugin.", level=logging.INFO)
if settings.get('enable_math_plugin', True):
load_math_plugin(kernel)
log_event("[SK Loader] Loaded Math plugin.", level=logging.INFO)
if settings.get('enable_text_plugin', True):
load_text_plugin(kernel)
log_event("[SK Loader] Loaded Text plugin.", level=logging.INFO)
# =================== Semantic Kernel Initialization ===================
def initialize_semantic_kernel(user_id: str=None, redis_client=None):
debug_print(f"[SK Loader] Initializing Semantic Kernel and plugins...")
log_event(
"[SK Loader] Initializing Semantic Kernel and plugins...",
level=logging.INFO
)
kernel, kernel_agents = Kernel(), None
if not kernel:
log_event(
"[SK Loader] Failed to initialize Semantic Kernel.",
level=logging.ERROR,
exceptionTraceback=True
)
log_event(
"[SK Loader] Starting to load Semantic Kernel Agent and Plugins",
level=logging.INFO
)
settings = app_settings_cache.get_settings_cache()
log_event(f"[SK Loader] Settings check - per_user_semantic_kernel: {settings.get('per_user_semantic_kernel', False)}, user_id: {user_id}", level=logging.INFO)
if settings.get('per_user_semantic_kernel', False) and user_id is not None:
debug_print(f"[SK Loader] Using per-user semantic kernel mode")
log_event("[SK Loader] Using per-user semantic kernel mode", level=logging.INFO)
kernel, kernel_agents = load_user_semantic_kernel(kernel, settings, user_id=user_id, redis_client=redis_client)
g.kernel = kernel
g.kernel_agents = kernel_agents
print(f"[SK Loader] Per-user mode - stored g.kernel_agents: {type(kernel_agents)} with {len(kernel_agents) if kernel_agents else 0} agents")
log_event(f"[SK Loader] Per-user mode - stored g.kernel_agents: {type(kernel_agents)} with {len(kernel_agents) if kernel_agents else 0} agents", level=logging.INFO)
else:
debug_print(f"[SK Loader] Using global semantic kernel mode")
log_event("[SK Loader] Using global semantic kernel mode", level=logging.INFO)
kernel, kernel_agents = load_semantic_kernel(kernel, settings)
builtins.kernel = kernel
builtins.kernel_agents = kernel_agents
print(f"[SK Loader] Global mode - stored builtins.kernel_agents: {type(kernel_agents)} with {len(kernel_agents) if kernel_agents else 0} agents")
log_event(f"[SK Loader] Global mode - stored builtins.kernel_agents: {type(kernel_agents)} with {len(kernel_agents) if kernel_agents else 0} agents", level=logging.INFO)
if kernel and not kernel_agents:
debug_print(f"[SK Loader] No agents loaded - proceeding in model-only mode")
log_event(
"[SK Loader] No agents loaded - proceeding in model-only mode",
level=logging.INFO
)
elif kernel_agents:
agent_names = []
if isinstance(kernel_agents, dict):
agent_names = list(kernel_agents.keys())
else:
agent_names = [getattr(agent, 'name', 'unnamed') for agent in kernel_agents]
print(f"[SK Loader] Successfully loaded {len(kernel_agents)} agents: {agent_names}")
log_event(f"[SK Loader] Successfully loaded {len(kernel_agents)} agents: {agent_names}", level=logging.INFO)
else:
debug_print(f"[SK Loader] No agents loaded - kernel_agents is None")
log_event("[SK Loader] No agents loaded - kernel_agents is None", level=logging.WARNING)
log_event(
"[SK Loader] Semantic Kernel Agent and Plugins loading completed.",
extra={
"kernel": str(kernel),
"agents": [agent.name for agent in kernel_agents.values()] if kernel_agents else []
},
level=logging.INFO
)
debug_print(f"[SK Loader] Semantic Kernel Agent and Plugins loading completed.")
def load_agent_specific_plugins(kernel, plugin_names, settings, mode_label="global", user_id=None, group_id=None):
"""
Load specific plugins by name for an agent with enhanced logging.
Args:
kernel: The Semantic Kernel instance
plugin_names: List of plugin names to load (from agent's actions_to_load)
mode_label: 'per-user' or 'global' for logging
user_id: User ID for per-user mode
group_id: Active group identifier when loading group-scoped plugins
"""
if not plugin_names:
debug_print(f"[SK Loader] No plugin names provided to load_agent_specific_plugins")
return
print(f"[SK Loader] Loading {len(plugin_names)} agent-specific plugins: {plugin_names}")
try:
merge_global = settings.get('merge_global_semantic_kernel_with_workspace', False)
# Create logged plugin loader for enhanced logging
logged_loader = create_logged_plugin_loader(kernel)
if mode_label == "group":
if not group_id:
debug_print(f"[SK Loader] Warning: Group mode requested without group_id. Skipping plugin load.")
all_plugin_manifests = []
else:
all_plugin_manifests = get_group_actions(group_id, return_type=SecretReturnType.NAME)
debug_print(f"[SK Loader] Retrieved {len(all_plugin_manifests)} group plugin manifests for group {group_id}")
if merge_global:
global_plugins = get_global_actions(return_type=SecretReturnType.NAME)
all_plugin_manifests.extend(global_plugins)
debug_print(f"[SK Loader] Merged global plugins for group mode. Total manifests: {len(all_plugin_manifests)}")
elif mode_label == "per-user":
if user_id:
all_plugin_manifests = get_personal_actions(user_id, return_type=SecretReturnType.NAME)
if merge_global:
global_plugins = get_global_actions(return_type=SecretReturnType.NAME)
for g in global_plugins:
all_plugin_manifests.append(g)
debug_print(f"[SK Loader] Retrieved {len(all_plugin_manifests)} personal plugin manifests for user {user_id}")
else:
debug_print(f"[SK Loader] Warning: No user_id provided for per-user plugin loading")
all_plugin_manifests = []
else:
# Global mode - get from global actions container
all_plugin_manifests = get_global_actions(return_type=SecretReturnType.NAME)
print(f"[SK Loader] Retrieved {len(all_plugin_manifests)} global plugin manifests")
# Filter manifests to only include requested plugins
# Check both 'name' and 'id' fields to support both UUID and name references
plugin_manifests = [
p for p in all_plugin_manifests
if p.get('name') in plugin_names or p.get('id') in plugin_names
]
debug_print(f"[SK Loader] Filtered to {len(plugin_manifests)} plugin manifests after matching names/IDs")
debug_print(f"[SK Loader] Plugin manifests to load: {plugin_manifests}")
if settings.get("enable_key_vault_secret_storage", False) and settings.get("key_vault_name"):
debug_print(f"[SK Loader] Resolving Key Vault secrets in plugin manifests if needed")
try:
plugin_manifests = [resolve_key_vault_secrets_in_plugins(p, settings) for p in plugin_manifests]
debug_print(f"[SK Loader] Resolved Key Vault secrets in plugin manifests {plugin_manifests}")
except Exception as e:
log_event(f"[SK Loader] Failed to resolve Key Vault secrets in plugin manifests: {e}", level=logging.ERROR, exceptionTraceback=True)
print(f"[SK Loader] Failed to resolve Key Vault secrets in plugin manifests: {e}")
if not plugin_manifests:
print(f"[SK Loader] Warning: No plugin manifests found for names/IDs: {plugin_names}")
print(f"[SK Loader] Available plugin names: {[p.get('name') for p in all_plugin_manifests]}")
print(f"[SK Loader] Available plugin IDs: {[p.get('id') for p in all_plugin_manifests]}")
return
print(f"[SK Loader] Found {len(plugin_manifests)} plugin manifests to load")
# Use logged plugin loader for enhanced logging
print(f"[SK Loader] Using logged plugin loader for enhanced logging")
results = logged_loader.load_multiple_plugins(plugin_manifests, user_id)
successful_count = sum(1 for success in results.values() if success)
total_count = len(results)
print(f"[SK Loader] Logged plugin loader results: {successful_count}/{total_count} successful")
if results:
for plugin_name, success in results.items():
print(f"[SK Loader] Plugin {plugin_name}: {'SUCCESS' if success else 'FAILED'}")
log_event(
f"[SK Loader] Agent-specific plugins loaded: {successful_count}/{total_count} with enhanced logging [{mode_label}]",
extra={
"mode": mode_label,
"user_id": user_id,
"requested_plugins": plugin_names,
"successful_plugins": [name for name, success in results.items() if success],
"failed_plugins": [name for name, success in results.items() if not success],
"total_plugins": total_count
},
level=logging.INFO
)
# Fallback to original method if logged loader fails completely
if successful_count == 0 and total_count > 0:
print(f"[SK Loader] WARNING: Logged plugin loader failed for all plugins, falling back to original method")
log_event("[SK Loader] Falling back to original plugin loading method for agent plugins", level=logging.WARNING)
_load_agent_plugins_original_method(kernel, plugin_manifests, mode_label)
else:
print(f"[SK Loader] Logged plugin loader completed successfully: {successful_count}/{total_count}")
except Exception as e:
log_event(
f"[SK Loader][Error] Error in agent-specific plugin loading: {e}",
extra={"error": str(e), "mode": mode_label, "user_id": user_id, "plugin_names": plugin_names},
level=logging.ERROR,
exceptionTraceback=True
)
print(f"[SK Loader][Error] Error in agent-specific plugin loading: {e}")
# Fallback to original method
try:
# Get plugin manifests again for fallback
if mode_label == "group":
if group_id:
all_plugin_manifests = get_group_actions(group_id, return_type=SecretReturnType.NAME)
if merge_global:
global_plugins = get_global_actions(return_type=SecretReturnType.NAME)
all_plugin_manifests.extend(global_plugins)
else:
all_plugin_manifests = []
elif mode_label == "per-user":
if user_id:
all_plugin_manifests = get_personal_actions(user_id, return_type=SecretReturnType.NAME)
if merge_global:
global_plugins = get_global_actions(return_type=SecretReturnType.NAME)
for g in global_plugins:
all_plugin_manifests.append(g)
else:
all_plugin_manifests = []
else:
all_plugin_manifests = get_global_actions(return_type=SecretReturnType.NAME)
plugin_manifests = [p for p in all_plugin_manifests if p.get('name') in plugin_names]
_load_agent_plugins_original_method(kernel, plugin_manifests, mode_label)
except Exception as fallback_error:
log_event(
f"[SK Loader][Error] Fallback plugin loading also failed: {fallback_error}",
extra={"error": str(fallback_error), "mode": mode_label, "user_id": user_id},
level=logging.ERROR,
exceptionTraceback=True
)
print(f"[SK Loader][Error] Fallback plugin loading also failed: {fallback_error}")
def _load_agent_plugins_original_method(kernel, plugin_manifests, mode_label="global"):
"""
Original agent plugin loading method as fallback.
"""
try:
# Load the filtered plugins using original method
discovered_plugins = discover_plugins()
for manifest in plugin_manifests:
plugin_type = manifest.get('type')
name = manifest.get('name')
description = manifest.get('description', '')
# Normalize for matching
def normalize(s):
return s.replace('_', '').replace('-', '').replace('plugin', '').lower() if s else ''
normalized_type = normalize(plugin_type)
matched_class = None
for class_name, cls in discovered_plugins.items():
normalized_class = normalize(class_name)
if normalized_type == normalized_class or normalized_type in normalized_class:
matched_class = cls
break
if matched_class:
try:
# Special handling for OpenAPI plugins
if normalized_type == normalize('openapi') or 'openapi' in normalized_type:
plugin = OpenApiPluginFactory.create_from_config(manifest)
print(f"[SK Loader] Created OpenAPI plugin: {name}")
else:
# Standard plugin instantiation
plugin_instance, instantiation_errors = PluginHealthChecker.create_plugin_safely(
matched_class, manifest, name
)
if plugin_instance is None:
plugin_instance = PluginErrorRecovery.create_fallback_plugin(name, plugin_type)
if plugin_instance is None:
raise Exception(f"Plugin creation failed: {'; '.join(instantiation_errors)}")
plugin = plugin_instance
# Special handling for OpenAPI plugins with dynamic functions
if hasattr(plugin, 'get_kernel_plugin'):
print(f"[SK Loader] Using custom kernel plugin method for: {name}")
kernel_plugin = plugin.get_kernel_plugin(name)
kernel.add_plugin(kernel_plugin)
else:
# Standard plugin registration
kernel.add_plugin(KernelPlugin.from_object(name, plugin, description=description))
print(f"[SK Loader] Successfully loaded agent plugin: {name} (type: {plugin_type})")
log_event(f"[SK Loader] Successfully loaded agent plugin: {name} (type: {plugin_type}) [{mode_label}]",
{"plugin_name": name, "plugin_type": plugin_type}, level=logging.INFO)
except Exception as e:
print(f"[SK Loader] Failed to load agent plugin {name}: {e}")
log_event(f"[SK Loader] Failed to load agent plugin: {name}: {e}",
{"plugin_name": name, "plugin_type": plugin_type, "error": str(e)},
level=logging.ERROR, exceptionTraceback=True)
else:
print(f"[SK Loader] No matching plugin class found for: {name} (type: {plugin_type})")
log_event(f"[SK Loader] No matching plugin class found for: {name} (type: {plugin_type})",
{"plugin_name": name, "plugin_type": plugin_type}, level=logging.WARNING)
except Exception as e:
print(f"[SK Loader] Error loading agent-specific plugins: {e}")
log_event(f"[SK Loader] Error loading agent-specific plugins: {e}", level=logging.ERROR, exceptionTraceback=True)
def _build_mi_token_provider(endpoint):
"""Build a bearer token provider for managed identity auth.
Selects the correct Azure Cognitive Services scope based on whether the
endpoint is in the US Government cloud (.azure.us) or the commercial cloud.
"""
scope = (
"https://cognitiveservices.azure.us/.default"
if ".azure.us" in (endpoint or "")
else "https://cognitiveservices.azure.com/.default"
)
return get_bearer_token_provider(DefaultAzureCredential(), scope)
def load_single_agent_for_kernel(kernel, agent_cfg, settings, context_obj, redis_client=None, mode_label="global"):
"""
DRY helper to load a single agent (default agent) for the kernel.
- context_obj: g (per-user) or builtins (global)
- redis_client: required for per-user mode
- mode_label: 'per-user' or 'global' (for logging)
Returns: kernel, agent_objs // dict (name->agent) or None
"""
print(f"[SK Loader] load_single_agent_for_kernel starting - agent: {agent_cfg.get('name')}, mode: {mode_label}")
log_event(f"[SK Loader] load_single_agent_for_kernel starting - agent: {agent_cfg.get('name')}, mode: {mode_label}", level=logging.INFO)
# Redis is now optional for per-user mode
if mode_label == "per-user":
context_obj.redis_client = redis_client
agent_objs = {}
agent_config = resolve_agent_config(agent_cfg, settings)
agent_type = (agent_config.get("agent_type") or agent_cfg.get("agent_type") or "local").lower()
service_id = f"aoai-chat-{agent_config['name']}"
chat_service = None
apim_enabled = settings.get("enable_gpt_apim", False)
if agent_type == "aifoundry":
foundry_agent = AzureAIFoundryChatCompletionAgent(agent_config, settings)
agent_objs[agent_config["name"]] = foundry_agent
log_event(
f"[SK Loader] Registered Foundry agent: {agent_config['name']} ({mode_label})",
{
"agent_name": agent_config["name"],
"agent_id": agent_config.get("id"),
"is_global": agent_config.get("is_global", False),
},
level=logging.INFO,
)
return kernel, agent_objs
log_event(f"[SK Loader] Agent config resolved for {agent_cfg.get('name')} - endpoint: {bool(agent_config.get('endpoint'))}, key: {bool(agent_config.get('key'))}, deployment: {agent_config.get('deployment')}, max_completion_tokens: {agent_config.get('max_completion_tokens')}", level=logging.INFO)
auth_type = settings.get('azure_openai_gpt_authentication_type', '')
use_managed_identity = (
auth_type == 'managed_identity'
and not apim_enabled
and not agent_config.get("key")
and bool(DefaultAzureCredential)
and not agent_config.get("endpoint_is_user_supplied", False)
)
if AzureChatCompletion and agent_config["endpoint"] and (agent_config["key"] or use_managed_identity) and agent_config["deployment"]:
print(f"[SK Loader] Azure config valid for {agent_config['name']}, creating chat service...")
if apim_enabled:
log_event(
f"[SK Loader] Initializing APIM AzureChatCompletion for agent: {agent_config['name']} ({mode_label})",
{
"aoai_endpoint": agent_config["endpoint"],
"aoai_key": f"{agent_config['key'][:3]}..." if agent_config["key"] else None,
"aoai_deployment": agent_config["deployment"],
"agent_name": agent_config["name"]
},
level=logging.INFO
)
chat_service = AzureChatCompletion(
service_id=service_id,
deployment_name=agent_config["deployment"],
endpoint=agent_config["endpoint"],
api_key=agent_config["key"],
api_version=agent_config["api_version"],
# default_headers={"Ocp-Apim-Subscription-Key": agent_config["key"]}
)
elif use_managed_identity:
log_event(
f"[SK Loader] Initializing Managed Identity AzureChatCompletion for agent: {agent_config['name']} ({mode_label})",
{
"aoai_endpoint": agent_config["endpoint"],
"aoai_deployment": agent_config["deployment"],
"agent_name": agent_config["name"]
},
level=logging.INFO
)
_token_provider = _build_mi_token_provider(agent_config.get("endpoint"))
chat_service = AzureChatCompletion(
service_id=service_id,
deployment_name=agent_config["deployment"],
endpoint=agent_config["endpoint"],
ad_token_provider=_token_provider,
api_version=agent_config["api_version"],
)
else:
log_event(
f"[SK Loader] Initializing GPT Direct AzureChatCompletion for agent: {agent_config['name']} ({mode_label})",
{
"aoai_endpoint": agent_config["endpoint"],
"aoai_key": f"{agent_config['key'][:3]}..." if agent_config["key"] else None,
"aoai_deployment": agent_config["deployment"],
"agent_name": agent_config["name"]
},
level=logging.INFO
)
chat_service = AzureChatCompletion(
service_id=service_id,
deployment_name=agent_config["deployment"],
endpoint=agent_config["endpoint"],
api_key=agent_config["key"],
api_version=agent_config["api_version"],
# default_headers={"Ocp-Apim-Subscription-Key": agent_config["key"]}
)
if agent_config.get('max_completion_tokens', -1) > 0:
print(f"[SK Loader] Using {agent_config['max_completion_tokens']} max_completion_tokens for {agent_config['name']}")
chat_service = set_prompt_settings_for_agent(chat_service, agent_config)
kernel.add_service(chat_service)
log_event(
f"[SK Loader] AOAI chat completion service registered for agent: {agent_config['name']} ({mode_label})",
{
"aoai_endpoint": agent_config["endpoint"],
"aoai_key": f"{agent_config['key'][:3]}..." if agent_config["key"] else None,
"aoai_deployment": agent_config["deployment"],
"agent_name": agent_config["name"],
"apim_enabled": agent_config.get("enable_agent_gpt_apim", False)
},
level=logging.INFO
)
else:
print(f"[SK Loader] Azure config INVALID for {agent_config['name']}:")
print(f" - AzureChatCompletion available: {bool(AzureChatCompletion)}")
print(f" - endpoint: {bool(agent_config.get('endpoint'))}")
print(f" - key: {bool(agent_config.get('key'))}")
print(f" - deployment: {bool(agent_config.get('deployment'))}")
log_event(
f"[SK Loader] AzureChatCompletion or configuration not resolved for agent: {agent_config['name']} ({mode_label})",
{
"agent_name": agent_config["name"],
"aoai_endpoint": agent_config["endpoint"],
"aoai_key": f"{agent_config['key'][:3]}..." if agent_config["key"] else None,
"aoai_deployment": agent_config["deployment"],
},
level=logging.ERROR,
exceptionTraceback=True
)
print(f"[SK Loader] Returning None, None for agent {agent_config['name']} due to invalid config")
return None, None
if LoggingChatCompletionAgent and chat_service:
print(f"[SK Loader] Creating LoggingChatCompletionAgent for {agent_config['name']}...")
# Load agent-specific plugins into the kernel before creating the agent
if agent_config.get("actions_to_load"):
print(f"[SK Loader] Loading agent-specific plugins: {agent_config['actions_to_load']}")
# Determine plugin source based on agent scope
agent_is_global = agent_config.get("is_global", False)
agent_is_group = agent_config.get("is_group", False)
if agent_is_global:
plugin_mode = "global"
elif agent_is_group:
plugin_mode = "group"
else:
plugin_mode = mode_label
resolved_user_id = None if agent_is_global else get_current_user_id()
group_id = agent_config.get("group_id") if agent_is_group else None
print(f"[SK Loader] Agent scope - is_global: {agent_is_global}, is_group: {agent_is_group}, plugin_mode: {plugin_mode}, group_id: {group_id}")
load_agent_specific_plugins(
kernel,
agent_config["actions_to_load"],
settings,
plugin_mode,
user_id=resolved_user_id,
group_id=group_id,
)
try:
kwargs = {
"name": agent_config["name"],
"instructions": agent_config["instructions"],
"kernel": kernel,
"service": chat_service,
"description": agent_config["description"] or agent_config["name"] or "This agent can be assigned to execute tasks and be part of a conversation as a generalist.",
"id": agent_config.get('id') or agent_config.get('name') or f"agent_1",
"display_name": agent_config.get('display_name') or agent_config.get('name') or "agent",
"default_agent": agent_config.get("default_agent", False),
"deployment_name": agent_config["deployment"],
"azure_endpoint": agent_config["endpoint"],
"api_version": agent_config["api_version"],
"function_choice_behavior": FunctionChoiceBehavior.Auto(maximum_auto_invoke_attempts=10)
}
# Don't pass plugins to agent since they're already loaded in kernel
agent_obj = LoggingChatCompletionAgent(**kwargs)
agent_objs[agent_config["name"]] = agent_obj
print(f"[SK Loader] Successfully created agent {agent_config['name']}")
log_event(
f"[SK Loader] ChatCompletionAgent initialized for agent: {agent_config['name']} ({mode_label})",
{
"aoai_endpoint": agent_config["endpoint"],
"aoai_key": f"{agent_config['key'][:3]}..." if agent_config["key"] else None,
"aoai_deployment": agent_config["deployment"],
"agent_name": agent_config["name"],
"max_completion_tokens": agent_config.get("max_completion_tokens", -1),
"agent_type": agent_type,
},
level=logging.INFO
)
except Exception as e:
print(f"[SK Loader] EXCEPTION creating agent {agent_config['name']}: {e}")
log_event(
f"[SK Loader] Failed to initialize ChatCompletionAgent for agent: {agent_config['name']} ({mode_label}): {e}",
{"error": str(e), "agent_name": agent_config["name"]},
level=logging.ERROR,
exceptionTraceback=True
)
print(f"[SK Loader] Returning None, None due to agent creation exception")
return None, None
else:
print(f"[SK Loader] Cannot create agent - LoggingChatCompletionAgent available: {bool(LoggingChatCompletionAgent)}, chat_service available: {bool(chat_service)}")
log_event(
f"[SK Loader] ChatCompletionAgent or AzureChatCompletion not available for agent: {agent_config['name']} ({mode_label})",
{"agent_name": agent_config["name"]},
level=logging.ERROR,
exceptionTraceback=True
)
print(f"[SK Loader] Returning None, None due to missing dependencies")
return None, None
print(f"[SK Loader] load_single_agent_for_kernel completed - returning {len(agent_objs)} agents: {list(agent_objs.keys())}")
log_event(f"[SK Loader] load_single_agent_for_kernel completed - returning {len(agent_objs)} agents: {list(agent_objs.keys())}", level=logging.INFO)
return kernel, agent_objs
def resolve_key_vault_secrets_in_plugins(plugin_manifest, settings):
"""
Resolve any Key Vault secrets in a plugin manifest.
"""
if not isinstance(plugin_manifest, dict):
raise ValueError("Plugin manifest must be a dictionary")
kv_name = settings.get("key_vault_name")
if not kv_name:
raise ValueError("Key Vault name not configured in settings")
def resolve_value(value):
if isinstance(value, str) and validate_secret_name_dynamic(value):
resolved = retrieve_secret_from_key_vault_by_full_name(value)
if resolved:
return resolved
else:
raise ValueError(f"Failed to retrieve secret '{value}' from Key Vault '{kv_name}'")
return value
resolved_manifest = {}
for k, v in plugin_manifest.items():
debug_print(f"[SK Loader] Resolving plugin manifest key: {k} with value type: {type(v)}")
if isinstance(v, str):
resolved_manifest[k] = resolve_value(v)