Skip to content

Commit d4b4efa

Browse files
committed
Merge remote-tracking branch 'upstream/feature/use-sk-threads-for-agent-comms'
2 parents 3bb2512 + 4888ff8 commit d4b4efa

File tree

10 files changed

+57
-32
lines changed

10 files changed

+57
-32
lines changed

src/backend/app_config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from azure.cosmos.aio import CosmosClient
88
from azure.identity import ClientSecretCredential, DefaultAzureCredential
99
from dotenv import load_dotenv
10+
from semantic_kernel.agents import AzureAIAgentThread # pylint:disable=E0611
1011
from semantic_kernel.agents.azure_ai.azure_ai_agent import AzureAIAgent
1112
from semantic_kernel.contents import ChatHistory
1213
from semantic_kernel.functions import KernelFunction

src/backend/kernel_agents/agent_base.py

Lines changed: 15 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from event_utils import track_event_if_configured
1313
from models.messages_kernel import (ActionRequest, ActionResponse,
1414
AgentMessage, Step, StepStatus)
15+
from semantic_kernel.agents import AzureAIAgentThread # pylint:disable=E0611
1516
from semantic_kernel.agents.azure_ai.azure_ai_agent import AzureAIAgent
1617
from semantic_kernel.functions import KernelFunction
1718
from semantic_kernel.functions.kernel_arguments import KernelArguments
@@ -34,6 +35,7 @@ def __init__(
3435
system_message: Optional[str] = None,
3536
client=None,
3637
definition=None,
38+
thread: AzureAIAgentThread=None,
3739
):
3840
"""Initialize the base agent.
3941
@@ -74,19 +76,12 @@ def __init__(
7476
self._tools = tools
7577
self._system_message = system_message
7678
self._chat_history = [{"role": "system", "content": self._system_message}]
77-
# self._agent = None # Will be initialized in async_init
79+
self._message = None # Will be initialized in handle_action_request
80+
self._thread = thread
7881

7982
# Required properties for AgentGroupChat compatibility
8083
self.name = agent_name # This is crucial for AgentGroupChat to identify agents
8184

82-
# @property
83-
# def plugins(self) -> Optional[dict[str, Callable]]:
84-
# """Get the plugins for this agent.
85-
86-
# Returns:
87-
# A list of plugins, or None if not applicable.
88-
# """
89-
# return None
9085
@staticmethod
9186
def default_system_message(agent_name=None) -> str:
9287
name = agent_name
@@ -114,32 +109,17 @@ async def handle_action_request(self, action_request: ActionRequest) -> str:
114109
status=StepStatus.failed,
115110
message="Step not found in memory.",
116111
)
117-
return response.json()
112+
return response.model_dump_json()
118113

119-
# Add messages to chat history for context
120-
# This gives the agent visibility of the conversation history
121-
self._chat_history.extend(
122-
[
123-
{"role": "assistant", "content": action_request.action},
124-
{
125-
"role": "user",
126-
"content": f"{step.human_feedback}. Now make the function call",
127-
},
128-
]
129-
)
114+
self._message = [
115+
action_request.action
116+
]
130117

131118
try:
132-
# Use the agent to process the action
133-
# chat_history = self._chat_history.copy()
134-
135-
# Call the agent to handle the action
136-
thread = None
137-
# thread = self.client.agents.get_thread(
138-
# thread=step.session_id
139-
# ) # AzureAIAgentThread(thread_id=step.session_id)
119+
# Use the agent to process the action request
140120
async_generator = self.invoke(
141-
messages=f"{str(self._chat_history)}\n\nPlease perform this action",
142-
thread=thread,
121+
messages=self._message,
122+
thread=self._thread,
143123
)
144124

145125
response_content = ""
@@ -149,6 +129,10 @@ async def handle_action_request(self, action_request: ActionRequest) -> str:
149129
if chunk is not None:
150130
response_content += str(chunk)
151131

132+
# Log the messages in the thread
133+
# async for msg in self._thread.get_messages():
134+
# logging.info(f"thread messages - role:{msg.role} - content:{msg.content}")
135+
152136
logging.info(f"Response content length: {len(response_content)}")
153137
logging.info(f"Response content: {response_content}")
154138

src/backend/kernel_agents/agent_factory.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ class AgentFactory:
7777
# Cache of agent instances by session_id and agent_type
7878
_agent_cache: Dict[str, Dict[AgentType, BaseAgent]] = {}
7979

