Skip to content

Commit a8f55e3

Browse files
committed
clean unuse code
1 parent 1ab3b41 commit a8f55e3

File tree

4 files changed

+72
-38
lines changed

4 files changed

+72
-38
lines changed

src/backend/app_config.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from semantic_kernel.kernel import Kernel
1010
from semantic_kernel.contents import ChatHistory
1111
from semantic_kernel.agents.azure_ai.azure_ai_agent import AzureAIAgent
12-
1312
# Load environment variables from .env file
1413
load_dotenv()
1514

@@ -139,6 +138,8 @@ def create_kernel(self):
139138
Returns:
140139
A new Semantic Kernel instance
141140
"""
141+
# Create a new kernel instance without manually configuring OpenAI services
142+
# The agents will be created using Azure AI Agent Project pattern instead
142143
kernel = Kernel()
143144
return kernel
144145

src/backend/app_kernel.py

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import uuid
66
import re
7+
import json
78
from typing import List, Dict, Optional, Any
89

910
# FastAPI imports
@@ -87,7 +88,8 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
8788
"""
8889
Receive the initial input task from the user.
8990
"""
90-
if not rai_success(input_task.description):
91+
# Fix 1: Properly await the async rai_success function
92+
if not await rai_success(input_task.description):
9193
print("RAI failed")
9294

9395
track_event_if_configured(
@@ -113,8 +115,8 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
113115
if not input_task.session_id:
114116
input_task.session_id = str(uuid.uuid4())
115117

116-
# Set user ID from authenticated user
117-
input_task.user_id = user_id
118+
# Fix 2: Don't try to set user_id on InputTask directly since it doesn't have that field
119+
# Instead, include it in the JSON we'll pass to the planner
118120

119121
try:
120122
# Create just the planner agent instead of all agents
@@ -125,8 +127,12 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
125127
user_id=user_id
126128
)
127129

128-
# Use the planner to handle the task - pass input_task_json for compatibility
129-
input_task_json = input_task.json()
130+
# Convert input task to JSON for the kernel function, add user_id here
131+
input_task_data = input_task.model_dump()
132+
input_task_data["user_id"] = user_id
133+
input_task_json = json.dumps(input_task_data)
134+
135+
# Use the planner to handle the task
130136
result = await planner_agent.handle_input_task(
131137
KernelArguments(input_task_json=input_task_json)
132138
)
@@ -151,12 +157,7 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
151157
"description": input_task.description,
152158
}
153159
)
154-
return {
155-
"status": "Error: Failed to create plan",
156-
"session_id": input_task.session_id,
157-
"plan_id": "",
158-
"description": input_task.description,
159-
}
160+
raise HTTPException(status_code=400, detail="Error: Failed to create plan")
160161

161162
# Log custom event for successful input task processing
162163
track_event_if_configured(
@@ -186,16 +187,13 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
186187
"error": str(e),
187188
}
188189
)
189-
return {
190-
"status": f"Error creating plan: {str(e)}",
191-
"session_id": input_task.session_id,
192-
"plan_id": "",
193-
"description": input_task.description,
194-
}
190+
raise HTTPException(status_code=400, detail="Error creating plan")
191+
195192

196193

197194
@app.post("/human_feedback")
198195
async def human_feedback_endpoint(human_feedback: HumanFeedback, request: Request):
196+
199197
"""
200198
Receive human feedback on a step.
201199
@@ -616,7 +614,7 @@ async def get_steps_by_plan(plan_id: str, request: Request) -> List[Step]:
616614
updated_action:
617615
type: string
618616
description: Optional modified action based on feedback
619-
400:
617+
400:
620618
description: Missing or invalid user information
621619
404:
622620
description: Plan or steps not found

src/backend/kernel_agents/agent_factory.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@
2121
from kernel_agents.tech_support_agent import TechSupportAgent
2222
from kernel_agents.procurement_agent import ProcurementAgent
2323
from kernel_agents.product_agent import ProductAgent
24+
from kernel_agents.planner_agent import PlannerAgent # Add PlannerAgent import
2425
from kernel_agents.group_chat_manager import GroupChatManager
2526

2627
from context.cosmos_memory_kernel import CosmosMemoryContext
27-
from azure.ai.projects.models import Agent
28+
2829

2930
logger = logging.getLogger(__name__)
3031

src/backend/kernel_agents/planner_agent.py

Lines changed: 52 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,21 @@ def __init__(
9595
"TechSupportAgent", "GenericAgent"]
9696
self._agent_tools_list = agent_tools_list or []
9797

98-
# Create the planning function
98+
# Create the planning function using prompt_template_config instead of direct string
99+
from semantic_kernel.prompt_template.prompt_template_config import PromptTemplateConfig
100+
101+
# Create a proper prompt template configuration
102+
prompt_config = PromptTemplateConfig(
103+
template=self._system_message,
104+
name="PlannerFunction",
105+
description="Creates and manages execution plans"
106+
)
107+
99108
self._planner_function = KernelFunction.from_prompt(
100109
function_name="PlannerFunction",
101110
plugin_name="planner_plugin",
102-
prompt_template=self._system_message,
103-
description="Creates and manages execution plans"
111+
description="Creates and manages execution plans",
112+
prompt_template_config=prompt_config
104113
)
105114
self._kernel.add_function("planner_plugin", self._planner_function)
106115

@@ -251,8 +260,30 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
251260

