Skip to content

Commit ff36a2a

Browse files
authored
Merge pull request microsoft#158 from Fr4nc3/main
fix: add back telemetry and close project client
2 parents 69860ac + b1805aa commit ff36a2a

File tree

4 files changed

+180
-98
lines changed

4 files changed

+180
-98
lines changed

src/backend/app_kernel.py

Lines changed: 91 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,21 @@
4040
from event_utils import track_event_if_configured
4141
from models.messages_kernel import AgentType
4242
from kernel_agents.agent_factory import AgentFactory
43+
from app_config import config
4344

4445
# # Check if the Application Insights Instrumentation Key is set in the environment variables
45-
# instrumentation_key = os.getenv("APPLICATIONINSIGHTS_INSTRUMENTATION_KEY")
46-
# if instrumentation_key:
47-
# # Configure Application Insights if the Instrumentation Key is found
48-
# configure_azure_monitor(connection_string=instrumentation_key)
49-
# logging.info("Application Insights configured with the provided Instrumentation Key")
50-
# else:
51-
# # Log a warning if the Instrumentation Key is not found
52-
# logging.warning("No Application Insights Instrumentation Key found. Skipping configuration")
46+
instrumentation_key = os.getenv("APPLICATIONINSIGHTS_INSTRUMENTATION_KEY")
47+
if instrumentation_key:
48+
# Configure Application Insights if the Instrumentation Key is found
49+
configure_azure_monitor(connection_string=instrumentation_key)
50+
logging.info(
51+
"Application Insights configured with the provided Instrumentation Key"
52+
)
53+
else:
54+
# Log a warning if the Instrumentation Key is not found
55+
logging.warning(
56+
"No Application Insights Instrumentation Key found. Skipping configuration"
57+
)
5358

5459
# Configure logging
5560
logging.basicConfig(level=logging.INFO)
@@ -61,9 +66,9 @@
6166
logging.getLogger("azure.identity.aio._internal").setLevel(logging.WARNING)
6267

6368
# # Suppress info logs from OpenTelemetry exporter
64-
# logging.getLogger("azure.monitor.opentelemetry.exporter.export._base").setLevel(
65-
# logging.WARNING
66-
# )
69+
logging.getLogger("azure.monitor.opentelemetry.exporter.export._base").setLevel(
70+
logging.WARNING
71+
)
6772

6873
# Initialize the FastAPI app
6974
app = FastAPI()
@@ -124,10 +129,17 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
124129
kernel, memory_store = await initialize_runtime_and_context(
125130
input_task.session_id, user_id
126131
)
132+
client = None
133+
try:
134+
client = config.get_ai_project_client()
135+
except Exception as client_exc:
136+
logging.error(f"Error creating AIProjectClient: {client_exc}")
137+
127138
agents = await AgentFactory.create_all_agents(
128139
session_id=input_task.session_id,
129140
user_id=user_id,
130141
memory_store=memory_store,
142+
client=client,
131143
)
132144

