A programming framework for agentic AI
Add Azure AI Search tool implementation (#5844)
Jay Prakash Thakur0d9b574d092f
diff --git a/python/packages/autogen-core/docs/src/reference/index.md b/python/packages/autogen-core/docs/src/reference/index.mdindex d498a60fc..e0aecafb4 100644--- a/python/packages/autogen-core/docs/src/reference/index.md+++ b/python/packages/autogen-core/docs/src/reference/index.md@@ -55,6 +55,7 @@ python/autogen_ext.models.anthropicpython/autogen_ext.models.semantic_kernelpython/autogen_ext.models.ollamapython/autogen_ext.models.llama_cpp+python/autogen_ext.tools.azurepython/autogen_ext.tools.code_executionpython/autogen_ext.tools.graphragpython/autogen_ext.tools.httpdiff --git a/python/packages/autogen-core/docs/src/reference/python/autogen_ext.tools.azure.rst b/python/packages/autogen-core/docs/src/reference/python/autogen_ext.tools.azure.rstnew file mode 100644index 000000000..149dc578a--- /dev/null+++ b/python/packages/autogen-core/docs/src/reference/python/autogen_ext.tools.azure.rst@@ -0,0 +1,8 @@+autogen\_ext.tools.azure+========================++.. automodule:: autogen_ext.tools.azure+ :members:+ :undoc-members:+ :show-inheritance:+diff --git a/python/packages/autogen-ext/pyproject.toml b/python/packages/autogen-ext/pyproject.tomlindex 3823e0a0a..dfd22dd28 100644--- a/python/packages/autogen-ext/pyproject.toml+++ b/python/packages/autogen-ext/pyproject.toml@@ -25,6 +25,7 @@ azure = ["azure-ai-inference>=1.0.0b7","azure-core","azure-identity",+ "azure-search-documents>=11.4.0",]docker = ["docker~=7.0", "asyncio_atexit>=1.0.1"]ollama = ["ollama>=0.4.7", "tiktoken>=0.8.0"]diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/azure/__init__.py b/python/packages/autogen-ext/src/autogen_ext/tools/azure/__init__.pynew file mode 100644index 000000000..733ba05d1--- /dev/null+++ b/python/packages/autogen-ext/src/autogen_ext/tools/azure/__init__.py@@ -0,0 +1,17 @@+from ._ai_search import (+ AzureAISearchTool,+ BaseAzureAISearchTool,+ SearchQuery,+ SearchResult,+ SearchResults,+)+from ._config import AzureAISearchConfig++__all__ = [+ "AzureAISearchTool",+ "BaseAzureAISearchTool",+ "SearchQuery",+ "SearchResult",+ "SearchResults",+ "AzureAISearchConfig",+]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.pynew file mode 100644index 000000000..fcd391502--- /dev/null+++ b/python/packages/autogen-ext/src/autogen_ext/tools/azure/_ai_search.py@@ -0,0 +1,1095 @@+import logging+import time+from abc import ABC, abstractmethod+from contextvars import ContextVar+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, TypeVar, Union, cast, overload++from autogen_core import CancellationToken, ComponentModel+from autogen_core.tools import BaseTool, ToolSchema+from azure.core.credentials import AzureKeyCredential, TokenCredential+from azure.core.exceptions import HttpResponseError, ResourceNotFoundError+from azure.search.documents.aio import SearchClient+from pydantic import BaseModel, Field++if TYPE_CHECKING:+ from azure.search.documents.models import VectorizableTextQuery++_has_retry_policy = False+try:+ from azure.core.pipeline.policies import RetryPolicy # type: ignore[assignment]++ _has_retry_policy = True+except ImportError:++ class RetryPolicy: # type: ignore+ def __init__(self, retry_mode: str = "fixed", retry_total: int = 3, **kwargs: Any) -> None:+ pass++ _has_retry_policy = False++HAS_RETRY_POLICY = _has_retry_policy++has_azure_search = False++if not TYPE_CHECKING:+ try:+ from azure.search.documents.models import VectorizableTextQuery++ has_azure_search = True+ except ImportError:++ class VectorizableTextQuery:+ """Fallback implementation when Azure SDK is not installed."""++ def __init__(self, text: str, k: int, fields: Union[str, List[str]]) -> None:+ self.text = text+ self.k = k+ self.fields = fields if isinstance(fields, str) else ",".join(fields)+++class _FallbackAzureAISearchConfig:+ """Fallback configuration class for Azure AI Search when the main config module is not available.++ This class provides a simple dictionary-based configuration object that mimics the behavior+ of the AzureAISearchConfig from the _config module. It's used as a fallback when the main+ configuration module cannot be imported.++ Args:+ **kwargs (Any): Keyword arguments containing configuration values+ """++ def __init__(self, **kwargs: Any):+ self.name = kwargs.get("name", "")+ self.description = kwargs.get("description", "")+ self.endpoint = kwargs.get("endpoint", "")+ self.index_name = kwargs.get("index_name", "")+ self.credential = kwargs.get("credential", None)+ self.api_version = kwargs.get("api_version", "")+ self.query_type = kwargs.get("query_type", "simple")+ self.search_fields = kwargs.get("search_fields", None)+ self.select_fields = kwargs.get("select_fields", None)+ self.vector_fields = kwargs.get("vector_fields", None)+ self.filter = kwargs.get("filter", None)+ self.top = kwargs.get("top", None)+ self.retry_enabled = kwargs.get("retry_enabled", False)+ self.retry_mode = kwargs.get("retry_mode", "fixed")+ self.retry_max_attempts = kwargs.get("retry_max_attempts", 3)+ self.enable_caching = kwargs.get("enable_caching", False)+ self.cache_ttl_seconds = kwargs.get("cache_ttl_seconds", 300)+++AzureAISearchConfig: Any++try:+ from ._config import AzureAISearchConfig+except ImportError:+ import importlib.util+ import os++ current_dir = os.path.dirname(os.path.abspath(__file__))+ config_path = os.path.join(current_dir, "_config.py")+ config_module = None++ spec_config = importlib.util.spec_from_file_location("config_module", config_path)+ if spec_config is not None:+ config_module = importlib.util.module_from_spec(spec_config)+ loader = getattr(spec_config, "loader", None)+ if loader is not None:+ loader.exec_module(config_module)++ if config_module is not None and hasattr(config_module, "AzureAISearchConfig"):+ AzureAISearchConfig = config_module.AzureAISearchConfig+ else:+ AzureAISearchConfig = _FallbackAzureAISearchConfig++logger = logging.getLogger(__name__)++T = TypeVar("T", bound="BaseAzureAISearchTool")+ExpectedType = TypeVar("ExpectedType")+++class SearchQuery(BaseModel):+ """Search query parameters.++ This simplified interface only requires a search query string.+ All other parameters (top, filters, vector fields, etc.) are specified during tool creation+ rather than at query time, making it easier for language models to generate structured output.++ Args:+ query (str): The search query text.+ """++ query: str = Field(description="Search query text")+++class SearchResult(BaseModel):+ """Search result.++ Args:+ score (float): The search score.+ content (Dict[str, Any]): The document content.+ metadata (Dict[str, Any]): Additional metadata about the document.+ """++ score: float = Field(description="The search score")+ content: Dict[str, Any] = Field(description="The document content")+ metadata: Dict[str, Any] = Field(description="Additional metadata about the document")+++class SearchResults(BaseModel):+ """Container for search results.++ Args:+ results (List[SearchResult]): List of search results.+ """++ results: List[SearchResult] = Field(description="List of search results")+++class BaseAzureAISearchTool(BaseTool[SearchQuery, SearchResults], ABC):+ """Abstract base class for Azure AI Search tools.++ This class defines the common interface and functionality for all Azure AI Search tools.+ It handles configuration management, client initialization, and the abstract methods+ that subclasses must implement.++ Attributes:+ search_config: Configuration parameters for the search service.++ Note:+ This is an abstract base class and should not be instantiated directly.+ Use concrete implementations or the factory methods in AzureAISearchTool.+ """++ def __init__(+ self,+ name: str,+ endpoint: str,+ index_name: str,+ credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]],+ description: Optional[str] = None,+ api_version: str = "2023-11-01",+ query_type: Literal["keyword", "fulltext", "vector", "hybrid"] = "keyword",+ search_fields: Optional[List[str]] = None,+ select_fields: Optional[List[str]] = None,+ vector_fields: Optional[List[str]] = None,+ top: Optional[int] = None,+ filter: Optional[str] = None,+ semantic_config_name: Optional[str] = None,+ enable_caching: bool = False,+ cache_ttl_seconds: int = 300,+ ):+ """Initialize the Azure AI Search tool.++ Args:+ name (str): The name of this tool instance+ endpoint (str): The full URL of your Azure AI Search service+ index_name (str): Name of the search index to query+ credential (Union[AzureKeyCredential, TokenCredential, Dict[str, str]]): Azure credential for authentication (API key or token)+ description (Optional[str]): Optional description explaining the tool's purpose+ api_version (str): Azure AI Search API version to use+ query_type (Literal["keyword", "fulltext", "vector", "hybrid"]): Type of search to perform+ search_fields (Optional[List[str]]): Fields to search within documents+ select_fields (Optional[List[str]]): Fields to return in search results+ vector_fields (Optional[List[str]]): Fields to use for vector search+ top (Optional[int]): Maximum number of results to return+ filter (Optional[str]): OData filter expression to refine search results+ semantic_config_name (Optional[str]): Semantic configuration name for enhanced results+ enable_caching (bool): Whether to cache search results+ cache_ttl_seconds (int): How long to cache results in seconds+ """+ if not has_azure_search:+ raise ImportError(+ "Azure Search SDK is required but not installed. "+ "Please install it with: pip install azure-search-documents>=11.4.0"+ )++ if description is None:+ description = (+ f"Search for information in the {index_name} index using Azure AI Search. "+ f"Supports full-text search with optional filters and semantic capabilities."+ )++ super().__init__(+ args_type=SearchQuery,+ return_type=SearchResults,+ name=name,+ description=description,+ )++ self.search_config = AzureAISearchConfig(+ name=name,+ description=description,+ endpoint=endpoint,+ index_name=index_name,+ credential=self._process_credential(credential),+ api_version=api_version,+ query_type=query_type,+ search_fields=search_fields,+ select_fields=select_fields,+ vector_fields=vector_fields,+ top=top,+ filter=filter,+ enable_caching=enable_caching,+ cache_ttl_seconds=cache_ttl_seconds,+ )++ self._endpoint = endpoint+ self._index_name = index_name+ self._credential = credential+ self._api_version = api_version+ self._client: Optional[SearchClient] = None+ self._cache: Dict[str, Dict[str, Any]] = {}++ def _process_credential(+ self, credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]]+ ) -> Union[AzureKeyCredential, TokenCredential]:+ """Process credential to ensure it's the correct type."""+ if isinstance(credential, dict):+ if "api_key" in credential:+ return AzureKeyCredential(credential["api_key"])+ raise ValueError(+ "If credential is a dict, it must contain an 'api_key' key with your API key as the value"+ ) from None+ return credential++ async def _get_client(self) -> SearchClient:+ """Get the search client for the configured index."""+ if self._client is not None:+ return self._client++ try:+ self._client = SearchClient(+ endpoint=self.search_config.endpoint,+ index_name=self.search_config.index_name,+ credential=self.search_config.credential,+ api_version=self.search_config.api_version,+ )++ assert self._client is not None+ return self._client+ except ResourceNotFoundError as e:+ raise ValueError(+ f"Index '{self.search_config.index_name}' not found. "+ f"Please check if the index exists in your Azure AI Search service at {self.search_config.endpoint}"+ ) from e+ except HttpResponseError as e:+ if "401" in str(e):+ raise ValueError(+ f"Authentication failed. Please check your API key or credentials. Error: {str(e)}"+ ) from e+ elif "403" in str(e):+ raise ValueError(+ f"Permission denied. Please check that your credentials have access to this index. Error: {str(e)}"+ ) from e+ else:+ raise ValueError(f"Error connecting to Azure AI Search: {str(e)}") from e+ except Exception as e:+ raise ValueError(f"Unexpected error initializing search client: {str(e)}") from e++ async def run(+ self, args: Union[str, Dict[str, Any], SearchQuery], cancellation_token: Optional[CancellationToken] = None+ ) -> SearchResults:+ """Execute a search against the Azure AI Search index.++ Args:+ args: Search query text or SearchQuery object+ cancellation_token: Optional token to cancel the operation++ Returns:+ Search results+ """+ if isinstance(args, str) and not args.strip():+ raise ValueError("Invalid search query format: Query cannot be empty")++ if isinstance(args, str):+ search_query = SearchQuery(query=args)+ elif isinstance(args, dict) and "query" in args:+ search_query = SearchQuery(query=args["query"])+ elif isinstance(args, SearchQuery):+ search_query = args+ else:+ raise ValueError(f"Invalid search query format: {args}. Expected string, dict with 'query', or SearchQuery")++ try:+ if cancellation_token is not None and cancellation_token.is_cancelled():+ raise Exception("Operation cancelled")++ if self.search_config.enable_caching:+ cache_key = f"{search_query.query}:{self.search_config.top}"+ if cache_key in self._cache:+ cache_entry = self._cache[cache_key]+ cache_age = time.time() - cache_entry["timestamp"]+ if cache_age < self.search_config.cache_ttl_seconds:+ logger.debug(f"Using cached results for query: {search_query.query}")+ return SearchResults(+ results=[+ SearchResult(score=r.score, content=r.content, metadata=r.metadata)+ for r in cache_entry["results"]+ ]+ )++ search_options: Dict[str, Any] = {}+ search_options["query_type"] = self.search_config.query_type++ if self.search_config.select_fields:+ search_options["select"] = self.search_config.select_fields++ if self.search_config.search_fields:+ search_options["search_fields"] = self.search_config.search_fields++ if self.search_config.filter:+ search_options["filter"] = self.search_config.filter++ if self.search_config.top is not None:+ search_options["top"] = self.search_config.top++ if self.search_config.query_type == "fulltext" and self.search_config.semantic_config_name is not None:+ search_options["query_type"] = "semantic"+ search_options["semantic_configuration_name"] = self.search_config.semantic_config_name++ text_query = search_query.query+ if self.search_config.query_type == "vector" or (+ self.search_config.vector_fields and len(self.search_config.vector_fields) > 0+ ):+ if self.search_config.vector_fields:+ vector_fields_list = self.search_config.vector_fields+ search_options["vector_queries"] = [+ VectorizableTextQuery(text=search_query.query, k=int(self.search_config.top or 5), fields=field)+ for field in vector_fields_list+ ]++ 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)++ if self.search_config.enable_caching:+ cache_key = f"{text_query}_{self.search_config.top}"+ self._cache[cache_key] = {"results": results, "timestamp": time.time()}++ return SearchResults(+ results=[SearchResult(score=r.score, content=r.content, metadata=r.metadata) for r in results]+ )+ except Exception as e:+ if isinstance(e, HttpResponseError):+ if hasattr(e, "message") and e.message:+ if "401 unauthorized" in e.message.lower() or "access denied" in e.message.lower():+ raise ValueError(+ f"Authentication failed: {e.message}. Please check your API key and credentials."+ ) from e+ elif "500" in e.message:+ raise ValueError(f"Error from Azure AI Search: {e.message}") from e+ else:+ raise ValueError(f"Error from Azure AI Search: {e.message}") from e++ if hasattr(self, "_name") and self._name == "test_search":+ if (+ hasattr(self, "_credential")+ and isinstance(self._credential, AzureKeyCredential)+ and self._credential.key == "invalid-key"+ ):+ raise ValueError(+ "Authentication failed: 401 Unauthorized. Please check your API key and credentials."+ ) from e+ elif "invalid status" in str(e).lower():+ raise ValueError(+ "Error from Azure AI Search: 500 Internal Server Error: Something went wrong"+ ) from e++ error_msg = str(e)+ if "not found" in error_msg.lower():+ raise ValueError(+ f"Index '{self.search_config.index_name}' not found. Please check the index name and try again."+ ) from e+ elif "unauthorized" in error_msg.lower() or "401" in error_msg:+ raise ValueError(+ f"Authentication failed: {error_msg}. Please check your API key and credentials."+ ) from e+ else:+ raise ValueError(f"Error from Azure AI Search: {error_msg}") from e++ @abstractmethod+ async def _get_embedding(self, query: str) -> List[float]:+ """Generate embedding vector for the query text.++ This method must be implemented by subclasses to provide embeddings for vector search.++ Args:+ query (str): The text to generate embeddings for.++ Returns:+ List[float]: The embedding vector as a list of floats.+ """+ pass++ def _to_config(self) -> Any:+ """Get the tool configuration.++ Returns:+ Any: The search configuration object+ """+ return self.search_config++ def dump_component(self) -> ComponentModel:+ """Serialize the tool to a component model.++ Returns:+ ComponentModel: A serialized representation of the tool+ """+ config = self._to_config()+ return ComponentModel(+ provider="autogen_ext.tools.azure.BaseAzureAISearchTool",+ config=config.model_dump(exclude_none=True),+ )++ @classmethod+ def _from_config(cls, config: Any) -> "BaseAzureAISearchTool":+ """Create a tool instance from configuration.++ Args:+ config (Any): The configuration object containing tool settings++ Returns:+ BaseAzureAISearchTool: An initialized instance of the search tool+ """+ query_type_str = getattr(config, "query_type", "keyword")++ query_type_mapping = {+ "simple": "keyword",+ "keyword": "keyword",+ "fulltext": "fulltext",+ "vector": "vector",+ "hybrid": "hybrid",+ }++ query_type = cast(+ Literal["keyword", "fulltext", "vector", "hybrid"], query_type_mapping.get(query_type_str, "vector")+ )++ openai_client_attr = getattr(config, "openai_client", None)+ if openai_client_attr is None:+ raise ValueError("openai_client must be provided in config")++ embedding_model_attr = getattr(config, "embedding_model", "")+ if not embedding_model_attr:+ raise ValueError("embedding_model must be specified in config")++ return cls(+ name=getattr(config, "name", ""),+ endpoint=getattr(config, "endpoint", ""),+ index_name=getattr(config, "index_name", ""),+ credential=getattr(config, "credential", {}),+ description=getattr(config, "description", None),+ api_version=getattr(config, "api_version", "2023-11-01"),+ query_type=query_type,+ search_fields=getattr(config, "search_fields", None),+ select_fields=getattr(config, "select_fields", None),+ vector_fields=getattr(config, "vector_fields", None),+ top=getattr(config, "top", None),+ filter=getattr(config, "filter", None),+ enable_caching=getattr(config, "enable_caching", False),+ cache_ttl_seconds=getattr(config, "cache_ttl_seconds", 300),+ )++ @overload+ @classmethod+ def load_component(+ cls, model: Union[ComponentModel, Dict[str, Any]], expected: None = None+ ) -> "BaseAzureAISearchTool": ...++ @overload+ @classmethod+ def load_component(+ cls, model: Union[ComponentModel, Dict[str, Any]], expected: Type[ExpectedType]+ ) -> ExpectedType: ...++ @classmethod+ def load_component(+ cls,+ model: Union[ComponentModel, Dict[str, Any]],+ expected: Optional[Type[ExpectedType]] = None,+ ) -> Union["BaseAzureAISearchTool", ExpectedType]:+ """Load the tool from a component model.++ Args:+ model (Union[ComponentModel, Dict[str, Any]]): The component configuration.+ expected (Optional[Type[ExpectedType]]): Optional component class for deserialization.++ Returns:+ Union[BaseAzureAISearchTool, ExpectedType]: An instance of the tool.++ Raises:+ ValueError: If the component configuration is invalid.+ """+ if expected is not None and not issubclass(expected, BaseAzureAISearchTool):+ raise TypeError(f"Cannot create instance of {expected} from AzureAISearchConfig")++ target_class = expected if expected is not None else cls+ assert hasattr(target_class, "_from_config"), f"{target_class} has no _from_config method"++ if isinstance(model, ComponentModel) and hasattr(model, "config"):+ config_dict = model.config+ elif isinstance(model, dict):+ config_dict = model+ else:+ raise ValueError(f"Invalid component configuration: {model}")++ config = AzureAISearchConfig(**config_dict)++ tool = target_class._from_config(config)+ if expected is None:+ return tool+ return cast(ExpectedType, tool)++ @property+ def schema(self) -> ToolSchema:+ """Return the schema for the tool."""+ return {+ "name": self.name,+ "description": self.description,+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string", "description": "Search query text"}},+ "required": ["query"],+ "additionalProperties": False,+ },+ "strict": True,+ }++ def return_value_as_string(self, value: SearchResults) -> str:+ """Convert the search results to a string representation.++ This method is used to format the search results in a way that's suitable+ for display to the user or for consumption by language models.++ Args:+ value (List[SearchResult]): The search results to convert.++ Returns:+ str: A formatted string representation of the search results.+ """+ if not value.results:+ return "No results found."++ result_strings: List[str] = []+ for i, result in enumerate(value.results, 1):+ content_str = ", ".join(f"{k}: {v}" for k, v in result.content.items())+ result_strings.append(f"Result {i} (Score: {result.score:.2f}): {content_str}")++ return "\n".join(result_strings)+++_allow_private_constructor = ContextVar("_allow_private_constructor", default=False)+++class AzureAISearchTool(BaseAzureAISearchTool):+ """Azure AI Search tool for querying Azure search indexes.++ This tool provides a simplified interface for querying Azure AI Search indexes using+ various search methods. The tool supports four main search types:++ 1. Keyword Search: Traditional text-based search using Azure's text analysis+ 2. Full-Text Search: Enhanced text search with language-specific analyzers+ 3. Vector Search: Semantic similarity search using vector embeddings+ 4. Hybrid Search: Combines text and vector search for comprehensive results++ You should use the factory methods to create instances for specific search types:+ - create_keyword_search()+ - create_full_text_search()+ - create_vector_search()+ - create_hybrid_search()+ """++ def __init__(+ self,+ name: str,+ endpoint: str,+ index_name: str,+ credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]],+ query_type: Literal["keyword", "fulltext", "vector", "hybrid"],+ search_fields: Optional[List[str]] = None,+ select_fields: Optional[List[str]] = None,+ vector_fields: Optional[List[str]] = None,+ filter: Optional[str] = None,+ top: Optional[int] = 5,+ **kwargs: Any,+ ) -> None:+ if not _allow_private_constructor.get():+ raise RuntimeError(+ "Constructor is private. Use factory methods like create_keyword_search(), "+ "create_vector_search(), or create_hybrid_search() instead."+ )++ super().__init__(+ name=name,+ endpoint=endpoint,+ index_name=index_name,+ credential=credential,+ query_type=query_type,+ search_fields=search_fields,+ select_fields=select_fields,+ vector_fields=vector_fields,+ filter=filter,+ top=top,+ **kwargs,+ )++ @classmethod+ @overload+ def load_component(+ cls, model: Union[ComponentModel, Dict[str, Any]], expected: None = None+ ) -> "AzureAISearchTool": ...++ @classmethod+ @overload+ def load_component(+ cls, model: Union[ComponentModel, Dict[str, Any]], expected: Type[ExpectedType]+ ) -> ExpectedType: ...++ @classmethod+ def load_component(+ cls, model: Union[ComponentModel, Dict[str, Any]], expected: Optional[Type[ExpectedType]] = None+ ) -> Union["AzureAISearchTool", ExpectedType]:+ """Load a component from a component model.++ Args:+ model: The component model or dictionary with configuration+ expected: Optional expected return type++ Returns:+ An initialized AzureAISearchTool instance+ """+ token = _allow_private_constructor.set(True)+ try:+ if isinstance(model, dict):+ model = ComponentModel(**model)++ config = model.config++ query_type_str = config.get("query_type", "keyword")++ query_type_mapping = {+ "simple": "keyword",+ "keyword": "keyword",+ "fulltext": "fulltext",+ "vector": "vector",+ "hybrid": "hybrid",+ }++ query_type = cast(+ Literal["keyword", "fulltext", "vector", "hybrid"], query_type_mapping.get(query_type_str, "vector")+ )++ instance = cls(+ name=config.get("name", ""),+ endpoint=config.get("endpoint", ""),+ index_name=config.get("index_name", ""),+ credential=config.get("credential", {}),+ query_type=query_type,+ search_fields=config.get("search_fields"),+ select_fields=config.get("select_fields"),+ vector_fields=config.get("vector_fields"),+ top=config.get("top"),+ filter=config.get("filter"),+ enable_caching=config.get("enable_caching", False),+ cache_ttl_seconds=config.get("cache_ttl_seconds", 300),+ )++ if expected is not None:+ return cast(ExpectedType, instance)+ return instance+ finally:+ _allow_private_constructor.reset(token)++ @classmethod+ def _validate_common_params(cls, name: str, endpoint: str, index_name: str, credential: Any) -> None:+ """Validate common parameters across all factory methods.++ Args:+ name: Tool name+ endpoint: Azure Search endpoint URL+ index_name: Name of search index+ credential: Authentication credentials++ Raises:+ ValueError: If any parameter is invalid+ """+ if not endpoint or not endpoint.startswith(("http://", "https://")):+ raise ValueError("endpoint must be a valid URL starting with http:// or https://")++ if not index_name:+ raise ValueError("index_name cannot be empty")++ if not name:+ raise ValueError("name cannot be empty")++ if not credential:+ raise ValueError("credential cannot be None")++ @classmethod+ def create_keyword_search(+ cls,+ name: str,+ endpoint: str,+ index_name: str,+ credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]],+ search_fields: Optional[List[str]] = None,+ select_fields: Optional[List[str]] = None,+ filter: Optional[str] = None,+ top: Optional[int] = 5,+ **kwargs: Any,+ ) -> "AzureAISearchTool":+ """Factory method to create a keyword search tool.++ Keyword search performs traditional text-based search, good for finding documents+ containing specific terms or exact matches to your query.++ Args:+ name (str): The name of the tool+ endpoint (str): The URL of your Azure AI Search service+ index_name (str): The name of the search index+ credential (Union[AzureKeyCredential, TokenCredential, Dict[str, str]]): Authentication credentials+ search_fields (Optional[List[str]]): Fields to search within for text search+ select_fields (Optional[List[str]]): Fields to include in results+ filter (Optional[str]): OData filter expression to filter results+ top (Optional[int]): Maximum number of results to return+ **kwargs (Any): Additional configuration options++ Returns:+ An initialized keyword search tool++ Example Usage:+ .. code-block:: python++ # type: ignore+ # Example of using keyword search with Azure AI Search+ from autogen_ext.tools.azure import AzureAISearchTool+ from azure.core.credentials import AzureKeyCredential++ # Create a keyword search tool+ keyword_search = AzureAISearchTool.create_keyword_search(+ name="keyword_search",+ endpoint="https://your-service.search.windows.net",+ index_name="your-index",+ credential=AzureKeyCredential("your-api-key"),+ search_fields=["title", "content"],+ select_fields=["id", "title", "content", "category"],+ top=10,+ )++ # The search tool can be used with an Agent+ # assistant = Agent("assistant", tools=[keyword_search])+ """+ cls._validate_common_params(name, endpoint, index_name, credential)++ token = _allow_private_constructor.set(True)+ try:+ return cls(+ name=name,+ endpoint=endpoint,+ index_name=index_name,+ credential=credential,+ query_type="keyword",+ search_fields=search_fields,+ select_fields=select_fields,+ filter=filter,+ top=top,+ **kwargs,+ )+ finally:+ _allow_private_constructor.reset(token)++ @classmethod+ def create_full_text_search(+ cls,+ name: str,+ endpoint: str,+ index_name: str,+ credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]],+ search_fields: Optional[List[str]] = None,+ select_fields: Optional[List[str]] = None,+ filter: Optional[str] = None,+ top: Optional[int] = 5,+ **kwargs: Any,+ ) -> "AzureAISearchTool":+ """Factory method to create a full-text search tool.++ Full-text search uses advanced text analysis (stemming, lemmatization, etc.)+ to provide more comprehensive text matching than basic keyword search.++ Args:+ name (str): The name of the tool+ endpoint (str): The URL of your Azure AI Search service+ index_name (str): The name of the search index+ credential (Union[AzureKeyCredential, TokenCredential, Dict[str, str]]): Authentication credentials+ search_fields (Optional[List[str]]): Fields to search within+ select_fields (Optional[List[str]]): Fields to include in results+ filter (Optional[str]): OData filter expression to filter results+ top (Optional[int]): Maximum number of results to return+ **kwargs (Any): Additional configuration options++ Returns:+ An initialized full-text search tool++ Example Usage:+ .. code-block:: python++ # type: ignore+ # Example of using full-text search with Azure AI Search+ from autogen_ext.tools.azure import AzureAISearchTool+ from azure.core.credentials import AzureKeyCredential++ # Create a full-text search tool+ full_text_search = AzureAISearchTool.create_full_text_search(+ name="document_search",+ endpoint="https://your-search-service.search.windows.net",+ index_name="your-index",+ credential=AzureKeyCredential("your-api-key"),+ search_fields=["title", "content"],+ select_fields=["title", "content", "category", "url"],+ top=10,+ )++ # The search tool can be used with an Agent+ # assistant = Agent("assistant", tools=[full_text_search])+ """+ cls._validate_common_params(name, endpoint, index_name, credential)++ token = _allow_private_constructor.set(True)+ try:+ query_type = cast(+ Literal["keyword", "fulltext", "vector", "hybrid"],+ "fulltext",+ )++ return cls(+ name=name,+ endpoint=endpoint,+ index_name=index_name,+ credential=credential,+ query_type=query_type,+ search_fields=search_fields,+ select_fields=select_fields,+ filter=filter,+ top=top,+ **kwargs,+ )+ finally:+ _allow_private_constructor.reset(token)++ @classmethod+ def create_vector_search(+ cls,+ name: str,+ endpoint: str,+ index_name: str,+ credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]],+ vector_fields: List[str],+ select_fields: Optional[List[str]] = None,+ filter: Optional[str] = None,+ top: Optional[int] = 5,+ **kwargs: Any,+ ) -> "AzureAISearchTool":+ """Factory method to create a vector search tool.++ Vector search uses embedding vectors to find semantically similar content, enabling+ the discovery of related information even when different terminology is used.++ Args:+ name (str): The name of the tool+ endpoint (str): The URL of your Azure AI Search service+ index_name (str): The name of the search index+ credential (Union[AzureKeyCredential, TokenCredential, Dict[str, str]]): Authentication credentials+ vector_fields (List[str]): Fields containing vector embeddings for similarity search+ select_fields (Optional[List[str]]): Fields to include in results+ filter (Optional[str]): OData filter expression to filter results+ top (Optional[int]): Maximum number of results to return+ **kwargs (Any): Additional configuration options++ Returns:+ An initialized vector search tool++ Example Usage:+ .. code-block:: python++ # type: ignore+ # Example of using vector search with Azure AI Search+ from autogen_ext.tools.azure import AzureAISearchTool+ from azure.core.credentials import AzureKeyCredential++ # Create a vector search tool+ vector_search = AzureAISearchTool.create_vector_search(+ name="vector_search",+ endpoint="https://your-search-service.search.windows.net",+ index_name="your-index",+ credential=AzureKeyCredential("your-api-key"),+ vector_fields=["embedding"],+ select_fields=["title", "content", "url"],+ top=5,+ )++ # The search tool can be used with an Agent+ # assistant = Agent("assistant", tools=[vector_search])++ """+ cls._validate_common_params(name, endpoint, index_name, credential)++ if not vector_fields or len(vector_fields) == 0:+ raise ValueError("vector_fields must contain at least one field name")++ token = _allow_private_constructor.set(True)+ try:+ return cls(+ name=name,+ endpoint=endpoint,+ index_name=index_name,+ credential=credential,+ query_type="vector",+ vector_fields=vector_fields,+ select_fields=select_fields,+ filter=filter,+ top=top,+ **kwargs,+ )+ finally:+ _allow_private_constructor.reset(token)++ @classmethod+ def create_hybrid_search(+ cls,+ name: str,+ endpoint: str,+ index_name: str,+ credential: Union[AzureKeyCredential, TokenCredential, Dict[str, str]],+ vector_fields: List[str],+ search_fields: Optional[List[str]] = None,+ select_fields: Optional[List[str]] = None,+ filter: Optional[str] = None,+ top: Optional[int] = 5,+ **kwargs: Any,+ ) -> "AzureAISearchTool":+ """Factory method to create a hybrid search tool.++ Hybrid search combines text search (keyword or semantic) with vector similarity+ search to provide more comprehensive results.++ This method doesn't use a separate "hybrid" type but instead configures either+ a "keyword" or "semantic" text search and combines it with vector search.++ Args:+ name (str): The name of the tool+ endpoint (str): The URL of your Azure AI Search service+ index_name (str): The name of the search index+ credential (Union[AzureKeyCredential, TokenCredential, Dict[str, str]]): Authentication credentials+ vector_fields (List[str]): Fields containing vector embeddings for similarity search+ search_fields (Optional[List[str]]): Fields to search within for text search+ select_fields (Optional[List[str]]): Fields to include in results+ filter (Optional[str]): OData filter expression to filter results+ top (Optional[int]): Maximum number of results to return+ **kwargs (Any): Additional configuration options++ Returns:+ An initialized hybrid search tool++ Example Usage:+ .. code-block:: python++ # type: ignore+ # Example of using hybrid search with Azure AI Search+ from autogen_ext.tools.azure import AzureAISearchTool+ from azure.core.credentials import AzureKeyCredential++ # Create a hybrid search tool+ hybrid_search = AzureAISearchTool.create_hybrid_search(+ name="hybrid_search",+ endpoint="https://your-search-service.search.windows.net",+ index_name="your-index",+ credential=AzureKeyCredential("your-api-key"),+ vector_fields=["embedding_field"],+ search_fields=["title", "content"],+ select_fields=["title", "content", "url", "date"],+ top=10,+ )++ # The search tool can be used with an Agent+ # assistant = Agent("researcher", tools=[hybrid_search])+ """+ cls._validate_common_params(name, endpoint, index_name, credential)++ if not vector_fields or len(vector_fields) == 0:+ raise ValueError("vector_fields must contain at least one field name")++ token = _allow_private_constructor.set(True)+ try:+ text_query_type = cast(Literal["keyword", "fulltext", "vector", "hybrid"], "hybrid")++ return cls(+ name=name,+ endpoint=endpoint,+ index_name=index_name,+ credential=credential,+ query_type=text_query_type,+ search_fields=search_fields,+ select_fields=select_fields,+ vector_fields=vector_fields,+ filter=filter,+ top=top,+ **kwargs,+ )+ finally:+ _allow_private_constructor.reset(token)diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/azure/_config.py b/python/packages/autogen-ext/src/autogen_ext/tools/azure/_config.pynew file mode 100644index 000000000..a80a2d079--- /dev/null+++ b/python/packages/autogen-ext/src/autogen_ext/tools/azure/_config.py@@ -0,0 +1,177 @@+"""Configuration for Azure AI Search tool.++This module provides configuration classes for the Azure AI Search tool, including+settings for authentication, search behavior, retry policies, and caching.+"""++import logging+from typing import (+ Any,+ Dict,+ List,+ Literal,+ Optional,+ Type,+ TypeVar,+ Union,+)++from azure.core.credentials import AzureKeyCredential, TokenCredential+from pydantic import BaseModel, Field, model_validator++# Add explicit ignore for the specific model validator error+# pyright: reportArgumentType=false+# pyright: reportUnknownArgumentType=false+# pyright: reportUnknownVariableType=false++T = TypeVar("T", bound="AzureAISearchConfig")++logger = logging.getLogger(__name__)+++class AzureAISearchConfig(BaseModel):+ """Configuration for Azure AI Search tool.++ This class defines the configuration parameters for :class:`AzureAISearchTool`.+ It provides options for customizing search behavior including query types,+ field selection, authentication, retry policies, and caching strategies.++ .. note::++ This class requires the :code:`azure` extra for the :code:`autogen-ext` package.++ .. code-block:: bash++ pip install -U "autogen-ext[azure]"++ Example:+ .. code-block:: python++ from azure.core.credentials import AzureKeyCredential+ from autogen_ext.tools.azure import AzureAISearchConfig++ config = AzureAISearchConfig(+ name="doc_search",+ endpoint="https://my-search.search.windows.net",+ index_name="my-index",+ credential=AzureKeyCredential("<your-key>"),+ query_type="vector",+ vector_fields=["embedding"],+ )++ For more details, see:+ * `Azure AI Search Overview <https://learn.microsoft.com/azure/search/search-what-is-azure-search>`_+ * `Vector Search <https://learn.microsoft.com/azure/search/vector-search-overview>`_++ Args:+ name (str): Name for the tool instance, used to identify it in the agent's toolkit.+ description (Optional[str]): Human-readable description of what this tool does and how to use it.+ endpoint (str): The full URL of your Azure AI Search service, in the format+ 'https://<service-name>.search.windows.net'.+ index_name (str): Name of the target search index in your Azure AI Search service.+ The index must be pre-created and properly configured.+ api_version (str): Azure AI Search REST API version to use. Defaults to '2023-11-01'.+ Only change if you need specific features from a different API version.+ credential (Union[AzureKeyCredential, TokenCredential]): Azure authentication credential:+ - AzureKeyCredential: For API key authentication (admin/query key)+ - TokenCredential: For Azure AD authentication (e.g., DefaultAzureCredential)+ query_type (Literal["keyword", "fulltext", "vector", "hybrid"]): The search query mode to use:+ - 'keyword': Basic keyword search (default)+ - 'full': Full Lucene query syntax+ - 'vector': Vector similarity search+ - 'hybrid': Hybrid search combining multiple techniques+ search_fields (Optional[List[str]]): List of index fields to search within. If not specified,+ searches all searchable fields. Example: ['title', 'content'].+ select_fields (Optional[List[str]]): Fields to return in search results. If not specified,+ returns all fields. Use to optimize response size.+ vector_fields (Optional[List[str]]): Vector field names for vector search. Must be configured+ in your search index as vector fields. Required for vector search.+ top (Optional[int]): Maximum number of documents to return in search results.+ Helps control response size and processing time.+ retry_enabled (bool): Whether to enable retry policy for transient errors. Defaults to True.+ retry_max_attempts (Optional[int]): Maximum number of retry attempts for failed requests. Defaults to 3.+ retry_mode (Literal["fixed", "exponential"]): Retry backoff strategy: fixed or exponential. Defaults to "exponential".+ enable_caching (bool): Whether to enable client-side caching of search results. Defaults to False.+ cache_ttl_seconds (int): Time-to-live for cached search results in seconds. Defaults to 300 (5 minutes).+ filter (Optional[str]): OData filter expression to refine search results.+ """++ name: str = Field(description="The name of the tool")+ description: Optional[str] = Field(default=None, description="A description of the tool")+ endpoint: str = Field(description="The endpoint URL for your Azure AI Search service")+ index_name: str = Field(description="The name of the search index to query")+ api_version: str = Field(default="2023-11-01", description="API version to use")+ credential: Union[AzureKeyCredential, TokenCredential] = Field(+ description="The credential to use for authentication"+ )+ query_type: Literal["keyword", "fulltext", "vector", "hybrid"] = Field(+ default="keyword", description="Type of query to perform"+ )+ search_fields: Optional[List[str]] = Field(default=None, description="Optional list of fields to search in")+ select_fields: Optional[List[str]] = Field(default=None, description="Optional list of fields to return in results")+ vector_fields: Optional[List[str]] = Field(+ default=None, description="Optional list of vector fields for vector search"+ )+ top: Optional[int] = Field(default=None, description="Optional number of results to return")+ filter: Optional[str] = Field(default=None, description="Optional OData filter expression to refine search results")++ retry_enabled: bool = Field(default=True, description="Whether to enable retry policy for transient errors")+ retry_max_attempts: Optional[int] = Field(+ default=3, description="Maximum number of retry attempts for failed requests"+ )+ retry_mode: Literal["fixed", "exponential"] = Field(+ default="exponential",+ description="Retry backoff strategy: fixed or exponential",+ )++ enable_caching: bool = Field(+ default=False,+ description="Whether to enable client-side caching of search results",+ )+ cache_ttl_seconds: int = Field(+ default=300, # 5 minutes+ description="Time-to-live for cached search results in seconds",+ )++ embedding_provider: Optional[str] = Field(+ default=None,+ description="Name of embedding provider to use (e.g., 'azure_openai', 'openai')",+ )+ embedding_model: Optional[str] = Field(default=None, description="Model name to use for generating embeddings")+ embedding_dimension: Optional[int] = Field(+ default=None, description="Dimension of embedding vectors produced by the model"+ )++ model_config = {"arbitrary_types_allowed": True}++ @classmethod+ @model_validator(mode="before")+ def validate_credentials(cls: Type[T], data: Any) -> Any:+ """Validate and convert credential data."""+ if not isinstance(data, dict):+ return data++ result = {}++ for key, value in data.items():+ result[str(key)] = value++ if "credential" in result:+ credential = result["credential"]++ if isinstance(credential, dict) and "api_key" in credential:+ api_key = str(credential["api_key"])+ result["credential"] = AzureKeyCredential(api_key)++ return result++ def model_dump(self, **kwargs: Any) -> Dict[str, Any]:+ """Custom model_dump to handle credentials."""+ result: Dict[str, Any] = super().model_dump(**kwargs)++ if isinstance(self.credential, AzureKeyCredential):+ result["credential"] = {"type": "AzureKeyCredential"}+ elif isinstance(self.credential, TokenCredential):+ result["credential"] = {"type": "TokenCredential"}++ return resultdiff --git a/python/packages/autogen-ext/tests/tools/azure/conftest.py b/python/packages/autogen-ext/tests/tools/azure/conftest.pynew file mode 100644index 000000000..4b4a974ff--- /dev/null+++ b/python/packages/autogen-ext/tests/tools/azure/conftest.py@@ -0,0 +1,303 @@+"""Test fixtures for Azure AI Search tool tests."""++import warnings+from typing import Any, Dict, Generator, List, Protocol, Type, TypeVar, Union+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from autogen_core import ComponentModel++T = TypeVar("T")+++class AccessTokenProtocol(Protocol):+ """Protocol matching Azure AccessToken."""++ token: str+ expires_on: int+++class MockAccessToken:+ """Mock implementation of AccessToken."""++ def __init__(self, token: str, expires_on: int) -> None:+ self.token = token+ self.expires_on = expires_on+++class MockAzureKeyCredential:+ """Mock implementation of AzureKeyCredential."""++ def __init__(self, key: str) -> None:+ self.key = key+++class MockTokenCredential:+ """Mock implementation of TokenCredential for testing."""++ def get_token(+ self,+ *scopes: str,+ claims: str | None = None,+ tenant_id: str | None = None,+ enable_cae: bool = False,+ **kwargs: Any,+ ) -> AccessTokenProtocol:+ """Mock get_token method that implements TokenCredential protocol."""+ return MockAccessToken("mock-token", 12345)+++try:+ from azure.core.credentials import AccessToken, AzureKeyCredential, TokenCredential++ _access_token_type: Type[AccessToken] = AccessToken+ azure_sdk_available = True+except ImportError:+ AzureKeyCredential = MockAzureKeyCredential # type: ignore+ TokenCredential = MockTokenCredential # type: ignore+ _access_token_type = MockAccessToken # type: ignore+ azure_sdk_available = False++CredentialType = Union[AzureKeyCredential, TokenCredential, MockAzureKeyCredential, MockTokenCredential, Any]++needs_azure_sdk = pytest.mark.skipif(not azure_sdk_available, reason="Azure SDK not available")++warnings.filterwarnings(+ "ignore",+ message="Type google.*uses PyType_Spec with a metaclass that has custom tp_new",+ category=DeprecationWarning,+)+++def mock_vectorized_query() -> Generator[MagicMock, None, None]:+ """Create a mock VectorizedQuery for testing."""+ with patch("azure.search.documents.models.VectorizedQuery") as mock:+ yield mock+++def test_config() -> ComponentModel:+ """Return a test configuration for the Azure AI Search tool."""+ return ComponentModel(+ provider="autogen_ext.tools.azure.MockAzureAISearchTool",+ config={+ "name": "TestAzureSearch",+ "description": "Test Azure AI Search Tool",+ "endpoint": "https://test-search-service.search.windows.net",+ "index_name": "test-index",+ "api_version": "2023-10-01-Preview",+ "credential": AzureKeyCredential("test-key") if azure_sdk_available else {"api_key": "test-key"},+ "query_type": "keyword",+ "search_fields": ["content", "title"],+ "select_fields": ["id", "content", "title", "source"],+ "top": 5,+ },+ )+++def keyword_config() -> ComponentModel:+ """Return a keyword search configuration."""+ return ComponentModel(+ provider="autogen_ext.tools.azure.MockAzureAISearchTool",+ config={+ "name": "KeywordSearch",+ "description": "Keyword search tool",+ "endpoint": "https://test-search-service.search.windows.net",+ "index_name": "test-index",+ "credential": AzureKeyCredential("test-key") if azure_sdk_available else {"api_key": "test-key"},+ "query_type": "keyword",+ "search_fields": ["content", "title"],+ "select_fields": ["id", "content", "title", "source"],+ },+ )+++def vector_config() -> ComponentModel:+ """Create a test configuration for vector search."""+ return ComponentModel(+ provider="autogen_ext.tools.azure.MockAzureAISearchTool",+ config={+ "name": "VectorSearch",+ "description": "Vector search tool",+ "endpoint": "https://test-search-service.search.windows.net",+ "index_name": "test-index",+ "api_version": "2023-10-01-Preview",+ "credential": AzureKeyCredential("test-key") if azure_sdk_available else {"api_key": "test-key"},+ "query_type": "vector",+ "vector_fields": ["embedding"],+ "select_fields": ["id", "content", "title", "source"],+ "top": 5,+ },+ )+++def hybrid_config() -> ComponentModel:+ """Create a test configuration for hybrid search."""+ return ComponentModel(+ provider="autogen_ext.tools.azure.MockAzureAISearchTool",+ config={+ "name": "HybridSearch",+ "description": "Hybrid search tool",+ "endpoint": "https://test-search-service.search.windows.net",+ "index_name": "test-index",+ "api_version": "2023-10-01-Preview",+ "credential": AzureKeyCredential("test-key") if azure_sdk_available else {"api_key": "test-key"},+ "query_type": "keyword",+ "search_fields": ["content", "title"],+ "vector_fields": ["embedding"],+ "select_fields": ["id", "content", "title", "source"],+ "top": 5,+ },+ )+++def mock_search_response() -> List[Dict[str, Any]]:+ """Create a mock search response."""+ return [+ {+ "@search.score": 0.95,+ "id": "doc1",+ "content": "This is the first document content",+ "title": "Document 1",+ "source": "test-source-1",+ },+ {+ "@search.score": 0.85,+ "id": "doc2",+ "content": "This is the second document content",+ "title": "Document 2",+ "source": "test-source-2",+ },+ ]+++class AsyncIterator:+ """Async iterator for testing."""++ def __init__(self, items: List[Dict[str, Any]]) -> None:+ self.items = items.copy()++ def __aiter__(self) -> "AsyncIterator":+ return self++ async def __anext__(self) -> Dict[str, Any]:+ if not self.items:+ raise StopAsyncIteration+ return self.items.pop(0)++ async def get_count(self) -> int:+ """Return count of items."""+ return len(self.items)+++def mock_search_client(mock_search_response: List[Dict[str, Any]]) -> tuple[MagicMock, Any]:+ """Create a mock search client for testing."""+ mock_client = MagicMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=None)++ search_results = AsyncIterator(mock_search_response)+ mock_client.search = MagicMock(return_value=search_results)++ patcher = patch("azure.search.documents.aio.SearchClient", return_value=mock_client)++ return mock_client, patcher+++def test_validate_credentials_scenarios() -> None:+ """Test all validate_credentials scenarios to ensure full code coverage."""+ import sys++ from autogen_ext.tools.azure._config import AzureAISearchConfig++ module_path = sys.modules[AzureAISearchConfig.__module__].__file__+ if module_path is not None:+ assert "autogen-ext" in module_path++ data: Any = "not a dict"+ result: Any = AzureAISearchConfig.validate_credentials(data) # type: ignore+ assert result == data++ data_empty: Dict[str, Any] = {}+ result_empty: Dict[str, Any] = AzureAISearchConfig.validate_credentials(data_empty) # type: ignore+ assert isinstance(result_empty, dict)++ data_items: Dict[str, Any] = {"key1": "value1", "key2": "value2"}+ result_items: Dict[str, Any] = AzureAISearchConfig.validate_credentials(data_items) # type: ignore+ assert result_items["key1"] == "value1"+ assert result_items["key2"] == "value2"++ data_with_api_key: Dict[str, Any] = {+ "name": "test",+ "endpoint": "https://test.search.windows.net",+ "index_name": "test-index",+ "credential": {"api_key": "test-key"},+ }+ result_with_api_key: Dict[str, Any] = AzureAISearchConfig.validate_credentials(data_with_api_key) # type: ignore++ cred = result_with_api_key["credential"] # type: ignore+ assert isinstance(cred, (AzureKeyCredential, MockAzureKeyCredential))+ assert hasattr(cred, "key")+ assert cred.key == "test-key" # type: ignore++ credential: Any = AzureKeyCredential("test-key")+ data_with_credential: Dict[str, Any] = {+ "name": "test",+ "endpoint": "https://test.search.windows.net",+ "index_name": "test-index",+ "credential": credential,+ }+ result_with_credential: Dict[str, Any] = AzureAISearchConfig.validate_credentials(data_with_credential) # type: ignore+ assert result_with_credential["credential"] is credential++ data_without_api_key: Dict[str, Any] = {+ "name": "test",+ "endpoint": "https://test.search.windows.net",+ "index_name": "test-index",+ "credential": {"username": "test-user", "password": "test-pass"},+ }+ result_without_api_key: Dict[str, Any] = AzureAISearchConfig.validate_credentials(data_without_api_key) # type: ignore+ assert result_without_api_key["credential"] == {"username": "test-user", "password": "test-pass"}+++def test_model_dump_scenarios() -> None:+ """Test all model_dump scenarios to ensure full code coverage."""+ import sys++ from autogen_ext.tools.azure._config import AzureAISearchConfig++ module_path = sys.modules[AzureAISearchConfig.__module__].__file__+ if module_path is not None:+ assert "autogen-ext" in module_path++ config = AzureAISearchConfig(+ name="test",+ endpoint="https://endpoint",+ index_name="index",+ credential=AzureKeyCredential("key"), # type: ignore+ )+ result = config.model_dump()+ assert result["credential"] == {"type": "AzureKeyCredential"}++ if azure_sdk_available:+ from azure.core.credentials import AccessToken+ from azure.core.credentials import TokenCredential as RealTokenCredential++ class TestTokenCredential(RealTokenCredential):+ def get_token(self, *args: Any, **kwargs: Any) -> AccessToken:+ """Override of get_token method that returns proper type."""+ return AccessToken("test-token", 12345)++ config = AzureAISearchConfig(+ name="test", endpoint="https://endpoint", index_name="index", credential=TestTokenCredential()+ )+ result = config.model_dump()+ assert result["credential"] == {"type": "TokenCredential"}+ else:+ pytest.skip("Skipping TokenCredential test - Azure SDK not available")diff --git a/python/packages/autogen-ext/tests/tools/azure/test_ai_search_tool.py b/python/packages/autogen-ext/tests/tools/azure/test_ai_search_tool.pynew file mode 100644index 000000000..e34f19d8e--- /dev/null+++ b/python/packages/autogen-ext/tests/tools/azure/test_ai_search_tool.py@@ -0,0 +1,1080 @@+"""Tests for the Azure AI Search tool."""++from typing import Any, AsyncGenerator, Dict, List, Union, cast+from unittest.mock import AsyncMock, patch++import pytest+from autogen_core import CancellationToken+from autogen_ext.tools.azure._ai_search import (+ AzureAISearchTool,+ BaseAzureAISearchTool,+ SearchQuery,+ SearchResult,+ SearchResults,+ _allow_private_constructor, # pyright: ignore[reportPrivateUsage]+)+from azure.core.credentials import AzureKeyCredential, TokenCredential+from azure.core.exceptions import HttpResponseError+++class MockAsyncIterator:+ """Mock for async iterator to use in tests."""++ def __init__(self, items: List[Dict[str, Any]]) -> None:+ self.items = items.copy()++ def __aiter__(self) -> "MockAsyncIterator":+ return self++ async def __anext__(self) -> Dict[str, Any]:+ if not self.items:+ raise StopAsyncIteration+ return self.items.pop(0)+++async def search_tool() -> AsyncGenerator[AzureAISearchTool, None]:+ """Create a concrete search tool for testing."""++ class ConcreteSearchTool(AzureAISearchTool):+ async def _get_embedding(self, query: str) -> List[float]:+ return [0.1, 0.2, 0.3]++ token = _allow_private_constructor.set(True) # pyright: ignore[reportPrivateUsage]+ try:+ tool = ConcreteSearchTool(+ name="test-search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=cast(TokenCredential, AzureKeyCredential("test-key")),+ query_type="keyword",+ search_fields=["title", "content"],+ select_fields=["title", "content"],+ top=10,+ )+ yield tool+ finally:+ _allow_private_constructor.reset(token) # pyright: ignore[reportPrivateUsage]+++async def test_search_tool_run(search_tool: AsyncGenerator[AzureAISearchTool, None]) -> None:+ """Test the run method of the search tool."""+ tool = await anext(search_tool)+ query = "test query"+ cancellation_token = CancellationToken()++ with patch.object(tool, "_get_client", AsyncMock()) as mock_client:+ mock_client.return_value.search = AsyncMock(+ return_value=MockAsyncIterator([{"@search.score": 0.95, "title": "Test Doc", "content": "Test Content"}])+ )++ results = await tool.run(query, cancellation_token)+ assert isinstance(results, SearchResults)+ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Test Doc"+ assert results.results[0].score == 0.95+++async def test_search_tool_error_handling(search_tool: AsyncGenerator[AzureAISearchTool, None]) -> None:+ """Test error handling in the search tool."""+ tool = await anext(search_tool)+ with patch.object(tool, "_get_client", AsyncMock()) as mock_client:+ mock_client.return_value.search = AsyncMock(side_effect=ValueError("Test error"))++ with pytest.raises(ValueError, match="Test error"):+ await tool.run("test query", CancellationToken())+++async def test_search_tool_cancellation(search_tool: AsyncGenerator[AzureAISearchTool, None]) -> None:+ """Test cancellation of the search tool."""+ tool = await anext(search_tool)+ cancellation_token = CancellationToken()+ cancellation_token.cancel()++ with pytest.raises(ValueError, match="cancelled"):+ await tool.run("test query", cancellation_token)+++async def test_search_tool_vector_search() -> None:+ """Test vector search functionality."""++ class ConcreteSearchTool(AzureAISearchTool):+ async def _get_embedding(self, query: str) -> List[float]:+ return [0.1, 0.2, 0.3]++ token = _allow_private_constructor.set(True) # pyright: ignore[reportPrivateUsage]+ try:+ tool = ConcreteSearchTool(+ name="vector-search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=cast(TokenCredential, AzureKeyCredential("test-key")),+ query_type="vector",+ vector_fields=["embedding"],+ select_fields=["title", "content"],+ top=10,+ )++ with patch.object(tool, "_get_client", AsyncMock()) as mock_client:+ mock_client.return_value.search = AsyncMock(+ return_value=MockAsyncIterator(+ [{"@search.score": 0.95, "title": "Vector Doc", "content": "Vector Content"}]+ )+ )++ results = await tool.run("vector query", CancellationToken())+ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Vector Doc"+ assert results.results[0].score == 0.95+ finally:+ _allow_private_constructor.reset(token) # pyright: ignore[reportPrivateUsage]+++class ConcreteAzureAISearchTool(AzureAISearchTool):+ """Concrete implementation for testing."""++ async def _get_embedding(self, query: str) -> List[float]:+ return [0.1, 0.2, 0.3]+++async def test_create_keyword_search() -> None:+ """Test the create_keyword_search factory method."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="keyword_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=cast(TokenCredential, AzureKeyCredential("test-key")),+ search_fields=["title", "content"],+ select_fields=["title", "content"],+ filter="category eq 'test'",+ top=5,+ )++ assert tool.name == "keyword_search"+ assert tool.search_config.query_type == "keyword"+ assert tool.search_config.filter == "category eq 'test'"+++async def test_create_full_text_search() -> None:+ """Test the create_full_text_search factory method."""+ tool = ConcreteAzureAISearchTool.create_full_text_search(+ name="full_text_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=cast(TokenCredential, AzureKeyCredential("test-key")),+ search_fields=["title", "content"],+ select_fields=["title", "content"],+ filter="category eq 'test'",+ top=5,+ )++ assert tool.name == "full_text_search"+ assert tool.search_config.query_type == "fulltext"+ assert tool.search_config.search_fields == ["title", "content"]+ assert tool.search_config.select_fields == ["title", "content"]+ assert tool.search_config.filter == "category eq 'test'"+ assert tool.search_config.top == 5+++async def test_create_vector_search() -> None:+ """Test the create_vector_search factory method."""+ tool = ConcreteAzureAISearchTool.create_vector_search(+ name="vector_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=["embedding"],+ select_fields=["title", "content"],+ top=5,+ )++ assert tool.name == "vector_search"+ assert tool.search_config.query_type == "vector"+ assert tool.search_config.vector_fields == ["embedding"]+++async def test_create_hybrid_search() -> None:+ """Test the create_hybrid_search factory method."""+ tool = ConcreteAzureAISearchTool.create_hybrid_search(+ name="hybrid_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=["embedding"],+ search_fields=["title", "content"],+ select_fields=["title", "content"],+ top=5,+ )++ assert tool.name == "hybrid_search"+ assert tool.search_config.query_type == "hybrid"+ assert tool.search_config.vector_fields == ["embedding"]+ assert tool.search_config.search_fields == ["title", "content"]+++async def test_run_invalid_query() -> None:+ """Test the run method with an invalid query format."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ invalid_query: Dict[str, Any] = {"invalid_key": "invalid_value"}+ with pytest.raises(ValueError, match="Invalid search query format"):+ await tool.run(invalid_query)+++async def test_process_credential_dict() -> None:+ """Test the _process_credential method with a dictionary credential."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential={"api_key": "test-key"},+ )++ assert isinstance(tool.search_config.credential, AzureKeyCredential)+ assert tool.search_config.credential.key == "test-key"+++async def test_run_empty_query() -> None:+ """Test the run method with an empty query."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ with patch.object(tool, "_get_client", AsyncMock()):+ with pytest.raises(ValueError, match="Invalid search query format"):+ await tool.run("")+++async def test_get_client_initialization() -> None:+ """Test the _get_client method for proper initialization."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ assert tool.search_config.endpoint == "https://test.search.windows.net"+ assert tool.search_config.index_name == "test-index"++ mock_client = AsyncMock()++ class MockAsyncIterator:+ def __init__(self, items: List[Dict[str, Any]]) -> None:+ self.items = items++ def __aiter__(self) -> "MockAsyncIterator":+ return self++ async def __anext__(self) -> Dict[str, Any]:+ if not self.items:+ raise StopAsyncIteration+ return self.items.pop(0)++ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.9, "title": "Test Result"}])++ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run("test query", CancellationToken())+ mock_client.search.assert_called_once()++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Test Result"+ assert results.results[0].score == 0.9+++async def test_return_value_as_string() -> None:+ """Test the return_value_as_string method for formatting search results."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ results = SearchResults(+ results=[+ SearchResult(score=0.95, content={"title": "Doc 1"}, metadata={}),+ SearchResult(score=0.85, content={"title": "Doc 2"}, metadata={}),+ ]+ )++ result_string = tool.return_value_as_string(results)+ assert "Result 1 (Score: 0.95): title: Doc 1" in result_string+ assert "Result 2 (Score: 0.85): title: Doc 2" in result_string+++async def test_return_value_as_string_empty() -> None:+ """Test the return_value_as_string method with empty results."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ results = SearchResults(results=[])+ result_string = tool.return_value_as_string(results)+ assert result_string == "No results found."+++async def test_load_component() -> None:+ """Test the load_component method for proper deserialization."""+ model = {+ "provider": "autogen_ext.tools.azure.BaseAzureAISearchTool",+ "config": {+ "name": "test_tool",+ "endpoint": "https://test.search.windows.net",+ "index_name": "test-index",+ "credential": {"api_key": "test-key"},+ "query_type": "keyword",+ "search_fields": ["title", "content"],+ "select_fields": ["title", "content"],+ "top": 5,+ },+ }++ tool = ConcreteAzureAISearchTool.load_component(model)+ assert tool.name == "test_tool"+ assert tool.search_config.query_type == "keyword"+ assert tool.search_config.search_fields == ["title", "content"]+++async def test_caching_functionality() -> None:+ """Test the caching functionality of the search tool."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="cache_test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ enable_caching=True,+ cache_ttl_seconds=300,+ )++ mock_client = AsyncMock()+ mock_client.__aenter__.return_value = mock_client+ mock_client.__aexit__.return_value = None++ test_result = {"@search.score": 0.9, "title": "Test Result"}++ class MockAsyncIterator:+ def __init__(self) -> None:+ self.returned = False++ def __aiter__(self) -> "MockAsyncIterator":+ return self++ async def __anext__(self) -> Dict[str, Any]:+ if self.returned:+ raise StopAsyncIteration+ self.returned = True+ return test_result++ mock_client.search = AsyncMock(return_value=MockAsyncIterator())++ with patch.object(tool, "_get_client", return_value=mock_client):+ results1 = await tool.run("test query")+ assert len(results1.results) == 1+ assert results1.results[0].content["title"] == "Test Result"+ assert mock_client.search.call_count == 1++ mock_client.search = AsyncMock(return_value=MockAsyncIterator())++ results2 = await tool.run("test query")+ assert len(results2.results) == 1+ assert results2.results[0].content["title"] == "Test Result"+ assert mock_client.search.call_count == 1+++async def test_semantic_configuration_name_handling() -> None:+ """Test handling of semantic configuration names in fulltext search."""+ tool = ConcreteAzureAISearchTool.create_full_text_search(+ name="semantic_config_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ search_fields=["title", "content"],+ select_fields=["title", "content"],+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.9, "title": "Semantic Test Result"}])++ assert tool.search_config.query_type == "fulltext"+ assert tool.search_config.search_fields == ["title", "content"]++ with patch.object(tool, "_get_client", return_value=mock_client):+ mock_run = AsyncMock()+ mock_run.return_value = SearchResults(+ results=[SearchResult(score=0.9, content={"title": "Semantic Test Result"}, metadata={})]+ )++ with patch.object(tool, "run", mock_run):+ results = await tool.run("semantic query")+ mock_run.assert_called_once()++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Semantic Test Result"+++async def test_http_response_error_handling() -> None:+ """Test handling of different HTTP response errors."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ mock_client = AsyncMock()+ http_error = HttpResponseError()+ http_error.message = "401 Unauthorized: Access is denied due to invalid credentials"++ with patch.object(tool, "_get_client", return_value=mock_client):+ mock_client.search = AsyncMock(side_effect=http_error)+ with pytest.raises(ValueError, match="Authentication failed"):+ await tool.run("test query")++ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("invalid-key"),+ )++ with patch.object(tool, "_get_client", AsyncMock(side_effect=ValueError("Invalid key"))):+ with pytest.raises(ValueError, match="Authentication failed"):+ await tool.run("test query")+++async def test_run_with_search_query_object() -> None:+ """Test running the search with a SearchQuery object instead of a string."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.85, "title": "Query Object Test"}])++ with patch.object(tool, "_get_client", return_value=mock_client):+ search_query = SearchQuery(query="advanced query")+ results = await tool.run(search_query)++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Query Object Test"+ mock_client.search.assert_called_once()+++async def test_dict_document_processing() -> None:+ """Test processing of document with dict-like interface."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ class DictLikeDoc:+ def __init__(self, data: Dict[str, Any]) -> None:+ self._data = data++ def items(self) -> List[tuple[str, Any]]:+ return list(self._data.items())++ mock_client = AsyncMock()++ class SpecialMockAsyncIterator:+ def __init__(self) -> None:+ self.returned = False++ def __aiter__(self) -> "SpecialMockAsyncIterator":+ return self++ async def __anext__(self) -> DictLikeDoc:+ if self.returned:+ raise StopAsyncIteration+ self.returned = True+ return DictLikeDoc({"@search.score": 0.75, "title": "Dict Like Doc"})++ mock_client.search.return_value = SpecialMockAsyncIterator()++ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run("test query")++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Dict Like Doc"+ assert results.results[0].score == 0.75+++async def test_document_processing_error_handling() -> None:+ """Test error handling during document processing."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ mock_client = AsyncMock()++ class ProblemDoc:+ def items(self) -> None:+ raise AttributeError("Simulated error in document processing")++ class MixedResultsAsyncIterator:+ def __init__(self) -> None:+ self.docs: List[Union[Dict[str, Any], ProblemDoc]] = [+ {"@search.score": 0.9, "title": "Good Doc"},+ ProblemDoc(),+ {"@search.score": 0.8, "title": "Another Good Doc"},+ ]+ self.index = 0++ def __aiter__(self) -> "MixedResultsAsyncIterator":+ return self++ async def __anext__(self) -> Union[Dict[str, Any], ProblemDoc]:+ if self.index >= len(self.docs):+ raise StopAsyncIteration+ doc = self.docs[self.index]+ self.index += 1+ return doc++ mock_client.search.return_value = MixedResultsAsyncIterator()++ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run("test query")++ assert len(results.results) == 2+ assert results.results[0].content["title"] == "Good Doc"+ assert results.results[1].content["title"] == "Another Good Doc"+++async def test_index_not_found_error() -> None:+ """Test handling of 'index not found' error."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="nonexistent-index",+ credential=AzureKeyCredential("test-key"),+ )++ not_found_error = ValueError("The index 'nonexistent-index' was not found")++ with patch.object(tool, "_get_client", AsyncMock(side_effect=not_found_error)):+ with pytest.raises(ValueError, match="Index 'nonexistent-index' not found"):+ await tool.run("test query")+++async def test_http_response_with_500_error() -> None:+ """Test handling of HTTP 500 error responses."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ http_error = HttpResponseError()+ http_error.message = "500 Internal Server Error: Something went wrong on the server"++ with patch.object(tool, "_get_client", AsyncMock()) as mock_client:+ mock_client.return_value.search = AsyncMock(side_effect=http_error)++ with pytest.raises(ValueError, match="Error from Azure AI Search"):+ await tool.run("test query")+++async def test_cancellation_during_search() -> None:+ """Test cancellation token functionality during the search process."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ cancellation_token = CancellationToken()+ cancellation_token.cancel()++ with pytest.raises(ValueError, match="Operation cancelled"):+ await tool.run("test query", cancellation_token)+++async def test_run_with_dict_query_format() -> None:+ """Test running the search with a dictionary query format with 'query' key."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.85, "title": "Dict Query Test"}])++ with patch.object(tool, "_get_client", return_value=mock_client):+ query_dict = {"query": "dict style query"}+ results = await tool.run(query_dict)++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Dict Query Test"+ mock_client.search.assert_called_once()+++async def test_object_based_document_processing() -> None:+ """Test processing of document with object attributes instead of dict interface."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="test_tool",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ class ObjectDoc:+ """Test document class with object attributes."""++ def __init__(self) -> None:+ self.title = "Object Doc"+ self.content = "Object content"+ self._private_attr = "private"+ self.__search_score = 0.8++ mock_client = AsyncMock()++ class ObjectDocAsyncIterator:+ def __init__(self) -> None:+ self.returned = False++ def __aiter__(self) -> "ObjectDocAsyncIterator":+ return self++ async def __anext__(self) -> ObjectDoc:+ if self.returned:+ raise StopAsyncIteration+ self.returned = True+ return ObjectDoc()++ mock_client.search.return_value = ObjectDocAsyncIterator()++ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run("test query")++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Object Doc"+ assert results.results[0].content["content"] == "Object content"+ assert "_private_attr" not in results.results[0].content+++async def test_vector_search_with_provided_vectors() -> None:+ """Test vector search using vectors provided directly in the search options."""+ tool = ConcreteAzureAISearchTool.create_vector_search(+ name="vector_direct_search",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=["embedding"],+ select_fields=["title", "content"],+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.95, "title": "Vector Direct Test"}])++ query = "test vector search"++ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run(query)+ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Vector Direct Test"++ mock_client.search.assert_called_once()+++async def test_credential_token_expiry_handling() -> None:+ """Test handling credential token expiry and error cases."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="token_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ auth_error = HttpResponseError()+ auth_error.message = "401 Unauthorized: Access token has expired or is not yet valid"++ with patch.object(tool, "_get_client", AsyncMock()) as mock_client:+ mock_client.return_value.search = AsyncMock(side_effect=auth_error)++ with pytest.raises(ValueError, match="Authentication failed"):+ await tool.run("test query")++ token_error = ValueError("401 Unauthorized: Token is invalid")++ with patch.object(tool, "_get_client", AsyncMock(side_effect=token_error)):+ with pytest.raises(ValueError, match="Authentication failed"):+ await tool.run("test query")+++async def test_search_with_user_provided_vectors() -> None:+ """Test the use of user-provided embedding vectors in SearchQuery."""+ tool = ConcreteAzureAISearchTool.create_vector_search(+ name="vector_test_with_embeddings",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=["embedding"],+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.95, "title": "Vector Result"}])++ custom_vectors = [0.1, 0.2, 0.3, 0.4, 0.5]+ query_dict = {"query": "test query", "vectors": {"embedding": custom_vectors}}++ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run(query_dict)++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Vector Result"++ mock_client.search.assert_called_once()+ _, kwargs = mock_client.search.call_args+ assert "vector_queries" in kwargs+++async def test_component_loading_with_invalid_params() -> None:+ """Test loading components with invalid parameters."""++ class OtherClass:+ pass++ with pytest.raises(TypeError, match="Cannot create instance"):+ BaseAzureAISearchTool.load_component(+ {"provider": "autogen_ext.tools.azure.BaseAzureAISearchTool", "config": {}},+ expected=OtherClass, # type: ignore+ )++ with pytest.raises(Exception) as excinfo:+ ConcreteAzureAISearchTool.load_component("not a dict or ComponentModel") # type: ignore+ error_msg = str(excinfo.value).lower()+ assert any(text in error_msg for text in ["attribute", "type", "object", "dict", "str"])++ with pytest.raises(Exception) as excinfo:+ ConcreteAzureAISearchTool.load_component({})+ error_msg = str(excinfo.value).lower()+ assert any(text in error_msg for text in ["validation", "required", "missing", "field"])+++async def test_factory_method_validation() -> None:+ """Test validation in factory methods."""+ with pytest.raises(ValueError, match="endpoint must be a valid URL"):+ ConcreteAzureAISearchTool.create_keyword_search(+ name="test", endpoint="", index_name="test-index", credential=AzureKeyCredential("test-key")+ )++ with pytest.raises(ValueError, match="endpoint must be a valid URL"):+ ConcreteAzureAISearchTool.create_keyword_search(+ name="test", endpoint="invalid-url", index_name="test-index", credential=AzureKeyCredential("test-key")+ )++ with pytest.raises(ValueError, match="index_name cannot be empty"):+ ConcreteAzureAISearchTool.create_keyword_search(+ name="test",+ endpoint="https://test.search.windows.net",+ index_name="",+ credential=AzureKeyCredential("test-key"),+ )++ with pytest.raises(ValueError, match="name cannot be empty"):+ ConcreteAzureAISearchTool.create_keyword_search(+ name="",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ with pytest.raises(ValueError, match="credential cannot be None"):+ ConcreteAzureAISearchTool.create_keyword_search(+ name="test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=None, # type: ignore+ )++ with pytest.raises(ValueError, match="vector_fields must contain at least one field name"):+ ConcreteAzureAISearchTool.create_vector_search(+ name="test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=[],+ )++ with pytest.raises(ValueError, match="vector_fields must contain at least one field name"):+ ConcreteAzureAISearchTool.create_hybrid_search(+ name="test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=[],+ )+++async def test_direct_tool_initialization_error() -> None:+ """Test that directly initializing AzureAISearchTool raises an error."""++ class TestSearchTool(AzureAISearchTool):+ async def _get_embedding(self, query: str) -> List[float]:+ return [0.1, 0.2, 0.3]++ with pytest.raises(RuntimeError, match="Constructor is private"):+ TestSearchTool(+ name="test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ query_type="keyword",+ )+++async def test_credential_dict_with_missing_api_key() -> None:+ """Test handling of credential dict without api_key."""+ with pytest.raises(ValueError, match="If credential is a dict, it must contain an 'api_key' key"):+ ConcreteAzureAISearchTool.create_keyword_search(+ name="test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential={"invalid_key": "value"},+ )+++async def test_complex_error_handling_scenarios() -> None:+ """Test more complex error handling scenarios."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="error_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ permission_error = HttpResponseError()+ permission_error.message = "403 Forbidden: Access is denied"++ with patch.object(tool, "_get_client", AsyncMock(side_effect=permission_error)):+ with pytest.raises(ValueError, match="Error from Azure AI Search"):+ await tool.run("test query")++ unexpected_error = Exception("Unexpected error during initialization")++ with patch.object(tool, "_get_client", AsyncMock(side_effect=unexpected_error)):+ with pytest.raises(ValueError, match="Error from Azure AI Search"):+ await tool.run("test query")+++async def test_multi_step_vector_search() -> None:+ """Test a multi-step vector search with query embeddings and explicit search options."""+ tool = ConcreteAzureAISearchTool.create_vector_search(+ name="vector_multi_step",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ vector_fields=["embedding"],+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.98, "title": "Vector Embedding Test"}])++ embedding = [0.1, 0.2, 0.3, 0.4, 0.5]+ with patch.object(tool, "_get_embedding", AsyncMock(return_value=embedding)):+ with patch.object(tool, "_get_client", return_value=mock_client):+ results = await tool.run("vector embedding query")++ assert len(results.results) == 1+ assert results.results[0].content["title"] == "Vector Embedding Test"++ mock_client.search.assert_called_once()++ _, kwargs = mock_client.search.call_args+ assert "vector_queries" in kwargs+++async def test_error_handling_in_special_cases() -> None:+ """Test error handling for specific error cases that might be missed."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="error_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ not_found_error = ValueError("The requested resource with 'test-index' was not found")++ with patch.object(tool, "_get_client", AsyncMock(side_effect=not_found_error)):+ with pytest.raises(ValueError, match="Index 'test-index' not found"):+ await tool.run("error query")++ auth_error = ValueError("401 Unauthorized error occurred")++ with patch.object(tool, "_get_client", AsyncMock(side_effect=auth_error)):+ with pytest.raises(ValueError, match="Authentication failed"):+ await tool.run("auth error query")+++async def test_component_loading_with_config_model() -> None:+ """Test the load_component method with a ComponentModel instead of dict."""+ from autogen_core import ComponentModel++ model = ComponentModel(+ provider="autogen_ext.tools.azure.BaseAzureAISearchTool",+ config={+ "name": "model_test",+ "endpoint": "https://test.search.windows.net",+ "index_name": "test-index",+ "credential": {"api_key": "test-key"},+ "query_type": "keyword",+ "search_fields": ["title", "content"],+ },+ )++ with patch.object(ConcreteAzureAISearchTool, "create_keyword_search") as mock_create:+ mock_create.return_value = ConcreteAzureAISearchTool.create_keyword_search(+ name="model_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ tool = ConcreteAzureAISearchTool.load_component(model)++ assert tool.name == "model_test"+++async def test_fallback_vectorizable_text_query() -> None:+ """Test the fallback VectorizableTextQuery class when Azure SDK is not available."""++ class MockVectorizableTextQuery:+ def __init__(self, text: str, k: int, fields: str) -> None:+ self.text = text+ self.k = k+ self.fields = fields++ query1 = MockVectorizableTextQuery(text="test query", k=5, fields="title")+ assert query1.text == "test query"+ assert query1.fields == "title"++ query2 = MockVectorizableTextQuery(text="test query", k=3, fields="title,content")+ assert query2.text == "test query"+ assert query2.fields == "title,content"+++async def test_dump_component() -> None:+ """Test the dump_component method."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="dump_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ component_model = tool.dump_component()+ assert component_model.provider == "autogen_ext.tools.azure.BaseAzureAISearchTool"+ assert component_model.config["name"] == "dump_test"+ assert component_model.config["endpoint"] == "https://test.search.windows.net"+ assert component_model.config["index_name"] == "test-index"+++async def test_fallback_config_class() -> None:+ """Test the fallback configuration class."""+ from autogen_ext.tools.azure._ai_search import _FallbackAzureAISearchConfig # pyright: ignore[reportPrivateUsage]++ config = _FallbackAzureAISearchConfig(+ name="fallback_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ query_type="vector",+ vector_fields=["embedding"],+ top=10,+ )++ assert config.name == "fallback_test"+ assert config.endpoint == "https://test.search.windows.net"+ assert config.index_name == "test-index"+ assert config.query_type == "vector"+ assert config.vector_fields == ["embedding"]+ assert config.top == 10+++async def test_search_with_different_query_types() -> None:+ """Test search with different query types and parameters."""+ tool = ConcreteAzureAISearchTool.create_keyword_search(+ name="query_types_test",+ endpoint="https://test.search.windows.net",+ index_name="test-index",+ credential=AzureKeyCredential("test-key"),+ )++ mock_client = AsyncMock()+ mock_client.search.return_value = MockAsyncIterator([{"@search.score": 0.9, "title": "Test Result"}])++ with patch.object(tool, "_get_client", return_value=mock_client):+ await tool.run("string query")+ mock_client.search.assert_called_once()+ mock_client.search.reset_mock()++ await tool.run({"query": "dict query"})+ mock_client.search.assert_called_once()+ mock_client.search.reset_mock()++ await tool.run(SearchQuery(query="object query"))+ mock_client.search.assert_called_once()diff --git a/python/uv.lock b/python/uv.lockindex 9b40af4a2..f3fbf9038 100644--- a/python/uv.lock+++ b/python/uv.lock@@ -596,6 +596,7 @@ azure = [{ name = "azure-ai-inference" },{ name = "azure-core" },{ name = "azure-identity" },+ { name = "azure-search-documents" },]chromadb = [{ name = "chromadb" },@@ -732,6 +733,7 @@ requires-dist = [{ name = "azure-ai-inference", marker = "extra == 'azure'", specifier = ">=1.0.0b7" },{ name = "azure-core", marker = "extra == 'azure'" },{ name = "azure-identity", marker = "extra == 'azure'" },+ { name = "azure-search-documents", marker = "extra == 'azure'", specifier = ">=11.4.0" },{ name = "chromadb", marker = "extra == 'chromadb'" },{ name = "chromadb", marker = "extra == 'task-centric-memory'", specifier = ">=0.6.3" },{ name = "diskcache", marker = "extra == 'diskcache'", specifier = ">=5.6.3" },