252261
# Ask the LLM to generate a structured plan
253262
args = KernelArguments(input=instruction)
254-
result = await self._planner_function.invoke_async(kernel_arguments=args)
255-
response_content = result.value.strip()
263+
264+
# Try different invocation methods based on available API
265+
try:
266+
# Method 1: Try direct invoke method (newer SK versions)
267+
result = await self._kernel.invoke(
268+
self._planner_function,
269+
args
270+
)
271+
except (AttributeError, TypeError) as e:
272+
# Method 2: Try using the kernel to invoke the function by name
273+
logging.debug(f"First invoke method failed: {e}, trying alternative")
274+
result = await self._kernel.invoke_function_async(
275+
"planner_plugin",
276+
"PlannerFunction",
277+
input=instruction
278+
)
279+
280+
# Extract the response content
281+
if hasattr(result, 'value'):
282+
response_content = result.value.strip()
283+
elif isinstance(result, str):
284+
response_content = result.strip()
285+
else:
286+
response_content = str(result).strip()
256287

257288
# Parse the JSON response using the structured output model
258289
try:
@@ -276,11 +307,11 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
276307
summary = parsed_result.summary_plan_and_steps
277308
human_clarification_request = parsed_result.human_clarification_request
278309

279-
# Create the Plan instance
310+
# Create the Plan instance - use self._user_id instead of input_task.user_id
280311
plan = Plan(
281312
id=str(uuid.uuid4()),
282313
session_id=input_task.session_id,
283-
user_id=input_task.user_id,
314+
user_id=self._user_id, # Use the agent's user_id instead
284315
initial_goal=initial_goal,
285316
overall_status=PlanStatus.in_progress,
286317
summary=summary,
@@ -294,7 +325,7 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
294325
"Planner - Initial plan and added into the cosmos",
295326
{
296327
"session_id": input_task.session_id,
297-
"user_id": input_task.user_id,
328+
"user_id": self._user_id, # Use the agent's user_id
298329
"initial_goal": initial_goal,
299330
"overall_status": PlanStatus.in_progress,
300331
"source": "PlannerAgent",
@@ -314,11 +345,12 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
314345
logging.warning(f"Invalid agent name: {agent_name}, defaulting to GenericAgent")
315346
agent_name = "GenericAgent"
316347

317-
# Create the step
348+
# Create the step - use self._user_id instead of input_task.user_id
318349
step = Step(
319350
id=str(uuid.uuid4()),
320351
plan_id=plan.id,
321352
session_id=input_task.session_id,
353+
user_id=self._user_id, # Use the agent's user_id
322354
action=action,
323355
agent=agent_name,
324356
status=StepStatus.planned,
@@ -337,7 +369,7 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
337369
"agent": agent_name,
338370
"status": StepStatus.planned,
339371
"session_id": input_task.session_id,
340-
"user_id": input_task.user_id,
372+
"user_id": self._user_id, # Use the agent's user_id
341373
"human_approval_status": HumanFeedbackStatus.requested,
342374
},
343375
)
@@ -356,19 +388,19 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
356388
f"Planner - Error in create_structured_plan: {e} into the cosmos",
357389
{
358390
"session_id": input_task.session_id,
359-
"user_id": input_task.user_id,
391+
"user_id": self._user_id, # Use the agent's user_id
360392
"initial_goal": "Error generating plan",
361393
"overall_status": PlanStatus.failed,
362394
"source": "PlannerAgent",
363395
"summary": f"Error generating plan: {e}",
364396
},
365397
)
366398

367-
# Create an error plan
399+
# Create an error plan - use self._user_id instead of input_task.user_id
368400
error_plan = Plan(
369401
id=str(uuid.uuid4()),
370402
session_id=input_task.session_id,
371-
user_id=input_task.user_id,
403+
user_id=self._user_id, # Use the agent's user_id
372404
initial_goal="Error generating plan",
373405
overall_status=PlanStatus.failed,
374406
summary=f"Error generating plan: {str(e)}"
@@ -395,7 +427,7 @@ async def _create_plan_from_text(self, input_task: InputTask, text_content: str)
395427
plan = Plan(
396428
id=str(uuid.uuid4()),
397429
session_id=input_task.session_id,
398-
user_id=input_task.user_id,
430+
user_id=self._user_id,
399431
initial_goal=goal,
400432
overall_status=PlanStatus.in_progress
401433
)
@@ -428,6 +460,7 @@ async def _create_plan_from_text(self, input_task: InputTask, text_content: str)
428460
id=str(uuid.uuid4()),
429461
plan_id=plan.id,
430462
session_id=input_task.session_id,
463+
user_id=self._user_id,
431464
action=action,
432465
agent=agent,
433466
status=StepStatus.planned,
@@ -454,6 +487,7 @@ def _generate_instruction(self, objective: str) -> str:
454487
# Create list of available tools
455488
tools_str = "\n".join(self._agent_tools_list) if self._agent_tools_list else "Various specialized tools"
456489

490+
# Use double curly braces to escape them in f-strings
457491
return f"""
458492
You are the Planner, an AI orchestrator that manages a group of AI agents to accomplish tasks.
459493
@@ -496,15 +530,15 @@ def _generate_instruction(self, objective: str) -> str:
496530
Choose from {agents_str} ONLY for planning your steps.
497531
498532
Return your response as a JSON object with the following structure:
499-
{
533+
{{
500534
"initial_goal": "The goal of the plan",
501535
"steps": [
502-
{
536+
{{
503537
"action": "Detailed description of the step action",
504538
"agent": "AgentName"
505-
}
539+
}}
506540
],
507541
"summary_plan_and_steps": "Brief summary of the plan and steps",
508542
"human_clarification_request": "Any additional information needed from the human"
509-
}
543+
}}
510544
"""

0 commit comments

Comments
 (0)