80+
# Cache of threads
81+
_thread_cache: Dict[str, AzureAIAgentThread] = {}
82+
8083
# Cache of Azure AI Agent instances
8184
_azure_ai_agent_cache: Dict[str, Dict[str, AzureAIAgent]] = {}
8285

@@ -91,6 +94,7 @@ async def create_agent(
9194
system_message: Optional[str] = None,
9295
response_format: Optional[Any] = None,
9396
client: Optional[Any] = None,
97+
thread: Optional[AzureAIAgentThread] = None,
9498
**kwargs,
9599
) -> BaseAgent:
96100
"""Create an agent of the specified type.
@@ -168,6 +172,7 @@ async def create_agent(
168172
"tools": tools,
169173
"system_message": system_message,
170174
"client": client,
175+
"thread": thread,
171176
**kwargs,
172177
}.items()
173178
if k in valid_keys
@@ -222,14 +227,20 @@ async def create_all_agents(
222227
planner_agent_type = AgentType.PLANNER
223228
group_chat_manager_type = AgentType.GROUP_CHAT_MANAGER
224229

230+
if cls._thread_cache is None or session_id not in cls._thread_cache:
231+
#Create thread for agent conversation
232+
thread = AzureAIAgentThread(client=client)
233+
cls._thread_cache[session_id] = thread
234+
225235
try:
226236
if client is None:
227237
# Create the AIProjectClient instance using the config
228238
# This is a placeholder; replace with actual client creation logic
229239
client = config.get_ai_project_client()
230240
except Exception as client_exc:
231241
logger.error(f"Error creating AIProjectClient: {client_exc}")
232-
# Initialize cache for this session if it doesn't exist
242+
243+
# Initialize agent cache for this session if it doesn't exist
233244
if session_id not in cls._agent_cache:
234245
cls._agent_cache[session_id] = {}
235246

@@ -246,6 +257,7 @@ async def create_all_agents(
246257
temperature=temperature,
247258
client=client,
248259
memory_store=memory_store,
260+
thread=cls._thread_cache[session_id],
249261
)
250262

251263
# Create agent name to instance mapping for the planner

src/backend/kernel_agents/generic_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ def __init__(
2222
agent_name: str = AgentType.GENERIC.value,
2323
client=None,
2424
definition=None,
25+
thread=None,
2526
) -> None:
2627
"""Initialize the Generic Agent.
2728
@@ -60,6 +61,7 @@ def __init__(
6061
system_message=system_message,
6162
client=client,
6263
definition=definition,
64+
thread=thread,
6365
)
6466

