Skip to content

Commit 2412026

Browse files
committed
fixing agent creating
1 parent a8f55e3 commit 2412026

File tree

2 files changed

+49
-80
lines changed

2 files changed

+49
-80
lines changed

src/backend/app_config.py

Lines changed: 3 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -237,34 +237,9 @@ async def create_azure_ai_agent(
237237
"kernel": kernel
238238
}
239239

240-
# Special case for PlannerAgent which doesn't accept agent_name parameter
241-
if agent_name == "PlannerAgent":
242-
# Import the PlannerAgent class dynamically to avoid circular imports
243-
from kernel_agents.planner_agent import PlannerAgent
244-
245-
# Import CosmosMemoryContext dynamically to avoid circular imports
246-
from context.cosmos_memory_kernel import CosmosMemoryContext
247-
248-
# Create a memory store for the agent
249-
memory_store = CosmosMemoryContext(
250-
session_id="default",
251-
user_id="system",
252-
cosmos_container=self.COSMOSDB_CONTAINER,
253-
cosmos_endpoint=self.COSMOSDB_ENDPOINT,
254-
cosmos_database=self.COSMOSDB_DATABASE
255-
)
256-
257-
# Create PlannerAgent with the correct parameters
258-
agent = PlannerAgent(
259-
kernel=kernel,
260-
session_id="default",
261-
user_id="system",
262-
memory_store=memory_store,
263-
# PlannerAgent doesn't need agent_name
264-
)
265-
else:
266-
# For other agents, create using standard AzureAIAgent
267-
agent = AzureAIAgent(**agent_kwargs)
240+
241+
# For other agents, create using standard AzureAIAgent
242+
agent = AzureAIAgent(**agent_kwargs)
268243

269244
# Register the kernel functions with the agent if any were provided
270245
if kernel_functions:

src/backend/kernel_agents/planner_agent.py

Lines changed: 46 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import semantic_kernel as sk
99
from semantic_kernel.functions import KernelFunction
1010
from semantic_kernel.functions.kernel_arguments import KernelArguments
11+
from semantic_kernel.agents.azure_ai.azure_ai_agent import AzureAIAgent
1112

1213
from kernel_agents.agent_base import BaseAgent
1314
from context.cosmos_memory_kernel import CosmosMemoryContext
@@ -21,6 +22,7 @@
2122
HumanFeedbackStatus,
2223
)
2324
from event_utils import track_event_if_configured
25+
from app_config import config
2426

2527
# Define structured output models
2628
class StructuredOutputStep(BaseModel):
@@ -95,23 +97,31 @@ def __init__(
9597
"TechSupportAgent", "GenericAgent"]
9698
self._agent_tools_list = agent_tools_list or []
9799

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+
# Create the Azure AI Agent for planning operations
101+
# This will be initialized in async_init
102+
self._azure_ai_agent = None
100103

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-
)
104+
async def async_init(self) -> None:
105+
"""Asynchronously initialize the PlannerAgent.
107106
108-
self._planner_function = KernelFunction.from_prompt(
109-
function_name="PlannerFunction",
110-
plugin_name="planner_plugin",
111-
description="Creates and manages execution plans",
112-
prompt_template_config=prompt_config
113-
)
114-
self._kernel.add_function("planner_plugin", self._planner_function)
107+
Creates the Azure AI Agent for planning operations.
108+
109+
Returns:
110+
None
111+
"""
112+
try:
113+
# Create the Azure AI Agent using AppConfig
114+
self._azure_ai_agent = await config.create_azure_ai_agent(
115+
kernel=self._kernel,
116+
agent_name="PlannerAgent",
117+
instructions=self._generate_instruction(""),
118+
temperature=0.0
119+
)
120+
logging.info("Successfully created Azure AI Agent for PlannerAgent")
121+
return True
122+
except Exception as e:
123+
logging.error(f"Failed to create Azure AI Agent for PlannerAgent: {e}")
124+
raise
115125