133145
group_chat_manager = agents[AgentType.GROUP_CHAT_MANAGER.value]
@@ -161,7 +173,11 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
161173
"description": input_task.description,
162174
},
163175
)
164-
176+
if client:
177+
try:
178+
client.close()
179+
except Exception as e:
180+
logging.error(f"Error sending to AIProjectClient: {e}")
165181
return {
166182
"status": f"Plan created with ID: {plan.id}",
167183
"session_id": input_task.session_id,
@@ -249,12 +265,31 @@ async def human_feedback_endpoint(human_feedback: HumanFeedback, request: Reques
249265
kernel, memory_store = await initialize_runtime_and_context(
250266
human_feedback.session_id, user_id
251267
)
252-
agents = await AgentFactory.create_all_agents(
253-
session_id=human_feedback.session_id, user_id=user_id, memory_store=memory_store
268+
269+
client = None
270+
try:
271+
client = config.get_ai_project_client()
272+
except Exception as client_exc:
273+
logging.error(f"Error creating AIProjectClient: {client_exc}")
274+
275+
human_agent = await AgentFactory.create_agent(
276+
agent_type=AgentType.HUMAN,
277+
session_id=human_feedback.session_id,
278+
user_id=user_id,
279+
memory_store=memory_store,
280+
client=client,
254281
)
255282

256-
# Send the feedback to the human agent
257-
human_agent = agents[AgentType.HUMAN.value]
283+
if human_agent is None:
284+
track_event_if_configured(
285+
"AgentNotFound",
286+
{
287+
"status": "Agent not found",
288+
"session_id": human_feedback.session_id,
289+
"step_id": human_feedback.step_id,
290+
},
291+
)
292+
raise HTTPException(status_code=404, detail="Agent not found")
258293

259294
# Use the human agent to handle the feedback
260295
await human_agent.handle_human_feedback(human_feedback=human_feedback)
@@ -267,7 +302,11 @@ async def human_feedback_endpoint(human_feedback: HumanFeedback, request: Reques
267302
"step_id": human_feedback.step_id,
268303
},
269304
)
270-
305+
if client:
306+
try:
307+
client.close()
308+
except Exception as e:
309+
logging.error(f"Error sending to AIProjectClient: {e}")
271310
return {
272311
"status": "Feedback received",
273312
"session_id": human_feedback.session_id,
@@ -333,14 +372,30 @@ async def human_clarification_endpoint(
333372
kernel, memory_store = await initialize_runtime_and_context(
334373
human_clarification.session_id, user_id
335374
)
336-
agents = await AgentFactory.create_all_agents(
375+
client = None
376+
try:
377+
client = config.get_ai_project_client()
378+
except Exception as client_exc:
379+
logging.error(f"Error creating AIProjectClient: {client_exc}")
380+
381+
human_agent = await AgentFactory.create_agent(
382+
agent_type=AgentType.HUMAN,
337383
session_id=human_clarification.session_id,
338384
user_id=user_id,
339385
memory_store=memory_store,
386+
client=client,
340387
)
341388

342-
# Send the feedback to the human agent
343-
human_agent = agents[AgentType.HUMAN.value]
389+
if human_agent is None:
390+
track_event_if_configured(
391+
"AgentNotFound",
392+
{
393+
"status": "Agent not found",
394+
"session_id": human_clarification.session_id,
395+
"step_id": human_clarification.step_id,
396+
},
397+
)
398+
raise HTTPException(status_code=404, detail="Agent not found")
344399

345400
# Use the human agent to handle the feedback
346401
await human_agent.handle_human_clarification(
@@ -354,7 +409,11 @@ async def human_clarification_endpoint(
354409
"session_id": human_clarification.session_id,
355410
},
356411
)
357-
412+
if client:
413+
try:
414+
client.close()
415+
except Exception as e:
416+
logging.error(f"Error sending to AIProjectClient: {e}")
358417
return {
359418
"status": "Clarification received",
360419
"session_id": human_clarification.session_id,
@@ -427,17 +486,28 @@ async def approve_step_endpoint(
427486
kernel, memory_store = await initialize_runtime_and_context(
428487
human_feedback.session_id, user_id
429488
)
489+
client = None
490+
try:
491+
client = config.get_ai_project_client()
492+
except Exception as client_exc:
493+
logging.error(f"Error creating AIProjectClient: {client_exc}")
430494
agents = await AgentFactory.create_all_agents(
431495
session_id=human_feedback.session_id,
432496
user_id=user_id,
433497
memory_store=memory_store,
498+
client=client,
434499
)
435500

436501
# Send the approval to the group chat manager
437502
group_chat_manager = agents[AgentType.GROUP_CHAT_MANAGER.value]
438503

439504
await group_chat_manager.handle_human_feedback(human_feedback)
440505

506+
if client:
507+
try:
508+
client.close()
509+
except Exception as e:
510+
logging.error(f"Error sending to AIProjectClient: {e}")
441511
# Return a status message
442512
if human_feedback.step_id:
443513
track_event_if_configured(

src/backend/event_utils.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55

66
def track_event_if_configured(event_name: str, event_data: dict):
77
"""Track an event if Application Insights is configured.
8-
8+
99
This function safely wraps the Azure Monitor track_event function
1010
to handle potential errors with the ProxyLogger.
11-
11+
1212
Args:
1313
event_name: The name of the event to track
1414
event_data: Dictionary of event data/dimensions
@@ -17,8 +17,10 @@ def track_event_if_configured(event_name: str, event_data: dict):
1717
instrumentation_key = os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")
1818
if instrumentation_key:
1919
track_event(event_name, event_data)
20-
# else:
21-
# logging.warning(f"Skipping track_event for {event_name} as Application Insights is not configured")
20+
else:
21+
logging.warning(
22+
f"Skipping track_event for {event_name} as Application Insights is not configured"
23+
)
2224
except AttributeError as e:
2325
# Handle the 'ProxyLogger' object has no attribute 'resource' error
2426
logging.warning(f"ProxyLogger error in track_event: {e}")

src/backend/kernel_agents/agent_factory.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,6 @@ async def create_agent(
158158

159159
# Build the agent definition (functions schema)
160160
definition = None
161-
client = None
162161

163162
try:
164163
if client is None:
@@ -239,6 +238,7 @@ async def create_all_agents(
239238
user_id: str,
240239
temperature: float = 0.0,
241240
memory_store: Optional[CosmosMemoryContext] = None,
241+
client: Optional[Any] = None,
242242
) -> Dict[AgentType, BaseAgent]:
243243
"""Create all agent types for a session in a specific order.
244244
@@ -265,6 +265,13 @@ async def create_all_agents(
265265
planner_agent_type = AgentType.PLANNER
266266
group_chat_manager_type = AgentType.GROUP_CHAT_MANAGER
267267

268+
try:
269+
if client is None:
270+
# Create the AIProjectClient instance using the config
271+
# This is a placeholder; replace with actual client creation logic
272+
client = config.get_ai_project_client()
273+
except Exception as client_exc:
274+
logger.error(f"Error creating AIProjectClient: {client_exc}")
268275
# Initialize cache for this session if it doesn't exist
269276
if session_id not in cls._agent_cache:
270277
cls._agent_cache[session_id] = {}
@@ -280,6 +287,7 @@ async def create_all_agents(
280287
session_id=session_id,
281288
user_id=user_id,
282289
temperature=temperature,
290+
client=client,
283291
memory_store=memory_store,
284292
)
285293

@@ -305,6 +313,7 @@ async def create_all_agents(
305313
user_id=user_id,
306314
temperature=temperature,
307315
agent_instances=agent_instances, # Pass agent instances to the planner
316+
client=client,
308317
response_format=ResponseFormatJsonSchemaType(
309318
json_schema=ResponseFormatJsonSchema(
310319
name=PlannerResponsePlan.__name__,
@@ -324,6 +333,7 @@ async def create_all_agents(
324333
session_id=session_id,
325334
user_id=user_id,
326335
temperature=temperature,
336+
client=client,
327337
agent_instances=agent_instances, # Pass agent instances to the planner
328338
)
329339
agents[group_chat_manager_type] = group_chat_manager

0 commit comments

Comments
 (0)