Skip to content

A programming framework for agentic AI

Fix: Azure AI Search Tool Client Lifetime Management (#6316)

Jay Prakash Thakurbb792b07342a
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/azure/_ai_search.py b/python/packages/autogen-ext/src/autogen_ext/tools/azure/_ai_search.py
index ec12a16ca..07da00e1b 100644
--- a/python/packages/autogen-ext/src/autogen_ext/tools/azure/_ai_search.py
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/azure/_ai_search.py
@@ -241,6 +241,12 @@ class BaseAzureAISearchTool(BaseTool[SearchQuery, SearchResults], ABC):
self._client: Optional[SearchClient] = None
self._cache: Dict[str, Dict[str, Any]] = {}
+ async def close(self) -> None:
+ """Explicitly close the Azure SearchClient if needed (for cleanup in long-running apps/tests)."""
+ if self._client is not None:
+ await self._client.close()
+ self._client = None
+
def _process_credential(
self, credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]]
) -> Union[AzureKeyCredential, TokenCredential]:
@@ -362,61 +368,62 @@ class BaseAzureAISearchTool(BaseTool[SearchQuery, SearchResults], ABC):
client = await self._get_client()
results: List[SearchResult] = []
- async with client:
- search_future = client.search(text_query, **search_options) # type: ignore
-
- if cancellation_token is not None:
- import asyncio
-
- # Using explicit type ignores to handle Azure SDK type complexity
- async def awaitable_wrapper(): # type: ignore # pyright: ignore[reportUnknownVariableType,reportUnknownLambdaType,reportUnknownMemberType]
- return await search_future # pyright: ignore[reportUnknownVariableType]
-
- task = asyncio.create_task(awaitable_wrapper()) # type: ignore # pyright: ignore[reportUnknownVariableType]
- cancellation_token.link_future(task) # pyright: ignore[reportUnknownArgumentType]
- search_results = await task # pyright: ignore[reportUnknownVariableType]
- else:
- search_results = await search_future # pyright: ignore[reportUnknownVariableType]
-
- async for doc in search_results: # type: ignore
- search_doc: Any = doc
- doc_dict: Dict[str, Any] = {}
-
- try:
- if hasattr(search_doc, "items") and callable(search_doc.items):
- dict_like_doc = cast(Dict[str, Any], search_doc)
- for key, value in dict_like_doc.items():
- doc_dict[str(key)] = value
- else:
- for key in [
- k
- for k in dir(search_doc)
- if not k.startswith("_") and not callable(getattr(search_doc, k, None))
- ]:
- doc_dict[key] = getattr(search_doc, key)
- except Exception as e:
- logger.warning(f"Error processing search document: {e}")
- continue
-
- metadata: Dict[str, Any] = {}
- content: Dict[str, Any] = {}
- for key, value in doc_dict.items():
- key_str: str = str(key)
- if key_str.startswith("@") or key_str.startswith("_"):
- metadata[key_str] = value
- else:
- content[key_str] = value
-
- score: float = 0.0
- if "@search.score" in doc_dict:
- score = float(doc_dict["@search.score"])
-
- result = SearchResult(
- score=score,
- content=content,
- metadata=metadata,
- )
- results.append(result)
+ # Use the persistent client directly. Do NOT close after each operation.
+ # WARNING: The SearchClient must live as long as the tool/agent is in use.
+ search_future = client.search(text_query, **search_options) # type: ignore
+
+ if cancellation_token is not None:
+ import asyncio
+
+ # Using explicit type ignores to handle Azure SDK type complexity
+ async def awaitable_wrapper(): # type: ignore # pyright: ignore[reportUnknownVariableType,reportUnknownLambdaType,reportUnknownMemberType]
+ return await search_future # pyright: ignore[reportUnknownVariableType]
+
+ task = asyncio.create_task(awaitable_wrapper()) # type: ignore # pyright: ignore[reportUnknownVariableType]
+ cancellation_token.link_future(task) # pyright: ignore[reportUnknownArgumentType]
+ search_results = await task # pyright: ignore[reportUnknownVariableType]
+ else:
+ search_results = await search_future # pyright: ignore[reportUnknownVariableType]
+
+ async for doc in search_results: # type: ignore
+ search_doc: Any = doc
+ doc_dict: Dict[str, Any] = {}
+
+ try:
+ if hasattr(search_doc, "items") and callable(search_doc.items):
+ dict_like_doc = cast(Dict[str, Any], search_doc)
+ for key, value in dict_like_doc.items():
+ doc_dict[str(key)] = value
+ else:
+ for key in [
+ k
+ for k in dir(search_doc)
+ if not k.startswith("_") and not callable(getattr(search_doc, k, None))
+ ]:
+ doc_dict[key] = getattr(search_doc, key)
+ except Exception as e:
+ logger.warning(f"Error processing search document: {e}")
+ continue
+
+ metadata: Dict[str, Any] = {}
+ content: Dict[str, Any] = {}
+ for key, value in doc_dict.items():
+ key_str: str = str(key)
+ if key_str.startswith("@") or key_str.startswith("_"):
+ metadata[key_str] = value
+ else:
+ content[key_str] = value
+
+ score: float = 0.0
+ if "@search.score" in doc_dict:
+ score = float(doc_dict["@search.score"])
+
+ result = SearchResult(
+ score=score,
+ content=content,
+ metadata=metadata,
+ )
+ results.append(result)
if self.search_config.enable_caching:
cache_key = f"{text_query}_{self.search_config.top}"