116126
async def handle_input_task(self, kernel_arguments: KernelArguments) -> str:
117127
"""Handle the initial input task from the user.
@@ -258,32 +268,17 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
258268
# Generate the instruction for the LLM
259269
instruction = self._generate_instruction(input_task.description)
260270

261-
# Ask the LLM to generate a structured plan
262-
args = KernelArguments(input=instruction)
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-
)
271+
# Use the Azure AI Agent instead of direct function invocation
272+
if self._azure_ai_agent is None:
273+
# Initialize the agent if it's not already done
274+
await self.async_init()
275+
276+
if self._azure_ai_agent is None:
277+
raise RuntimeError("Failed to initialize Azure AI Agent for planning")
279278

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()
279+
# Get response from the Azure AI Agent
280+
response = await self._azure_ai_agent.invoke_async(instruction)
281+
response_content = str(response).strip()
287282

288283
# Parse the JSON response using the structured output model
289284
try:
@@ -307,11 +302,11 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
307302
summary = parsed_result.summary_plan_and_steps
308303
human_clarification_request = parsed_result.human_clarification_request
309304

310-
# Create the Plan instance - use self._user_id instead of input_task.user_id
305+
# Create the Plan instance
311306
plan = Plan(
312307
id=str(uuid.uuid4()),
313308
session_id=input_task.session_id,
314-
user_id=self._user_id, # Use the agent's user_id instead
309+
user_id=self._user_id,
315310
initial_goal=initial_goal,
316311
overall_status=PlanStatus.in_progress,
317312
summary=summary,
@@ -325,7 +320,7 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
325320
"Planner - Initial plan and added into the cosmos",
326321
{
327322
"session_id": input_task.session_id,
328-
"user_id": self._user_id, # Use the agent's user_id
323+
"user_id": self._user_id,
329324
"initial_goal": initial_goal,
330325
"overall_status": PlanStatus.in_progress,
331326
"source": "PlannerAgent",
@@ -345,12 +340,12 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
345340
logging.warning(f"Invalid agent name: {agent_name}, defaulting to GenericAgent")
346341
agent_name = "GenericAgent"
347342

348-
# Create the step - use self._user_id instead of input_task.user_id
343+
# Create the step
349344
step = Step(
350345
id=str(uuid.uuid4()),
351346
plan_id=plan.id,
352347
session_id=input_task.session_id,
353-
user_id=self._user_id, # Use the agent's user_id
348+
user_id=self._user_id,
354349
action=action,
355350
agent=agent_name,
356351
status=StepStatus.planned,
@@ -369,7 +364,7 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
369364
"agent": agent_name,
370365
"status": StepStatus.planned,
371366
"session_id": input_task.session_id,
372-
"user_id": self._user_id, # Use the agent's user_id
367+
"user_id": self._user_id,
373368
"human_approval_status": HumanFeedbackStatus.requested,
374369
},
375370
)
@@ -388,19 +383,19 @@ async def _create_structured_plan(self, input_task: InputTask) -> Tuple[Plan, Li
388383
f"Planner - Error in create_structured_plan: {e} into the cosmos",
389384
{
390385
"session_id": input_task.session_id,
391-
"user_id": self._user_id, # Use the agent's user_id
386+
"user_id": self._user_id,
392387
"initial_goal": "Error generating plan",
393388
"overall_status": PlanStatus.failed,
394389
"source": "PlannerAgent",
395390
"summary": f"Error generating plan: {e}",
396391
},
397392
)
398393

399-
# Create an error plan - use self._user_id instead of input_task.user_id
394+
# Create an error plan
400395
error_plan = Plan(
401396
id=str(uuid.uuid4()),
402397
session_id=input_task.session_id,
403-
user_id=self._user_id, # Use the agent's user_id
398+
user_id=self._user_id,
404399
initial_goal="Error generating plan",
405400
overall_status=PlanStatus.failed,
406401
summary=f"Error generating plan: {str(e)}"
@@ -496,9 +491,8 @@ def _generate_instruction(self, objective: str) -> str:
496491
The result of the final step should be the final answer. Make sure that each step has all the information needed - do not skip steps.
497492
498493
These actions are passed to the specific agent. Make sure the action contains all the information required for the agent to execute the task.
499-
500-
Your objective is:
501-
{objective}
494+
495+
{f"Your objective is:\\n{objective}" if objective else "When given an objective, analyze it and create a plan to accomplish it."}
502496
503497
The agents you have access to are:
504498
{agents_str}

0 commit comments

Comments
 (0)