Skip to content

Commit 25bf29f

Browse files
fix: Dynamic Agent Naming and Thread-Safe Deletion for Agent Factories
2 parents 411a26a + 5e250fa commit 25bf29f

File tree

5 files changed

+29
-18
lines changed

5 files changed

+29
-18
lines changed

infra/main.bicep

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ module backend_docker 'deploy_backend_docker.bicep' = {
252252
DISPLAY_CHART_DEFAULT: 'False'
253253
APPLICATIONINSIGHTS_CONNECTION_STRING: aifoundry.outputs.applicationInsightsConnectionString
254254
DUMMY_TEST: 'True'
255+
SOLUTION_NAME: solutionPrefix
255256
}
256257
}
257258
scope: resourceGroup(resourceGroup().name)

infra/main.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"_generator": {
66
"name": "bicep",
77
"version": "0.36.1.42791",
8-
"templateHash": "373408339880701879"
8+
"templateHash": "1377300534086071379"
99
}
1010
},
1111
"parameters": {
@@ -2694,7 +2694,8 @@
26942694
"USE_AI_PROJECT_CLIENT": "True",
26952695
"DISPLAY_CHART_DEFAULT": "False",
26962696
"APPLICATIONINSIGHTS_CONNECTION_STRING": "[reference(extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, resourceGroup().name), 'Microsoft.Resources/deployments', 'deploy_ai_foundry'), '2022-09-01').outputs.applicationInsightsConnectionString.value]",
2697-
"DUMMY_TEST": "True"
2697+
"DUMMY_TEST": "True",
2698+
"SOLUTION_NAME": "[variables('solutionPrefix')]"
26982699
}
26992700
}
27002701
},

src/api/agents/conversation_agent_factory.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
from plugins.chat_with_data_plugin import ChatWithDataPlugin
88
from services.chat_service import ChatService
99

10+
from common.config.config import Config
11+
1012

1113
class ConversationAgentFactory:
1214
_lock = asyncio.Lock()
@@ -16,11 +18,13 @@ class ConversationAgentFactory:
1618
async def get_agent(cls) -> AzureAIAgent:
1719
async with cls._lock:
1820
if cls._agent is None:
21+
config = Config()
22+
solution_name = config.solution_name
1923
ai_agent_settings = AzureAIAgentSettings()
2024
creds = DefaultAzureCredential()
2125
client = AzureAIAgent.create_client(credential=creds, endpoint=ai_agent_settings.endpoint)
2226

23-
agent_name = "KM-ConversationKnowledgeAgent"
27+
agent_name = f"KM-ConversationKnowledgeAgent-{solution_name}"
2428
agent_instructions = '''You are a helpful assistant.
2529
Always return the citations as is in final response.
2630
Always return citation markers exactly as they appear in the source data, placed in the "answer" field at the correct location. Do not modify, convert, or simplify these markers.
@@ -48,14 +52,15 @@ async def get_agent(cls) -> AzureAIAgent:
4852

4953
@classmethod
5054
async def delete_agent(cls):
51-
if cls._agent is not None:
52-
thread_cache = getattr(ChatService, "thread_cache", None)
53-
if thread_cache is not None:
54-
for conversation_id, thread_id in list(thread_cache.items()):
55-
try:
56-
thread = AzureAIAgentThread(client=cls._agent.client, thread_id=thread_id)
57-
await thread.delete()
58-
except Exception as e:
59-
print(f"Failed to delete thread {thread_id} for conversation {conversation_id}: {e}", flush=True)
60-
await cls._agent.client.agents.delete_agent(cls._agent.id)
61-
cls._agent = None
55+
async with cls._lock:
56+
if cls._agent is not None:
57+
thread_cache = getattr(ChatService, "thread_cache", None)
58+
if thread_cache is not None:
59+
for conversation_id, thread_id in list(thread_cache.items()):
60+
try:
61+
thread = AzureAIAgentThread(client=cls._agent.client, thread_id=thread_id)
62+
await thread.delete()
63+
except Exception as e:
64+
print(f"Failed to delete thread {thread_id} for conversation {conversation_id}: {e}", flush=True)
65+
await cls._agent.client.agents.delete_agent(cls._agent.id)
66+
cls._agent = None

src/api/agents/search_agent_factory.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ async def get_agent(cls) -> dict:
2121
azure_ai_search_connection_name = config.azure_ai_search_connection_name
2222
azure_ai_search_index_name = config.azure_ai_search_index
2323
deployment_model = config.azure_openai_deployment_model
24+
solution_name = config.solution_name
2425

2526
field_mapping = {
2627
"contentFields": ["content"],
@@ -56,7 +57,7 @@ async def get_agent(cls) -> dict:
5657

5758
agent = project_client.agents.create_agent(
5859
model=deployment_model,
59-
name="KM-ChatWithCallTranscriptsAgent",
60+
name=f"KM-ChatWithCallTranscriptsAgent-{solution_name}",
6061
instructions="You are a helpful agent. Use the tools provided and always cite your sources.",
6162
tools=ai_search.definitions,
6263
tool_resources=ai_search.resources,
@@ -70,6 +71,7 @@ async def get_agent(cls) -> dict:
7071

7172
@classmethod
7273
async def delete_agent(cls):
73-
if cls._agent is not None:
74-
cls._agent["client"].agents.delete_agent(cls._agent["agent"].id)
75-
cls._agent = None
74+
async with cls._lock:
75+
if cls._agent is not None:
76+
cls._agent["client"].agents.delete_agent(cls._agent["agent"].id)
77+
cls._agent = None

src/api/common/config/config.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,5 @@ def __init__(self):
4141
self.azure_cosmosdb_account = os.getenv("AZURE_COSMOSDB_ACCOUNT")
4242
self.azure_cosmosdb_conversations_container = os.getenv("AZURE_COSMOSDB_CONVERSATIONS_CONTAINER")
4343
self.azure_cosmosdb_enable_feedback = os.getenv("AZURE_COSMOSDB_ENABLE_FEEDBACK", "false").lower() == "true"
44+
45+
self.solution_name = os.getenv("SOLUTION_NAME", "")

0 commit comments

Comments
 (0)