6567
@classmethod
@@ -82,6 +84,7 @@ async def create(
8284
system_message = kwargs.get("system_message", None)
8385
agent_name = kwargs.get("agent_name")
8486
client = kwargs.get("client")
87+
thread = kwargs.get("thread")
8588

8689
try:
8790
logging.info("Initializing GenericAgent from async init azure AI Agent")
@@ -102,6 +105,7 @@ async def create(
102105
system_message=system_message,
103106
agent_name=agent_name,
104107
client=client,
108+
thread=thread,
105109
definition=agent_definition,
106110
)
107111

src/backend/kernel_agents/hr_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def __init__(
2626
agent_name: str = AgentType.HR.value,
2727
client=None,
2828
definition=None,
29+
thread=None,
2930
) -> None:
3031
"""Initialize the HR Agent.
3132
@@ -62,6 +63,7 @@ def __init__(
6263
system_message=system_message,
6364
client=client,
6465
definition=definition,
66+
thread=thread,
6567
)
6668

6769
@classmethod
@@ -84,6 +86,7 @@ async def create(
8486
system_message = kwargs.get("system_message", None)
8587
agent_name = kwargs.get("agent_name")
8688
client = kwargs.get("client")
89+
thread = kwargs.get("thread")
8790

8891
try:
8992
logging.info("Initializing HRAgent from async init azure AI Agent")
@@ -104,6 +107,7 @@ async def create(
104107
system_message=system_message,
105108
agent_name=agent_name,
106109
client=client,
110+
thread=thread,
107111
definition=agent_definition,
108112
)
109113

src/backend/kernel_agents/human_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def __init__(
2828
agent_name: str = AgentType.HUMAN.value,
2929
client=None,
3030
definition=None,
31+
thread=None,
3132
) -> None:
3233
"""Initialize the Human Agent.
3334
@@ -59,6 +60,7 @@ def __init__(
5960
system_message=system_message,
6061
client=client,
6162
definition=definition,
63+
thread=thread,
6264
)
6365

6466
@classmethod
@@ -81,6 +83,7 @@ async def create(
8183
system_message = kwargs.get("system_message", None)
8284
agent_name = kwargs.get("agent_name")
8385
client = kwargs.get("client")
86+
thread = kwargs.get("thread")
8487

8588
try:
8689
logging.info("Initializing HumanAgent from async init azure AI Agent")
@@ -101,6 +104,7 @@ async def create(
101104
system_message=system_message,
102105
agent_name=agent_name,
103106
client=client,
107+
thread=thread,
104108
definition=agent_definition,
105109
)
106110

src/backend/kernel_agents/marketing_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def __init__(
2525
agent_name: str = AgentType.MARKETING.value,
2626
client=None,
2727
definition=None,
28+
thread=None,
2829
) -> None:
2930
"""Initialize the Marketing Agent.
3031
@@ -61,6 +62,7 @@ def __init__(
6162
system_message=system_message,
6263
client=client,
6364
definition=definition,
65+
thread=thread,
6466
)
6567

6668
@classmethod
@@ -83,6 +85,7 @@ async def create(
8385
system_message = kwargs.get("system_message", None)
8486
agent_name = kwargs.get("agent_name")
8587
client = kwargs.get("client")
88+
thread = kwargs.get("thread")
8689

8790
try:
8891
logging.info("Initializing MarketingAgent from async init azure AI Agent")
@@ -103,6 +106,7 @@ async def create(
103106
system_message=system_message,
104107
agent_name=agent_name,
105108
client=client,
109+
thread=thread,
106110
definition=agent_definition,
107111
)
108112

src/backend/kernel_agents/procurement_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def __init__(
2525
agent_name: str = AgentType.PROCUREMENT.value,
2626
client=None,
2727
definition=None,
28+
thread=None,
2829
) -> None:
2930
"""Initialize the Procurement Agent.
3031
@@ -61,6 +62,7 @@ def __init__(
6162
system_message=system_message,
6263
client=client,
6364
definition=definition,
65+
thread=thread,
6466
)
6567

6668
@classmethod
@@ -83,6 +85,7 @@ async def create(
8385
system_message = kwargs.get("system_message", None)
8486
agent_name = kwargs.get("agent_name")
8587
client = kwargs.get("client")
88+
thread = kwargs.get("thread")
8689

8790
try:
8891
logging.info("Initializing ProcurementAgent from async init azure AI Agent")
@@ -103,6 +106,7 @@ async def create(
103106
system_message=system_message,
104107
agent_name=agent_name,
105108
client=client,
109+
thread=thread,
106110
definition=agent_definition,
107111
)
108112

src/backend/kernel_agents/product_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def __init__(
2828
agent_name: str = AgentType.PRODUCT.value,
2929
client=None,
3030
definition=None,
31+
thread=None,
3132
) -> None:
3233
"""Initialize the Product Agent.
3334
@@ -65,6 +66,7 @@ def __init__(
6566
system_message=system_message,
6667
client=client,
6768
definition=definition,
69+
thread=thread,
6870
)
6971

7072
@classmethod
@@ -87,6 +89,7 @@ async def create(
8789
system_message = kwargs.get("system_message", None)
8890
agent_name = kwargs.get("agent_name")
8991
client = kwargs.get("client")
92+
thread = kwargs.get("thread")
9093

9194
try:
9295
logging.info("Initializing ProductAgent from async init azure AI Agent")
@@ -107,6 +110,7 @@ async def create(
107110
system_message=system_message,
108111
agent_name=agent_name,
109112
client=client,
113+
thread=thread,
110114
definition=agent_definition,
111115
)
112116

src/backend/kernel_agents/tech_support_agent.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ def __init__(
2525
agent_name: str = AgentType.TECH_SUPPORT.value,
2626
client=None,
2727
definition=None,
28+
thread=None,
2829
) -> None:
2930
"""Initialize the Tech Support Agent.
3031
@@ -62,6 +63,7 @@ def __init__(
6263
system_message=system_message,
6364
client=client,
6465
definition=definition,
66+
thread=thread,
6567
)
6668

6769
@classmethod
@@ -84,6 +86,7 @@ async def create(
8486
system_message = kwargs.get("system_message", None)
8587
agent_name = kwargs.get("agent_name")
8688
client = kwargs.get("client")
89+
thread = kwargs.get("thread")
8790

8891
try:
8992
logging.info("Initializing TechSupportAgent from async init azure AI Agent")
@@ -104,6 +107,7 @@ async def create(
104107
system_message=system_message,
105108
agent_name=agent_name,
106109
client=client,
110+
thread=thread,
107111
definition=agent_definition,
108112
)
109113

0 commit comments

Comments
 (0)