diff --git a/testbed/deepset-ai__haystack/haystack/__init__.py b/testbed/deepset-ai__haystack/haystack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a8712024c887d030eaca80ae4eabb26d2ebe9353 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/__init__.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import haystack.logging +import haystack.tracing +from haystack.core.component import component +from haystack.core.errors import ComponentError, DeserializationError +from haystack.core.pipeline import Pipeline, PredefinedPipeline +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.dataclasses import Answer, Document, ExtractedAnswer, GeneratedAnswer + +# Initialize the logging configuration +# This is a no-op unless `structlog` is installed +haystack.logging.configure_logging() + +# Same for tracing (no op if `opentelemetry` or `ddtrace` is not installed) +haystack.tracing.auto_enable_tracing() + +__all__ = [ + "component", + "default_from_dict", + "default_to_dict", + "DeserializationError", + "ComponentError", + "Pipeline", + "PredefinedPipeline", + "Document", + "Answer", + "GeneratedAnswer", + "ExtractedAnswer", +] + +# FIXME: remove before merging PR diff --git a/testbed/deepset-ai__haystack/haystack/components/__init__.py b/testbed/deepset-ai__haystack/haystack/components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/haystack/components/connectors/__init__.py b/testbed/deepset-ai__haystack/haystack/components/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9fbe418aa57b08bb00c58b62c167e9697e87dae --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/connectors/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.connectors.openapi_service import OpenAPIServiceConnector + +__all__ = ["OpenAPIServiceConnector"] diff --git a/testbed/deepset-ai__haystack/haystack/components/connectors/openapi_service.py b/testbed/deepset-ai__haystack/haystack/components/connectors/openapi_service.py new file mode 100644 index 0000000000000000000000000000000000000000..5238722f7fedce5bdb018c2271a417020d7b30e7 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/connectors/openapi_service.py @@ -0,0 +1,270 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from collections import defaultdict +from copy import copy +from typing import Any, Dict, List, Optional, Union + +from haystack import component, logging +from haystack.dataclasses import ChatMessage, ChatRole +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install openapi3'") as openapi_imports: + from openapi3 import OpenAPI + + +@component +class OpenAPIServiceConnector: + """ + A component which connects the Haystack framework to OpenAPI services. + + The `OpenAPIServiceConnector` component connects the Haystack framework to OpenAPI services, enabling it to call + operations as defined in the OpenAPI specification of the service. + + It integrates with `ChatMessage` dataclass, where the payload in messages is used to determine the method to be + called and the parameters to be passed. The message payload should be an OpenAI JSON formatted function calling + string consisting of the method name and the parameters to be passed to the method. The method name and parameters + are then used to invoke the method on the OpenAPI service. The response from the service is returned as a + `ChatMessage`. + + Before using this component, users usually resolve service endpoint parameters with a help of + `OpenAPIServiceToFunctions` component. + + The example below demonstrates how to use the `OpenAPIServiceConnector` to invoke a method on a https://serper.dev/ + service specified via OpenAPI specification. + + Note, however, that `OpenAPIServiceConnector` is usually not meant to be used directly, but rather as part of a + pipeline that includes the `OpenAPIServiceToFunctions` component and an `OpenAIChatGenerator` component using LLM + with the function calling capabilities. In the example below we use the function calling payload directly, but in a + real-world scenario, the function calling payload would usually be generated by the `OpenAIChatGenerator` component. + + Usage example: + + ```python + import json + import requests + + from haystack.components.connectors import OpenAPIServiceConnector + from haystack.dataclasses import ChatMessage + + + fc_payload = [{'function': {'arguments': '{"q": "Why was Sam Altman ousted from OpenAI?"}', 'name': 'search'}, + 'id': 'call_PmEBYvZ7mGrQP5PUASA5m9wO', 'type': 'function'}] + + serper_token = + serperdev_openapi_spec = json.loads(requests.get("https://bit.ly/serper_dev_spec").text) + service_connector = OpenAPIServiceConnector() + result = service_connector.run(messages=[ChatMessage.from_assistant(json.dumps(fc_payload))], + service_openapi_spec=serperdev_openapi_spec, service_credentials=serper_token) + print(result) + + >> {'service_response': [ChatMessage(content='{"searchParameters": {"q": "Why was Sam Altman ousted from OpenAI?", + >> "type": "search", "engine": "google"}, "answerBox": {"snippet": "Concerns over AI safety and OpenAI\'s role + >> in protecting were at the center of Altman\'s brief ouster from the company."... + ``` + + """ + + def __init__(self): + """ + Initializes the OpenAPIServiceConnector instance + """ + openapi_imports.check() + + @component.output_types(service_response=Dict[str, Any]) + def run( + self, + messages: List[ChatMessage], + service_openapi_spec: Dict[str, Any], + service_credentials: Optional[Union[dict, str]] = None, + ) -> Dict[str, List[ChatMessage]]: + """ + Processes a list of chat messages to invoke a method on an OpenAPI service. + + It parses the last message in the list, expecting it to contain an OpenAI function calling descriptor + (name & parameters) in JSON format. + + :param messages: A list of `ChatMessage` objects containing the messages to be processed. The last message + should contain the function invocation payload in OpenAI function calling format. See the example in the class + docstring for the expected format. + :param service_openapi_spec: The OpenAPI JSON specification object of the service to be invoked. All the refs + should already be resolved. + :param service_credentials: The credentials to be used for authentication with the service. + Currently, only the http and apiKey OpenAPI security schemes are supported. + + :return: A dictionary with the following keys: + - `service_response`: a list of `ChatMessage` objects, each containing the response from the service. The + response is in JSON format, and the `content` attribute of the `ChatMessage` contains + the JSON string. + + :raises ValueError: If the last message is not from the assistant or if it does not contain the correct payload + to invoke a method on the service. + """ + + last_message = messages[-1] + if not last_message.is_from(ChatRole.ASSISTANT): + raise ValueError(f"{last_message} is not from the assistant.") + + function_invocation_payloads = self._parse_message(last_message) + + # instantiate the OpenAPI service for the given specification + openapi_service = OpenAPI(service_openapi_spec) + self._authenticate_service(openapi_service, service_credentials) + + response_messages = [] + for method_invocation_descriptor in function_invocation_payloads: + service_response = self._invoke_method(openapi_service, method_invocation_descriptor) + # openapi3 parses the JSON service response into a model object, which is not our focus at the moment. + # Instead, we require direct access to the raw JSON data of the response, rather than the model objects + # provided by the openapi3 library. This approach helps us avoid issues related to (de)serialization. + # By accessing the raw JSON response through `service_response._raw_data`, we can serialize this data + # into a string. Finally, we use this string to create a ChatMessage object. + response_messages.append(ChatMessage.from_user(json.dumps(service_response._raw_data))) + + return {"service_response": response_messages} + + def _parse_message(self, message: ChatMessage) -> List[Dict[str, Any]]: + """ + Parses the message to extract the method invocation descriptor. + + :param message: ChatMessage containing the tools calls + :return: A list of function invocation payloads + :raises ValueError: If the content is not valid JSON or lacks required fields. + """ + function_payloads = [] + try: + tool_calls = json.loads(message.content) + except json.JSONDecodeError: + raise ValueError("Invalid JSON content, expected OpenAI tools message.", message.content) + + for tool_call in tool_calls: + # this should never happen, but just in case do a sanity check + if "type" not in tool_call: + raise ValueError("Message payload doesn't seem to be a tool invocation descriptor", message.content) + + # In OpenAPIServiceConnector we know how to handle functions tools only + if tool_call["type"] == "function": + function_call = tool_call["function"] + function_payloads.append( + {"arguments": json.loads(function_call["arguments"]), "name": function_call["name"]} + ) + return function_payloads + + def _authenticate_service(self, openapi_service: OpenAPI, credentials: Optional[Union[dict, str]] = None): + """ + Authentication with an OpenAPI service. + + Authenticates with the OpenAPI service if required, supporting both single (str) and multiple + authentication methods (dict). + + OpenAPI spec v3 supports the following security schemes: + http – for Basic, Bearer and other HTTP authentications schemes + apiKey – for API keys and cookie authentication + oauth2 – for OAuth 2 + openIdConnect – for OpenID Connect Discovery + + Currently, only the http and apiKey schemes are supported. Multiple security schemes can be defined in the + OpenAPI spec, and the credentials should be provided as a dictionary with keys matching the security scheme + names. If only one security scheme is defined, the credentials can be provided as a simple string. + + :param openapi_service: The OpenAPI service instance. + :param credentials: Credentials for authentication, which can be either a string (e.g. token) or a dictionary + with keys matching the authentication method names. + :raises ValueError: If authentication fails, is not found, or if appropriate credentials are missing. + """ + if openapi_service.raw_element.get("components", {}).get("securitySchemes"): + service_name = openapi_service.info.title + if not credentials: + raise ValueError(f"Service {service_name} requires authentication but no credentials were provided.") + + # a dictionary of security schemes defined in the OpenAPI spec + # each key is the name of the security scheme, and the value is the scheme definition + security_schemes = openapi_service.components.securitySchemes.raw_element + supported_schemes = ["http", "apiKey"] # todo: add support for oauth2 and openIdConnect + + authenticated = False + for scheme_name, scheme in security_schemes.items(): + if scheme["type"] in supported_schemes: + auth_credentials = None + if isinstance(credentials, str): + auth_credentials = credentials + elif isinstance(credentials, dict) and scheme_name in credentials: + auth_credentials = credentials[scheme_name] + if auth_credentials: + openapi_service.authenticate(scheme_name, auth_credentials) + authenticated = True + break + + raise ValueError( + f"Service {service_name} requires {scheme_name} security scheme but no " + f"credentials were provided for it. Check the service configuration and credentials." + ) + if not authenticated: + raise ValueError( + f"Service {service_name} requires authentication but no credentials were provided " + f"for it. Check the service configuration and credentials." + ) + + def _invoke_method(self, openapi_service: OpenAPI, method_invocation_descriptor: Dict[str, Any]) -> Any: + """ + Invokes the specified method on the OpenAPI service. + + The method name and arguments are passed in the method_invocation_descriptor. + + :param openapi_service: The OpenAPI service instance. + :param method_invocation_descriptor: The method name and arguments to be passed to the method. The payload + should contain the method name (key: "name") and the arguments (key: "arguments"). The name is a string, and + the arguments are a dictionary of key-value pairs. + :return: A service JSON response. + :raises RuntimeError: If the method is not found or invocation fails. + """ + name = method_invocation_descriptor.get("name") + invocation_arguments = copy(method_invocation_descriptor.get("arguments", {})) + if not name or not invocation_arguments: + raise ValueError( + f"Invalid function calling descriptor: {method_invocation_descriptor} . It should contain " + f"a method name and arguments." + ) + + # openapi3 specific method to call the operation, do we have it? + method_to_call = getattr(openapi_service, f"call_{name}", None) + if not callable(method_to_call): + raise RuntimeError(f"Operation {name} not found in OpenAPI specification {openapi_service.info.title}") + + # get the operation reference from the method_to_call + operation = method_to_call.operation.__self__ + operation_dict = operation.raw_element + + # Pack URL/query parameters under "parameters" key + method_call_params: Dict[str, Dict[str, Any]] = defaultdict(dict) + parameters = operation_dict.get("parameters", []) + request_body = operation_dict.get("requestBody", {}) + + for param in parameters: + param_name = param["name"] + param_value = invocation_arguments.get(param_name) + if param_value: + method_call_params["parameters"][param_name] = param_value + else: + if param.get("required", False): + raise ValueError(f"Missing parameter: '{param_name}' required for the '{name}' operation.") + + # Pack request body parameters under "data" key + if request_body: + schema = request_body.get("content", {}).get("application/json", {}).get("schema", {}) + required_params = schema.get("required", []) + for param_name in schema.get("properties", {}): + param_value = invocation_arguments.get(param_name) + if param_value: + method_call_params["data"][param_name] = param_value + else: + if param_name in required_params: + raise ValueError( + f"Missing requestBody parameter: '{param_name}' required for the '{name}' operation." + ) + # call the underlying service REST API with the parameters + return method_to_call(**method_call_params) diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/__init__.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d57da5c1f2bf129478ab8fd7e864de569de1943a --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/__init__.py @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .answer_exact_match import AnswerExactMatchEvaluator +from .context_relevance import ContextRelevanceEvaluator +from .document_map import DocumentMAPEvaluator +from .document_mrr import DocumentMRREvaluator +from .document_ndcg import DocumentNDCGEvaluator +from .document_recall import DocumentRecallEvaluator +from .faithfulness import FaithfulnessEvaluator +from .llm_evaluator import LLMEvaluator +from .sas_evaluator import SASEvaluator + +__all__ = [ + "AnswerExactMatchEvaluator", + "ContextRelevanceEvaluator", + "DocumentMAPEvaluator", + "DocumentMRREvaluator", + "DocumentNDCGEvaluator", + "DocumentRecallEvaluator", + "FaithfulnessEvaluator", + "LLMEvaluator", + "SASEvaluator", +] diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/answer_exact_match.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/answer_exact_match.py new file mode 100644 index 0000000000000000000000000000000000000000..dd9026b2bdf85e3f357564bc050482a852830b9b --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/answer_exact_match.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack.core.component import component + + +@component +class AnswerExactMatchEvaluator: + """ + An answer exact match evaluator class. + + The evaluator that checks if the predicted answers matches any of the ground truth answers exactly. + The result is a number from 0.0 to 1.0, it represents the proportion of predicted answers + that matched one of the ground truth answers. + There can be multiple ground truth answers and multiple predicted answers as input. + + + Usage example: + ```python + from haystack.components.evaluators import AnswerExactMatchEvaluator + + evaluator = AnswerExactMatchEvaluator() + result = evaluator.run( + ground_truth_answers=["Berlin", "Paris"], + predicted_answers=["Berlin", "Lyon"], + ) + + print(result["individual_scores"]) + # [1, 0] + print(result["score"]) + # 0.5 + ``` + """ + + @component.output_types(individual_scores=List[int], score=float) + def run(self, ground_truth_answers: List[str], predicted_answers: List[str]) -> Dict[str, Any]: + """ + Run the AnswerExactMatchEvaluator on the given inputs. + + The `ground_truth_answers` and `retrieved_answers` must have the same length. + + :param ground_truth_answers: + A list of expected answers. + :param predicted_answers: + A list of predicted answers. + :returns: + A dictionary with the following outputs: + - `individual_scores` - A list of 0s and 1s, where 1 means that the predicted answer matched one of the + ground truth. + - `score` - A number from 0.0 to 1.0 that represents the proportion of questions where any predicted + answer matched one of the ground truth answers. + """ + if not len(ground_truth_answers) == len(predicted_answers): + raise ValueError("The length of ground_truth_answers and predicted_answers must be the same.") + + matches = [] + for truth, extracted in zip(ground_truth_answers, predicted_answers): + if truth == extracted: + matches.append(1) + else: + matches.append(0) + + # The proportion of questions where any predicted answer matched one of the ground truth answers + average = sum(matches) / len(predicted_answers) + + return {"individual_scores": matches, "score": average} diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/context_relevance.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/context_relevance.py new file mode 100644 index 0000000000000000000000000000000000000000..c60bd0bd53304052bf17d26efe93e0f33f4ecd84 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/context_relevance.py @@ -0,0 +1,222 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from statistics import mean +from typing import Any, Dict, List, Optional + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.evaluators.llm_evaluator import LLMEvaluator +from haystack.utils import Secret, deserialize_secrets_inplace + +# Private global variable for default examples to include in the prompt if the user does not provide any examples +_DEFAULT_EXAMPLES = [ + { + "inputs": { + "questions": "What is the capital of Germany?", + "contexts": ["Berlin is the capital of Germany. Berlin and was founded in 1244."], + }, + "outputs": {"relevant_statements": ["Berlin is the capital of Germany."]}, + }, + { + "inputs": { + "questions": "What is the capital of France?", + "contexts": [ + "Berlin is the capital of Germany and was founded in 1244.", + "Europe is a continent with 44 countries.", + "Madrid is the capital of Spain.", + ], + }, + "outputs": {"relevant_statements": []}, + }, + { + "inputs": {"questions": "What is the capital of Italy?", "contexts": ["Rome is the capital of Italy."]}, + "outputs": {"relevant_statements": ["Rome is the capital of Italy."]}, + }, +] + + +@component +class ContextRelevanceEvaluator(LLMEvaluator): + """ + Evaluator that checks if a provided context is relevant to the question. + + An LLM breaks up a context into multiple statements and checks whether each statement + is relevant for answering a question. + The score for each context is either binary score of 1 or 0, where 1 indicates that the context is relevant + to the question and 0 indicates that the context is not relevant. + The evaluator also provides the relevant statements from the context and an average score over all the provided + input questions contexts pairs. + + Usage example: + ```python + from haystack.components.evaluators import ContextRelevanceEvaluator + + questions = ["Who created the Python language?", "Why does Java needs a JVM?", "Is C++ better than Python?"] + contexts = [ + [( + "Python, created by Guido van Rossum in the late 1980s, is a high-level general-purpose programming " + "language. Its design philosophy emphasizes code readability, and its language constructs aim to help " + "programmers write clear, logical code for both small and large-scale software projects." + )], + [( + "Java is a high-level, class-based, object-oriented programming language that is designed to have as few " + "implementation dependencies as possible. The JVM has two primary functions: to allow Java programs to run" + "on any device or operating system (known as the 'write once, run anywhere' principle), and to manage and" + "optimize program memory." + )], + [( + "C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C " + "programming language." + )], + ] + + evaluator = ContextRelevanceEvaluator() + result = evaluator.run(questions=questions, contexts=contexts) + print(result["score"]) + # 0.67 + print(result["individual_scores"]) + # [1,1,0] + print(result["results"]) + # [{ + # 'relevant_statements': ['Python, created by Guido van Rossum in the late 1980s.'], + # 'score': 1.0 + # }, + # { + # 'relevant_statements': ['The JVM has two primary functions: to allow Java programs to run on any device or + # operating system (known as the "write once, run anywhere" principle), and to manage and + # optimize program memory'], + # 'score': 1.0 + # }, + # { + # 'relevant_statements': [], + # 'score': 0.0 + # }] + ``` + """ + + def __init__( + self, + examples: Optional[List[Dict[str, Any]]] = None, + progress_bar: bool = True, + api: str = "openai", + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + api_params: Optional[Dict[str, Any]] = None, + raise_on_failure: bool = True, + ): + """ + Creates an instance of ContextRelevanceEvaluator. + + :param examples: + Optional few-shot examples conforming to the expected input and output format of ContextRelevanceEvaluator. + Default examples will be used if none are provided. + Each example must be a dictionary with keys "inputs" and "outputs". + "inputs" must be a dictionary with keys "questions" and "contexts". + "outputs" must be a dictionary with "relevant_statements". + Expected format: + [{ + "inputs": { + "questions": "What is the capital of Italy?", "contexts": ["Rome is the capital of Italy."], + }, + "outputs": { + "relevant_statements": ["Rome is the capital of Italy."], + }, + }] + :param progress_bar: + Whether to show a progress bar during the evaluation. + :param api: + The API to use for calling an LLM through a Generator. + Supported APIs: "openai". + :param api_key: + The API key. + :param api_params: + Parameters for an OpenAI API compatible completions call. + :param raise_on_failure: + Whether to raise an exception if the API call fails. + + """ + + self.instructions = ( + "Please extract only sentences from the provided context which are absolutely relevant and " + "required to answer the following question. If no relevant sentences are found, or if you " + "believe the question cannot be answered from the given context, return an empty list, example: []" + ) + self.inputs = [("questions", List[str]), ("contexts", List[List[str]])] + self.outputs = ["relevant_statements"] + self.examples = examples or _DEFAULT_EXAMPLES + self.api = api + self.api_key = api_key + self.api_params = api_params or {} + + super(ContextRelevanceEvaluator, self).__init__( + instructions=self.instructions, + inputs=self.inputs, + outputs=self.outputs, + examples=self.examples, + api=self.api, + api_key=self.api_key, + api_params=self.api_params, + raise_on_failure=raise_on_failure, + progress_bar=progress_bar, + ) + + @component.output_types(score=float, results=List[Dict[str, Any]]) + def run(self, **inputs) -> Dict[str, Any]: + """ + Run the LLM evaluator. + + :param questions: + A list of questions. + :param contexts: + A list of lists of contexts. Each list of contexts corresponds to one question. + :returns: + A dictionary with the following outputs: + - `score`: Mean context relevance score over all the provided input questions. + - `results`: A list of dictionaries with `relevant_statements` and `score` for each input context. + """ + result = super(ContextRelevanceEvaluator, self).run(**inputs) + + for idx, res in enumerate(result["results"]): + if res is None: + result["results"][idx] = {"relevant_statements": [], "score": float("nan")} + continue + if len(res["relevant_statements"]) > 0: + res["score"] = 1 + else: + res["score"] = 0 + + # calculate average context relevance score over all queries + result["score"] = mean([res["score"] for res in result["results"]]) + result["individual_scores"] = [res["score"] for res in result["results"]] # useful for the EvaluationRunResult + + return result + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + A dictionary with serialized data. + """ + return default_to_dict( + self, + api=self.api, + api_key=self.api_key.to_dict() if self.api_key else None, + examples=self.examples, + progress_bar=self.progress_bar, + api_params=self.api_params, + raise_on_failure=self.raise_on_failure, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ContextRelevanceEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/document_map.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_map.py new file mode 100644 index 0000000000000000000000000000000000000000..f4543671c0088be00e066314027175a0d557ea96 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_map.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack import Document, component + + +@component +class DocumentMAPEvaluator: + """ + A Mean Average Precision (MAP) evaluator for documents. + + Evaluator that calculates the mean average precision of the retrieved documents, a metric + that measures how high retrieved documents are ranked. + Each question can have multiple ground truth documents and multiple retrieved documents. + + `DocumentMAPEvaluator` doesn't normalize its inputs, the `DocumentCleaner` component + should be used to clean and normalize the documents before passing them to this evaluator. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentMAPEvaluator + + evaluator = DocumentMAPEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + ], + ) + + print(result["individual_scores"]) + # [1.0, 0.8333333333333333] + print(result["score"]) + # 0.9166666666666666 + ``` + """ + + # Refer to https://www.pinecone.io/learn/offline-evaluation/ for the algorithm. + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentMAPEvaluator on the given inputs. + + All lists must have the same length. + + :param ground_truth_documents: + A list of expected documents for each question. + :param retrieved_documents: + A list of retrieved documents for each question. + :returns: + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `individual_scores` - A list of numbers from 0.0 to 1.0 that represents how high retrieved documents + are ranked. + """ + if len(ground_truth_documents) != len(retrieved_documents): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + individual_scores = [] + + for ground_truth, retrieved in zip(ground_truth_documents, retrieved_documents): + average_precision = 0.0 + average_precision_numerator = 0.0 + relevant_documents = 0 + + ground_truth_contents = [doc.content for doc in ground_truth if doc.content is not None] + for rank, retrieved_document in enumerate(retrieved): + if retrieved_document.content is None: + continue + + if retrieved_document.content in ground_truth_contents: + relevant_documents += 1 + average_precision_numerator += relevant_documents / (rank + 1) + if relevant_documents > 0: + average_precision = average_precision_numerator / relevant_documents + individual_scores.append(average_precision) + + score = sum(individual_scores) / len(ground_truth_documents) + return {"score": score, "individual_scores": individual_scores} diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/document_mrr.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_mrr.py new file mode 100644 index 0000000000000000000000000000000000000000..fbbaa1265680f6d9d34b0ea966f92e0581d117ea --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_mrr.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List + +from haystack import Document, component + + +@component +class DocumentMRREvaluator: + """ + Evaluator that calculates the mean reciprocal rank of the retrieved documents. + + MRR measures how high the first retrieved document is ranked. + Each question can have multiple ground truth documents and multiple retrieved documents. + + `DocumentMRREvaluator` doesn't normalize its inputs, the `DocumentCleaner` component + should be used to clean and normalize the documents before passing them to this evaluator. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentMRREvaluator + + evaluator = DocumentMRREvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + ], + ) + print(result["individual_scores"]) + # [1.0, 1.0] + print(result["score"]) + # 1.0 + ``` + """ + + # Refer to https://www.pinecone.io/learn/offline-evaluation/ for the algorithm. + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentMRREvaluator on the given inputs. + + `ground_truth_documents` and `retrieved_documents` must have the same length. + + :param ground_truth_documents: + A list of expected documents for each question. + :param retrieved_documents: + A list of retrieved documents for each question. + :returns: + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `individual_scores` - A list of numbers from 0.0 to 1.0 that represents how high the first retrieved + document is ranked. + """ + if len(ground_truth_documents) != len(retrieved_documents): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + individual_scores = [] + + for ground_truth, retrieved in zip(ground_truth_documents, retrieved_documents): + reciprocal_rank = 0.0 + + ground_truth_contents = [doc.content for doc in ground_truth if doc.content is not None] + for rank, retrieved_document in enumerate(retrieved): + if retrieved_document.content is None: + continue + if retrieved_document.content in ground_truth_contents: + reciprocal_rank = 1 / (rank + 1) + break + individual_scores.append(reciprocal_rank) + + score = sum(individual_scores) / len(ground_truth_documents) + + return {"score": score, "individual_scores": individual_scores} diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/document_ndcg.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_ndcg.py new file mode 100644 index 0000000000000000000000000000000000000000..e3430f1db7cc35f3600228ac9a8d9e06f92ce7df --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_ndcg.py @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from math import log2 +from typing import Any, Dict, List + +from haystack import Document, component + + +@component +class DocumentNDCGEvaluator: + """ + Evaluator that calculates the normalized discounted cumulative gain (NDCG) of retrieved documents. + + Each question can have multiple ground truth documents and multiple retrieved documents. + If the ground truth documents have relevance scores, the NDCG calculation uses these scores. + Otherwise, it assumes binary relevance of all ground truth documents. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentNDCGEvaluator + + evaluator = DocumentNDCGEvaluator() + result = evaluator.run( + ground_truth_documents=[[Document(content="France", score=1.0), Document(content="Paris", score=0.5)]], + retrieved_documents=[[Document(content="France"), Document(content="Germany"), Document(content="Paris")]], + ) + print(result["individual_scores"]) + # [0.8869] + print(result["score"]) + # 0.8869 + ``` + """ + + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentNDCGEvaluator on the given inputs. + + `ground_truth_documents` and `retrieved_documents` must have the same length. + The list items within `ground_truth_documents` and `retrieved_documents` can differ in length. + + :param ground_truth_documents: + Lists of expected documents, one list per question. Binary relevance is used if documents have no scores. + :param retrieved_documents: + Lists of retrieved documents, one list per question. + :returns: + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `individual_scores` - A list of numbers from 0.0 to 1.0 that represents the NDCG for each question. + """ + self.validate_inputs(ground_truth_documents, retrieved_documents) + + individual_scores = [] + + for gt_docs, ret_docs in zip(ground_truth_documents, retrieved_documents): + dcg = self.calculate_dcg(gt_docs, ret_docs) + idcg = self.calculate_idcg(gt_docs) + ndcg = dcg / idcg if idcg > 0 else 0 + individual_scores.append(ndcg) + + score = sum(individual_scores) / len(ground_truth_documents) + + return {"score": score, "individual_scores": individual_scores} + + @staticmethod + def validate_inputs(gt_docs: List[List[Document]], ret_docs: List[List[Document]]): + """ + Validate the input parameters. + + :param gt_docs: + The ground_truth_documents to validate. + :param ret_docs: + The retrieved_documents to validate. + + :raises ValueError: + If the ground_truth_documents or the retrieved_documents are an empty a list. + If the length of ground_truth_documents and retrieved_documents differs. + If any list of documents in ground_truth_documents contains a mix of documents with and without a score. + """ + if len(gt_docs) == 0 or len(ret_docs) == 0: + msg = "ground_truth_documents and retrieved_documents must be provided." + raise ValueError(msg) + + if len(gt_docs) != len(ret_docs): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + for docs in gt_docs: + if any(doc.score is not None for doc in docs) and any(doc.score is None for doc in docs): + msg = "Either none or all documents in each list of ground_truth_documents must have a score." + raise ValueError(msg) + + @staticmethod + def calculate_dcg(gt_docs: List[Document], ret_docs: List[Document]) -> float: + """ + Calculate the discounted cumulative gain (DCG) of the retrieved documents. + + :param gt_docs: + The ground truth documents. + :param ret_docs: + The retrieved documents. + :returns: + The discounted cumulative gain (DCG) of the retrieved + documents based on the ground truth documents. + """ + dcg = 0.0 + relevant_id_to_score = {doc.id: doc.score if doc.score is not None else 1 for doc in gt_docs} + for i, doc in enumerate(ret_docs): + if doc.id in relevant_id_to_score: # TODO Related to https://github.com/deepset-ai/haystack/issues/8412 + dcg += relevant_id_to_score[doc.id] / log2(i + 2) # i + 2 because i is 0-indexed + return dcg + + @staticmethod + def calculate_idcg(gt_docs: List[Document]) -> float: + """ + Calculate the ideal discounted cumulative gain (IDCG) of the ground truth documents. + + :param gt_docs: + The ground truth documents. + :returns: + The ideal discounted cumulative gain (IDCG) of the ground truth documents. + """ + idcg = 0.0 + for i, doc in enumerate(sorted(gt_docs, key=lambda x: x.score if x.score is not None else 1, reverse=True)): + # If the document has a score, use it; otherwise, use 1 for binary relevance. + relevance = doc.score if doc.score is not None else 1 + idcg += relevance / log2(i + 2) # i + 2 because i is 0-indexed + return idcg diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/document_recall.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0f1be3c90b079a4d9bf781788f78533cbefa96 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/document_recall.py @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from typing import Any, Dict, List, Union + +from haystack import component, default_to_dict +from haystack.dataclasses import Document + + +class RecallMode(Enum): + """ + Enum for the mode to use for calculating the recall score. + """ + + # Score is based on whether any document is retrieved. + SINGLE_HIT = "single_hit" + # Score is based on how many documents were retrieved. + MULTI_HIT = "multi_hit" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "RecallMode": + """ + Convert a string to a RecallMode enum. + """ + enum_map = {e.value: e for e in RecallMode} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown recall mode '{string}'. Supported modes are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +@component +class DocumentRecallEvaluator: + """ + Evaluator that calculates the Recall score for a list of documents. + + Returns both a list of scores for each question and the average. + There can be multiple ground truth documents and multiple predicted documents as input. + + Usage example: + ```python + from haystack import Document + from haystack.components.evaluators import DocumentRecallEvaluator + + evaluator = DocumentRecallEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + ], + ) + print(result["individual_scores"]) + # [1.0, 1.0] + print(result["score"]) + # 1.0 + ``` + """ + + def __init__(self, mode: Union[str, RecallMode] = RecallMode.SINGLE_HIT): + """ + Create a DocumentRecallEvaluator component. + + :param mode: + Mode to use for calculating the recall score. + """ + if isinstance(mode, str): + mode = RecallMode.from_str(mode) + + mode_functions = {RecallMode.SINGLE_HIT: self._recall_single_hit, RecallMode.MULTI_HIT: self._recall_multi_hit} + self.mode_function = mode_functions[mode] + self.mode = mode + + def _recall_single_hit(self, ground_truth_documents: List[Document], retrieved_documents: List[Document]) -> float: + unique_truths = {g.content for g in ground_truth_documents} + unique_retrievals = {p.content for p in retrieved_documents} + retrieved_ground_truths = unique_truths.intersection(unique_retrievals) + + return float(len(retrieved_ground_truths) > 0) + + def _recall_multi_hit(self, ground_truth_documents: List[Document], retrieved_documents: List[Document]) -> float: + unique_truths = {g.content for g in ground_truth_documents} + unique_retrievals = {p.content for p in retrieved_documents} + retrieved_ground_truths = unique_truths.intersection(unique_retrievals) + + return len(retrieved_ground_truths) / len(ground_truth_documents) + + @component.output_types(score=float, individual_scores=List[float]) + def run( + self, ground_truth_documents: List[List[Document]], retrieved_documents: List[List[Document]] + ) -> Dict[str, Any]: + """ + Run the DocumentRecallEvaluator on the given inputs. + + `ground_truth_documents` and `retrieved_documents` must have the same length. + + :param ground_truth_documents: + A list of expected documents for each question. + :param retrieved_documents: + A list of retrieved documents for each question. + A dictionary with the following outputs: + - `score` - The average of calculated scores. + - `invididual_scores` - A list of numbers from 0.0 to 1.0 that represents the proportion of matching + documents retrieved. If the mode is `single_hit`, the individual scores are 0 or 1. + """ + if len(ground_truth_documents) != len(retrieved_documents): + msg = "The length of ground_truth_documents and retrieved_documents must be the same." + raise ValueError(msg) + + scores = [] + for ground_truth, retrieved in zip(ground_truth_documents, retrieved_documents): + score = self.mode_function(ground_truth, retrieved) + scores.append(score) + + return {"score": sum(scores) / len(retrieved_documents), "individual_scores": scores} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, mode=str(self.mode)) diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/faithfulness.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/faithfulness.py new file mode 100644 index 0000000000000000000000000000000000000000..8daf9dc0e0dc71031ada2ef1d113d6919137c3aa --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/faithfulness.py @@ -0,0 +1,216 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from numpy import mean as np_mean + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.evaluators.llm_evaluator import LLMEvaluator +from haystack.utils import Secret, deserialize_secrets_inplace + +# Default examples to include in the prompt if the user does not provide any examples +_DEFAULT_EXAMPLES = [ + { + "inputs": { + "questions": "What is the capital of Germany and when was it founded?", + "contexts": ["Berlin is the capital of Germany and was founded in 1244."], + "predicted_answers": "The capital of Germany, Berlin, was founded in the 13th century.", + }, + "outputs": { + "statements": ["Berlin is the capital of Germany.", "Berlin was founded in 1244."], + "statement_scores": [1, 1], + }, + }, + { + "inputs": { + "questions": "What is the capital of France?", + "contexts": ["Berlin is the capital of Germany."], + "predicted_answers": "Paris", + }, + "outputs": {"statements": ["Paris is the capital of France."], "statement_scores": [0]}, + }, + { + "inputs": { + "questions": "What is the capital of Italy?", + "contexts": ["Rome is the capital of Italy."], + "predicted_answers": "Rome is the capital of Italy with more than 4 million inhabitants.", + }, + "outputs": { + "statements": ["Rome is the capital of Italy.", "Rome has more than 4 million inhabitants."], + "statement_scores": [1, 0], + }, + }, +] + + +@component +class FaithfulnessEvaluator(LLMEvaluator): + """ + Evaluator that checks if a generated answer can be inferred from the provided contexts. + + An LLM separates the answer into multiple statements and checks whether the statement can be inferred from the + context or not. The final score for the full answer is a number from 0.0 to 1.0. It represents the proportion of + statements that can be inferred from the provided contexts. + + Usage example: + ```python + from haystack.components.evaluators import FaithfulnessEvaluator + + questions = ["Who created the Python language?"] + contexts = [ + [( + "Python, created by Guido van Rossum in the late 1980s, is a high-level general-purpose programming " + "language. Its design philosophy emphasizes code readability, and its language constructs aim to help " + "programmers write clear, logical code for both small and large-scale software projects." + )], + ] + predicted_answers = [ + "Python is a high-level general-purpose programming language that was created by George Lucas." + ] + evaluator = FaithfulnessEvaluator() + result = evaluator.run(questions=questions, contexts=contexts, predicted_answers=predicted_answers) + + print(result["individual_scores"]) + # [0.5] + print(result["score"]) + # 0.5 + print(result["results"]) + # [{'statements': ['Python is a high-level general-purpose programming language.', + 'Python was created by George Lucas.'], 'statement_scores': [1, 0], 'score': 0.5}] + ``` + """ + + def __init__( + self, + examples: Optional[List[Dict[str, Any]]] = None, + progress_bar: bool = True, + api: str = "openai", + api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"), + api_params: Optional[Dict[str, Any]] = None, + raise_on_failure: bool = True, + ): + """ + Creates an instance of FaithfulnessEvaluator. + + :param examples: + Optional few-shot examples conforming to the expected input and output format of FaithfulnessEvaluator. + Default examples will be used if none are provided. + Each example must be a dictionary with keys "inputs" and "outputs". + "inputs" must be a dictionary with keys "questions", "contexts", and "predicted_answers". + "outputs" must be a dictionary with "statements" and "statement_scores". + Expected format: + [{ + "inputs": { + "questions": "What is the capital of Italy?", "contexts": ["Rome is the capital of Italy."], + "predicted_answers": "Rome is the capital of Italy with more than 4 million inhabitants.", + }, + "outputs": { + "statements": ["Rome is the capital of Italy.", "Rome has more than 4 million inhabitants."], + "statement_scores": [1, 0], + }, + }] + :param progress_bar: + Whether to show a progress bar during the evaluation. + :param api: + The API to use for calling an LLM through a Generator. + Supported APIs: "openai". + :param api_key: + The API key. + :param api_params: + Parameters for an OpenAI API compatible completions call. + :param raise_on_failure: + Whether to raise an exception if the API call fails. + + """ + self.instructions = ( + "Your task is to judge the faithfulness or groundedness of statements based " + "on context information. First, please extract statements from a provided " + "predicted answer to a question. Second, calculate a faithfulness score for each " + "statement made in the predicted answer. The score is 1 if the statement can be " + "inferred from the provided context or 0 if it cannot be inferred." + ) + self.inputs = [("questions", List[str]), ("contexts", List[List[str]]), ("predicted_answers", List[str])] + self.outputs = ["statements", "statement_scores"] + self.examples = examples or _DEFAULT_EXAMPLES + self.api = api + self.api_key = api_key + self.api_params = api_params or {} + + super(FaithfulnessEvaluator, self).__init__( + instructions=self.instructions, + inputs=self.inputs, + outputs=self.outputs, + examples=self.examples, + api=self.api, + api_key=self.api_key, + api_params=self.api_params, + raise_on_failure=raise_on_failure, + progress_bar=progress_bar, + ) + + @component.output_types(individual_scores=List[int], score=float, results=List[Dict[str, Any]]) + def run(self, **inputs) -> Dict[str, Any]: + """ + Run the LLM evaluator. + + :param questions: + A list of questions. + :param contexts: + A nested list of contexts that correspond to the questions. + :param predicted_answers: + A list of predicted answers. + :returns: + A dictionary with the following outputs: + - `score`: Mean faithfulness score over all the provided input answers. + - `individual_scores`: A list of faithfulness scores for each input answer. + - `results`: A list of dictionaries with `statements` and `statement_scores` for each input answer. + """ + result = super(FaithfulnessEvaluator, self).run(**inputs) + + # calculate average statement faithfulness score per query + for idx, res in enumerate(result["results"]): + if res is None: + result["results"][idx] = {"statements": [], "statement_scores": [], "score": float("nan")} + continue + if not res["statements"]: + res["score"] = 0 + else: + res["score"] = np_mean(res["statement_scores"]) + + # calculate average answer faithfulness score over all queries + result["score"] = np_mean([res["score"] for res in result["results"]]) + result["individual_scores"] = [res["score"] for res in result["results"]] + + return result + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + A dictionary with serialized data. + """ + return default_to_dict( + self, + api=self.api, + api_key=self.api_key.to_dict() if self.api_key else None, + api_params=self.api_params, + examples=self.examples, + progress_bar=self.progress_bar, + raise_on_failure=self.raise_on_failure, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "FaithfulnessEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/llm_evaluator.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/llm_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..39a80b93a5c21617774bdc49fee2fac9c8227fb2 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/llm_evaluator.py @@ -0,0 +1,387 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional, Tuple, Type +from warnings import warn + +from tqdm import tqdm + +from haystack import component, default_from_dict, default_to_dict +from haystack.components.builders import PromptBuilder +from haystack.components.generators import OpenAIGenerator +from haystack.utils import Secret, deserialize_secrets_inplace, deserialize_type, serialize_type + + +@component +class LLMEvaluator: + """ + Uses an LLM to evaluate inputs based on a prompt containing instructions and examples. + + The default API requires an OpenAI API key to be provided as an environment variable "OPENAI_API_KEY". + The inputs are lists that are user-defined depending on the desired metric. + The output is a dictionary with a key `results` containing a list of evaluation results. + Each result is a dictionary with user-defined keys and values of either 0 for FALSE or 1 for TRUE respectively. + + Usage example: + ```python + from typing import List + from haystack.components.evaluators import LLMEvaluator + evaluator = LLMEvaluator( + instructions="Is this answer problematic for children?", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, "outputs": {"score": 1}}, + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}}, + ], + ) + predicted_answers = [ + "Football is the most popular sport with around 4 billion followers worldwide", + "Python language was created by Guido van Rossum.", + ] + results = evaluator.run(predicted_answers=predicted_answers) + print(results) + # {'results': [{'score': 0}, {'score': 0}]} + ``` + """ + + def __init__( + self, + instructions: str, + inputs: List[Tuple[str, Type[List]]], + outputs: List[str], + examples: List[Dict[str, Any]], + progress_bar: bool = True, + *, + raise_on_failure: bool = True, + api: str = "openai", + api_key: Optional[Secret] = None, + api_params: Optional[Dict[str, Any]] = None, + ): + """ + Creates an instance of LLMEvaluator. + + :param instructions: + The prompt instructions to use for evaluation. + Should be a question about the inputs that can be answered with yes or no. + :param inputs: + The inputs that the component expects as incoming connections and that it evaluates. + Each input is a tuple of an input name and input type. Input types must be lists. + :param outputs: + Output names of the evaluation results. They correspond to keys in the output dictionary. + :param examples: + Few-shot examples conforming to the expected input and output format as defined in the `inputs` and + `outputs` parameters. + Each example is a dictionary with keys "inputs" and "outputs" + They contain the input and output as dictionaries respectively. + :param raise_on_failure: + If True, the component will raise an exception on an unsuccessful API call. + :param progress_bar: + Whether to show a progress bar during the evaluation. + :param api: + The API to use for calling an LLM through a Generator. + Supported APIs: "openai". + :param api_key: + The API key to be passed to a LLM provider. It may not be necessary when using a locally hosted model. + :param api_params: + Parameters for an OpenAI API compatible completions call. + + """ + self.validate_init_parameters(inputs, outputs, examples) + self.raise_on_failure = raise_on_failure + self.instructions = instructions + self.inputs = inputs + self.outputs = outputs + self.examples = examples + self.api = api + self.api_key = api_key + self.api_params = api_params or {} + self.progress_bar = progress_bar + + default_generation_kwargs = {"response_format": {"type": "json_object"}, "seed": 42} + user_generation_kwargs = self.api_params.get("generation_kwargs", {}) + merged_generation_kwargs = {**default_generation_kwargs, **user_generation_kwargs} + self.api_params["generation_kwargs"] = merged_generation_kwargs + + if api == "openai": + generator_kwargs = {**self.api_params} + if api_key: + generator_kwargs["api_key"] = api_key + self.generator = OpenAIGenerator(**generator_kwargs) + else: + raise ValueError(f"Unsupported API: {api}") + + template = self.prepare_template() + self.builder = PromptBuilder(template=template) + + component.set_input_types(self, **dict(inputs)) + + @staticmethod + def validate_init_parameters( + inputs: List[Tuple[str, Type[List]]], outputs: List[str], examples: List[Dict[str, Any]] + ): + """ + Validate the init parameters. + + :param inputs: + The inputs to validate. + :param outputs: + The outputs to validate. + :param examples: + The examples to validate. + + :raises ValueError: + If the inputs are not a list of tuples with a string and a type of list. + If the outputs are not a list of strings. + If the examples are not a list of dictionaries. + If any example does not have keys "inputs" and "outputs" with values that are dictionaries with string keys. + """ + # Validate inputs + if ( + not isinstance(inputs, list) + or not all(isinstance(_input, tuple) for _input in inputs) + or not all(isinstance(_input[0], str) and _input[1] is not list and len(_input) == 2 for _input in inputs) + ): + msg = ( + f"LLM evaluator expects inputs to be a list of tuples. Each tuple must contain an input name and " + f"type of list but received {inputs}." + ) + raise ValueError(msg) + + # Validate outputs + if not isinstance(outputs, list) or not all(isinstance(output, str) for output in outputs): + msg = f"LLM evaluator expects outputs to be a list of str but received {outputs}." + raise ValueError(msg) + + # Validate examples are lists of dicts + if not isinstance(examples, list) or not all(isinstance(example, dict) for example in examples): + msg = f"LLM evaluator expects examples to be a list of dictionaries but received {examples}." + raise ValueError(msg) + + # Validate each example + for example in examples: + if ( + {"inputs", "outputs"} != example.keys() + or not all(isinstance(example[param], dict) for param in ["inputs", "outputs"]) + or not all(isinstance(key, str) for param in ["inputs", "outputs"] for key in example[param]) + ): + msg = ( + f"LLM evaluator expects each example to have keys `inputs` and `outputs` with values that are " + f"dictionaries with str keys but received {example}." + ) + raise ValueError(msg) + + @component.output_types(results=List[Dict[str, Any]]) + def run(self, **inputs) -> Dict[str, Any]: + """ + Run the LLM evaluator. + + :param inputs: + The input values to evaluate. The keys are the input names and the values are lists of input values. + :returns: + A dictionary with a `results` entry that contains a list of results. + Each result is a dictionary containing the keys as defined in the `outputs` parameter of the LLMEvaluator + and the evaluation results as the values. If an exception occurs for a particular input value, the result + will be `None` for that entry. + If the API is "openai" and the response contains a "meta" key, the metadata from OpenAI will be included + in the output dictionary, under the key "meta". + :raises ValueError: + Only in the case that `raise_on_failure` is set to True and the received inputs are not lists or have + different lengths, or if the output is not a valid JSON or doesn't contain the expected keys. + """ + self.validate_input_parameters(dict(self.inputs), inputs) + + # inputs is a dictionary with keys being input names and values being a list of input values + # We need to iterate through the lists in parallel for all keys of the dictionary + input_names, values = inputs.keys(), list(zip(*inputs.values())) + list_of_input_names_to_values = [dict(zip(input_names, v)) for v in values] + + results: List[Optional[Dict[str, Any]]] = [] + metadata = None + errors = 0 + for input_names_to_values in tqdm(list_of_input_names_to_values, disable=not self.progress_bar): + prompt = self.builder.run(**input_names_to_values) + try: + result = self.generator.run(prompt=prompt["prompt"]) + except Exception as e: + msg = f"Error while generating response for prompt: {prompt}. Error: {e}" + if self.raise_on_failure: + raise ValueError(msg) + warn(msg) + results.append(None) + errors += 1 + continue + + if self.is_valid_json_and_has_expected_keys(expected=self.outputs, received=result["replies"][0]): + parsed_result = json.loads(result["replies"][0]) + results.append(parsed_result) + else: + results.append(None) + errors += 1 + + if self.api == "openai" and "meta" in result: + metadata = result["meta"] + + if errors > 0: + msg = f"LLM evaluator failed for {errors} out of {len(list_of_input_names_to_values)} inputs." + warn(msg) + + return {"results": results, "meta": metadata} + + def prepare_template(self) -> str: + """ + Prepare the prompt template. + + Combine instructions, inputs, outputs, and examples into one prompt template with the following format: + Instructions: + + + Generate the response in JSON format with the following keys: + + Consider the instructions and the examples below to determine those values. + + Examples: + + + Inputs: + + Outputs: + + :returns: + The prompt template. + """ + inputs_section = ( + "{" + ", ".join([f'"{input_socket[0]}": {{{{ {input_socket[0]} }}}}' for input_socket in self.inputs]) + "}" + ) + + examples_section = "\n".join( + [ + "Inputs:\n" + json.dumps(example["inputs"]) + "\nOutputs:\n" + json.dumps(example["outputs"]) + for example in self.examples + ] + ) + return ( + f"Instructions:\n" + f"{self.instructions}\n\n" + f"Generate the response in JSON format with the following keys:\n" + f"{json.dumps(self.outputs)}\n" + f"Consider the instructions and the examples below to determine those values.\n\n" + f"Examples:\n" + f"{examples_section}\n\n" + f"Inputs:\n" + f"{inputs_section}\n" + f"Outputs:\n" + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + # Since we cannot currently serialize tuples, convert the inputs to a list. + inputs = [[name, serialize_type(type_)] for name, type_ in self.inputs] + return default_to_dict( + self, + instructions=self.instructions, + inputs=inputs, + outputs=self.outputs, + examples=self.examples, + api=self.api, + api_key=self.api_key and self.api_key.to_dict(), + api_params=self.api_params, + progress_bar=self.progress_bar, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "LLMEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + data["init_parameters"]["inputs"] = [ + (name, deserialize_type(type_)) for name, type_ in data["init_parameters"]["inputs"] + ] + + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @staticmethod + def validate_input_parameters(expected: Dict[str, Any], received: Dict[str, Any]) -> None: + """ + Validate the input parameters. + + :param expected: + The expected input parameters. + :param received: + The received input parameters. + + :raises ValueError: + If not all expected inputs are present in the received inputs + If the received inputs are not lists or have different lengths + """ + # Validate that all expected inputs are present in the received inputs + for param in expected.keys(): + if param not in received: + msg = f"LLM evaluator expected input parameter '{param}' but received only {received.keys()}." + raise ValueError(msg) + + # Validate that all received inputs are lists + if not all(isinstance(_input, list) for _input in received.values()): + msg = ( + "LLM evaluator expects all input values to be lists but received " + f"{[type(_input) for _input in received.values()]}." + ) + raise ValueError(msg) + + # Validate that all received inputs are of the same length + inputs = received.values() + length = len(next(iter(inputs))) + if not all(len(_input) == length for _input in inputs): + msg = ( + f"LLM evaluator expects all input lists to have the same length but received {inputs} with lengths " + f"{[len(_input) for _input in inputs]}." + ) + raise ValueError(msg) + + def is_valid_json_and_has_expected_keys(self, expected: List[str], received: str) -> bool: + """ + Output must be a valid JSON with the expected keys. + + :param expected: + Names of expected outputs + :param received: + Names of received outputs + + :raises ValueError: + If the output is not a valid JSON with the expected keys: + - with `raise_on_failure` set to True a ValueError is raised. + - with `raise_on_failure` set to False a warning is issued and False is returned. + + :returns: + True if the received output is a valid JSON with the expected keys, False otherwise. + """ + try: + parsed_output = json.loads(received) + except json.JSONDecodeError: + msg = "Response from LLM evaluator is not a valid JSON." + if self.raise_on_failure: + raise ValueError(msg) + warn(msg) + return False + + if not all(output in parsed_output for output in expected): + msg = f"Expected response from LLM evaluator to be JSON with keys {expected}, got {received}." + if self.raise_on_failure: + raise ValueError(msg) + warn(msg) + return False + + return True diff --git a/testbed/deepset-ai__haystack/haystack/components/evaluators/sas_evaluator.py b/testbed/deepset-ai__haystack/haystack/components/evaluators/sas_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..b9645a1ab9a95c15cea2df19ee855adf8a95b55c --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/evaluators/sas_evaluator.py @@ -0,0 +1,201 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from numpy import mean as np_mean + +from haystack import component, default_from_dict, default_to_dict +from haystack.lazy_imports import LazyImport +from haystack.utils import ComponentDevice, expit +from haystack.utils.auth import Secret, deserialize_secrets_inplace + +with LazyImport(message="Run 'pip install \"sentence-transformers>=3.0.0\"'") as sas_import: + from sentence_transformers import CrossEncoder, SentenceTransformer, util + from transformers import AutoConfig + + +@component +class SASEvaluator: + """ + SASEvaluator computes the Semantic Answer Similarity (SAS) between a list of predictions and a one of ground truths. + + It's usually used in Retrieval Augmented Generation (RAG) pipelines to evaluate the quality of the generated + answers. The SAS is computed using a pre-trained model from the Hugging Face model hub. The model can be either a + Bi-Encoder or a Cross-Encoder. The choice of the model is based on the `model` parameter. + + Usage example: + ```python + from haystack.components.evaluators.sas_evaluator import SASEvaluator + + evaluator = SASEvaluator(model="cross-encoder/ms-marco-MiniLM-L-6-v2") + evaluator.warm_up() + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + result = evaluator.run( + ground_truths_answers=ground_truths, predicted_answers=predictions + ) + + print(result["score"]) + # 0.9999673763910929 + + print(result["individual_scores"]) + # [0.9999765157699585, 0.999968409538269, 0.9999572038650513] + ``` + """ + + def __init__( + self, + model: str = "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", + batch_size: int = 32, + device: Optional[ComponentDevice] = None, + token: Secret = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False), + ): + """ + Creates a new instance of SASEvaluator. + + :param model: + SentenceTransformers semantic textual similarity model, should be path or string pointing to a downloadable + model. + :param batch_size: + Number of prediction-label pairs to encode at once. + :param device: + The device on which the model is loaded. If `None`, the default device is automatically selected. + :param token: + The Hugging Face token for HTTP bearer authorization. + You can find your HF token in your [account settings](https://huggingface.co/settings/tokens) + """ + sas_import.check() + + self._model = model + self._batch_size = batch_size + self._device = device + self._token = token + self._similarity_model = None + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + return default_to_dict( + self, + model=self._model, + batch_size=self._batch_size, + device=self._device.to_dict() if self._device else None, + token=self._token.to_dict() if self._token else None, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SASEvaluator": + """ + Deserialize this component from a dictionary. + + :param data: + The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["token"]) + if device := data.get("init_parameters", {}).get("device"): + data["init_parameters"]["device"] = ComponentDevice.from_dict(device) + return default_from_dict(cls, data) + + def warm_up(self): + """ + Initializes the component. + """ + if self._similarity_model: + return + + token = self._token.resolve_value() if self._token else None + config = AutoConfig.from_pretrained(self._model, use_auth_token=token) + cross_encoder_used = False + if config.architectures: + cross_encoder_used = any(arch.endswith("ForSequenceClassification") for arch in config.architectures) + device = ComponentDevice.resolve_device(self._device).to_torch_str() + # Based on the Model string we can load either Bi-Encoders or Cross Encoders. + # Similarity computation changes for both approaches + if cross_encoder_used: + self._similarity_model = CrossEncoder( + self._model, + device=device, + tokenizer_args={"use_auth_token": token}, + automodel_args={"use_auth_token": token}, + ) + else: + self._similarity_model = SentenceTransformer(self._model, device=device, use_auth_token=token) + + @component.output_types(score=float, individual_scores=List[float]) + def run(self, ground_truth_answers: List[str], predicted_answers: List[str]) -> Dict[str, Any]: + """ + SASEvaluator component run method. + + Run the SASEvaluator to compute the Semantic Answer Similarity (SAS) between a list of predicted answers + and a list of ground truth answers. Both must be list of strings of same length. + + :param ground_truth_answers: + A list of expected answers for each question. + :param predicted_answers: + A list of generated answers for each question. + :returns: + A dictionary with the following outputs: + - `score`: Mean SAS score over all the predictions/ground-truth pairs. + - `individual_scores`: A list of similarity scores for each prediction/ground-truth pair. + """ + if len(ground_truth_answers) != len(predicted_answers): + raise ValueError("The number of predictions and labels must be the same.") + + if any(answer is None for answer in predicted_answers): + raise ValueError("Predicted answers must not contain None values.") + + if len(predicted_answers) == 0: + return {"score": 0.0, "individual_scores": [0.0]} + + if not self._similarity_model: + msg = "The model has not been initialized. Call warm_up() before running the evaluator." + raise RuntimeError(msg) + + if isinstance(self._similarity_model, CrossEncoder): + # For Cross Encoders we create a list of pairs of predictions and labels + sentence_pairs = list(zip(predicted_answers, ground_truth_answers)) + similarity_scores = self._similarity_model.predict( + sentence_pairs, batch_size=self._batch_size, convert_to_numpy=True + ) + + # All Cross Encoders do not return a set of logits scores that are normalized + # We normalize scores if they are larger than 1 + if (similarity_scores > 1).any(): + similarity_scores = expit(similarity_scores) + + # Convert scores to list of floats from numpy array + similarity_scores = similarity_scores.tolist() + + else: + # For Bi-encoders we create embeddings separately for predictions and labels + predictions_embeddings = self._similarity_model.encode( + predicted_answers, batch_size=self._batch_size, convert_to_tensor=True + ) + label_embeddings = self._similarity_model.encode( + ground_truth_answers, batch_size=self._batch_size, convert_to_tensor=True + ) + + # Compute cosine-similarities + similarity_scores = [ + float(util.cos_sim(p, l).cpu().numpy()) for p, l in zip(predictions_embeddings, label_embeddings) + ] + + sas_score = np_mean(similarity_scores) + + return {"score": sas_score, "individual_scores": similarity_scores} diff --git a/testbed/deepset-ai__haystack/haystack/components/extractors/__init__.py b/testbed/deepset-ai__haystack/haystack/components/extractors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..510cf691f96556ce2b5f3b0846e379b2d8184f40 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/extractors/__init__.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.extractors.named_entity_extractor import ( + NamedEntityAnnotation, + NamedEntityExtractor, + NamedEntityExtractorBackend, +) + +__all__ = ["NamedEntityExtractor", "NamedEntityExtractorBackend", "NamedEntityAnnotation"] diff --git a/testbed/deepset-ai__haystack/haystack/components/extractors/named_entity_extractor.py b/testbed/deepset-ai__haystack/haystack/components/extractors/named_entity_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..00350e6aedacaab3aeb93f273ce170f2a0d42dc4 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/extractors/named_entity_extractor.py @@ -0,0 +1,485 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from abc import ABC, abstractmethod +from contextlib import contextmanager +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict, List, Optional, Union + +from haystack import ComponentError, DeserializationError, Document, component, default_from_dict, default_to_dict +from haystack.lazy_imports import LazyImport +from haystack.utils.device import ComponentDevice + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as transformers_import: + from transformers import AutoModelForTokenClassification, AutoTokenizer, pipeline + from transformers import Pipeline as HfPipeline + +with LazyImport(message="Run 'pip install spacy'") as spacy_import: + import spacy + from spacy import Language as SpacyPipeline + + +class NamedEntityExtractorBackend(Enum): + """ + NLP backend to use for Named Entity Recognition. + """ + + #: Uses an Hugging Face model and pipeline. + HUGGING_FACE = "hugging_face" + + #: Uses a spaCy model and pipeline. + SPACY = "spacy" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "NamedEntityExtractorBackend": + """ + Convert a string to a NamedEntityExtractorBackend enum. + """ + enum_map = {e.value: e for e in NamedEntityExtractorBackend} + mode = enum_map.get(string) + if mode is None: + msg = ( + f"Invalid backend '{string}' for named entity extractor. " + f"Supported backends are: {list(enum_map.keys())}" + ) + raise ComponentError(msg) + return mode + + +@dataclass +class NamedEntityAnnotation: + """ + Describes a single NER annotation. + + :param entity: + Entity label. + :param start: + Start index of the entity in the document. + :param end: + End index of the entity in the document. + :param score: + Score calculated by the model. + """ + + entity: str + start: int + end: int + score: Optional[float] = None + + +@component +class NamedEntityExtractor: + """ + Annotates named entities in a collection of documents. + + The component supports two backends: Hugging Face and spaCy. The + former can be used with any sequence classification model from the + [Hugging Face model hub](https://huggingface.co/models), while the + latter can be used with any [spaCy model](https://spacy.io/models) + that contains an NER component. Annotations are stored as metadata + in the documents. + + Usage example: + ```python + from haystack import Document + from haystack.components.extractors.named_entity_extractor import NamedEntityExtractor + + documents = [ + Document(content="I'm Merlin, the happy pig!"), + Document(content="My name is Clara and I live in Berkeley, California."), + ] + extractor = NamedEntityExtractor(backend="hugging_face", model="dslim/bert-base-NER") + extractor.warm_up() + results = extractor.run(documents=documents)["documents"] + annotations = [NamedEntityExtractor.get_stored_annotations(doc) for doc in results] + print(annotations) + ``` + """ + + _METADATA_KEY = "named_entities" + + def __init__( + self, + *, + backend: Union[str, NamedEntityExtractorBackend], + model: str, + pipeline_kwargs: Optional[Dict[str, Any]] = None, + device: Optional[ComponentDevice] = None, + ) -> None: + """ + Create a Named Entity extractor component. + + :param backend: + Backend to use for NER. + :param model: + Name of the model or a path to the model on + the local disk. Dependent on the backend. + :param pipeline_kwargs: + Keyword arguments passed to the pipeline. The + pipeline can override these arguments. Dependent on the backend. + :param device: + The device on which the model is loaded. If `None`, + the default device is automatically selected. If a + device/device map is specified in `pipeline_kwargs`, + it overrides this parameter (only applicable to the + HuggingFace backend). + """ + + if isinstance(backend, str): + backend = NamedEntityExtractorBackend.from_str(backend) + + self._backend: _NerBackend + self._warmed_up: bool = False + device = ComponentDevice.resolve_device(device) + + if backend == NamedEntityExtractorBackend.HUGGING_FACE: + self._backend = _HfBackend(model_name_or_path=model, device=device, pipeline_kwargs=pipeline_kwargs) + elif backend == NamedEntityExtractorBackend.SPACY: + self._backend = _SpacyBackend(model_name_or_path=model, device=device, pipeline_kwargs=pipeline_kwargs) + else: + raise ComponentError(f"Unknown NER backend '{type(backend).__name__}' for extractor") + + def warm_up(self): + """ + Initialize the component. + + :raises ComponentError: + If the backend fails to initialize successfully. + """ + if self._warmed_up: + return + + try: + self._backend.initialize() + self._warmed_up = True + except Exception as e: + raise ComponentError( + f"Named entity extractor with backend '{self._backend.type} failed to initialize." + ) from e + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document], batch_size: int = 1) -> Dict[str, Any]: + """ + Annotate named entities in each document and store the annotations in the document's metadata. + + :param documents: + Documents to process. + :param batch_size: + Batch size used for processing the documents. + :returns: + Processed documents. + :raises ComponentError: + If the backend fails to process a document. + """ + if not self._warmed_up: + msg = "The component NamedEntityExtractor was not warmed up. Call warm_up() before running the component." + raise RuntimeError(msg) + + texts = [doc.content if doc.content is not None else "" for doc in documents] + annotations = self._backend.annotate(texts, batch_size=batch_size) + + if len(annotations) != len(documents): + raise ComponentError( + "NER backend did not return the correct number of annotations; " + f"got {len(annotations)} but expected {len(documents)}" + ) + + for doc, doc_annotations in zip(documents, annotations): + doc.meta[self._METADATA_KEY] = doc_annotations + + return {"documents": documents} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + backend=self._backend.type.name, + model=self._backend.model_name, + device=self._backend.device.to_dict(), + pipeline_kwargs=self._backend._pipeline_kwargs, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "NamedEntityExtractor": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + try: + init_params = data["init_parameters"] + if init_params.get("device") is not None: + init_params["device"] = ComponentDevice.from_dict(init_params["device"]) + init_params["backend"] = NamedEntityExtractorBackend[init_params["backend"]] + return default_from_dict(cls, data) + except Exception as e: + raise DeserializationError(f"Couldn't deserialize {cls.__name__} instance") from e + + @property + def initialized(self) -> bool: + """ + Returns if the extractor is ready to annotate text. + """ + return self._backend.initialized + + @classmethod + def get_stored_annotations(cls, document: Document) -> Optional[List[NamedEntityAnnotation]]: + """ + Returns the document's named entity annotations stored in its metadata, if any. + + :param document: + Document whose annotations are to be fetched. + :returns: + The stored annotations. + """ + + return document.meta.get(cls._METADATA_KEY) + + +class _NerBackend(ABC): + """ + Base class for NER backends. + """ + + def __init__( + self, + _type: NamedEntityExtractorBackend, + device: ComponentDevice, + pipeline_kwargs: Optional[Dict[str, Any]] = None, + ) -> None: + super().__init__() + + self._type = _type + self._device = device + self._pipeline_kwargs = pipeline_kwargs if pipeline_kwargs is not None else {} + + @abstractmethod + def initialize(self): + """ + Initializes the backend. This would usually entail loading models, pipelines, and so on. + """ + + @property + @abstractmethod + def initialized(self) -> bool: + """ + Returns if the backend has been initialized, for example, ready to annotate text. + """ + + @abstractmethod + def annotate(self, texts: List[str], *, batch_size: int = 1) -> List[List[NamedEntityAnnotation]]: + """ + Predict annotations for a collection of documents. + + :param texts: + Raw texts to be annotated. + :param batch_size: + Size of text batches that are + passed to the model. + :returns: + NER annotations. + """ + + @property + @abstractmethod + def model_name(self) -> str: + """ + Returns the model name or path on the local disk. + """ + + @property + def device(self) -> ComponentDevice: + """ + The device on which the backend's model is loaded. + + :returns: + The device on which the backend's model is loaded. + """ + return self._device + + @property + def type(self) -> NamedEntityExtractorBackend: + """ + Returns the type of the backend. + """ + return self._type + + +class _HfBackend(_NerBackend): + """ + Hugging Face backend for NER. + """ + + def __init__( + self, *, model_name_or_path: str, device: ComponentDevice, pipeline_kwargs: Optional[Dict[str, Any]] = None + ) -> None: + """ + Construct a Hugging Face NER backend. + + :param model_name_or_path: + Name of the model or a path to the Hugging Face + model on the local disk. + :param device: + The device on which the model is loaded. If `None`, + the default device is automatically selected. + + If a device/device map is specified in `pipeline_kwargs`, + it overrides this parameter. + :param pipeline_kwargs: + Keyword arguments passed to the pipeline. The + pipeline can override these arguments. + """ + super().__init__(NamedEntityExtractorBackend.HUGGING_FACE, device, pipeline_kwargs) + + transformers_import.check() + + self._model_name_or_path = model_name_or_path + self.tokenizer: Optional[AutoTokenizer] = None + self.model: Optional[AutoModelForTokenClassification] = None + self.pipeline: Optional[HfPipeline] = None + + def initialize(self): + self.tokenizer = AutoTokenizer.from_pretrained(self._model_name_or_path) + self.model = AutoModelForTokenClassification.from_pretrained(self._model_name_or_path) + + pipeline_params = { + "task": "ner", + "model": self.model, + "tokenizer": self.tokenizer, + "aggregation_strategy": "simple", + } + pipeline_params.update({k: v for k, v in self._pipeline_kwargs.items() if k not in pipeline_params}) + self.device.update_hf_kwargs(pipeline_params, overwrite=False) + self.pipeline = pipeline(**pipeline_params) + + def annotate(self, texts: List[str], *, batch_size: int = 1) -> List[List[NamedEntityAnnotation]]: + if not self.initialized: + raise ComponentError("Hugging Face NER backend was not initialized - Did you call `warm_up()`?") + + assert self.pipeline is not None + outputs = self.pipeline(texts, batch_size=batch_size) + return [ + [ + NamedEntityAnnotation( + entity=annotation["entity"] if "entity" in annotation else annotation["entity_group"], + start=annotation["start"], + end=annotation["end"], + score=annotation["score"], + ) + for annotation in annotations + ] + for annotations in outputs + ] + + @property + def initialized(self) -> bool: + return self.tokenizer is not None and self.model is not None or self.pipeline is not None + + @property + def model_name(self) -> str: + return self._model_name_or_path + + +class _SpacyBackend(_NerBackend): + """ + spaCy backend for NER. + """ + + def __init__( + self, *, model_name_or_path: str, device: ComponentDevice, pipeline_kwargs: Optional[Dict[str, Any]] = None + ) -> None: + """ + Construct a spaCy NER backend. + + :param model_name_or_path: + Name of the model or a path to the spaCy + model on the local disk. + :param device: + The device on which the model is loaded. If `None`, + the default device is automatically selected. + :param pipeline_kwargs: + Keyword arguments passed to the pipeline. The + pipeline can override these arguments. + """ + super().__init__(NamedEntityExtractorBackend.SPACY, device, pipeline_kwargs) + + spacy_import.check() + + self._model_name_or_path = model_name_or_path + self.pipeline: Optional[SpacyPipeline] = None + + if self.device.has_multiple_devices: + raise ValueError("spaCy backend for named entity extractor only supports inference on single devices") + + def initialize(self): + # We need to initialize the model on the GPU if needed. + with self._select_device(): + self.pipeline = spacy.load(self._model_name_or_path) + + if not self.pipeline.has_pipe("ner"): + raise ComponentError(f"spaCy pipeline '{self._model_name_or_path}' does not contain an NER component") + + # Disable unnecessary pipes. + pipes_to_keep = ("ner", "tok2vec", "transformer", "curated_transformer") + for name in self.pipeline.pipe_names: + if name not in pipes_to_keep: + self.pipeline.disable_pipe(name) + + self._pipeline_kwargs = {k: v for k, v in self._pipeline_kwargs.items() if k not in ("texts", "batch_size")} + + def annotate(self, texts: List[str], *, batch_size: int = 1) -> List[List[NamedEntityAnnotation]]: + if not self.initialized: + raise ComponentError("spaCy NER backend was not initialized - Did you call `warm_up()`?") + + assert self.pipeline is not None + with self._select_device(): + outputs = list(self.pipeline.pipe(texts=texts, batch_size=batch_size, **self._pipeline_kwargs)) + + return [ + [ + NamedEntityAnnotation(entity=entity.label_, start=entity.start_char, end=entity.end_char) + for entity in doc.ents + ] + for doc in outputs + ] + + @property + def initialized(self) -> bool: + return self.pipeline is not None + + @property + def model_name(self) -> str: + return self._model_name_or_path + + @contextmanager + def _select_device(self): + """ + Context manager used to run spaCy models on a specific GPU in a scoped manner. + """ + + # TODO: This won't restore the active device. + # Since there are no opaque API functions to determine + # the active device in spaCy/Thinc, we can't do much + # about it as a consumer unless we start poking into their + # internals. + device_id = self._device.to_spacy() + try: + if device_id >= 0: + spacy.require_gpu(device_id) + yield + finally: + if device_id >= 0: + spacy.require_cpu() diff --git a/testbed/deepset-ai__haystack/haystack/components/joiners/answer_joiner.py b/testbed/deepset-ai__haystack/haystack/components/joiners/answer_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6a8b824653097ae8ae11d5e90ee35ed558bc83 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/joiners/answer_joiner.py @@ -0,0 +1,172 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import itertools +from enum import Enum +from math import inf +from typing import Any, Callable, Dict, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.core.component.types import Variadic +from haystack.dataclasses.answer import ExtractedAnswer, ExtractedTableAnswer, GeneratedAnswer + +AnswerType = Union[GeneratedAnswer, ExtractedTableAnswer, ExtractedAnswer] + +logger = logging.getLogger(__name__) + + +class JoinMode(Enum): + """ + Enum for AnswerJoiner join modes. + """ + + CONCATENATE = "concatenate" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "JoinMode": + """ + Convert a string to a JoinMode enum. + """ + enum_map = {e.value: e for e in JoinMode} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown join mode '{string}'. Supported modes in AnswerJoiner are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +@component +class AnswerJoiner: + """ + Merges multiple lists of `Answer` objects into a single list. + + Use this component to combine answers from different Generators into a single list. + Currently, the component supports only one join mode: `CONCATENATE`. + This mode concatenates multiple lists of answers into a single list. + + ### Usage example + + In this example, AnswerJoiner merges answers from two different Generators: + + ```python + from haystack.components.builders import AnswerBuilder + from haystack.components.joiners import AnswerJoiner + + from haystack.core.pipeline import Pipeline + + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.dataclasses import ChatMessage + + + query = "What's Natural Language Processing?" + messages = [ChatMessage.from_system("You are a helpful, respectful and honest assistant. Be super concise."), + ChatMessage.from_user(query)] + + pipe = Pipeline() + pipe.add_component("gpt-4o", OpenAIChatGenerator(model="gpt-4o")) + pipe.add_component("llama", OpenAIChatGenerator(model="gpt-3.5-turbo")) + pipe.add_component("aba", AnswerBuilder()) + pipe.add_component("abb", AnswerBuilder()) + pipe.add_component("joiner", AnswerJoiner()) + + pipe.connect("gpt-4o.replies", "aba") + pipe.connect("llama.replies", "abb") + pipe.connect("aba.answers", "joiner") + pipe.connect("abb.answers", "joiner") + + results = pipe.run(data={"gpt-4o": {"messages": messages}, + "llama": {"messages": messages}, + "aba": {"query": query}, + "abb": {"query": query}}) + ``` + """ + + def __init__( + self, + join_mode: Union[str, JoinMode] = JoinMode.CONCATENATE, + top_k: Optional[int] = None, + sort_by_score: bool = False, + ): + """ + Creates an AnswerJoiner component. + + :param join_mode: + Specifies the join mode to use. Available modes: + - `concatenate`: Concatenates multiple lists of Answers into a single list. + :param top_k: + The maximum number of Answers to return. + :param sort_by_score: + If `True`, sorts the documents by score in descending order. + If a document has no score, it is handled as if its score is -infinity. + """ + if isinstance(join_mode, str): + join_mode = JoinMode.from_str(join_mode) + join_mode_functions: Dict[JoinMode, Callable[[List[List[AnswerType]]], List[AnswerType]]] = { + JoinMode.CONCATENATE: self._concatenate + } + self.join_mode_function: Callable[[List[List[AnswerType]]], List[AnswerType]] = join_mode_functions[join_mode] + self.join_mode = join_mode + self.top_k = top_k + self.sort_by_score = sort_by_score + + @component.output_types(answers=List[AnswerType]) + def run(self, answers: Variadic[List[AnswerType]], top_k: Optional[int] = None): + """ + Joins multiple lists of Answers into a single list depending on the `join_mode` parameter. + + :param answers: + Nested list of Answers to be merged. + + :param top_k: + The maximum number of Answers to return. Overrides the instance's `top_k` if provided. + + :returns: + A dictionary with the following keys: + - `answers`: Merged list of Answers + """ + answers_list = list(answers) + join_function = self.join_mode_function + output_answers: List[AnswerType] = join_function(answers_list) + + if self.sort_by_score: + output_answers = sorted( + output_answers, key=lambda answer: answer.score if hasattr(answer, "score") else -inf, reverse=True + ) + + top_k = top_k or self.top_k + if top_k: + output_answers = output_answers[:top_k] + return {"answers": output_answers} + + def _concatenate(self, answer_lists: List[List[AnswerType]]) -> List[AnswerType]: + """ + Concatenate multiple lists of Answers, flattening them into a single list and sorting by score. + + :param answer_lists: List of lists of Answers to be flattened. + """ + return list(itertools.chain.from_iterable(answer_lists)) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, join_mode=str(self.join_mode), top_k=self.top_k, sort_by_score=self.sort_by_score) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AnswerJoiner": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) diff --git a/testbed/deepset-ai__haystack/haystack/components/joiners/branch.py b/testbed/deepset-ai__haystack/haystack/components/joiners/branch.py new file mode 100644 index 0000000000000000000000000000000000000000..49404ac4924ce86a66259559052ce17f8c20ef86 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/joiners/branch.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, Type + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.core.component.types import GreedyVariadic +from haystack.utils import deserialize_type, serialize_type + +logger = logging.getLogger(__name__) + + +@component() +class BranchJoiner: + """ + A component to join different branches of a pipeline into one single output. + + `BranchJoiner` receives multiple data connections of the same type from other components and passes the first + value coming to its single output, possibly distributing it to various other components. + + `BranchJoiner` is fundamental to close loops in a pipeline, where the two branches it joins are the ones + coming from the previous component and one coming back from a loop. For example, `BranchJoiner` could be used + to send data to a component evaluating errors. `BranchJoiner` would receive two connections, one to get the + original data and another one to get modified data in case there was an error. In both cases, `BranchJoiner` + would send (or re-send in case of a loop) data to the component evaluating errors. See "Usage example" below. + + Another use case with a need for `BranchJoiner` is to reconcile multiple branches coming out of a decision + or Classifier component. For example, in a RAG pipeline, there might be a "query language classifier" component + sending the query to different retrievers, selecting one specifically according to the detected language. After the + retrieval step the pipeline would ideally continue with a `PromptBuilder`, and since we don't know in advance the + language of the query, all the retrievers should be ideally connected to the single `PromptBuilder`. Since the + `PromptBuilder` won't accept more than one connection in input, we would connect all the retrievers to a + `BranchJoiner` component and reconcile them in a single output that can be connected to the `PromptBuilder` + downstream. + + Usage example: + + ```python + import json + from typing import List + + from haystack import Pipeline + from haystack.components.converters import OutputAdapter + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.components.joiners import BranchJoiner + from haystack.components.validators import JsonSchemaValidator + from haystack.dataclasses import ChatMessage + + person_schema = { + "type": "object", + "properties": { + "first_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"}, + "last_name": {"type": "string", "pattern": "^[A-Z][a-z]+$"}, + "nationality": {"type": "string", "enum": ["Italian", "Portuguese", "American"]}, + }, + "required": ["first_name", "last_name", "nationality"] + } + + # Initialize a pipeline + pipe = Pipeline() + + # Add components to the pipeline + pipe.add_component('joiner', BranchJoiner(List[ChatMessage])) + pipe.add_component('fc_llm', OpenAIChatGenerator(model="gpt-4o-mini")) + pipe.add_component('validator', JsonSchemaValidator(json_schema=person_schema)) + pipe.add_component('adapter', OutputAdapter("{{chat_message}}", List[ChatMessage])), + # And connect them + pipe.connect("adapter", "joiner") + pipe.connect("joiner", "fc_llm") + pipe.connect("fc_llm.replies", "validator.messages") + pipe.connect("validator.validation_error", "joiner") + + result = pipe.run(data={"fc_llm": {"generation_kwargs": {"response_format": {"type": "json_object"}}}, + "adapter": {"chat_message": [ChatMessage.from_user("Create json from Peter Parker")]}}) + + print(json.loads(result["validator"]["validated"][0].content)) + + + >> {'first_name': 'Peter', 'last_name': 'Parker', 'nationality': 'American', 'name': 'Spider-Man', 'occupation': + >> 'Superhero', 'age': 23, 'location': 'New York City'} + ``` + + Note that `BranchJoiner` can manage only one data type at a time. In this case, `BranchJoiner` is created for + passing `List[ChatMessage]`. This determines the type of data that `BranchJoiner` will receive from the upstream + connected components and also the type of data that `BranchJoiner` will send through its output. + + In the code example, `BranchJoiner` receives a looped back `List[ChatMessage]` from the `JsonSchemaValidator` and + sends it down to the `OpenAIChatGenerator` for re-generation. We can have multiple loopback connections in the + pipeline. In this instance, the downstream component is only one (the `OpenAIChatGenerator`), but the pipeline might + have more than one downstream component. + """ + + def __init__(self, type_: Type): + """ + Create a `BranchJoiner` component. + + :param type_: The type of data that the `BranchJoiner` will receive from the upstream connected components and + distribute to the downstream connected components. + """ + self.type_ = type_ + # type_'s type can't be determined statically + component.set_input_types(self, value=GreedyVariadic[type_]) # type: ignore + component.set_output_types(self, value=type_) + + def to_dict(self): + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, type_=serialize_type(self.type_)) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "BranchJoiner": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ + data["init_parameters"]["type_"] = deserialize_type(data["init_parameters"]["type_"]) + return default_from_dict(cls, data) + + def run(self, **kwargs): + """ + The run method of the `BranchJoiner` component. + + Multiplexes the input data from the upstream connected components and distributes it to the downstream connected + components. + + :param **kwargs: The input data. Must be of the type declared in `__init__`. + :return: A dictionary with the following keys: + - `value`: The input data. + """ + if (inputs_count := len(kwargs["value"])) != 1: + raise ValueError(f"BranchJoiner expects only one input, but {inputs_count} were received.") + return {"value": kwargs["value"][0]} diff --git a/testbed/deepset-ai__haystack/haystack/components/joiners/document_joiner.py b/testbed/deepset-ai__haystack/haystack/components/joiners/document_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..7451f6089ce283798faf86e5b1d38a421d4ddfc5 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/joiners/document_joiner.py @@ -0,0 +1,264 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import itertools +from collections import defaultdict +from enum import Enum +from math import inf +from typing import Any, Dict, List, Optional, Union + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.core.component.types import Variadic + +logger = logging.getLogger(__name__) + + +class JoinMode(Enum): + """ + Enum for join mode. + """ + + CONCATENATE = "concatenate" + MERGE = "merge" + RECIPROCAL_RANK_FUSION = "reciprocal_rank_fusion" + DISTRIBUTION_BASED_RANK_FUSION = "distribution_based_rank_fusion" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "JoinMode": + """ + Convert a string to a JoinMode enum. + """ + enum_map = {e.value: e for e in JoinMode} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown join mode '{string}'. Supported modes in DocumentJoiner are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +@component +class DocumentJoiner: + """ + Joins multiple lists of documents into a single list. + + It supports different join modes: + - concatenate: Keeps the highest-scored document in case of duplicates. + - merge: Calculates a weighted sum of scores for duplicates and merges them. + - reciprocal_rank_fusion: Merges and assigns scores based on reciprocal rank fusion. + - distribution_based_rank_fusion: Merges and assigns scores based on scores distribution in each Retriever. + + ### Usage example: + + ```python + document_store = InMemoryDocumentStore() + p = Pipeline() + p.add_component(instance=InMemoryBM25Retriever(document_store=document_store), name="bm25_retriever") + p.add_component( + instance=SentenceTransformersTextEmbedder(model="sentence-transformers/all-MiniLM-L6-v2"), + name="text_embedder", + ) + p.add_component(instance=InMemoryEmbeddingRetriever(document_store=document_store), name="embedding_retriever") + p.add_component(instance=DocumentJoiner(), name="joiner") + p.connect("bm25_retriever", "joiner") + p.connect("embedding_retriever", "joiner") + p.connect("text_embedder", "embedding_retriever") + query = "What is the capital of France?" + p.run(data={"query": query}) + ``` + """ + + def __init__( + self, + join_mode: Union[str, JoinMode] = JoinMode.CONCATENATE, + weights: Optional[List[float]] = None, + top_k: Optional[int] = None, + sort_by_score: bool = True, + ): + """ + Creates a DocumentJoiner component. + + :param join_mode: + Specifies the join mode to use. Available modes: + - `concatenate`: Keeps the highest-scored document in case of duplicates. + - `merge`: Calculates a weighted sum of scores for duplicates and merges them. + - `reciprocal_rank_fusion`: Merges and assigns scores based on reciprocal rank fusion. + - `distribution_based_rank_fusion`: Merges and assigns scores based on scores + distribution in each Retriever. + :param weights: + Assign importance to each list of documents to influence how they're joined. + This parameter is ignored for + `concatenate` or `distribution_based_rank_fusion` join modes. + Weight for each list of documents must match the number of inputs. + :param top_k: + The maximum number of documents to return. + :param sort_by_score: + If `True`, sorts the documents by score in descending order. + If a document has no score, it is handled as if its score is -infinity. + """ + if isinstance(join_mode, str): + join_mode = JoinMode.from_str(join_mode) + join_mode_functions = { + JoinMode.CONCATENATE: self._concatenate, + JoinMode.MERGE: self._merge, + JoinMode.RECIPROCAL_RANK_FUSION: self._reciprocal_rank_fusion, + JoinMode.DISTRIBUTION_BASED_RANK_FUSION: self._distribution_based_rank_fusion, + } + self.join_mode_function = join_mode_functions[join_mode] + self.join_mode = join_mode + self.weights = [float(i) / sum(weights) for i in weights] if weights else None + self.top_k = top_k + self.sort_by_score = sort_by_score + + @component.output_types(documents=List[Document]) + def run(self, documents: Variadic[List[Document]], top_k: Optional[int] = None): + """ + Joins multiple lists of Documents into a single list depending on the `join_mode` parameter. + + :param documents: + List of list of documents to be merged. + :param top_k: + The maximum number of documents to return. Overrides the instance's `top_k` if provided. + + :returns: + A dictionary with the following keys: + - `documents`: Merged list of Documents + """ + output_documents = [] + + documents = list(documents) + output_documents = self.join_mode_function(documents) + + if self.sort_by_score: + output_documents = sorted( + output_documents, key=lambda doc: doc.score if doc.score is not None else -inf, reverse=True + ) + if any(doc.score is None for doc in output_documents): + logger.info( + "Some of the Documents DocumentJoiner got have score=None. It was configured to sort Documents by " + "score, so those with score=None were sorted as if they had a score of -infinity." + ) + + if top_k: + output_documents = output_documents[:top_k] + elif self.top_k: + output_documents = output_documents[: self.top_k] + + return {"documents": output_documents} + + def _concatenate(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Concatenate multiple lists of Documents and return only the Document with the highest score for duplicates. + """ + output = [] + docs_per_id = defaultdict(list) + for doc in itertools.chain.from_iterable(document_lists): + docs_per_id[doc.id].append(doc) + for docs in docs_per_id.values(): + doc_with_best_score = max(docs, key=lambda doc: doc.score if doc.score else -inf) + output.append(doc_with_best_score) + return output + + def _merge(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Merge multiple lists of Documents and calculate a weighted sum of the scores of duplicate Documents. + """ + scores_map: dict = defaultdict(int) + documents_map = {} + weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists) + + for documents, weight in zip(document_lists, weights): + for doc in documents: + scores_map[doc.id] += (doc.score if doc.score else 0) * weight + documents_map[doc.id] = doc + + for doc in documents_map.values(): + doc.score = scores_map[doc.id] + + return list(documents_map.values()) + + def _reciprocal_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Merge multiple lists of Documents and assign scores based on reciprocal rank fusion. + + The constant k is set to 61 (60 was suggested by the original paper, + plus 1 as python lists are 0-based and the paper used 1-based ranking). + """ + k = 61 + + scores_map: dict = defaultdict(int) + documents_map = {} + weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists) + + # Calculate weighted reciprocal rank fusion score + for documents, weight in zip(document_lists, weights): + for rank, doc in enumerate(documents): + scores_map[doc.id] += (weight * len(document_lists)) / (k + rank) + documents_map[doc.id] = doc + + # Normalize scores. Note: len(results) / k is the maximum possible score, + # achieved by being ranked first in all doc lists with non-zero weight. + for _id in scores_map: + scores_map[_id] /= len(document_lists) / k + + for doc in documents_map.values(): + doc.score = scores_map[doc.id] + + return list(documents_map.values()) + + def _distribution_based_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]: + """ + Merge multiple lists of Documents and assign scores based on Distribution-Based Score Fusion. + + (https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18) + If a Document is in more than one retriever, the one with the highest score is used. + """ + for documents in document_lists: + scores_list = [] + + for doc in documents: + scores_list.append(doc.score if doc.score is not None else 0) + + mean_score = sum(scores_list) / len(scores_list) + std_dev = (sum((x - mean_score) ** 2 for x in scores_list) / len(scores_list)) ** 0.5 + min_score = mean_score - 3 * std_dev + max_score = mean_score + 3 * std_dev + delta_score = max_score - min_score + + for doc in documents: + doc.score = (doc.score - min_score) / delta_score if delta_score != 0.0 else 0.0 + # if all docs have the same score delta_score is 0, the docs are uninformative for the query + + output = self._concatenate(document_lists=document_lists) + + return output + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + join_mode=str(self.join_mode), + weights=self.weights, + top_k=self.top_k, + sort_by_score=self.sort_by_score, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentJoiner": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) diff --git a/testbed/deepset-ai__haystack/haystack/components/joiners/string_joiner.py b/testbed/deepset-ai__haystack/haystack/components/joiners/string_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..42d42fe4cf6fb84a7bfc68f096a2e64dcfcb235e --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/joiners/string_joiner.py @@ -0,0 +1,59 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack import component, logging +from haystack.core.component.types import Variadic + +logger = logging.getLogger(__name__) + + +@component +class StringJoiner: + """ + Component to join strings from different components to a list of strings. + + ### Usage example + + ```python + from haystack.components.joiners import StringJoiner + from haystack.components.builders import PromptBuilder + from haystack.core.pipeline import Pipeline + + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.dataclasses import ChatMessage + + string_1 = "What's Natural Language Processing?" + string_2 = "What is life?" + + pipeline = Pipeline() + pipeline.add_component("prompt_builder_1", PromptBuilder("Builder 1: {{query}}")) + pipeline.add_component("prompt_builder_2", PromptBuilder("Builder 2: {{query}}")) + pipeline.add_component("string_joiner", StringJoiner()) + + pipeline.connect("prompt_builder_1.prompt", "string_joiner.strings") + pipeline.connect("prompt_builder_2.prompt", "string_joiner.strings") + + print(pipeline.run(data={"prompt_builder_1": {"query": string_1}, "prompt_builder_2": {"query": string_2}})) + + >> {"string_joiner": {"strings": ["Builder 1: What's Natural Language Processing?", "Builder 2: What is life?"]}} + ``` + """ + + @component.output_types(strings=List[str]) + def run(self, strings: Variadic[str]): + """ + Joins strings into a list of strings + + :param strings: + strings from different components + + :returns: + A dictionary with the following keys: + - `strings`: Merged list of strings + """ + + out_strings = list(strings) + return {"strings": out_strings} diff --git a/testbed/deepset-ai__haystack/haystack/components/retrievers/__init__.py b/testbed/deepset-ai__haystack/haystack/components/retrievers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91d1288a19553db2b456855cd2af49a3d5a9e4d5 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/retrievers/__init__.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.retrievers.filter_retriever import FilterRetriever +from haystack.components.retrievers.in_memory.bm25_retriever import InMemoryBM25Retriever +from haystack.components.retrievers.in_memory.embedding_retriever import InMemoryEmbeddingRetriever +from haystack.components.retrievers.sentence_window_retriever import SentenceWindowRetriever + +__all__ = ["FilterRetriever", "InMemoryEmbeddingRetriever", "InMemoryBM25Retriever", "SentenceWindowRetriever"] diff --git a/testbed/deepset-ai__haystack/haystack/components/retrievers/sentence_window_retriever.py b/testbed/deepset-ai__haystack/haystack/components/retrievers/sentence_window_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc389ed3ebc53205ca8780311cd4cfb5ef172d8 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/retrievers/sentence_window_retriever.py @@ -0,0 +1,197 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_from_dict, default_to_dict +from haystack.document_stores.types import DocumentStore +from haystack.utils import deserialize_document_store_in_init_params_inplace + + +@component +class SentenceWindowRetriever: + """ + Retrieves documents adjacent to a given document in the Document Store. + + During indexing, documents are broken into smaller chunks, or sentences. When you submit a query, + the Retriever fetches the most relevant sentence. To provide full context, + SentenceWindowRetriever fetches a number of neighboring sentences before and after each + relevant one. You can set this number with the `window_size` parameter. + It uses `source_id` and `doc.meta['split_id']` to locate the surrounding documents. + + This component works with existing Retrievers, like BM25Retriever or + EmbeddingRetriever. First, use a Retriever to find documents based on a query and then use + SentenceWindowRetriever to get the surrounding documents for context. + + The SentenceWindowRetriever is compatible with the following DocumentStores: + - [Astra](https://docs.haystack.deepset.ai/docs/astradocumentstore) + - [Elasticsearch](https://docs.haystack.deepset.ai/docs/elasticsearch-document-store) + - [OpenSearch](https://docs.haystack.deepset.ai/docs/opensearch-document-store) + - [Pgvector](https://docs.haystack.deepset.ai/docs/pgvectordocumentstore) + - [Pinecone](https://docs.haystack.deepset.ai/docs/pinecone-document-store) + - [Qdrant](https://docs.haystack.deepset.ai/docs/qdrant-document-store) + + ### Usage example + + ```python + from haystack import Document, Pipeline + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + from haystack.components.retrievers import SentenceWindowRetriever + from haystack.components.preprocessors import DocumentSplitter + from haystack.document_stores.in_memory import InMemoryDocumentStore + + splitter = DocumentSplitter(split_length=10, split_overlap=5, split_by="word") + text = ( + "This is a text with some words. There is a second sentence. And there is also a third sentence. " + "It also contains a fourth sentence. And a fifth sentence. And a sixth sentence. And a seventh sentence" + ) + doc = Document(content=text) + docs = splitter.run([doc]) + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs["documents"]) + + + rag = Pipeline() + rag.add_component("bm25_retriever", InMemoryBM25Retriever(doc_store, top_k=1)) + rag.add_component("sentence_window_retriever", SentenceWindowRetriever(document_store=doc_store, window_size=2)) + rag.connect("bm25_retriever", "sentence_window_retriever") + + rag.run({'bm25_retriever': {"query":"third"}}) + + >> {'sentence_window_retriever': {'context_windows': ['some words. There is a second sentence. + >> And there is also a third sentence. It also contains a fourth sentence. And a fifth sentence. And a sixth + >> sentence. And a'], 'context_documents': [[Document(id=..., content: 'some words. There is a second sentence. + >> And there is ', meta: {'source_id': '...', 'page_number': 1, 'split_id': 1, 'split_idx_start': 20, + >> '_split_overlap': [{'doc_id': '...', 'range': (20, 43)}, {'doc_id': '...', 'range': (0, 30)}]}), + >> Document(id=..., content: 'second sentence. And there is also a third sentence. It ', + >> meta: {'source_id': '74ea87deb38012873cf8c07e...f19d01a26a098447113e1d7b83efd30c02987114', 'page_number': 1, + >> 'split_id': 2, 'split_idx_start': 43, '_split_overlap': [{'doc_id': '...', 'range': (23, 53)}, {'doc_id': '...', + >> 'range': (0, 26)}]}), Document(id=..., content: 'also a third sentence. It also contains a fourth sentence. ', + >> meta: {'source_id': '...', 'page_number': 1, 'split_id': 3, 'split_idx_start': 73, '_split_overlap': + >> [{'doc_id': '...', 'range': (30, 56)}, {'doc_id': '...', 'range': (0, 33)}]}), Document(id=..., content: + >> 'also contains a fourth sentence. And a fifth sentence. And ', meta: {'source_id': '...', 'page_number': 1, + >> 'split_id': 4, 'split_idx_start': 99, '_split_overlap': [{'doc_id': '...', 'range': (26, 59)}, + >> {'doc_id': '...', 'range': (0, 26)}]}), Document(id=..., content: 'And a fifth sentence. And a sixth sentence. + >> And a ', meta: {'source_id': '...', 'page_number': 1, 'split_id': 5, 'split_idx_start': 132, + >> '_split_overlap': [{'doc_id': '...', 'range': (33, 59)}, {'doc_id': '...', 'range': (0, 24)}]})]]}}}} + ``` + """ + + def __init__(self, document_store: DocumentStore, window_size: int = 3): + """ + Creates a new SentenceWindowRetriever component. + + :param document_store: The Document Store to retrieve the surrounding documents from. + :param window_size: The number of documents to retrieve before and after the relevant one. + For example, `window_size: 2` fetches 2 preceding and 2 following documents. + """ + if window_size < 1: + raise ValueError("The window_size parameter must be greater than 0.") + + self.window_size = window_size + self.document_store = document_store + + @staticmethod + def merge_documents_text(documents: List[Document]) -> str: + """ + Merge a list of document text into a single string. + + This functions concatenates the textual content of a list of documents into a single string, eliminating any + overlapping content. + + :param documents: List of Documents to merge. + """ + sorted_docs = sorted(documents, key=lambda doc: doc.meta["split_idx_start"]) + merged_text = "" + last_idx_end = 0 + for doc in sorted_docs: + start = doc.meta["split_idx_start"] # start of the current content + + # if the start of the current content is before the end of the last appended content, adjust it + start = max(start, last_idx_end) + + # append the non-overlapping part to the merged text + merged_text += doc.content[start - doc.meta["split_idx_start"] :] # type: ignore + + # update the last end index + last_idx_end = doc.meta["split_idx_start"] + len(doc.content) # type: ignore + + return merged_text + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + docstore = self.document_store.to_dict() + return default_to_dict(self, document_store=docstore, window_size=self.window_size) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SentenceWindowRetriever": + """ + Deserializes the component from a dictionary. + + :returns: + Deserialized component. + """ + # deserialize the document store + deserialize_document_store_in_init_params_inplace(data) + + # deserialize the component + return default_from_dict(cls, data) + + @component.output_types(context_windows=List[str], context_documents=List[List[Document]]) + def run(self, retrieved_documents: List[Document], window_size: Optional[int] = None): + """ + Based on the `source_id` and on the `doc.meta['split_id']` get surrounding documents from the document store. + + Implements the logic behind the sentence-window technique, retrieving the surrounding documents of a given + document from the document store. + + :param retrieved_documents: List of retrieved documents from the previous retriever. + :param window_size: The number of documents to retrieve before and after the relevant one. This will overwrite + the `window_size` parameter set in the constructor. + :returns: + A dictionary with the following keys: + - `context_windows`: A list of strings, where each string represents the concatenated text from the + context window of the corresponding document in `retrieved_documents`. + - `context_documents`: A list of lists of `Document` objects, where each inner list contains the + documents that come from the context window for the corresponding document in + `retrieved_documents`. + + """ + window_size = window_size or self.window_size + + if window_size < 1: + raise ValueError("The window_size parameter must be greater than 0.") + + if not all("split_id" in doc.meta for doc in retrieved_documents): + raise ValueError("The retrieved documents must have 'split_id' in the metadata.") + + if not all("source_id" in doc.meta for doc in retrieved_documents): + raise ValueError("The retrieved documents must have 'source_id' in the metadata.") + + context_text = [] + context_documents = [] + for doc in retrieved_documents: + source_id = doc.meta["source_id"] + split_id = doc.meta["split_id"] + min_before = min(list(range(split_id - 1, split_id - window_size - 1, -1))) + max_after = max(list(range(split_id + 1, split_id + window_size + 1, 1))) + context_docs = self.document_store.filter_documents( + { + "operator": "AND", + "conditions": [ + {"field": "meta.source_id", "operator": "==", "value": source_id}, + {"field": "meta.split_id", "operator": ">=", "value": min_before}, + {"field": "meta.split_id", "operator": "<=", "value": max_after}, + ], + } + ) + context_text.append(self.merge_documents_text(context_docs)) + context_documents.append(context_docs) + + return {"context_windows": context_text, "context_documents": context_documents} diff --git a/testbed/deepset-ai__haystack/haystack/components/routers/file_type_router.py b/testbed/deepset-ai__haystack/haystack/components/routers/file_type_router.py new file mode 100644 index 0000000000000000000000000000000000000000..be20c7d7e774d5d2ddb4f3c55fca29de322257f6 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/routers/file_type_router.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import mimetypes +import re +from collections import defaultdict +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata +from haystack.dataclasses import ByteStream + +logger = logging.getLogger(__name__) + + +# we add markdown because it is not added by the mimetypes module +# see https://github.com/python/cpython/pull/17995 +CUSTOM_MIMETYPES = {".md": "text/markdown", ".markdown": "text/markdown"} + + +@component +class FileTypeRouter: + """ + Categorizes files or byte streams by their MIME types, helping in context-based routing. + + FileTypeRouter supports both exact MIME type matching and regex patterns. + + For file paths, MIME types come from extensions, while byte streams use metadata. + You can use regex patterns in the `mime_types` parameter to set broad categories + (such as 'audio/*' or 'text/*') or specific types. + MIME types without regex patterns are treated as exact matches. + + ### Usage example + + ```python + from haystack.components.routers import FileTypeRouter + from pathlib import Path + + # For exact MIME type matching + router = FileTypeRouter(mime_types=["text/plain", "application/pdf"]) + + # For flexible matching using regex, to handle all audio types + router_with_regex = FileTypeRouter(mime_types=[r"audio/.*", r"text/plain"]) + + sources = [Path("file.txt"), Path("document.pdf"), Path("song.mp3")] + print(router.run(sources=sources)) + print(router_with_regex.run(sources=sources)) + + # Expected output: + # {'text/plain': [ + # PosixPath('file.txt')], 'application/pdf': [PosixPath('document.pdf')], 'unclassified': [PosixPath('song.mp3') + # ]} + # {'audio/.*': [ + # PosixPath('song.mp3')], 'text/plain': [PosixPath('file.txt')], 'unclassified': [PosixPath('document.pdf') + # ]} + ``` + """ + + def __init__(self, mime_types: List[str], additional_mimetypes: Optional[Dict[str, str]] = None): + """ + Initialize the FileTypeRouter component. + + :param mime_types: + A list of MIME types or regex patterns to classify the input files or byte streams. + (for example: `["text/plain", "audio/x-wav", "image/jpeg"]`). + + :param additional_mimetypes: + A dictionary containing the MIME type to add to the mimetypes package to prevent unsupported or non native + packages from being unclassified. + (for example: `{"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}`). + """ + if not mime_types: + raise ValueError("The list of mime types cannot be empty.") + + if additional_mimetypes: + for mime, ext in additional_mimetypes.items(): + mimetypes.add_type(mime, ext) + + self.mime_type_patterns = [] + for mime_type in mime_types: + try: + pattern = re.compile(mime_type) + except re.error: + raise ValueError(f"Invalid regex pattern '{mime_type}'.") + self.mime_type_patterns.append(pattern) + + # the actual output type is List[Union[Path, ByteStream]], + # but this would cause PipelineConnectError with Converters + component.set_output_types( + self, + unclassified=List[Union[str, Path, ByteStream]], + **{mime_type: List[Union[str, Path, ByteStream]] for mime_type in mime_types}, + ) + self.mime_types = mime_types + self._additional_mimetypes = additional_mimetypes + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, mime_types=self.mime_types, additional_mimetypes=self._additional_mimetypes) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "FileTypeRouter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) + + def run( + self, + sources: List[Union[str, Path, ByteStream]], + meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + ) -> Dict[str, List[Union[ByteStream, Path]]]: + """ + Categorize files or byte streams according to their MIME types. + + :param sources: + A list of file paths or byte streams to categorize. + + :param meta: + Optional metadata to attach to the sources. + When provided, the sources are internally converted to ByteStream objects and the metadata is added. + This value can be a list of dictionaries or a single dictionary. + If it's a single dictionary, its content is added to the metadata of all ByteStream objects. + If it's a list, its length must match the number of sources, as they are zipped together. + + :returns: A dictionary where the keys are MIME types (or `"unclassified"`) and the values are lists of data + sources. + """ + + mime_types = defaultdict(list) + meta_list = normalize_metadata(meta=meta, sources_count=len(sources)) + + for source, meta_dict in zip(sources, meta_list): + if isinstance(source, str): + source = Path(source) + + if isinstance(source, Path): + mime_type = self._get_mime_type(source) + elif isinstance(source, ByteStream): + mime_type = source.mime_type + else: + raise ValueError(f"Unsupported data source type: {type(source).__name__}") + + # If we have metadata, we convert the source to ByteStream and add the metadata + if meta_dict: + source = get_bytestream_from_source(source) + source.meta.update(meta_dict) + + matched = False + if mime_type: + for pattern in self.mime_type_patterns: + if pattern.fullmatch(mime_type): + mime_types[pattern.pattern].append(source) + matched = True + break + if not matched: + mime_types["unclassified"].append(source) + + return dict(mime_types) + + def _get_mime_type(self, path: Path) -> Optional[str]: + """ + Get the MIME type of the provided file path. + + :param path: The file path to get the MIME type for. + + :returns: The MIME type of the provided file path, or `None` if the MIME type cannot be determined. + """ + extension = path.suffix.lower() + mime_type = mimetypes.guess_type(path.as_posix())[0] + # lookup custom mappings if the mime type is not found + return CUSTOM_MIMETYPES.get(extension, mime_type) diff --git a/testbed/deepset-ai__haystack/haystack/components/routers/text_language_router.py b/testbed/deepset-ai__haystack/haystack/components/routers/text_language_router.py new file mode 100644 index 0000000000000000000000000000000000000000..2c517df2fc0919dd1ecd774604e062dc7a7e351d --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/routers/text_language_router.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List, Optional + +from haystack import component, logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport("Run 'pip install langdetect'") as langdetect_import: + import langdetect + + +@component +class TextLanguageRouter: + """ + Routes text strings to different output connections based on their language. + + Provide a list of languages during initialization. If the document's text doesn't match any of the + specified languages, the metadata value is set to "unmatched". + For routing documents based on their language, use the DocumentLanguageClassifier component, + followed by the MetaDataRouter. + + ### Usage example + + ```python + from haystack import Pipeline, Document + from haystack.components.routers import TextLanguageRouter + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + + document_store = InMemoryDocumentStore() + document_store.write_documents([Document(content="Elvis Presley was an American singer and actor.")]) + + p = Pipeline() + p.add_component(instance=TextLanguageRouter(languages=["en"]), name="text_language_router") + p.add_component(instance=InMemoryBM25Retriever(document_store=document_store), name="retriever") + p.connect("text_language_router.en", "retriever.query") + + result = p.run({"text_language_router": {"text": "Who was Elvis Presley?"}}) + assert result["retriever"]["documents"][0].content == "Elvis Presley was an American singer and actor." + + result = p.run({"text_language_router": {"text": "ένα ελληνικό κείμενο"}}) + assert result["text_language_router"]["unmatched"] == "ένα ελληνικό κείμενο" + ``` + """ + + def __init__(self, languages: Optional[List[str]] = None): + """ + Initialize the TextLanguageRouter component. + + :param languages: A list of ISO language codes. + See the supported languages in [`langdetect` documentation](https://github.com/Mimino666/langdetect#languages). + If not specified, defaults to ["en"]. + """ + langdetect_import.check() + if not languages: + languages = ["en"] + self.languages = languages + component.set_output_types(self, unmatched=str, **{language: str for language in languages}) + + def run(self, text: str) -> Dict[str, str]: + """ + Routes the text strings to different output connections based on their language. + + If the document's text doesn't match any of the specified languages, the metadata value is set to "unmatched". + + :param text: A text string to route. + + :returns: A dictionary in which the key is the language (or `"unmatched"`), + and the value is the text. + + :raises TypeError: If the input is not a string. + """ + if not isinstance(text, str): + msg = ( + "TextLanguageRouter expects a string as input. In case you want to classify a document, please use " + "the DocumentLanguageClassifier and MetaDataRouter." + ) + raise TypeError(msg) + + output: Dict[str, str] = {} + + detected_language = self._detect_language(text) + if detected_language in self.languages: + output[detected_language] = text + else: + output["unmatched"] = text + + return output + + def _detect_language(self, text: str) -> Optional[str]: + try: + language = langdetect.detect(text) + except langdetect.LangDetectException as exception: + logger.warning("Langdetect cannot detect the language of text. Error: {error}", error=exception) + # Only log the text in debug mode, as it might contain sensitive information + logger.debug("Langdetect cannot detect the language of text: {text}", text=text) + language = None + return language diff --git a/testbed/deepset-ai__haystack/haystack/components/samplers/top_p.py b/testbed/deepset-ai__haystack/haystack/components/samplers/top_p.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2327291c2a71a12a495bdfeec3b8ef5c469629 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/samplers/top_p.py @@ -0,0 +1,177 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List, Optional, Tuple + +from haystack import Document, component, logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + + +with LazyImport(message="Run 'pip install \"torch>=1.13\"'") as torch_import: + import torch + + +@component +class TopPSampler: + """ + Implements top-p (nucleus) sampling for document filtering based on cumulative probability scores. + + This component provides functionality to filter a list of documents by selecting those whose scores fall + within the top 'p' percent of the cumulative distribution. It is useful for focusing on high-probability + documents while filtering out less relevant ones based on their assigned scores. + + Usage example: + + ```python + from haystack import Document + from haystack.components.samplers import TopPSampler + + sampler = TopPSampler(top_p=0.95, score_field="similarity_score") + docs = [ + Document(content="Berlin", meta={"similarity_score": -10.6}), + Document(content="Belgrade", meta={"similarity_score": -8.9}), + Document(content="Sarajevo", meta={"similarity_score": -4.6}), + ] + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 1 + assert docs[0].content == "Sarajevo" + ``` + """ + + def __init__(self, top_p: float = 1.0, score_field: Optional[str] = None, min_top_k: Optional[int] = None): + """ + Creates an instance of TopPSampler. + + :param top_p: Float between 0 and 1 representing the cumulative probability threshold for document selection. + A value of 1.0 indicates no filtering (all documents are retained). + :param score_field: Name of the field in each document's metadata that contains the score. If None, the default + document score field is used. + :param min_top_k: If specified, the minimum number of documents to return. If the top_p selects + fewer documents, additional ones with the next highest scores are added to the selection. + """ + torch_import.check() + + self.top_p = top_p + if not 0 <= top_p <= 1: + raise ValueError(f"top_p must be between 0 and 1. Got {top_p}.") + self.score_field = score_field + self.min_top_k = min_top_k + + @component.output_types(documents=List[Document]) + def run(self, documents: List[Document], top_p: Optional[float] = None): + """ + Filters documents using top-p sampling based on their scores. + + If the specified top_p results in no documents being selected (especially in cases of a low top_p value), the + method returns the document with the highest score. + + :param documents: List of Document objects to be filtered. + :param top_p: If specified, a float to override the cumulative probability threshold set during initialization. + + :returns: A dictionary with the following key: + - `documents`: List of Document objects that have been selected based on the top-p sampling. + :raises ValueError: If the top_p value is not within the range [0, 1]. + """ + if not documents: + return {"documents": []} + + top_p = top_p or self.top_p + if not 0 <= top_p <= 1: + raise ValueError(f"top_p must be between 0 and 1. Got {top_p}.") + + documents_with_scores, scores = self._get_documents_and_scores(documents) + if len(documents_with_scores) == 0: + logger.warning("No documents with scores found. Returning the original documents.") + return {"documents": documents} + + sorted_docs_with_scores = sorted(zip(documents_with_scores, scores), key=lambda x: x[1], reverse=True) + sorted_documents, sorted_scores = [list(t) for t in zip(*sorted_docs_with_scores)] + + tensor_scores = torch.tensor(sorted_scores, dtype=torch.float32) + probs = torch.nn.functional.softmax(tensor_scores, dim=-1) + cumulative_probs = torch.cumsum(probs, dim=-1) + + # Check if the cumulative probabilities are close to top_p with a 1e-6 tolerance + close_to_top_p = torch.isclose(cumulative_probs, torch.tensor(top_p, device=cumulative_probs.device), atol=1e-6) + + # Combine the close_to_top_p with original condition using logical OR + condition = (cumulative_probs <= top_p) | close_to_top_p + + # Find the indices with cumulative probabilities that exceed top_p + top_p_indices = torch.where(torch.BoolTensor(condition))[0] + + # Map the selected indices back to their original indices + selected_docs = [sorted_documents[i.item()] for i in top_p_indices] + + if self.min_top_k and len(selected_docs) < self.min_top_k: + selected_docs = sorted_documents[: self.min_top_k] + + # If low p resulted in no documents being selected, then return at least one document + if len(selected_docs) == 0: + logger.warning( + "Top-p sampling with p={top_p} resulted in no documents being selected. " + "Returning the document with the highest score.", + top_p=top_p, + ) + selected_docs = [sorted_documents[0]] + + return {"documents": selected_docs} + + @staticmethod + def _get_doc_score(doc: Document, score_field: Optional[str] = None) -> Optional[float]: + """ + Get the score of a document. + + :param doc: Document object. + :param score_field: Name of the field in the document's metadata that contains the score. + If None, the document score field is used. + + :return: Score of the document. + """ + if score_field: + score = doc.meta.get(score_field) + else: + score = doc.score + + if not isinstance(score, float): + score = None + return score + + def _get_documents_and_scores(self, documents: List[Document]) -> Tuple[List[Document], List[float]]: + """ + Checks if documents have scores in their metadata or score field and returns the documents with scores. + + :param documents: List of Documents. + :return: List of scores. + """ + docs_with_scores = [] + scores = [] + docs_missing_scores = [] + for doc in documents: + score = self._get_doc_score(doc=doc, score_field=self.score_field) + if score is None: + docs_missing_scores.append(doc) + else: + scores.append(score) + docs_with_scores.append(doc) + + if len(docs_missing_scores) > 0: + missing_scores_docs_ids = [d.id for d in docs_missing_scores if d.id] + if self.score_field: + logger.warning( + "Score field '{score_field}' not found in metadata of documents with IDs: {doc_ids}." + "Make sure that all documents have a score field '{score_field_2}' in their metadata.", + score_field=self.score_field, + doc_ids=",".join(missing_scores_docs_ids), + score_field_2=self.score_field, + ) + else: + logger.warning( + "Ensure all documents have a valid score value. These documents {doc_ids} are missing scores.", + doc_ids=",".join(missing_scores_docs_ids), + ) + return docs_with_scores, scores diff --git a/testbed/deepset-ai__haystack/haystack/components/validators/__init__.py b/testbed/deepset-ai__haystack/haystack/components/validators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe2bf26ab76557f86a8f386f0f8e49757da22f0 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/validators/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.validators.json_schema import JsonSchemaValidator + +__all__ = ["JsonSchemaValidator"] diff --git a/testbed/deepset-ai__haystack/haystack/components/validators/json_schema.py b/testbed/deepset-ai__haystack/haystack/components/validators/json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..13f35be87e7b8fbc376df7df03ab1ea1ae42723f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/validators/json_schema.py @@ -0,0 +1,263 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Dict, List, Optional + +from haystack import component +from haystack.dataclasses import ChatMessage +from haystack.lazy_imports import LazyImport + +with LazyImport(message="Run 'pip install jsonschema'") as jsonschema_import: + from jsonschema import ValidationError, validate + + +def is_valid_json(s: str) -> bool: + """ + Check if the provided string is a valid JSON. + + :param s: The string to be checked. + :returns: `True` if the string is a valid JSON; otherwise, `False`. + """ + try: + json.loads(s) + except ValueError: + return False + return True + + +@component +class JsonSchemaValidator: + """ + Validates JSON content of `ChatMessage` against a specified [JSON Schema](https://json-schema.org/). + + If JSON content of a message conforms to the provided schema, the message is passed along the "validated" output. + If the JSON content does not conform to the schema, the message is passed along the "validation_error" output. + In the latter case, the error message is constructed using the provided `error_template` or a default template. + These error ChatMessages can be used by LLMs in Haystack 2.x recovery loops. + + Usage example: + + ```python + from typing import List + + from haystack import Pipeline + from haystack.components.generators.chat import OpenAIChatGenerator + from haystack.components.joiners import BranchJoiner + from haystack.components.validators import JsonSchemaValidator + from haystack import component + from haystack.dataclasses import ChatMessage + + + @component + class MessageProducer: + + @component.output_types(messages=List[ChatMessage]) + def run(self, messages: List[ChatMessage]) -> dict: + return {"messages": messages} + + + p = Pipeline() + p.add_component("llm", OpenAIChatGenerator(model="gpt-4-1106-preview", + generation_kwargs={"response_format": {"type": "json_object"}})) + p.add_component("schema_validator", JsonSchemaValidator()) + p.add_component("joiner_for_llm", BranchJoiner(List[ChatMessage])) + p.add_component("message_producer", MessageProducer()) + + p.connect("message_producer.messages", "joiner_for_llm") + p.connect("joiner_for_llm", "llm") + p.connect("llm.replies", "schema_validator.messages") + p.connect("schema_validator.validation_error", "joiner_for_llm") + + result = p.run(data={ + "message_producer": { + "messages":[ChatMessage.from_user("Generate JSON for person with name 'John' and age 30")]}, + "schema_validator": { + "json_schema": { + "type": "object", + "properties": {"name": {"type": "string"}, + "age": {"type": "integer"} + } + } + } + }) + print(result) + >> {'schema_validator': {'validated': [ChatMessage(content='\\n{\\n "name": "John",\\n "age": 30\\n}', + role=, name=None, meta={'model': 'gpt-4-1106-preview', 'index': 0, + 'finish_reason': 'stop', 'usage': {'completion_tokens': 17, 'prompt_tokens': 20, 'total_tokens': 37}})]}} + ``` + """ + + # Default error description template + default_error_template = ( + "The following generated JSON does not conform to the provided schema.\n" + "Generated JSON: {failing_json}\n" + "Error details:\n- Message: {error_message}\n" + "- Error Path in JSON: {error_path}\n" + "- Schema Path: {error_schema_path}\n" + "Please match the following schema:\n" + "{json_schema}\n" + "and provide the corrected JSON content ONLY. Please do not output anything else than the raw corrected " + "JSON string, this is the most important part of the task. Don't use any markdown and don't add any comment." + ) + + def __init__(self, json_schema: Optional[Dict[str, Any]] = None, error_template: Optional[str] = None): + """ + Initialize the JsonSchemaValidator component. + + :param json_schema: A dictionary representing the [JSON schema](https://json-schema.org/) against which + the messages' content is validated. + :param error_template: A custom template string for formatting the error message in case of validation failure. + """ + jsonschema_import.check() + self.json_schema = json_schema + self.error_template = error_template + + @component.output_types(validated=List[ChatMessage], validation_error=List[ChatMessage]) + def run( + self, + messages: List[ChatMessage], + json_schema: Optional[Dict[str, Any]] = None, + error_template: Optional[str] = None, + ) -> Dict[str, List[ChatMessage]]: + """ + Validates the last of the provided messages against the specified json schema. + + If it does, the message is passed along the "validated" output. If it does not, the message is passed along + the "validation_error" output. + + :param messages: A list of ChatMessage instances to be validated. The last message in this list is the one + that is validated. + :param json_schema: A dictionary representing the [JSON schema](https://json-schema.org/) + against which the messages' content is validated. If not provided, the schema from the component init + is used. + :param error_template: A custom template string for formatting the error message in case of validation. If not + provided, the `error_template` from the component init is used. + :return: A dictionary with the following keys: + - "validated": A list of messages if the last message is valid. + - "validation_error": A list of messages if the last message is invalid. + :raises ValueError: If no JSON schema is provided or if the message content is not a dictionary or a list of + dictionaries. + """ + last_message = messages[-1] + if not is_valid_json(last_message.content): + return { + "validation_error": [ + ChatMessage.from_user( + f"The message '{last_message.content}' is not a valid JSON object. " + f"Please provide only a valid JSON object in string format." + f"Don't use any markdown and don't add any comment." + ) + ] + } + + last_message_content = json.loads(last_message.content) + json_schema = json_schema or self.json_schema + error_template = error_template or self.error_template or self.default_error_template + + if not json_schema: + raise ValueError("Provide a JSON schema for validation either in the run method or in the component init.") + # fc payload is json object but subtree `parameters` is string - we need to convert to json object + # we need complete json to validate it against schema + last_message_json = self._recursive_json_to_object(last_message_content) + using_openai_schema: bool = self._is_openai_function_calling_schema(json_schema) + if using_openai_schema: + validation_schema = json_schema["parameters"] + else: + validation_schema = json_schema + try: + last_message_json = [last_message_json] if not isinstance(last_message_json, list) else last_message_json + for content in last_message_json: + if using_openai_schema: + validate(instance=content["function"]["arguments"], schema=validation_schema) + else: + validate(instance=content, schema=validation_schema) + + return {"validated": [last_message]} + except ValidationError as e: + error_path = " -> ".join(map(str, e.absolute_path)) if e.absolute_path else "N/A" + error_schema_path = " -> ".join(map(str, e.absolute_schema_path)) if e.absolute_schema_path else "N/A" + + error_template = error_template or self.default_error_template + + recovery_prompt = self._construct_error_recovery_message( + error_template, + str(e), + error_path, + error_schema_path, + validation_schema, + failing_json=last_message.content, + ) + return {"validation_error": [ChatMessage.from_user(recovery_prompt)]} + + def _construct_error_recovery_message( + self, + error_template: str, + error_message: str, + error_path: str, + error_schema_path: str, + json_schema: Dict[str, Any], + failing_json: str, + ) -> str: + """ + Constructs an error recovery message using a specified template or the default one if none is provided. + + :param error_template: A custom template string for formatting the error message in case of validation failure. + :param error_message: The error message returned by the JSON schema validator. + :param error_path: The path in the JSON content where the error occurred. + :param error_schema_path: The path in the JSON schema where the error occurred. + :param json_schema: The JSON schema against which the content is validated. + :param failing_json: The generated invalid JSON string. + """ + error_template = error_template or self.default_error_template + + return error_template.format( + error_message=error_message, + error_path=error_path, + error_schema_path=error_schema_path, + json_schema=json_schema, + failing_json=failing_json, + ) + + def _is_openai_function_calling_schema(self, json_schema: Dict[str, Any]) -> bool: + """ + Checks if the provided schema is a valid OpenAI function calling schema. + + :param json_schema: The JSON schema to check + :return: `True` if the schema is a valid OpenAI function calling schema; otherwise, `False`. + """ + return all(key in json_schema for key in ["name", "description", "parameters"]) + + def _recursive_json_to_object(self, data: Any) -> Any: + """ + Convert any string values that are valid JSON objects into dictionary objects. + + Returns a new data structure. + + :param data: The data structure to be traversed. + :return: A new data structure with JSON strings converted to dictionary objects. + """ + if isinstance(data, list): + return [self._recursive_json_to_object(item) for item in data] + + if isinstance(data, dict): + new_dict = {} + for key, value in data.items(): + if isinstance(value, str): + try: + json_value = json.loads(value) + if isinstance(json_value, (dict, list)): + new_dict[key] = self._recursive_json_to_object(json_value) + else: + new_dict[key] = value # Preserve the original string value + except json.JSONDecodeError: + new_dict[key] = value + elif isinstance(value, dict): + new_dict[key] = self._recursive_json_to_object(value) + else: + new_dict[key] = value + return new_dict + + # If it's neither a list nor a dictionary, return the value directly + raise ValueError("Input must be a dictionary or a list of dictionaries.") diff --git a/testbed/deepset-ai__haystack/haystack/components/websearch/__init__.py b/testbed/deepset-ai__haystack/haystack/components/websearch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5d3af2090d553799752142ed9ffbeb3c4b6b5f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/websearch/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.websearch.searchapi import SearchApiWebSearch +from haystack.components.websearch.serper_dev import SerperDevWebSearch + +__all__ = ["SerperDevWebSearch", "SearchApiWebSearch"] diff --git a/testbed/deepset-ai__haystack/haystack/components/websearch/searchapi.py b/testbed/deepset-ai__haystack/haystack/components/websearch/searchapi.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf22f02109d9c496f0c8b21ad9596e8c7783009 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/websearch/searchapi.py @@ -0,0 +1,179 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Union + +import requests + +from haystack import ComponentError, Document, component, default_from_dict, default_to_dict, logging +from haystack.utils import Secret, deserialize_secrets_inplace + +logger = logging.getLogger(__name__) + + +SEARCHAPI_BASE_URL = "https://www.searchapi.io/api/v1/search" + + +class SearchApiError(ComponentError): ... + + +@component +class SearchApiWebSearch: + """ + Uses [SearchApi](https://www.searchapi.io/) to search the web for relevant documents. + + Usage example: + ```python + from haystack.components.websearch import SearchApiWebSearch + from haystack.utils import Secret + + websearch = SearchApiWebSearch(top_k=10, api_key=Secret.from_token("test-api-key")) + results = websearch.run(query="Who is the boyfriend of Olivia Wilde?") + + assert results["documents"] + assert results["links"] + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("SEARCHAPI_API_KEY"), + top_k: Optional[int] = 10, + allowed_domains: Optional[List[str]] = None, + search_params: Optional[Dict[str, Any]] = None, + ): + """ + Initialize the SearchApiWebSearch component. + + :param api_key: API key for the SearchApi API + :param top_k: Number of documents to return. + :param allowed_domains: List of domains to limit the search to. + :param search_params: Additional parameters passed to the SearchApi API. + For example, you can set 'num' to 100 to increase the number of search results. + See the [SearchApi website](https://www.searchapi.io/) for more details. + + The default search engine is Google, however, users can change it by setting the `engine` + parameter in the `search_params`. + """ + + self.api_key = api_key + self.top_k = top_k + self.allowed_domains = allowed_domains + self.search_params = search_params or {} + if "engine" not in self.search_params: + self.search_params["engine"] = "google" + + # Ensure that the API key is resolved. + _ = self.api_key.resolve_value() + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + top_k=self.top_k, + allowed_domains=self.allowed_domains, + search_params=self.search_params, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SearchApiWebSearch": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + return default_from_dict(cls, data) + + @component.output_types(documents=List[Document], links=List[str]) + def run(self, query: str) -> Dict[str, Union[List[Document], List[str]]]: + """ + Uses [SearchApi](https://www.searchapi.io/) to search the web. + + :param query: Search query. + :returns: A dictionary with the following keys: + - "documents": List of documents returned by the search engine. + - "links": List of links returned by the search engine. + :raises TimeoutError: If the request to the SearchApi API times out. + :raises SearchApiError: If an error occurs while querying the SearchApi API. + """ + query_prepend = "OR ".join(f"site:{domain} " for domain in self.allowed_domains) if self.allowed_domains else "" + payload = {"q": query_prepend + " " + query, **self.search_params} + headers = {"Authorization": f"Bearer {self.api_key.resolve_value()}", "X-SearchApi-Source": "Haystack"} + try: + response = requests.get(SEARCHAPI_BASE_URL, headers=headers, params=payload, timeout=90) + response.raise_for_status() # Will raise an HTTPError for bad responses + except requests.Timeout as error: + raise TimeoutError(f"Request to {self.__class__.__name__} timed out.") from error + + except requests.RequestException as e: + raise SearchApiError(f"An error occurred while querying {self.__class__.__name__}. Error: {e}") from e + + # Request succeeded + json_result = response.json() + + # organic results are the main results from the search engine + organic_results = [] + if "organic_results" in json_result: + for result in json_result["organic_results"]: + organic_results.append( + Document.from_dict({"title": result["title"], "content": result["snippet"], "link": result["link"]}) + ) + + # answer box has a direct answer to the query + answer_box = [] + if "answer_box" in json_result: + answer_box = [ + Document.from_dict( + { + "title": json_result["answer_box"].get("title", ""), + "content": json_result["answer_box"].get("answer", ""), + "link": json_result["answer_box"].get("link", ""), + } + ) + ] + + knowledge_graph = [] + if "knowledge_graph" in json_result: + knowledge_graph = [ + Document.from_dict( + { + "title": json_result["knowledge_graph"].get("title", ""), + "content": json_result["knowledge_graph"].get("description", ""), + } + ) + ] + + related_questions = [] + if "related_questions" in json_result: + for result in json_result["related_questions"]: + related_questions.append( + Document.from_dict( + { + "title": result["question"], + "content": result["answer"] if result.get("answer") else result.get("answer_highlight", ""), + "link": result.get("source", {}).get("link", ""), + } + ) + ) + + documents = answer_box + knowledge_graph + organic_results + related_questions + + links = [result["link"] for result in json_result["organic_results"]] + + logger.debug( + "SearchApi returned {number_documents} documents for the query '{query}'", + number_documents=len(documents), + query=query, + ) + return {"documents": documents[: self.top_k], "links": links[: self.top_k]} diff --git a/testbed/deepset-ai__haystack/haystack/components/writers/__init__.py b/testbed/deepset-ai__haystack/haystack/components/writers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d609f59d98caabfb410a5a2cba10c433ad7a762 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/writers/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.components.writers.document_writer import DocumentWriter + +__all__ = ["DocumentWriter"] diff --git a/testbed/deepset-ai__haystack/haystack/components/writers/document_writer.py b/testbed/deepset-ai__haystack/haystack/components/writers/document_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..7e757596389e129ae9906ba9a6a18ee11754e03a --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/components/writers/document_writer.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional + +from haystack import Document, component, default_from_dict, default_to_dict, logging +from haystack.document_stores.types import DocumentStore, DuplicatePolicy +from haystack.utils import deserialize_document_store_in_init_params_inplace + +logger = logging.getLogger(__name__) + + +@component +class DocumentWriter: + """ + Writes documents to a DocumentStore. + + ### Usage example + ```python + from haystack import Document + from haystack.components.writers import DocumentWriter + from haystack.document_stores.in_memory import InMemoryDocumentStore + docs = [ + Document(content="Python is a popular programming language"), + ] + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs) + ``` + """ + + def __init__(self, document_store: DocumentStore, policy: DuplicatePolicy = DuplicatePolicy.NONE): + """ + Create a DocumentWriter component. + + :param document_store: + The instance of the document store where you want to store your documents. + :param policy: + The policy to apply when a Document with the same ID already exists in the DocumentStore. + - `DuplicatePolicy.NONE`: Default policy, relies on the DocumentStore settings. + - `DuplicatePolicy.SKIP`: Skips documents with the same ID and doesn't write them to the DocumentStore. + - `DuplicatePolicy.OVERWRITE`: Overwrites documents with the same ID. + - `DuplicatePolicy.FAIL`: Raises an error if a Document with the same ID is already in the DocumentStore. + """ + self.document_store = document_store + self.policy = policy + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"document_store": type(self.document_store).__name__} + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict(self, document_store=self.document_store.to_dict(), policy=self.policy.name) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentWriter": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + + :raises DeserializationError: + If the document store is not properly specified in the serialization data or its type cannot be imported. + """ + # deserialize the document store + deserialize_document_store_in_init_params_inplace(data) + + data["init_parameters"]["policy"] = DuplicatePolicy[data["init_parameters"]["policy"]] + + return default_from_dict(cls, data) + + @component.output_types(documents_written=int) + def run(self, documents: List[Document], policy: Optional[DuplicatePolicy] = None): + """ + Run the DocumentWriter on the given input data. + + :param documents: + A list of documents to write to the document store. + :param policy: + The policy to use when encountering duplicate documents. + :returns: + Number of documents written to the document store. + + :raises ValueError: + If the specified document store is not found. + """ + if policy is None: + policy = self.policy + + documents_written = self.document_store.write_documents(documents=documents, policy=policy) + return {"documents_written": documents_written} diff --git a/testbed/deepset-ai__haystack/haystack/core/__init__.py b/testbed/deepset-ai__haystack/haystack/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/haystack/core/component/__init__.py b/testbed/deepset-ai__haystack/haystack/core/component/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..425b357eb8a681ed6afdcae3d136a61ebda4cd3e --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/component/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component.component import Component, component +from haystack.core.component.types import InputSocket, OutputSocket + +__all__ = ["component", "Component", "InputSocket", "OutputSocket"] diff --git a/testbed/deepset-ai__haystack/haystack/core/component/component.py b/testbed/deepset-ai__haystack/haystack/core/component/component.py new file mode 100644 index 0000000000000000000000000000000000000000..e1dbf2c5f0723a7cd1d9c0fae17366131fafa65a --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/component/component.py @@ -0,0 +1,560 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +""" +Attributes: + + component: Marks a class as a component. Any class decorated with `@component` can be used by a Pipeline. + +All components must follow the contract below. This docstring is the source of truth for components contract. + +
+ +`@component` decorator + +All component classes must be decorated with the `@component` decorator. This allows Canals to discover them. + +
+ +`__init__(self, **kwargs)` + +Optional method. + +Components may have an `__init__` method where they define: + +- `self.init_parameters = {same parameters that the __init__ method received}`: + In this dictionary you can store any state the components wish to be persisted when they are saved. + These values will be given to the `__init__` method of a new instance when the pipeline is loaded. + Note that by default the `@component` decorator saves the arguments automatically. + However, if a component sets their own `init_parameters` manually in `__init__()`, that will be used instead. + Note: all of the values contained here **must be JSON serializable**. Serialize them manually if needed. + +Components should take only "basic" Python types as parameters of their `__init__` function, or iterables and +dictionaries containing only such values. Anything else (objects, functions, etc) will raise an exception at init +time. If there's the need for such values, consider serializing them to a string. + +_(TODO explain how to use classes and functions in init. In the meantime see `test/components/test_accumulate.py`)_ + +The `__init__` must be extremely lightweight, because it's a frequent operation during the construction and +validation of the pipeline. If a component has some heavy state to initialize (models, backends, etc...) refer to +the `warm_up()` method. + +
+ +`warm_up(self)` + +Optional method. + +This method is called by Pipeline before the graph execution. Make sure to avoid double-initializations, +because Pipeline will not keep track of which components it called `warm_up()` on. + +
+ +`run(self, data)` + +Mandatory method. + +This is the method where the main functionality of the component should be carried out. It's called by +`Pipeline.run()`. + +When the component should run, Pipeline will call this method with an instance of the dataclass returned by the +method decorated with `@component.input`. This dataclass contains: + +- all the input values coming from other components connected to it, +- if any is missing, the corresponding value defined in `self.defaults`, if it exists. + +`run()` must return a single instance of the dataclass declared through the method decorated with +`@component.output`. + +""" + +import inspect +import sys +import warnings +from collections.abc import Callable +from contextlib import contextmanager +from contextvars import ContextVar +from copy import deepcopy +from dataclasses import dataclass +from types import new_class +from typing import Any, Dict, Optional, Protocol, Type, runtime_checkable + +from haystack import logging +from haystack.core.errors import ComponentError + +from .sockets import Sockets +from .types import InputSocket, OutputSocket, _empty + +logger = logging.getLogger(__name__) + + +@dataclass +class PreInitHookPayload: + """ + Payload for the hook called before a component instance is initialized. + + :param callback: + Receives the following inputs: component class and init parameter keyword args. + :param in_progress: + Flag to indicate if the hook is currently being executed. + Used to prevent it from being called recursively (if the component's constructor + instantiates another component). + """ + + callback: Callable + in_progress: bool = False + + +_COMPONENT_PRE_INIT_HOOK: ContextVar[Optional[PreInitHookPayload]] = ContextVar("component_pre_init_hook", default=None) + + +@contextmanager +def _hook_component_init(callback: Callable): + """ + Context manager to set a callback that will be invoked before a component's constructor is called. + + The callback receives the component class and the init parameters (as keyword arguments) and can modify the init + parameters in place. + + :param callback: + Callback function to invoke. + """ + token = _COMPONENT_PRE_INIT_HOOK.set(PreInitHookPayload(callback)) + try: + yield + finally: + _COMPONENT_PRE_INIT_HOOK.reset(token) + + +@runtime_checkable +class Component(Protocol): + """ + Note this is only used by type checking tools. + + In order to implement the `Component` protocol, custom components need to + have a `run` method. The signature of the method and its return value + won't be checked, i.e. classes with the following methods: + + def run(self, param: str) -> Dict[str, Any]: + ... + + and + + def run(self, **kwargs): + ... + + will be both considered as respecting the protocol. This makes the type + checking much weaker, but we have other places where we ensure code is + dealing with actual Components. + + The protocol is runtime checkable so it'll be possible to assert: + + isinstance(MyComponent, Component) + """ + + # This is the most reliable way to define the protocol for the `run` method. + # Defining a method doesn't work as different Components will have different + # arguments. Even defining here a method with `**kwargs` doesn't work as the + # expected signature must be identical. + # This makes most Language Servers and type checkers happy and shows less errors. + # NOTE: This check can be removed when we drop Python 3.8 support. + if sys.version_info >= (3, 9): + run: Callable[..., Dict[str, Any]] + else: + run: Callable + + +class ComponentMeta(type): + @staticmethod + def _positional_to_kwargs(cls_type, args) -> Dict[str, Any]: + """ + Convert positional arguments to keyword arguments based on the signature of the `__init__` method. + """ + init_signature = inspect.signature(cls_type.__init__) + init_params = {name: info for name, info in init_signature.parameters.items() if name != "self"} + + out = {} + for arg, (name, info) in zip(args, init_params.items()): + if info.kind == inspect.Parameter.VAR_POSITIONAL: + raise ComponentError( + "Pre-init hooks do not support components with variadic positional args in their init method" + ) + + assert info.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY) + out[name] = arg + return out + + @staticmethod + def _parse_and_set_output_sockets(instance: Any): + has_async_run = hasattr(instance, "run_async") + + # If `component.set_output_types()` was called in the component constructor, + # `__haystack_output__` is already populated, no need to do anything. + if not hasattr(instance, "__haystack_output__"): + # If that's not the case, we need to populate `__haystack_output__` + # + # If either of the run methods were decorated, they'll have a field assigned that + # stores the output specification. If both run methods were decorated, we ensure that + # outputs are the same. We deepcopy the content of the cache to transfer ownership from + # the class method to the actual instance, so that different instances of the same class + # won't share this data. + + run_output_types = getattr(instance.run, "_output_types_cache", {}) + async_run_output_types = getattr(instance.run_async, "_output_types_cache", {}) if has_async_run else {} + + if has_async_run and run_output_types != async_run_output_types: + raise ComponentError("Output type specifications of 'run' and 'run_async' methods must be the same") + output_types_cache = run_output_types + + instance.__haystack_output__ = Sockets(instance, deepcopy(output_types_cache), OutputSocket) + + @staticmethod + def _parse_and_set_input_sockets(component_cls: Type, instance: Any): + def inner(method, sockets): + from inspect import Parameter + + run_signature = inspect.signature(method) + + for param_name, param_info in run_signature.parameters.items(): + if param_name == "self" or param_info.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD): + continue + + socket_kwargs = {"name": param_name, "type": param_info.annotation} + if param_info.default != Parameter.empty: + socket_kwargs["default_value"] = param_info.default + + new_socket = InputSocket(**socket_kwargs) + + # Also ensure that new sockets don't override existing ones. + existing_socket = sockets.get(param_name) + if existing_socket is not None and existing_socket != new_socket: + raise ComponentError( + "set_input_types()/set_input_type() cannot override the parameters of the 'run' method" + ) + + sockets[param_name] = new_socket + + return run_signature + + # Create the sockets if set_input_types() wasn't called in the constructor. + if not hasattr(instance, "__haystack_input__"): + instance.__haystack_input__ = Sockets(instance, {}, InputSocket) + + inner(getattr(component_cls, "run"), instance.__haystack_input__) + + # Ensure that the sockets are the same for the async method, if it exists. + async_run = getattr(component_cls, "run_async", None) + if async_run is not None: + run_sockets = Sockets(instance, {}, InputSocket) + async_run_sockets = Sockets(instance, {}, InputSocket) + + # Can't use the sockets from above as they might contain + # values set with set_input_types(). + run_sig = inner(getattr(component_cls, "run"), run_sockets) + async_run_sig = inner(async_run, async_run_sockets) + + if async_run_sockets != run_sockets or run_sig != async_run_sig: + raise ComponentError("Parameters of 'run' and 'run_async' methods must be the same") + + def __call__(cls, *args, **kwargs): + """ + This method is called when clients instantiate a Component and runs before __new__ and __init__. + """ + # This will call __new__ then __init__, giving us back the Component instance + pre_init_hook = _COMPONENT_PRE_INIT_HOOK.get() + if pre_init_hook is None or pre_init_hook.in_progress: + instance = super().__call__(*args, **kwargs) + else: + try: + pre_init_hook.in_progress = True + named_positional_args = ComponentMeta._positional_to_kwargs(cls, args) + assert ( + set(named_positional_args.keys()).intersection(kwargs.keys()) == set() + ), "positional and keyword arguments overlap" + kwargs.update(named_positional_args) + pre_init_hook.callback(cls, kwargs) + instance = super().__call__(**kwargs) + finally: + pre_init_hook.in_progress = False + + # Before returning, we have the chance to modify the newly created + # Component instance, so we take the chance and set up the I/O sockets + has_async_run = hasattr(instance, "run_async") + if has_async_run and not inspect.iscoroutinefunction(instance.run_async): + raise ComponentError(f"Method 'run_async' of component '{cls.__name__}' must be a coroutine") + instance.__haystack_supports_async__ = has_async_run + + ComponentMeta._parse_and_set_input_sockets(cls, instance) + ComponentMeta._parse_and_set_output_sockets(instance) + + # Since a Component can't be used in multiple Pipelines at the same time + # we need to know if it's already owned by a Pipeline when adding it to one. + # We use this flag to check that. + instance.__haystack_added_to_pipeline__ = None + + return instance + + +def _component_repr(component: Component) -> str: + """ + All Components override their __repr__ method with this one. + + It prints the component name and the input/output sockets. + """ + result = object.__repr__(component) + if pipeline := getattr(component, "__haystack_added_to_pipeline__", None): + # This Component has been added in a Pipeline, let's get the name from there. + result += f"\n{pipeline.get_component_name(component)}" + + # We're explicitly ignoring the type here because we're sure that the component + # has the __haystack_input__ and __haystack_output__ attributes at this point + return ( + f'{result}\n{getattr(component, "__haystack_input__", "")}' + f'\n{getattr(component, "__haystack_output__", "")}' + ) + + +def _component_run_has_kwargs(component_cls: Type) -> bool: + run_method = getattr(component_cls, "run", None) + if run_method is None: + return False + else: + return any( + param.kind == inspect.Parameter.VAR_KEYWORD for param in inspect.signature(run_method).parameters.values() + ) + + +class _Component: + """ + See module's docstring. + + Args: + class_: the class that Canals should use as a component. + serializable: whether to check, at init time, if the component can be saved with + `save_pipelines()`. + + Returns: + A class that can be recognized as a component. + + Raises: + ComponentError: if the class provided has no `run()` method or otherwise doesn't respect the component contract. + """ + + def __init__(self): + self.registry = {} + + def set_input_type( + self, + instance, + name: str, + type: Any, # noqa: A002 + default: Any = _empty, + ): + """ + Add a single input socket to the component instance. + + Replaces any existing input socket with the same name. + + :param instance: Component instance where the input type will be added. + :param name: name of the input socket. + :param type: type of the input socket. + :param default: default value of the input socket, defaults to _empty + """ + if not _component_run_has_kwargs(instance.__class__): + raise ComponentError( + "Cannot set input types on a component that doesn't have a kwargs parameter in the 'run' method" + ) + + if not hasattr(instance, "__haystack_input__"): + instance.__haystack_input__ = Sockets(instance, {}, InputSocket) + instance.__haystack_input__[name] = InputSocket(name=name, type=type, default_value=default) + + def set_input_types(self, instance, **types): + """ + Method that specifies the input types when 'kwargs' is passed to the run method. + + Use as: + + ```python + @component + class MyComponent: + + def __init__(self, value: int): + component.set_input_types(self, value_1=str, value_2=str) + ... + + @component.output_types(output_1=int, output_2=str) + def run(self, **kwargs): + return {"output_1": kwargs["value_1"], "output_2": ""} + ``` + + Note that if the `run()` method also specifies some parameters, those will take precedence. + + For example: + + ```python + @component + class MyComponent: + + def __init__(self, value: int): + component.set_input_types(self, value_1=str, value_2=str) + ... + + @component.output_types(output_1=int, output_2=str) + def run(self, value_0: str, value_1: Optional[str] = None, **kwargs): + return {"output_1": kwargs["value_1"], "output_2": ""} + ``` + + would add a mandatory `value_0` parameters, make the `value_1` + parameter optional with a default None, and keep the `value_2` + parameter mandatory as specified in `set_input_types`. + + """ + if not _component_run_has_kwargs(instance.__class__): + raise ComponentError( + "Cannot set input types on a component that doesn't have a kwargs parameter in the 'run' method" + ) + + instance.__haystack_input__ = Sockets( + instance, {name: InputSocket(name=name, type=type_) for name, type_ in types.items()}, InputSocket + ) + + def set_output_types(self, instance, **types): + """ + Method that specifies the output types when the 'run' method is not decorated with 'component.output_types'. + + Use as: + + ```python + @component + class MyComponent: + + def __init__(self, value: int): + component.set_output_types(self, output_1=int, output_2=str) + ... + + # no decorators here + def run(self, value: int): + return {"output_1": 1, "output_2": "2"} + ``` + """ + has_decorator = hasattr(instance.run, "_output_types_cache") + if has_decorator: + raise ComponentError( + "Cannot call `set_output_types` on a component that already has " + "the 'output_types' decorator on its `run` method" + ) + + instance.__haystack_output__ = Sockets( + instance, {name: OutputSocket(name=name, type=type_) for name, type_ in types.items()}, OutputSocket + ) + + def output_types(self, **types): + """ + Decorator factory that specifies the output types of a component. + + Use as: + + ```python + @component + class MyComponent: + @component.output_types(output_1=int, output_2=str) + def run(self, value: int): + return {"output_1": 1, "output_2": "2"} + ``` + """ + + def output_types_decorator(run_method): + """ + Decorator that sets the output types of the decorated method. + + This happens at class creation time, and since we don't have the decorated + class available here, we temporarily store the output types as an attribute of + the decorated method. The ComponentMeta metaclass will use this data to create + sockets at instance creation time. + """ + method_name = run_method.__name__ + if method_name not in ("run", "run_async"): + raise ComponentError("'output_types' decorator can only be used on 'run' and 'run_async' methods") + + setattr( + run_method, + "_output_types_cache", + {name: OutputSocket(name=name, type=type_) for name, type_ in types.items()}, + ) + return run_method + + return output_types_decorator + + def _component(self, cls, is_greedy: Optional[bool] = None): + """ + Decorator validating the structure of the component and registering it in the components registry. + """ + logger.debug("Registering {component} as a component", component=cls) + + if is_greedy is not None: + msg = ( + "The 'is_greedy' argument is deprecated and will be removed in version '2.7.0'. " + "Change the 'Variadic' input of your Component to 'GreedyVariadic' instead." + ) + warnings.warn(msg, DeprecationWarning) + else: + is_greedy = False + + # Check for required methods and fail as soon as possible + if not hasattr(cls, "run"): + raise ComponentError(f"{cls.__name__} must have a 'run()' method. See the docs for more information.") + + def copy_class_namespace(namespace): + """ + This is the callback that `typing.new_class` will use to populate the newly created class. + + Simply copy the whole namespace from the decorated class. + """ + for key, val in dict(cls.__dict__).items(): + # __dict__ and __weakref__ are class-bound, we should let Python recreate them. + if key in ("__dict__", "__weakref__"): + continue + namespace[key] = val + + # Recreate the decorated component class so it uses our metaclass. + # We must explicitly redefine the type of the class to make sure language servers + # and type checkers understand that the class is of the correct type. + # mypy doesn't like that we do this though so we explicitly ignore the type check. + cls: cls.__name__ = new_class(cls.__name__, cls.__bases__, {"metaclass": ComponentMeta}, copy_class_namespace) # type: ignore[no-redef] + + # Save the component in the class registry (for deserialization) + class_path = f"{cls.__module__}.{cls.__name__}" + if class_path in self.registry: + # Corner case, but it may occur easily in notebooks when re-running cells. + logger.debug( + "Component {component} is already registered. Previous imported from '{module_name}', \ + new imported from '{new_module_name}'", + component=class_path, + module_name=self.registry[class_path], + new_module_name=cls, + ) + self.registry[class_path] = cls + logger.debug("Registered Component {component}", component=cls) + + # Override the __repr__ method with a default one + cls.__repr__ = _component_repr + + return cls + + def __call__(self, cls: Optional[type] = None, is_greedy: Optional[bool] = None): + # We must wrap the call to the decorator in a function for it to work + # correctly with or without parens + def wrap(cls): + return self._component(cls, is_greedy=is_greedy) + + if cls: + # Decorator is called without parens + return wrap(cls) + + # Decorator is called with parens + return wrap + + +component = _Component() diff --git a/testbed/deepset-ai__haystack/haystack/core/component/sockets.py b/testbed/deepset-ai__haystack/haystack/core/component/sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..2d84db2bfbc82f1d9d0a28c09b3c483f1fd2fb6b --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/component/sockets.py @@ -0,0 +1,148 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, Optional, Type, Union + +from haystack import logging +from haystack.core.type_utils import _type_name + +from .types import InputSocket, OutputSocket + +logger = logging.getLogger(__name__) + +SocketsDict = Dict[str, Union[InputSocket, OutputSocket]] +SocketsIOType = Union[Type[InputSocket], Type[OutputSocket]] + + +class Sockets: + """ + Represents the inputs or outputs of a `Component`. + + Depending on the type passed to the constructor, it will represent either the inputs or the outputs of + the `Component`. + + Usage: + ```python + from typing import Any + from haystack.components.builders.prompt_builder import PromptBuilder + from haystack.core.component.sockets import Sockets + from haystack.core.component.types import InputSocket, OutputSocket + + + prompt_template = \""" + Given these documents, answer the question.\nDocuments: + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + + \nQuestion: {{question}} + \nAnswer: + \""" + + prompt_builder = PromptBuilder(template=prompt_template) + sockets = {"question": InputSocket("question", Any), "documents": InputSocket("documents", Any)} + inputs = Sockets(component=prompt_builder, sockets_dict=sockets, sockets_io_type=InputSocket) + inputs + >>> Inputs: + >>> - question: Any + >>> - documents: Any + + inputs.question + >>> InputSocket(name='question', type=typing.Any, default_value=, ... + ``` + """ + + # We're using a forward declaration here to avoid a circular import. + def __init__( + self, + component: "Component", # type: ignore[name-defined] # noqa: F821 + sockets_dict: SocketsDict, + sockets_io_type: SocketsIOType, + ): + """ + Create a new Sockets object. + + We don't do any enforcement on the types of the sockets here, the `sockets_type` is only used for + the `__repr__` method. + We could do without it and use the type of a random value in the `sockets` dict, but that wouldn't + work for components that have no sockets at all. Either input or output. + + :param component: + The component that these sockets belong to. + :param sockets_dict: + A dictionary of sockets. + :param sockets_io_type: + The type of the sockets. + """ + self._sockets_io_type = sockets_io_type + self._component = component + self._sockets_dict = sockets_dict + self.__dict__.update(sockets_dict) + + def __eq__(self, value: object) -> bool: + if not isinstance(value, Sockets): + return False + + return ( + self._sockets_io_type == value._sockets_io_type + and self._component == value._component + and self._sockets_dict == value._sockets_dict + ) + + def __setitem__(self, key: str, socket: Union[InputSocket, OutputSocket]): + """ + Adds a new socket to this Sockets object. + + This eases a bit updating the list of sockets after Sockets has been created. + That should happen only in the `component` decorator. + """ + self._sockets_dict[key] = socket + self.__dict__[key] = socket + + def __contains__(self, key: str) -> bool: + return key in self._sockets_dict + + def get( + self, key: str, default: Optional[Union[InputSocket, OutputSocket]] = None + ) -> Optional[Union[InputSocket, OutputSocket]]: + """ + Get a socket from the Sockets object. + + :param key: + The name of the socket to get. + :param default: + The value to return if the key is not found. + :returns: + The socket with the given key or `default` if the key is not found. + """ + return self._sockets_dict.get(key, default) + + def _component_name(self) -> str: + if pipeline := getattr(self._component, "__haystack_added_to_pipeline__"): + # This Component has been added in a Pipeline, let's get the name from there. + return pipeline.get_component_name(self._component) + + # This Component has not been added to a Pipeline yet, so we can't know its name. + # Let's use default __repr__. We don't call repr() directly as Components have a custom + # __repr__ method and that would lead to infinite recursion since we call Sockets.__repr__ in it. + return object.__repr__(self._component) + + def __getattribute__(self, name): + try: + sockets = object.__getattribute__(self, "_sockets") + if name in sockets: + return sockets[name] + except AttributeError: + pass + + return object.__getattribute__(self, name) + + def __repr__(self) -> str: + result = "" + if self._sockets_io_type == InputSocket: + result = "Inputs:\n" + elif self._sockets_io_type == OutputSocket: + result = "Outputs:\n" + + return result + "\n".join([f" - {n}: {_type_name(s.type)}" for n, s in self._sockets_dict.items()]) diff --git a/testbed/deepset-ai__haystack/haystack/core/component/types.py b/testbed/deepset-ai__haystack/haystack/core/component/types.py new file mode 100644 index 0000000000000000000000000000000000000000..b08681a750a581b0f551913590cd71c46db230c7 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/component/types.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from typing import Any, Iterable, List, Type, TypeVar, get_args + +from typing_extensions import Annotated, TypeAlias # Python 3.8 compatibility + +HAYSTACK_VARIADIC_ANNOTATION = "__haystack__variadic_t" +HAYSTACK_GREEDY_VARIADIC_ANNOTATION = "__haystack__greedy_variadic_t" + +# # Generic type variable used in the Variadic container +T = TypeVar("T") + + +# Variadic is a custom annotation type we use to mark input types. +# This type doesn't do anything else than "marking" the contained +# type so it can be used in the `InputSocket` creation where we +# check that its annotation equals to HAYSTACK_VARIADIC_ANNOTATION +Variadic: TypeAlias = Annotated[Iterable[T], HAYSTACK_VARIADIC_ANNOTATION] + +# GreedyVariadic type is similar to Variadic. +# The only difference is the way it's treated by the Pipeline when input is received +# in a socket with this type. +# Instead of waiting for other inputs to be received, Components that have a GreedyVariadic +# input will be run right after receiving the first input. +# Even if there are multiple connections to that socket. +GreedyVariadic: TypeAlias = Annotated[Iterable[T], HAYSTACK_GREEDY_VARIADIC_ANNOTATION] + + +class _empty: + """Custom object for marking InputSocket.default_value as not set.""" + + +@dataclass +class InputSocket: + """ + Represents an input of a `Component`. + + :param name: + The name of the input. + :param type: + The type of the input. + :param default_value: + The default value of the input. If not set, the input is mandatory. + :param is_variadic: + Whether the input is variadic or not. + :param is_greedy + Whether the input is a greedy variadic or not. + :param senders: + The list of components that send data to this input. + """ + + name: str + type: Type + default_value: Any = _empty + is_variadic: bool = field(init=False) + is_greedy: bool = field(init=False) + senders: List[str] = field(default_factory=list) + + @property + def is_mandatory(self): + """Check if the input is mandatory.""" + return self.default_value == _empty + + def __post_init__(self): + try: + # __metadata__ is a tuple + self.is_variadic = self.type.__metadata__[0] in [ + HAYSTACK_VARIADIC_ANNOTATION, + HAYSTACK_GREEDY_VARIADIC_ANNOTATION, + ] + self.is_greedy = self.type.__metadata__[0] == HAYSTACK_GREEDY_VARIADIC_ANNOTATION + except AttributeError: + self.is_variadic = False + self.is_greedy = False + if self.is_variadic: + # We need to "unpack" the type inside the Variadic annotation, + # otherwise the pipeline connection api will try to match + # `Annotated[type, HAYSTACK_VARIADIC_ANNOTATION]`. + # + # Note1: Variadic is expressed as an annotation of one single type, + # so the return value of get_args will always be a one-item tuple. + # + # Note2: a pipeline always passes a list of items when a component + # input is declared as Variadic, so the type itself always wraps + # an iterable of the declared type. For example, Variadic[int] + # is eventually an alias for Iterable[int]. Since we're interested + # in getting the inner type `int`, we call `get_args` twice: the + # first time to get `List[int]` out of `Variadic`, the second time + # to get `int` out of `List[int]`. + self.type = get_args(get_args(self.type)[0])[0] + + +@dataclass +class OutputSocket: + """ + Represents an output of a `Component`. + + :param name: + The name of the output. + :param type: + The type of the output. + :param receivers: + The list of components that receive the output of this component. + """ + + name: str + type: type + receivers: List[str] = field(default_factory=list) diff --git a/testbed/deepset-ai__haystack/haystack/core/errors.py b/testbed/deepset-ai__haystack/haystack/core/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..bd76fbcce09b0a656340b2b0f56803fa846321a3 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/errors.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +class PipelineError(Exception): + pass + + +class PipelineRuntimeError(Exception): + pass + + +class PipelineConnectError(PipelineError): + pass + + +class PipelineValidationError(PipelineError): + pass + + +class PipelineDrawingError(PipelineError): + pass + + +class PipelineMaxComponentRuns(PipelineError): + pass + + +class PipelineUnmarshalError(PipelineError): + pass + + +class ComponentError(Exception): + pass + + +class ComponentDeserializationError(Exception): + pass + + +class DeserializationError(Exception): + pass + + +class SerializationError(Exception): + pass diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/__init__.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..744c282f8c0b821df1b8f7e4770860280da2b7b7 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .pipeline import Pipeline +from .template import PredefinedPipeline + +__all__ = ["Pipeline", "PredefinedPipeline"] diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/base.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/base.py new file mode 100644 index 0000000000000000000000000000000000000000..31ad2ad93ce8a804d5a4cbbfe7dff35dd6f19222 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/base.py @@ -0,0 +1,1375 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import importlib +import itertools +from collections import defaultdict +from copy import deepcopy +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional, Set, TextIO, Tuple, Type, TypeVar, Union + +import networkx # type:ignore + +from haystack import logging +from haystack.core.component import Component, InputSocket, OutputSocket, component +from haystack.core.errors import ( + DeserializationError, + PipelineConnectError, + PipelineDrawingError, + PipelineError, + PipelineRuntimeError, + PipelineUnmarshalError, + PipelineValidationError, +) +from haystack.core.serialization import DeserializationCallbacks, component_from_dict, component_to_dict +from haystack.core.type_utils import _type_name, _types_are_compatible +from haystack.marshal import Marshaller, YamlMarshaller +from haystack.utils import is_in_jupyter + +from .descriptions import find_pipeline_inputs, find_pipeline_outputs +from .draw import _to_mermaid_image +from .template import PipelineTemplate, PredefinedPipeline +from .utils import parse_connect_string + +DEFAULT_MARSHALLER = YamlMarshaller() + +# We use a generic type to annotate the return value of classmethods, +# so that static analyzers won't be confused when derived classes +# use those methods. +T = TypeVar("T", bound="PipelineBase") + +logger = logging.getLogger(__name__) + + +class PipelineBase: + """ + Components orchestration engine. + + Builds a graph of components and orchestrates their execution according to the execution graph. + """ + + def __init__(self, metadata: Optional[Dict[str, Any]] = None, max_runs_per_component: int = 100): + """ + Creates the Pipeline. + + :param metadata: + Arbitrary dictionary to store metadata about this `Pipeline`. Make sure all the values contained in + this dictionary can be serialized and deserialized if you wish to save this `Pipeline` to file. + :param max_runs_per_component: + How many times the `Pipeline` can run the same Component. + If this limit is reached a `PipelineMaxComponentRuns` exception is raised. + If not set defaults to 100 runs per Component. + """ + self._telemetry_runs = 0 + self._last_telemetry_sent: Optional[datetime] = None + self.metadata = metadata or {} + self.graph = networkx.MultiDiGraph() + self._max_runs_per_component = max_runs_per_component + + def __eq__(self, other) -> bool: + """ + Pipeline equality is defined by their type and the equality of their serialized form. + + Pipelines of the same type share every metadata, node and edge, but they're not required to use + the same node instances: this allows pipeline saved and then loaded back to be equal to themselves. + """ + if not isinstance(self, type(other)): + return False + return self.to_dict() == other.to_dict() + + def __repr__(self) -> str: + """ + Returns a text representation of the Pipeline. + """ + res = f"{object.__repr__(self)}\n" + if self.metadata: + res += "🧱 Metadata\n" + for k, v in self.metadata.items(): + res += f" - {k}: {v}\n" + + res += "🚅 Components\n" + for name, instance in self.graph.nodes(data="instance"): # type: ignore # type wrongly defined in networkx + res += f" - {name}: {instance.__class__.__name__}\n" + + res += "🛤️ Connections\n" + for sender, receiver, edge_data in self.graph.edges(data=True): + sender_socket = edge_data["from_socket"].name + receiver_socket = edge_data["to_socket"].name + res += f" - {sender}.{sender_socket} -> {receiver}.{receiver_socket} ({edge_data['conn_type']})\n" + + return res + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the pipeline to a dictionary. + + This is meant to be an intermediate representation but it can be also used to save a pipeline to file. + + :returns: + Dictionary with serialized data. + """ + components = {} + for name, instance in self.graph.nodes(data="instance"): # type:ignore + components[name] = component_to_dict(instance, name) + + connections = [] + for sender, receiver, edge_data in self.graph.edges.data(): + sender_socket = edge_data["from_socket"].name + receiver_socket = edge_data["to_socket"].name + connections.append({"sender": f"{sender}.{sender_socket}", "receiver": f"{receiver}.{receiver_socket}"}) + return { + "metadata": self.metadata, + "max_runs_per_component": self._max_runs_per_component, + "components": components, + "connections": connections, + } + + @classmethod + def from_dict( + cls: Type[T], data: Dict[str, Any], callbacks: Optional[DeserializationCallbacks] = None, **kwargs + ) -> T: + """ + Deserializes the pipeline from a dictionary. + + :param data: + Dictionary to deserialize from. + :param callbacks: + Callbacks to invoke during deserialization. + :param kwargs: + `components`: a dictionary of {name: instance} to reuse instances of components instead of creating new + ones. + :returns: + Deserialized component. + """ + data_copy = deepcopy(data) # to prevent modification of original data + metadata = data_copy.get("metadata", {}) + max_runs_per_component = data_copy.get("max_runs_per_component", 100) + pipe = cls(metadata=metadata, max_runs_per_component=max_runs_per_component) + components_to_reuse = kwargs.get("components", {}) + for name, component_data in data_copy.get("components", {}).items(): + if name in components_to_reuse: + # Reuse an instance + instance = components_to_reuse[name] + else: + if "type" not in component_data: + raise PipelineError(f"Missing 'type' in component '{name}'") + + if component_data["type"] not in component.registry: + try: + # Import the module first... + module, _ = component_data["type"].rsplit(".", 1) + logger.debug("Trying to import module {module_name}", module_name=module) + importlib.import_module(module) + # ...then try again + if component_data["type"] not in component.registry: + raise PipelineError( + f"Successfully imported module {module} but can't find it in the component registry." + "This is unexpected and most likely a bug." + ) + except (ImportError, PipelineError) as e: + raise PipelineError(f"Component '{component_data['type']}' not imported.") from e + + # Create a new one + component_class = component.registry[component_data["type"]] + + try: + instance = component_from_dict(component_class, component_data, name, callbacks) + except Exception as e: + msg = ( + f"Couldn't deserialize component '{name}' of class '{component_class.__name__}' " + f"with the following data: {str(component_data)}. Possible reasons include " + "malformed serialized data, mismatch between the serialized component and the " + "loaded one (due to a breaking change, see " + "https://github.com/deepset-ai/haystack/releases), etc." + ) + raise DeserializationError(msg) from e + pipe.add_component(name=name, instance=instance) + + for connection in data.get("connections", []): + if "sender" not in connection: + raise PipelineError(f"Missing sender in connection: {connection}") + if "receiver" not in connection: + raise PipelineError(f"Missing receiver in connection: {connection}") + pipe.connect(sender=connection["sender"], receiver=connection["receiver"]) + + return pipe + + def dumps(self, marshaller: Marshaller = DEFAULT_MARSHALLER) -> str: + """ + Returns the string representation of this pipeline according to the format dictated by the `Marshaller` in use. + + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + :returns: + A string representing the pipeline. + """ + return marshaller.marshal(self.to_dict()) + + def dump(self, fp: TextIO, marshaller: Marshaller = DEFAULT_MARSHALLER): + """ + Writes the string representation of this pipeline to the file-like object passed in the `fp` argument. + + :param fp: + A file-like object ready to be written to. + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + """ + fp.write(marshaller.marshal(self.to_dict())) + + @classmethod + def loads( + cls: Type[T], + data: Union[str, bytes, bytearray], + marshaller: Marshaller = DEFAULT_MARSHALLER, + callbacks: Optional[DeserializationCallbacks] = None, + ) -> T: + """ + Creates a `Pipeline` object from the string representation passed in the `data` argument. + + :param data: + The string representation of the pipeline, can be `str`, `bytes` or `bytearray`. + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + :param callbacks: + Callbacks to invoke during deserialization. + :raises DeserializationError: + If an error occurs during deserialization. + :returns: + A `Pipeline` object. + """ + try: + deserialized_data = marshaller.unmarshal(data) + except Exception as e: + raise DeserializationError( + "Error while unmarshalling serialized pipeline data. This is usually " + "caused by malformed or invalid syntax in the serialized representation." + ) from e + + return cls.from_dict(deserialized_data, callbacks) + + @classmethod + def load( + cls: Type[T], + fp: TextIO, + marshaller: Marshaller = DEFAULT_MARSHALLER, + callbacks: Optional[DeserializationCallbacks] = None, + ) -> T: + """ + Creates a `Pipeline` object a string representation. + + The string representation is read from the file-like object passed in the `fp` argument. + + + :param fp: + A file-like object ready to be read from. + :param marshaller: + The Marshaller used to create the string representation. Defaults to `YamlMarshaller`. + :param callbacks: + Callbacks to invoke during deserialization. + :raises DeserializationError: + If an error occurs during deserialization. + :returns: + A `Pipeline` object. + """ + return cls.loads(fp.read(), marshaller, callbacks) + + def add_component(self, name: str, instance: Component) -> None: + """ + Add the given component to the pipeline. + + Components are not connected to anything by default: use `Pipeline.connect()` to connect components together. + Component names must be unique, but component instances can be reused if needed. + + :param name: + The name of the component to add. + :param instance: + The component instance to add. + + :raises ValueError: + If a component with the same name already exists. + :raises PipelineValidationError: + If the given instance is not a Canals component. + """ + # Component names are unique + if name in self.graph.nodes: + raise ValueError(f"A component named '{name}' already exists in this pipeline: choose another name.") + + # Components can't be named `_debug` + if name == "_debug": + raise ValueError("'_debug' is a reserved name for debug output. Choose another name.") + + # Component instances must be components + if not isinstance(instance, Component): + raise PipelineValidationError( + f"'{type(instance)}' doesn't seem to be a component. Is this class decorated with @component?" + ) + + if getattr(instance, "__haystack_added_to_pipeline__", None): + msg = ( + "Component has already been added in another Pipeline. Components can't be shared between Pipelines. " + "Create a new instance instead." + ) + raise PipelineError(msg) + + setattr(instance, "__haystack_added_to_pipeline__", self) + + # Add component to the graph, disconnected + logger.debug("Adding component '{component_name}' ({component})", component_name=name, component=instance) + # We're completely sure the fields exist so we ignore the type error + self.graph.add_node( + name, + instance=instance, + input_sockets=instance.__haystack_input__._sockets_dict, # type: ignore[attr-defined] + output_sockets=instance.__haystack_output__._sockets_dict, # type: ignore[attr-defined] + visits=0, + ) + + def remove_component(self, name: str) -> Component: + """ + Remove and returns component from the pipeline. + + Remove an existing component from the pipeline by providing its name. + All edges that connect to the component will also be deleted. + + :param name: + The name of the component to remove. + :returns: + The removed Component instance. + + :raises ValueError: + If there is no component with that name already in the Pipeline. + """ + + # Check that a component with that name is in the Pipeline + try: + instance = self.get_component(name) + except ValueError as exc: + raise ValueError( + f"There is no component named '{name}' in the pipeline. The valid component names are: ", + ", ".join(n for n in self.graph.nodes), + ) from exc + + # Delete component from the graph, deleting all its connections + self.graph.remove_node(name) + + # Reset the Component sockets' senders and receivers + input_sockets = instance.__haystack_input__._sockets_dict # type: ignore[attr-defined] + for socket in input_sockets.values(): + socket.senders = [] + + output_sockets = instance.__haystack_output__._sockets_dict # type: ignore[attr-defined] + for socket in output_sockets.values(): + socket.receivers = [] + + # Reset the Component's pipeline reference + setattr(instance, "__haystack_added_to_pipeline__", None) + + return instance + + def connect(self, sender: str, receiver: str) -> "PipelineBase": # noqa: PLR0915 + """ + Connects two components together. + + All components to connect must exist in the pipeline. + If connecting to a component that has several output connections, specify the inputs and output names as + 'component_name.connections_name'. + + :param sender: + The component that delivers the value. This can be either just a component name or can be + in the format `component_name.connection_name` if the component has multiple outputs. + :param receiver: + The component that receives the value. This can be either just a component name or can be + in the format `component_name.connection_name` if the component has multiple inputs. + :returns: + The Pipeline instance. + + :raises PipelineConnectError: + If the two components cannot be connected (for example if one of the components is + not present in the pipeline, or the connections don't match by type, and so on). + """ + # Edges may be named explicitly by passing 'node_name.edge_name' to connect(). + sender_component_name, sender_socket_name = parse_connect_string(sender) + receiver_component_name, receiver_socket_name = parse_connect_string(receiver) + + if sender_component_name == receiver_component_name: + raise PipelineConnectError("Connecting a Component to itself is not supported.") + + # Get the nodes data. + try: + from_sockets = self.graph.nodes[sender_component_name]["output_sockets"] + except KeyError as exc: + raise ValueError(f"Component named {sender_component_name} not found in the pipeline.") from exc + try: + to_sockets = self.graph.nodes[receiver_component_name]["input_sockets"] + except KeyError as exc: + raise ValueError(f"Component named {receiver_component_name} not found in the pipeline.") from exc + + # If the name of either socket is given, get the socket + sender_socket: Optional[OutputSocket] = None + if sender_socket_name: + sender_socket = from_sockets.get(sender_socket_name) + if not sender_socket: + raise PipelineConnectError( + f"'{sender} does not exist. " + f"Output connections of {sender_component_name} are: " + + ", ".join([f"{name} (type {_type_name(socket.type)})" for name, socket in from_sockets.items()]) + ) + + receiver_socket: Optional[InputSocket] = None + if receiver_socket_name: + receiver_socket = to_sockets.get(receiver_socket_name) + if not receiver_socket: + raise PipelineConnectError( + f"'{receiver} does not exist. " + f"Input connections of {receiver_component_name} are: " + + ", ".join([f"{name} (type {_type_name(socket.type)})" for name, socket in to_sockets.items()]) + ) + + # Look for a matching connection among the possible ones. + # Note that if there is more than one possible connection but two sockets match by name, they're paired. + sender_socket_candidates: List[OutputSocket] = [sender_socket] if sender_socket else list(from_sockets.values()) + receiver_socket_candidates: List[InputSocket] = ( + [receiver_socket] if receiver_socket else list(to_sockets.values()) + ) + + # Find all possible connections between these two components + possible_connections = [ + (sender_sock, receiver_sock) + for sender_sock, receiver_sock in itertools.product(sender_socket_candidates, receiver_socket_candidates) + if _types_are_compatible(sender_sock.type, receiver_sock.type) + ] + + # We need this status for error messages, since we might need it in multiple places we calculate it here + status = _connections_status( + sender_node=sender_component_name, + sender_sockets=sender_socket_candidates, + receiver_node=receiver_component_name, + receiver_sockets=receiver_socket_candidates, + ) + + if not possible_connections: + # There's no possible connection between these two components + if len(sender_socket_candidates) == len(receiver_socket_candidates) == 1: + msg = ( + f"Cannot connect '{sender_component_name}.{sender_socket_candidates[0].name}' with " + f"'{receiver_component_name}.{receiver_socket_candidates[0].name}': " + f"their declared input and output types do not match.\n{status}" + ) + else: + msg = ( + f"Cannot connect '{sender_component_name}' with '{receiver_component_name}': " + f"no matching connections available.\n{status}" + ) + raise PipelineConnectError(msg) + + if len(possible_connections) == 1: + # There's only one possible connection, use it + sender_socket = possible_connections[0][0] + receiver_socket = possible_connections[0][1] + + if len(possible_connections) > 1: + # There are multiple possible connection, let's try to match them by name + name_matches = [ + (out_sock, in_sock) for out_sock, in_sock in possible_connections if in_sock.name == out_sock.name + ] + if len(name_matches) != 1: + # There's are either no matches or more than one, we can't pick one reliably + msg = ( + f"Cannot connect '{sender_component_name}' with " + f"'{receiver_component_name}': more than one connection is possible " + "between these components. Please specify the connection name, like: " + f"pipeline.connect('{sender_component_name}.{possible_connections[0][0].name}', " + f"'{receiver_component_name}.{possible_connections[0][1].name}').\n{status}" + ) + raise PipelineConnectError(msg) + + # Get the only possible match + sender_socket = name_matches[0][0] + receiver_socket = name_matches[0][1] + + # Connection must be valid on both sender/receiver sides + if not sender_socket or not receiver_socket or not sender_component_name or not receiver_component_name: + if sender_component_name and sender_socket: + sender_repr = f"{sender_component_name}.{sender_socket.name} ({_type_name(sender_socket.type)})" + else: + sender_repr = "input needed" + + if receiver_component_name and receiver_socket: + receiver_repr = f"({_type_name(receiver_socket.type)}) {receiver_component_name}.{receiver_socket.name}" + else: + receiver_repr = "output" + msg = f"Connection must have both sender and receiver: {sender_repr} -> {receiver_repr}" + raise PipelineConnectError(msg) + + logger.debug( + "Connecting '{sender_component}.{sender_socket_name}' to '{receiver_component}.{receiver_socket_name}'", + sender_component=sender_component_name, + sender_socket_name=sender_socket.name, + receiver_component=receiver_component_name, + receiver_socket_name=receiver_socket.name, + ) + + if receiver_component_name in sender_socket.receivers and sender_component_name in receiver_socket.senders: + # This is already connected, nothing to do + return self + + if receiver_socket.senders and not receiver_socket.is_variadic: + # Only variadic input sockets can receive from multiple senders + msg = ( + f"Cannot connect '{sender_component_name}.{sender_socket.name}' with " + f"'{receiver_component_name}.{receiver_socket.name}': " + f"{receiver_component_name}.{receiver_socket.name} is already connected to {receiver_socket.senders}.\n" + ) + raise PipelineConnectError(msg) + + # Update the sockets with the new connection + sender_socket.receivers.append(receiver_component_name) + receiver_socket.senders.append(sender_component_name) + + # Create the new connection + self.graph.add_edge( + sender_component_name, + receiver_component_name, + key=f"{sender_socket.name}/{receiver_socket.name}", + conn_type=_type_name(sender_socket.type), + from_socket=sender_socket, + to_socket=receiver_socket, + mandatory=receiver_socket.is_mandatory, + ) + return self + + def get_component(self, name: str) -> Component: + """ + Get the component with the specified name from the pipeline. + + :param name: + The name of the component. + :returns: + The instance of that component. + + :raises ValueError: + If a component with that name is not present in the pipeline. + """ + try: + return self.graph.nodes[name]["instance"] + except KeyError as exc: + raise ValueError(f"Component named {name} not found in the pipeline.") from exc + + def get_component_name(self, instance: Component) -> str: + """ + Returns the name of the Component instance if it has been added to this Pipeline or an empty string otherwise. + + :param instance: + The Component instance to look for. + :returns: + The name of the Component instance. + """ + for name, inst in self.graph.nodes(data="instance"): # type: ignore # type wrongly defined in networkx + if inst == instance: + return name + return "" + + def inputs(self, include_components_with_connected_inputs: bool = False) -> Dict[str, Dict[str, Any]]: + """ + Returns a dictionary containing the inputs of a pipeline. + + Each key in the dictionary corresponds to a component name, and its value is another dictionary that describes + the input sockets of that component, including their types and whether they are optional. + + :param include_components_with_connected_inputs: + If `False`, only components that have disconnected input edges are + included in the output. + :returns: + A dictionary where each key is a pipeline component name and each value is a dictionary of + inputs sockets of that component. + """ + inputs: Dict[str, Dict[str, Any]] = {} + for component_name, data in find_pipeline_inputs(self.graph, include_components_with_connected_inputs).items(): + sockets_description = {} + for socket in data: + sockets_description[socket.name] = {"type": socket.type, "is_mandatory": socket.is_mandatory} + if not socket.is_mandatory: + sockets_description[socket.name]["default_value"] = socket.default_value + + if sockets_description: + inputs[component_name] = sockets_description + return inputs + + def outputs(self, include_components_with_connected_outputs: bool = False) -> Dict[str, Dict[str, Any]]: + """ + Returns a dictionary containing the outputs of a pipeline. + + Each key in the dictionary corresponds to a component name, and its value is another dictionary that describes + the output sockets of that component. + + :param include_components_with_connected_outputs: + If `False`, only components that have disconnected output edges are + included in the output. + :returns: + A dictionary where each key is a pipeline component name and each value is a dictionary of + output sockets of that component. + """ + outputs = { + comp: {socket.name: {"type": socket.type} for socket in data} + for comp, data in find_pipeline_outputs(self.graph, include_components_with_connected_outputs).items() + if data + } + return outputs + + def show(self) -> None: + """ + If running in a Jupyter notebook, display an image representing this `Pipeline`. + + """ + if is_in_jupyter(): + from IPython.display import Image, display # type: ignore + + image_data = _to_mermaid_image(self.graph) + + display(Image(image_data)) + else: + msg = "This method is only supported in Jupyter notebooks. Use Pipeline.draw() to save an image locally." + raise PipelineDrawingError(msg) + + def draw(self, path: Path) -> None: + """ + Save an image representing this `Pipeline` to `path`. + + :param path: + The path to save the image to. + """ + # Before drawing we edit a bit the graph, to avoid modifying the original that is + # used for running the pipeline we copy it. + image_data = _to_mermaid_image(self.graph) + Path(path).write_bytes(image_data) + + def walk(self) -> Iterator[Tuple[str, Component]]: + """ + Visits each component in the pipeline exactly once and yields its name and instance. + + No guarantees are provided on the visiting order. + + :returns: + An iterator of tuples of component name and component instance. + """ + for component_name, instance in self.graph.nodes(data="instance"): # type: ignore # type is wrong in networkx + yield component_name, instance + + def warm_up(self): + """ + Make sure all nodes are warm. + + It's the node's responsibility to make sure this method can be called at every `Pipeline.run()` + without re-initializing everything. + """ + for node in self.graph.nodes: + if hasattr(self.graph.nodes[node]["instance"], "warm_up"): + logger.info("Warming up component {node}...", node=node) + self.graph.nodes[node]["instance"].warm_up() + + def _validate_input(self, data: Dict[str, Any]): + """ + Validates pipeline input data. + + Validates that data: + * Each Component name actually exists in the Pipeline + * Each Component is not missing any input + * Each Component has only one input per input socket, if not variadic + * Each Component doesn't receive inputs that are already sent by another Component + + :param data: + A dictionary of inputs for the pipeline's components. Each key is a component name. + + :raises ValueError: + If inputs are invalid according to the above. + """ + for component_name, component_inputs in data.items(): + if component_name not in self.graph.nodes: + raise ValueError(f"Component named {component_name} not found in the pipeline.") + instance = self.graph.nodes[component_name]["instance"] + for socket_name, socket in instance.__haystack_input__._sockets_dict.items(): + if socket.senders == [] and socket.is_mandatory and socket_name not in component_inputs: + raise ValueError(f"Missing input for component {component_name}: {socket_name}") + for input_name in component_inputs.keys(): + if input_name not in instance.__haystack_input__._sockets_dict: + raise ValueError(f"Input {input_name} not found in component {component_name}.") + + for component_name in self.graph.nodes: + instance = self.graph.nodes[component_name]["instance"] + for socket_name, socket in instance.__haystack_input__._sockets_dict.items(): + component_inputs = data.get(component_name, {}) + if socket.senders == [] and socket.is_mandatory and socket_name not in component_inputs: + raise ValueError(f"Missing input for component {component_name}: {socket_name}") + if socket.senders and socket_name in component_inputs and not socket.is_variadic: + raise ValueError( + f"Input {socket_name} for component {component_name} is already sent by {socket.senders}." + ) + + def _prepare_component_input_data(self, data: Dict[str, Any]) -> Dict[str, Dict[str, Any]]: + """ + Prepares input data for pipeline components. + + Organizes input data for pipeline components and identifies any inputs that are not matched to any + component's input slots. Deep-copies data items to avoid sharing mutables across multiple components. + + This method processes a flat dictionary of input data, where each key-value pair represents an input name + and its corresponding value. It distributes these inputs to the appropriate pipeline components based on + their input requirements. Inputs that don't match any component's input slots are classified as unresolved. + + :param data: + A dictionary potentially having input names as keys and input values as values. + + :returns: + A dictionary mapping component names to their respective matched inputs. + """ + # check whether the data is a nested dictionary of component inputs where each key is a component name + # and each value is a dictionary of input parameters for that component + is_nested_component_input = all(isinstance(value, dict) for value in data.values()) + if not is_nested_component_input: + # flat input, a dict where keys are input names and values are the corresponding values + # we need to convert it to a nested dictionary of component inputs and then run the pipeline + # just like in the previous case + pipeline_input_data: Dict[str, Dict[str, Any]] = defaultdict(dict) + unresolved_kwargs = {} + + # Retrieve the input slots for each component in the pipeline + available_inputs: Dict[str, Dict[str, Any]] = self.inputs() + + # Go through all provided to distribute them to the appropriate component inputs + for input_name, input_value in data.items(): + resolved_at_least_once = False + + # Check each component to see if it has a slot for the current kwarg + for component_name, component_inputs in available_inputs.items(): + if input_name in component_inputs: + # If a match is found, add the kwarg to the component's input data + pipeline_input_data[component_name][input_name] = input_value + resolved_at_least_once = True + + if not resolved_at_least_once: + unresolved_kwargs[input_name] = input_value + + if unresolved_kwargs: + logger.warning( + "Inputs {input_keys} were not matched to any component inputs, please check your run parameters.", + input_keys=list(unresolved_kwargs.keys()), + ) + + data = dict(pipeline_input_data) + + # deepcopying the inputs prevents the Pipeline run logic from being altered unexpectedly + # when the same input reference is passed to multiple components. + for component_name, component_inputs in data.items(): + data[component_name] = {k: deepcopy(v) for k, v in component_inputs.items()} + + return data + + def _normalize_varidiac_input_data(self, data: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: + """ + Variadic inputs expect their value to be a list, this utility method creates that list from the user's input. + """ + for component_name, component_inputs in data.items(): + if component_name not in self.graph.nodes: + # This is not a component name, it must be the name of one or more input sockets. + # Those are handled in a different way, so we skip them here. + continue + instance = self.graph.nodes[component_name]["instance"] + for component_input, input_value in component_inputs.items(): + if instance.__haystack_input__._sockets_dict[component_input].is_variadic: + # Components that have variadic inputs need to receive lists as input. + # We don't want to force the user to always pass lists, so we convert single values to lists here. + # If it's already a list we assume the component takes a variadic input of lists, so we + # convert it in any case. + data[component_name][component_input] = [input_value] + + return {**data} + + @classmethod + def from_template( + cls, predefined_pipeline: PredefinedPipeline, template_params: Optional[Dict[str, Any]] = None + ) -> "PipelineBase": + """ + Create a Pipeline from a predefined template. See `PredefinedPipeline` for available options. + + :param predefined_pipeline: + The predefined pipeline to use. + :param template_params: + An optional dictionary of parameters to use when rendering the pipeline template. + :returns: + An instance of `Pipeline`. + """ + tpl = PipelineTemplate.from_predefined(predefined_pipeline) + # If tpl.render() fails, we let bubble up the original error + rendered = tpl.render(template_params) + + # If there was a problem with the rendered version of the + # template, we add it to the error stack for debugging + try: + return cls.loads(rendered) + except Exception as e: + msg = f"Error unmarshalling pipeline: {e}\n" + msg += f"Source:\n{rendered}" + raise PipelineUnmarshalError(msg) + + def _init_graph(self): + """Resets the visits count for each component""" + for node in self.graph.nodes: + self.graph.nodes[node]["visits"] = 0 + + def _find_receivers_from(self, component_name: str) -> List[Tuple[str, OutputSocket, InputSocket]]: + """ + Utility function to find all Components that receive input form `component_name`. + + :param component_name: + Name of the sender Component + + :returns: + List of tuples containing name of the receiver Component and sender OutputSocket + and receiver InputSocket instances + """ + res = [] + for _, receiver_name, connection in self.graph.edges(nbunch=component_name, data=True): + sender_socket: OutputSocket = connection["from_socket"] + receiver_socket: InputSocket = connection["to_socket"] + res.append((receiver_name, sender_socket, receiver_socket)) + return res + + def _distribute_output( # pylint: disable=too-many-positional-arguments + self, + receiver_components: List[Tuple[str, OutputSocket, InputSocket]], + component_result: Dict[str, Any], + components_inputs: Dict[str, Dict[str, Any]], + run_queue: List[Tuple[str, Component]], + waiting_queue: List[Tuple[str, Component]], + ) -> Dict[str, Any]: + """ + Distributes the output of a Component to the next Components that need it. + + This also updates the queues that keep track of which Components are ready to run and which are waiting for + input. + + :param receiver_components: + List of tuples containing name of receiver Components and relative sender OutputSocket + and receiver InputSocket instances + :param component_result: + The output of the Component + :param components_inputs: + The current state of the inputs divided by Component name + :param run_queue: + Queue of Components to run + :param waiting_queue: + Queue of Components waiting for input + + :returns: + The updated output of the Component without the keys that were distributed to other Components + """ + # We keep track of which keys to remove from component_result at the end of the loop. + # This is done after the output has been distributed to the next components, so that + # we're sure all components that need this output have received it. + to_remove_from_component_result = set() + + for receiver_name, sender_socket, receiver_socket in receiver_components: + if sender_socket.name not in component_result: + # This output wasn't created by the sender, nothing we can do. + # + # Some Components might have conditional outputs, so we need to check if they actually returned + # some output while iterating over their output sockets. + # + # A perfect example of this would be the ConditionalRouter, which will have an output for each + # condition it has been initialized with. + # Though it will return only one output at a time. + continue + + if receiver_name not in components_inputs: + components_inputs[receiver_name] = {} + + # We keep track of the keys that were distributed to other Components. + # This key will be removed from component_result at the end of the loop. + to_remove_from_component_result.add(sender_socket.name) + + value = component_result[sender_socket.name] + + if receiver_socket.is_variadic: + # Usually Component inputs can only be received from one sender, the Variadic type allows + # instead to receive inputs from multiple senders. + # + # To keep track of all the inputs received internally we always store them in a list. + if receiver_socket.name not in components_inputs[receiver_name]: + # Create the list if it doesn't exist + components_inputs[receiver_name][receiver_socket.name] = [] + else: + # Check if the value is actually a list + assert isinstance(components_inputs[receiver_name][receiver_socket.name], list) + components_inputs[receiver_name][receiver_socket.name].append(value) + else: + components_inputs[receiver_name][receiver_socket.name] = value + + receiver = self.graph.nodes[receiver_name]["instance"] + pair = (receiver_name, receiver) + + if receiver_socket.is_variadic: + if receiver_socket.is_greedy: + # If the receiver is greedy, we can run it as soon as possible. + # First we remove it from the status lists it's in if it's there or + # we risk running it multiple times. + if pair in run_queue: + run_queue.remove(pair) + if pair in waiting_queue: + waiting_queue.remove(pair) + run_queue.insert(0, pair) + else: + # If the receiver Component has a variadic input that is not greedy + # we put it in the waiting queue. + # This make sure that we don't run it earlier than necessary and we can collect + # as many inputs as we can before running it. + if pair not in waiting_queue: + waiting_queue.append(pair) + + if pair not in waiting_queue and pair not in run_queue: + # Queue up the Component that received this input to run, only if it's not already waiting + # for input or already ready to run. + run_queue.append(pair) + + # Returns the output without the keys that were distributed to other Components + return {k: v for k, v in component_result.items() if k not in to_remove_from_component_result} + + def _find_next_runnable_component( + self, components_inputs: Dict[str, Dict[str, Any]], waiting_queue: List[Tuple[str, Component]] + ) -> Tuple[str, Component]: + """ + Finds the next Component that can be run and returns it. + + :param components_inputs: The current state of the inputs divided by Component name + :param waiting_queue: Queue of Components waiting for input + + :returns: The name and the instance of the next Component that can be run + """ + all_lazy_variadic = True + all_with_default_inputs = True + + filtered_waiting_queue = [] + + for name, comp in waiting_queue: + if not _is_lazy_variadic(comp): + # Components with variadic inputs that are not greedy must be removed only if there's nothing else to + # run at this stage. + # We need to wait as long as possible to run them, so we can collect as most inputs as we can. + all_lazy_variadic = False + + if not _has_all_inputs_with_defaults(comp): + # Components that have defaults for all their inputs must be treated the same identical way as we treat + # lazy variadic components. If there are only components with defaults we can run them. + # If we don't do this the order of execution of the Pipeline's Components will be affected cause we + # enqueue the Components in `run_queue` at the start using the order they are added in the Pipeline. + # If a Component A with defaults is added before a Component B that has no defaults, but in the Pipeline + # logic A must be executed after B. However, B could run before A if we don't do this check. + all_with_default_inputs = False + + if not _is_lazy_variadic(comp) and not _has_all_inputs_with_defaults(comp): + # Keep track of the Components that are not lazy variadic and don't have all inputs with defaults. + # We'll handle these later if necessary. + filtered_waiting_queue.append((name, comp)) + + # If all Components are lazy variadic or all Components have all inputs with defaults we can get one to run + if all_lazy_variadic or all_with_default_inputs: + return waiting_queue[0] + + for name, comp in filtered_waiting_queue: + # Find the first component that has all the inputs it needs to run + has_enough_inputs = True + for input_socket in comp.__haystack_input__._sockets_dict.values(): # type: ignore + if input_socket.name not in components_inputs.get(name, {}) and input_socket.is_mandatory: + has_enough_inputs = False + break + + if has_enough_inputs: + return name, comp + + # If we reach this point it means that we found no Component that has enough inputs to run. + # Ideally we should never reach this point, though we can't raise an exception either as + # existing use cases rely on this behavior. + # So we return the last Component, that could be the last from waiting_queue or filtered_waiting_queue. + return name, comp + + def _find_next_runnable_lazy_variadic_or_default_component( + self, waiting_queue: List[Tuple[str, Component]] + ) -> Tuple[str, Component]: + """ + Finds the next Component that can be run and has a lazy variadic input or all inputs with default values. + + :param waiting_queue: Queue of Components waiting for input + + :returns: The name and the instance of the next Component that can be run + """ + for name, comp in waiting_queue: + is_lazy_variadic = _is_lazy_variadic(comp) + has_only_defaults = _has_all_inputs_with_defaults(comp) + if is_lazy_variadic or has_only_defaults: + return name, comp + + # If we reach this point it means that we found no Component that has a lazy variadic input or all inputs with + # default values to run. + # Similar to `_find_next_runnable_component` we might not find the Component we want, so we optimistically + # return the last Component in the list. + # We're probably stuck in a loop in this case, but we can't raise an exception as existing use cases might + # rely on this behaviour. + # The loop detection will be handled later on. + return name, comp + + def _find_components_that_will_receive_no_input( + self, component_name: str, component_result: Dict[str, Any], components_inputs: Dict[str, Dict[str, Any]] + ) -> Set[Tuple[str, Component]]: + """ + Find all the Components that are connected to component_name and didn't receive any input from it. + + Components that have a Variadic input and received already some input from other Components + but not from component_name won't be returned as they have enough inputs to run. + + This includes the descendants of the Components that didn't receive any input from component_name. + That is necessary to avoid getting stuck into infinite loops waiting for inputs that will never arrive. + + :param component_name: Name of the Component that created the output + :param component_result: Output of the Component + :param components_inputs: The current state of the inputs divided by Component name + :return: A set of Components that didn't receive any input from component_name + """ + + # Simplifies the check if a Component is Variadic and received some input from other Components. + def has_variadic_socket_with_existing_inputs( + component: Component, component_name: str, sender_name: str, components_inputs: Dict[str, Dict[str, Any]] + ) -> bool: + for socket in component.__haystack_input__._sockets_dict.values(): # type: ignore + if sender_name not in socket.senders: + continue + if socket.is_variadic and len(components_inputs.get(component_name, {}).get(socket.name, [])) > 0: + return True + return False + + # Makes it easier to verify if all connections between two Components are optional + def all_connections_are_optional(sender_name: str, receiver: Component) -> bool: + for socket in receiver.__haystack_input__._sockets_dict.values(): # type: ignore + if sender_name not in socket.senders: + continue + if socket.is_mandatory: + return False + return True + + # Eases checking if other connections that are not between sender_name and receiver_name + # already received inputs + def other_connections_received_input(sender_name: str, receiver_name: str) -> bool: + receiver: Component = self.graph.nodes[receiver_name]["instance"] + for receiver_socket in receiver.__haystack_input__._sockets_dict.values(): # type: ignore + if sender_name in receiver_socket.senders: + continue + if components_inputs.get(receiver_name, {}).get(receiver_socket.name) is not None: + return True + return False + + components = set() + instance: Component = self.graph.nodes[component_name]["instance"] + for socket_name, socket in instance.__haystack_output__._sockets_dict.items(): # type: ignore + if socket_name in component_result: + continue + for receiver in socket.receivers: + receiver_instance: Component = self.graph.nodes[receiver]["instance"] + + if has_variadic_socket_with_existing_inputs( + receiver_instance, receiver, component_name, components_inputs + ): + # Components with Variadic input that already received some input + # can still run, even if branch is skipped. + # If we remove them they won't run. + continue + + if all_connections_are_optional(component_name, receiver_instance) and other_connections_received_input( + component_name, receiver + ): + # If all the connections between component_name and receiver are optional + # and receiver received other inputs already it still has enough inputs to run. + # Even if it didn't receive input from component_name, so we can't remove it or its + # descendants. + continue + + components.add((receiver, receiver_instance)) + # Get the descendants too. When we remove a Component that received no input + # it's extremely likely that its descendants will receive no input as well. + # This is fine even if the Pipeline will merge back into a single Component + # at a certain point. The merging Component will be put back into the run + # queue at a later stage. + for descendant_name in networkx.descendants(self.graph, receiver): + descendant = self.graph.nodes[descendant_name]["instance"] + + # Components with Variadic input that already received some input + # can still run, even if branch is skipped. + # If we remove them they won't run. + if has_variadic_socket_with_existing_inputs( + descendant, descendant_name, receiver, components_inputs + ): + continue + + components.add((descendant_name, descendant)) + + return components + + def _is_stuck_in_a_loop(self, waiting_queue: List[Tuple[str, Component]]) -> bool: + """ + Checks if the Pipeline is stuck in a loop. + + :param waiting_queue: Queue of Components waiting for input + + :returns: True if the Pipeline is stuck in a loop, False otherwise + """ + # Are we actually stuck or there's a lazy variadic or a component with has only default inputs + # waiting for input? + # This is our last resort, if there's no lazy variadic or component with only default inputs + # waiting for input we're stuck for real and we can't make any progress. + component_found = False + for _, comp in waiting_queue: + if _is_lazy_variadic(comp) or _has_all_inputs_with_defaults(comp): + component_found = True + break + + if not component_found: + # We're stuck in a loop for real, we can't make any progress. + # BAIL! + return True + + # If we have a single component with no variadic input or only default inputs waiting for input + # it means it has been waiting for input for at least 2 iterations. + # This will never run. + # BAIL! + return len(waiting_queue) == 1 + + def _component_has_enough_inputs_to_run(self, name: str, inputs: Dict[str, Dict[str, Any]]) -> bool: + """ + Returns True if the Component has all the inputs it needs to run. + + :param name: Name of the Component as defined in the Pipeline. + :param inputs: The current state of the inputs divided by Component name. + + :return: Whether the Component can run or not. + """ + instance: Component = self.graph.nodes[name]["instance"] + if name not in inputs: + return False + expected_inputs = instance.__haystack_input__._sockets_dict.keys() # type: ignore + current_inputs = inputs[name].keys() + return expected_inputs == current_inputs + + def _break_supported_cycles_in_graph(self) -> Tuple[networkx.MultiDiGraph, Dict[str, List[List[str]]]]: + """ + Utility function to remove supported cycles in the Pipeline's graph. + + Given that the Pipeline execution would wait to run a Component until it has received + all its mandatory inputs, it doesn't make sense for us to try and break cycles by + removing a connection to a mandatory input. The Pipeline would just get stuck at a later time. + + So we can only break connections in cycles that have a Variadic or GreedyVariadic type or a default value. + + This will raise a PipelineRuntimeError if we there are cycles that can't be broken. + That is bound to happen when at least one of the inputs in a cycle is mandatory. + + If the Pipeline's graph doesn't have any cycle it will just return that graph and an empty dictionary. + + :returns: + A tuple containing: + * A copy of the Pipeline's graph without cycles + * A dictionary of Component's names and a list of all the cycles they were part of. + The cycles are a list of Component's names that create that cycle. + """ + if networkx.is_directed_acyclic_graph(self.graph): + return self.graph, {} + + temp_graph: networkx.MultiDiGraph = self.graph.copy() + # A list of all the cycles that are found in the graph, each inner list contains + # the Component names that create that cycle. + cycles: List[List[str]] = list(networkx.simple_cycles(self.graph)) + # Maps a Component name to a list of its output socket names that have been broken + edges_removed: Dict[str, List[str]] = defaultdict(list) + # This keeps track of all the cycles that a component is part of. + # Maps a Component name to a list of cycles, each inner list contains + # the Component names that create that cycle (the key will also be + # an element in each list). The last Component in each list is implicitly + # connected to the first. + components_in_cycles: Dict[str, List[List[str]]] = defaultdict(list) + + # Used to minimize the number of time we check whether the graph has any more + # cycles left to break or not. + graph_has_cycles = True + + # Iterate all the cycles to find the least amount of connections that we can remove + # to make the Pipeline graph acyclic. + # As soon as the graph is acyclic we stop breaking connections and return. + for cycle in cycles: + for comp in cycle: + components_in_cycles[comp].append(cycle) + + # Iterate this cycle, we zip the cycle with itself so that at the last iteration + # sender_comp will be the last element of cycle and receiver_comp will be the first. + # So if cycle is [1, 2, 3, 4] we would call zip([1, 2, 3, 4], [2, 3, 4, 1]). + for sender_comp, receiver_comp in zip(cycle, cycle[1:] + cycle[:1]): + # We get the key and iterate those as we want to edit the graph data while + # iterating the edges and that would raise. + # Even though the connection key set in Pipeline.connect() uses only the + # sockets name we don't have clashes since it's only used to differentiate + # multiple edges between two nodes. + edge_keys = list(temp_graph.get_edge_data(sender_comp, receiver_comp).keys()) + for edge_key in edge_keys: + edge_data = temp_graph.get_edge_data(sender_comp, receiver_comp)[edge_key] + receiver_socket = edge_data["to_socket"] + if not receiver_socket.is_variadic and receiver_socket.is_mandatory: + continue + + # We found a breakable edge + sender_socket = edge_data["from_socket"] + edges_removed[sender_comp].append(sender_socket.name) + temp_graph.remove_edge(sender_comp, receiver_comp, edge_key) + + graph_has_cycles = not networkx.is_directed_acyclic_graph(temp_graph) + if not graph_has_cycles: + # We removed all the cycles, we can stop + break + + if not graph_has_cycles: + # We removed all the cycles, nice + break + + if graph_has_cycles: + msg = "Pipeline contains a cycle that we can't execute" + raise PipelineRuntimeError(msg) + + return temp_graph, components_in_cycles + + +def _connections_status( + sender_node: str, receiver_node: str, sender_sockets: List[OutputSocket], receiver_sockets: List[InputSocket] +): + """ + Lists the status of the sockets, for error messages. + """ + sender_sockets_entries = [] + for sender_socket in sender_sockets: + sender_sockets_entries.append(f" - {sender_socket.name}: {_type_name(sender_socket.type)}") + sender_sockets_list = "\n".join(sender_sockets_entries) + + receiver_sockets_entries = [] + for receiver_socket in receiver_sockets: + if receiver_socket.senders: + sender_status = f"sent by {','.join(receiver_socket.senders)}" + else: + sender_status = "available" + receiver_sockets_entries.append( + f" - {receiver_socket.name}: {_type_name(receiver_socket.type)} ({sender_status})" + ) + receiver_sockets_list = "\n".join(receiver_sockets_entries) + + return f"'{sender_node}':\n{sender_sockets_list}\n'{receiver_node}':\n{receiver_sockets_list}" + + +def _is_lazy_variadic(c: Component) -> bool: + """ + Small utility function to check if a Component has at least a Variadic input and no GreedyVariadic input. + """ + is_variadic = any( + socket.is_variadic + for socket in c.__haystack_input__._sockets_dict.values() # type: ignore + ) + if not is_variadic: + return False + return not any( + socket.is_greedy + for socket in c.__haystack_input__._sockets_dict.values() # type: ignore + ) + + +def _has_all_inputs_with_defaults(c: Component) -> bool: + """ + Small utility function to check if a Component has all inputs with defaults. + """ + return all( + not socket.is_mandatory + for socket in c.__haystack_input__._sockets_dict.values() # type: ignore + ) + + +def _add_missing_input_defaults(name: str, comp: Component, components_inputs: Dict[str, Dict[str, Any]]): + """ + Updates the inputs with the default values for the inputs that are missing + + :param name: Name of the Component + :param comp: Instance of the Component + :param components_inputs: The current state of the inputs divided by Component name + """ + if name not in components_inputs: + components_inputs[name] = {} + + for input_socket in comp.__haystack_input__._sockets_dict.values(): # type: ignore + if input_socket.is_mandatory: + continue + + if input_socket.name not in components_inputs[name]: + components_inputs[name][input_socket.name] = input_socket.default_value + + +def _enqueue_component( + component_pair: Tuple[str, Component], + run_queue: List[Tuple[str, Component]], + waiting_queue: List[Tuple[str, Component]], +): + """ + Append a Component in the queue of Components to run if not already in it. + + Remove it from the waiting list if it's there. + + :param component_pair: Tuple of Component name and instance + :param run_queue: Queue of Components to run + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair in waiting_queue: + waiting_queue.remove(component_pair) + + if component_pair not in run_queue: + run_queue.append(component_pair) + + +def _dequeue_component( + component_pair: Tuple[str, Component], + run_queue: List[Tuple[str, Component]], + waiting_queue: List[Tuple[str, Component]], +): + """ + Removes a Component both from the queue of Components to run and the waiting list. + + :param component_pair: Tuple of Component name and instance + :param run_queue: Queue of Components to run + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair in waiting_queue: + waiting_queue.remove(component_pair) + + if component_pair in run_queue: + run_queue.remove(component_pair) + + +def _enqueue_waiting_component(component_pair: Tuple[str, Component], waiting_queue: List[Tuple[str, Component]]): + """ + Append a Component in the queue of Components that are waiting for inputs if not already in it. + + :param component_pair: Tuple of Component name and instance + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair not in waiting_queue: + waiting_queue.append(component_pair) + + +def _dequeue_waiting_component(component_pair: Tuple[str, Component], waiting_queue: List[Tuple[str, Component]]): + """ + Removes a Component from the queue of Components that are waiting for inputs. + + :param component_pair: Tuple of Component name and instance + :param waiting_queue: Queue of Components waiting for input + """ + if component_pair in waiting_queue: + waiting_queue.remove(component_pair) diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/descriptions.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/descriptions.py new file mode 100644 index 0000000000000000000000000000000000000000..59e4bbcf86bf265e0ae78547aa34147f73882a4f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/descriptions.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Dict, List + +import networkx # type:ignore + +from haystack import logging +from haystack.core.component.types import InputSocket, OutputSocket +from haystack.core.type_utils import _type_name + +logger = logging.getLogger(__name__) + + +def find_pipeline_inputs( + graph: networkx.MultiDiGraph, include_connected_sockets: bool = False +) -> Dict[str, List[InputSocket]]: + """ + Collect components that have disconnected/connected input sockets. + + Note that this method returns *ALL* disconnected input sockets, including all such sockets with default values. + """ + return { + name: [ + socket + for socket in data.get("input_sockets", {}).values() + if socket.is_variadic or (include_connected_sockets or not socket.senders) + ] + for name, data in graph.nodes(data=True) + } + + +def find_pipeline_outputs( + graph: networkx.MultiDiGraph, include_connected_sockets: bool = False +) -> Dict[str, List[OutputSocket]]: + """ + Collect components that have disconnected/connected output sockets. They define the pipeline output. + """ + return { + name: [ + socket + for socket in data.get("output_sockets", {}).values() + if (include_connected_sockets or not socket.receivers) + ] + for name, data in graph.nodes(data=True) + } + + +def describe_pipeline_inputs(graph: networkx.MultiDiGraph): + """ + Returns a dictionary with the input names and types that this pipeline accepts. + """ + inputs = { + comp: {socket.name: {"type": socket.type, "is_mandatory": socket.is_mandatory} for socket in data} + for comp, data in find_pipeline_inputs(graph).items() + if data + } + return inputs + + +def describe_pipeline_inputs_as_string(graph: networkx.MultiDiGraph): + """ + Returns a string representation of the input names and types that this pipeline accepts. + """ + inputs = describe_pipeline_inputs(graph) + message = "This pipeline expects the following inputs:\n" + for comp, sockets in inputs.items(): + if sockets: + message += f"- {comp}:\n" + for name, socket in sockets.items(): + message += f" - {name}: {_type_name(socket['type'])}\n" + return message diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/draw.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/draw.py new file mode 100644 index 0000000000000000000000000000000000000000..83df7915153f6da538cf8364c78153a01bf02492 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/draw.py @@ -0,0 +1,154 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import base64 + +import networkx # type:ignore +import requests + +from haystack import logging +from haystack.core.errors import PipelineDrawingError +from haystack.core.pipeline.descriptions import find_pipeline_inputs, find_pipeline_outputs +from haystack.core.type_utils import _type_name + +logger = logging.getLogger(__name__) + + +def _prepare_for_drawing(graph: networkx.MultiDiGraph) -> networkx.MultiDiGraph: + """ + Add some extra nodes to show the inputs and outputs of the pipeline. + + Also adds labels to edges. + """ + # Label the edges + for inp, outp, key, data in graph.edges(keys=True, data=True): + data["label"] = ( + f"{data['from_socket'].name} -> {data['to_socket'].name}{' (opt.)' if not data['mandatory'] else ''}" + ) + graph.add_edge(inp, outp, key=key, **data) + + # Add inputs fake node + graph.add_node("input") + for node, in_sockets in find_pipeline_inputs(graph).items(): + for in_socket in in_sockets: + if not in_socket.senders and in_socket.is_mandatory: + # If this socket has no sender it could be a socket that receives input + # directly when running the Pipeline. We can't know that for sure, in doubt + # we draw it as receiving input directly. + graph.add_edge("input", node, label=in_socket.name, conn_type=_type_name(in_socket.type)) + + # Add outputs fake node + graph.add_node("output") + for node, out_sockets in find_pipeline_outputs(graph).items(): + for out_socket in out_sockets: + graph.add_edge(node, "output", label=out_socket.name, conn_type=_type_name(out_socket.type)) + + return graph + + +ARROWTAIL_MANDATORY = "--" +ARROWTAIL_OPTIONAL = "-." +ARROWHEAD_MANDATORY = "-->" +ARROWHEAD_OPTIONAL = ".->" +MERMAID_STYLED_TEMPLATE = """ +%%{{ init: {{'theme': 'neutral' }} }}%% + +graph TD; + +{connections} + +classDef component text-align:center; +""" + + +def _to_mermaid_image(graph: networkx.MultiDiGraph): + """ + Renders a pipeline using Mermaid (hosted version at 'https://mermaid.ink'). Requires Internet access. + """ + # Copy the graph to avoid modifying the original + graph_styled = _to_mermaid_text(graph.copy()) + + graphbytes = graph_styled.encode("ascii") + base64_bytes = base64.b64encode(graphbytes) + base64_string = base64_bytes.decode("ascii") + url = f"https://mermaid.ink/img/{base64_string}?type=png" + + logger.debug("Rendering graph at {url}", url=url) + try: + resp = requests.get(url, timeout=10) + if resp.status_code >= 400: + logger.warning( + "Failed to draw the pipeline: https://mermaid.ink/img/ returned status {status_code}", + status_code=resp.status_code, + ) + logger.info("Exact URL requested: {url}", url=url) + logger.warning("No pipeline diagram will be saved.") + resp.raise_for_status() + + except Exception as exc: # pylint: disable=broad-except + logger.warning( + "Failed to draw the pipeline: could not connect to https://mermaid.ink/img/ ({error})", error=exc + ) + logger.info("Exact URL requested: {url}", url=url) + logger.warning("No pipeline diagram will be saved.") + raise PipelineDrawingError( + "There was an issue with https://mermaid.ink/, see the stacktrace for details." + ) from exc + + return resp.content + + +def _to_mermaid_text(graph: networkx.MultiDiGraph) -> str: + """ + Converts a Networkx graph into Mermaid syntax. + + The output of this function can be used in the documentation with `mermaid` codeblocks and will be + automatically rendered. + """ + # Copy the graph to avoid modifying the original + graph = _prepare_for_drawing(graph.copy()) + sockets = { + comp: "".join( + [ + f"
  • {name} ({_type_name(socket.type)})
  • " + for name, socket in data.get("input_sockets", {}).items() + if (not socket.is_mandatory and not socket.senders) or socket.is_variadic + ] + ) + for comp, data in graph.nodes(data=True) + } + optional_inputs = { + comp: f"

    Optional inputs:
      {sockets}
    " if sockets else "" + for comp, sockets in sockets.items() + } + + states = { + comp: f"{comp}[\"{comp}
    {type(data['instance']).__name__}{optional_inputs[comp]}\"]:::component" # noqa + for comp, data in graph.nodes(data=True) + if comp not in ["input", "output"] + } + + connections_list = [] + for from_comp, to_comp, conn_data in graph.edges(data=True): + if from_comp != "input" and to_comp != "output": + arrowtail = ARROWTAIL_MANDATORY if conn_data["mandatory"] else ARROWTAIL_OPTIONAL + arrowhead = ARROWHEAD_MANDATORY if conn_data["mandatory"] else ARROWHEAD_OPTIONAL + label = f'"{conn_data["label"]}
    {conn_data["conn_type"]}"' + conn_string = f"{states[from_comp]} {arrowtail} {label} {arrowhead} {states[to_comp]}" + connections_list.append(conn_string) + + input_connections = [ + f"i{{*}}--\"{conn_data['label']}
    {conn_data['conn_type']}\"--> {states[to_comp]}" + for _, to_comp, conn_data in graph.out_edges("input", data=True) + ] + output_connections = [ + f"{states[from_comp]}--\"{conn_data['label']}
    {conn_data['conn_type']}\"--> o{{*}}" + for from_comp, _, conn_data in graph.in_edges("output", data=True) + ] + connections = "\n".join(connections_list + input_connections + output_connections) + + graph_styled = MERMAID_STYLED_TEMPLATE.format(connections=connections) + logger.debug("Mermaid diagram:\n{diagram}", diagram=graph_styled) + + return graph_styled diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/pipeline.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b631ff63c7e53addde571c368da6235e44f9ce --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/pipeline.py @@ -0,0 +1,550 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Dict, List, Mapping, Optional, Set, Tuple +from warnings import warn + +import networkx as nx + +from haystack import logging, tracing +from haystack.core.component import Component +from haystack.core.errors import PipelineMaxComponentRuns, PipelineRuntimeError +from haystack.core.pipeline.base import ( + _dequeue_component, + _dequeue_waiting_component, + _enqueue_component, + _enqueue_waiting_component, +) +from haystack.telemetry import pipeline_running + +from .base import PipelineBase, _add_missing_input_defaults, _is_lazy_variadic + +logger = logging.getLogger(__name__) + + +class Pipeline(PipelineBase): + """ + Synchronous version of the orchestration engine. + + Orchestrates component execution according to the execution graph, one after the other. + """ + + def _run_component( + self, name: str, inputs: Dict[str, Any], parent_span: Optional[tracing.Span] = None + ) -> Dict[str, Any]: + """ + Runs a Component with the given inputs. + + :param name: Name of the Component as defined in the Pipeline. + :param inputs: Inputs for the Component. + :param parent_span: The parent span to use for the newly created span. + This is to allow tracing to be correctly linked to the pipeline run. + :raises PipelineRuntimeError: If Component doesn't return a dictionary. + :return: The output of the Component. + """ + instance: Component = self.graph.nodes[name]["instance"] + + with tracing.tracer.trace( + "haystack.component.run", + tags={ + "haystack.component.name": name, + "haystack.component.type": instance.__class__.__name__, + "haystack.component.input_types": {k: type(v).__name__ for k, v in inputs.items()}, + "haystack.component.input_spec": { + key: { + "type": (value.type.__name__ if isinstance(value.type, type) else str(value.type)), + "senders": value.senders, + } + for key, value in instance.__haystack_input__._sockets_dict.items() # type: ignore + }, + "haystack.component.output_spec": { + key: { + "type": (value.type.__name__ if isinstance(value.type, type) else str(value.type)), + "receivers": value.receivers, + } + for key, value in instance.__haystack_output__._sockets_dict.items() # type: ignore + }, + }, + parent_span=parent_span, + ) as span: + # We deepcopy the inputs otherwise we might lose that information + # when we delete them in case they're sent to other Components + span.set_content_tag("haystack.component.input", deepcopy(inputs)) + logger.info("Running component {component_name}", component_name=name) + res: Dict[str, Any] = instance.run(**inputs) + self.graph.nodes[name]["visits"] += 1 + + # After a Component that has variadic inputs is run, we need to reset the variadic inputs that were consumed + for socket in instance.__haystack_input__._sockets_dict.values(): # type: ignore + if socket.name not in inputs: + continue + if socket.is_variadic: + inputs[socket.name] = [] + + if not isinstance(res, Mapping): + raise PipelineRuntimeError( + f"Component '{name}' didn't return a dictionary. " + "Components must always return dictionaries: check the documentation." + ) + span.set_tag("haystack.component.visits", self.graph.nodes[name]["visits"]) + span.set_content_tag("haystack.component.output", res) + + return res + + def _run_subgraph( # noqa: PLR0915 + self, + cycle: List[str], + component_name: str, + components_inputs: Dict[str, Dict[str, Any]], + include_outputs_from: Optional[Set[str]] = None, + ) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """ + Runs a `cycle` in the Pipeline starting from `component_name`. + + This will return once there are no inputs for the Components in `cycle`. + + This is an internal method meant to be used in `Pipeline.run()` only. + + :param cycle: + List of Components that are part of the cycle being run + :param component_name: + Name of the Component that will start execution of the cycle + :param components_inputs: + Components inputs, this might include inputs for Components that are not part + of the cycle but part of the wider Pipeline's graph + :param include_outputs_from: + Set of component names whose individual outputs are to be + included in the cycle's output. In case a Component is executed multiple times + only the last-produced output is included. + :returns: + Outputs of all the Components that are not connected to other Components in `cycle`. + If `include_outputs_from` is set those Components' outputs will be included. + :raises PipelineMaxComponentRuns: + If a Component reaches the maximum number of times it can be run in this Pipeline + """ + waiting_queue: List[Tuple[str, Component]] = [] + run_queue: List[Tuple[str, Component]] = [] + + # Create the run queue starting with the component that needs to run first + start_index = cycle.index(component_name) + for node in cycle[start_index:]: + run_queue.append((node, self.graph.nodes[node]["instance"])) + + include_outputs_from = set() if include_outputs_from is None else include_outputs_from + + before_last_waiting_queue: Optional[Set[str]] = None + last_waiting_queue: Optional[Set[str]] = None + + subgraph_outputs = {} + # These are outputs that are sent to other Components but the user explicitly + # asked to include them in the final output. + extra_outputs = {} + + # This variable is used to keep track if we still need to run the cycle or not. + # When a Component doesn't send outputs to another Component + # that's inside the subgraph, we stop running this subgraph. + cycle_received_inputs = False + + while not cycle_received_inputs: + # Here we run the Components + name, comp = run_queue.pop(0) + if _is_lazy_variadic(comp) and not all(_is_lazy_variadic(comp) for _, comp in run_queue): + # We run Components with lazy variadic inputs only if there only Components with + # lazy variadic inputs left to run + _enqueue_waiting_component((name, comp), waiting_queue) + continue + + # As soon as a Component returns only output that is not part of the cycle, we can stop + if self._component_has_enough_inputs_to_run(name, components_inputs): + if self.graph.nodes[name]["visits"] > self._max_runs_per_component: + msg = f"Maximum run count {self._max_runs_per_component} reached for component '{name}'" + raise PipelineMaxComponentRuns(msg) + + res: Dict[str, Any] = self._run_component(name, components_inputs[name]) + + # Delete the inputs that were consumed by the Component and are not received from + # the user or from Components that are part of this cycle + sockets = list(components_inputs[name].keys()) + for socket_name in sockets: + senders = comp.__haystack_input__._sockets_dict[socket_name].senders # type: ignore + if not senders: + # We keep inputs that came from the user + continue + all_senders_in_cycle = all(sender in cycle for sender in senders) + if all_senders_in_cycle: + # All senders are in the cycle, we can remove the input. + # We'll receive it later at a certain point. + del components_inputs[name][socket_name] + + if name in include_outputs_from: + # Deepcopy the outputs to prevent downstream nodes from modifying them + # We don't care about loops - Always store the last output. + extra_outputs[name] = deepcopy(res) + + # Reset the waiting for input previous states, we managed to run a component + before_last_waiting_queue = None + last_waiting_queue = None + + # Check if a component doesn't send any output to components that are part of the cycle + final_output_reached = False + for output_socket in res.keys(): + for receiver in comp.__haystack_output__._sockets_dict[output_socket].receivers: # type: ignore + if receiver in cycle: + final_output_reached = True + break + if final_output_reached: + break + + if not final_output_reached: + # We stop only if the Component we just ran doesn't send any output to sockets that + # are part of the cycle + cycle_received_inputs = True + + # We manage to run this component that was in the waiting list, we can remove it. + # This happens when a component was put in the waiting list but we reached it from another edge. + _dequeue_waiting_component((name, comp), waiting_queue) + for pair in self._find_components_that_will_receive_no_input(name, res, components_inputs): + _dequeue_component(pair, run_queue, waiting_queue) + + receivers = [item for item in self._find_receivers_from(name) if item[0] in cycle] + + res = self._distribute_output(receivers, res, components_inputs, run_queue, waiting_queue) + + # We treat a cycle as a completely independent graph, so we keep track of output + # that is not sent inside the cycle. + # This output is going to get distributed to the wider graph after we finish running + # a cycle. + # All values that are left at this point go outside the cycle. + if len(res) > 0: + subgraph_outputs[name] = res + else: + # This component doesn't have enough inputs so we can't run it yet + _enqueue_waiting_component((name, comp), waiting_queue) + + if len(run_queue) == 0 and len(waiting_queue) > 0: + # Check if we're stuck in a loop. + # It's important to check whether previous waitings are None as it could be that no + # Component has actually been run yet. + if ( + before_last_waiting_queue is not None + and last_waiting_queue is not None + and before_last_waiting_queue == last_waiting_queue + ): + if self._is_stuck_in_a_loop(waiting_queue): + # We're stuck! We can't make any progress. + msg = ( + "Pipeline is stuck running in a loop. Partial outputs will be returned. " + "Check the Pipeline graph for possible issues." + ) + warn(RuntimeWarning(msg)) + break + + (name, comp) = self._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + _add_missing_input_defaults(name, comp, components_inputs) + _enqueue_component((name, comp), run_queue, waiting_queue) + continue + + before_last_waiting_queue = last_waiting_queue.copy() if last_waiting_queue is not None else None + last_waiting_queue = {item[0] for item in waiting_queue} + + (name, comp) = self._find_next_runnable_component(components_inputs, waiting_queue) + _add_missing_input_defaults(name, comp, components_inputs) + _enqueue_component((name, comp), run_queue, waiting_queue) + + return subgraph_outputs, extra_outputs + + def run( # noqa: PLR0915, PLR0912 + self, data: Dict[str, Any], include_outputs_from: Optional[Set[str]] = None + ) -> Dict[str, Any]: + """ + Runs the Pipeline with given input data. + + Usage: + ```python + from haystack import Pipeline, Document + from haystack.utils import Secret + from haystack.document_stores.in_memory import InMemoryDocumentStore + from haystack.components.retrievers.in_memory import InMemoryBM25Retriever + from haystack.components.generators import OpenAIGenerator + from haystack.components.builders.answer_builder import AnswerBuilder + from haystack.components.builders.prompt_builder import PromptBuilder + + # Write documents to InMemoryDocumentStore + document_store = InMemoryDocumentStore() + document_store.write_documents([ + Document(content="My name is Jean and I live in Paris."), + Document(content="My name is Mark and I live in Berlin."), + Document(content="My name is Giorgio and I live in Rome.") + ]) + + prompt_template = \"\"\" + Given these documents, answer the question. + Documents: + {% for doc in documents %} + {{ doc.content }} + {% endfor %} + Question: {{question}} + Answer: + \"\"\" + + retriever = InMemoryBM25Retriever(document_store=document_store) + prompt_builder = PromptBuilder(template=prompt_template) + llm = OpenAIGenerator(api_key=Secret.from_token(api_key)) + + rag_pipeline = Pipeline() + rag_pipeline.add_component("retriever", retriever) + rag_pipeline.add_component("prompt_builder", prompt_builder) + rag_pipeline.add_component("llm", llm) + rag_pipeline.connect("retriever", "prompt_builder.documents") + rag_pipeline.connect("prompt_builder", "llm") + + # Ask a question + question = "Who lives in Paris?" + results = rag_pipeline.run( + { + "retriever": {"query": question}, + "prompt_builder": {"question": question}, + } + ) + + print(results["llm"]["replies"]) + # Jean lives in Paris + ``` + + :param data: + A dictionary of inputs for the pipeline's components. Each key is a component name + and its value is a dictionary of that component's input parameters: + ``` + data = { + "comp1": {"input1": 1, "input2": 2}, + } + ``` + For convenience, this format is also supported when input names are unique: + ``` + data = { + "input1": 1, "input2": 2, + } + ``` + :param include_outputs_from: + Set of component names whose individual outputs are to be + included in the pipeline's output. For components that are + invoked multiple times (in a loop), only the last-produced + output is included. + :returns: + A dictionary where each entry corresponds to a component name + and its output. If `include_outputs_from` is `None`, this dictionary + will only contain the outputs of leaf components, i.e., components + without outgoing connections. + + :raises PipelineRuntimeError: + If the Pipeline contains cycles with unsupported connections that would cause + it to get stuck and fail running. + Or if a Component fails or returns output in an unsupported type. + :raises PipelineMaxComponentRuns: + If a Component reaches the maximum number of times it can be run in this Pipeline. + """ + pipeline_running(self) + + # Reset the visits count for each component + self._init_graph() + + # TODO: Remove this warmup once we can check reliably whether a component has been warmed up or not + # As of now it's here to make sure we don't have failing tests that assume warm_up() is called in run() + self.warm_up() + + # normalize `data` + data = self._prepare_component_input_data(data) + + # Raise if input is malformed in some way + self._validate_input(data) + + # Normalize the input data + components_inputs: Dict[str, Dict[str, Any]] = self._normalize_varidiac_input_data(data) + + # These variables are used to detect when we're stuck in a loop. + # Stuck loops can happen when one or more components are waiting for input but + # no other component is going to run. + # This can happen when a whole branch of the graph is skipped for example. + # When we find that two consecutive iterations of the loop where the waiting_queue is the same, + # we know we're stuck in a loop and we can't make any progress. + # + # They track the previous two states of the waiting_queue. So if waiting_queue would n, + # before_last_waiting_queue would be n-2 and last_waiting_queue would be n-1. + # When we run a component, we reset both. + before_last_waiting_queue: Optional[Set[str]] = None + last_waiting_queue: Optional[Set[str]] = None + + # The waiting_for_input list is used to keep track of components that are waiting for input. + waiting_queue: List[Tuple[str, Component]] = [] + + include_outputs_from = set() if include_outputs_from is None else include_outputs_from + + # This is what we'll return at the end + final_outputs: Dict[Any, Any] = {} + + # Break cycles in case there are, this is a noop if no cycle is found. + # This will raise if a cycle can't be broken. + graph_without_cycles, components_in_cycles = self._break_supported_cycles_in_graph() + + run_queue: List[Tuple[str, Component]] = [] + for node in nx.topological_sort(graph_without_cycles): + run_queue.append((node, self.graph.nodes[node]["instance"])) + + # Set defaults inputs for those sockets that don't receive input neither from the user + # nor from other Components. + # If they have no default nothing is done. + # This is important to ensure correct order execution, otherwise some variadic + # Components that receive input from the user might be run before than they should. + for name, comp in self.graph.nodes(data="instance"): + if name not in components_inputs: + components_inputs[name] = {} + for socket_name, socket in comp.__haystack_input__._sockets_dict.items(): + if socket_name in components_inputs[name]: + continue + if not socket.senders: + value = socket.default_value + if socket.is_variadic: + value = [value] + components_inputs[name][socket_name] = value + + with tracing.tracer.trace( + "haystack.pipeline.run", + tags={ + "haystack.pipeline.input_data": data, + "haystack.pipeline.output_data": final_outputs, + "haystack.pipeline.metadata": self.metadata, + "haystack.pipeline.max_runs_per_component": self._max_runs_per_component, + }, + ) as span: + # Cache for extra outputs, if enabled. + extra_outputs: Dict[Any, Any] = {} + + while len(run_queue) > 0: + name, comp = run_queue.pop(0) + + if _is_lazy_variadic(comp) and not all(_is_lazy_variadic(comp) for _, comp in run_queue): + # We run Components with lazy variadic inputs only if there only Components with + # lazy variadic inputs left to run + _enqueue_waiting_component((name, comp), waiting_queue) + continue + if self._component_has_enough_inputs_to_run(name, components_inputs) and components_in_cycles.get( + name, [] + ): + cycles = components_in_cycles.get(name, []) + + # This component is part of one or more cycles, let's get the first one and run it. + # We can reliably pick any of the cycles if there are multiple ones, the way cycles + # are run doesn't make a different whether we pick the first or any of the others a + # Component is part of. + subgraph_output, subgraph_extra_output = self._run_subgraph( + cycles[0], name, components_inputs, include_outputs_from + ) + + # After a cycle is run the previous run_queue can't be correct anymore cause it's + # not modified when running the subgraph. + # So we reset it given the output returned by the subgraph. + run_queue = [] + + # Reset the waiting for input previous states, we managed to run at least one component + before_last_waiting_queue = None + last_waiting_queue = None + + # Merge the extra outputs + extra_outputs.update(subgraph_extra_output) + + for component_name, component_output in subgraph_output.items(): + receivers = self._find_receivers_from(component_name) + component_output = self._distribute_output( + receivers, component_output, components_inputs, run_queue, waiting_queue + ) + + if len(component_output) > 0: + final_outputs[component_name] = component_output + + elif self._component_has_enough_inputs_to_run(name, components_inputs): + if self.graph.nodes[name]["visits"] > self._max_runs_per_component: + msg = f"Maximum run count {self._max_runs_per_component} reached for component '{name}'" + raise PipelineMaxComponentRuns(msg) + + res: Dict[str, Any] = self._run_component(name, components_inputs[name], parent_span=span) + + # Delete the inputs that were consumed by the Component and are not received from the user + sockets = list(components_inputs[name].keys()) + for socket_name in sockets: + senders = comp.__haystack_input__._sockets_dict[socket_name].senders + if senders: + # Delete all inputs that are received from other Components + del components_inputs[name][socket_name] + # We keep inputs that came from the user + + if name in include_outputs_from: + # Deepcopy the outputs to prevent downstream nodes from modifying them + # We don't care about loops - Always store the last output. + extra_outputs[name] = deepcopy(res) + + # Reset the waiting for input previous states, we managed to run a component + before_last_waiting_queue = None + last_waiting_queue = None + + # We manage to run this component that was in the waiting list, we can remove it. + # This happens when a component was put in the waiting list but we reached it from another edge. + _dequeue_waiting_component((name, comp), waiting_queue) + + for pair in self._find_components_that_will_receive_no_input(name, res, components_inputs): + _dequeue_component(pair, run_queue, waiting_queue) + receivers = self._find_receivers_from(name) + res = self._distribute_output(receivers, res, components_inputs, run_queue, waiting_queue) + + if len(res) > 0: + final_outputs[name] = res + else: + # This component doesn't have enough inputs so we can't run it yet + _enqueue_waiting_component((name, comp), waiting_queue) + + if len(run_queue) == 0 and len(waiting_queue) > 0: + # Check if we're stuck in a loop. + # It's important to check whether previous waitings are None as it could be that no + # Component has actually been run yet. + if ( + before_last_waiting_queue is not None + and last_waiting_queue is not None + and before_last_waiting_queue == last_waiting_queue + ): + if self._is_stuck_in_a_loop(waiting_queue): + # We're stuck! We can't make any progress. + msg = ( + "Pipeline is stuck running in a loop. Partial outputs will be returned. " + "Check the Pipeline graph for possible issues." + ) + warn(RuntimeWarning(msg)) + break + + (name, comp) = self._find_next_runnable_lazy_variadic_or_default_component(waiting_queue) + _add_missing_input_defaults(name, comp, components_inputs) + _enqueue_component((name, comp), run_queue, waiting_queue) + continue + + before_last_waiting_queue = last_waiting_queue.copy() if last_waiting_queue is not None else None + last_waiting_queue = {item[0] for item in waiting_queue} + + (name, comp) = self._find_next_runnable_component(components_inputs, waiting_queue) + _add_missing_input_defaults(name, comp, components_inputs) + _enqueue_component((name, comp), run_queue, waiting_queue) + + if len(include_outputs_from) > 0: + for name, output in extra_outputs.items(): + inner = final_outputs.get(name) + if inner is None: + final_outputs[name] = output + else: + # Let's not override any keys that are already + # in the final_outputs as they might be different + # from what we cached in extra_outputs, e.g. when loops + # are involved. + for k, v in output.items(): + if k not in inner: + inner[k] = v + + return final_outputs diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/chat_with_website.yaml.jinja2 b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/chat_with_website.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..c4ef14d49d9cb218af9bf9d96cd012e21f8f5c44 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/chat_with_website.yaml.jinja2 @@ -0,0 +1,52 @@ +components: + converter: + type: haystack.components.converters.html.HTMLToDocument + init_parameters: + extraction_kwargs: null + + fetcher: + init_parameters: + raise_on_failure: true + retry_attempts: 2 + timeout: 3 + user_agents: + - haystack/LinkContentFetcher/2.0.0b8 + type: haystack.components.fetchers.link_content.LinkContentFetcher + + llm: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + generation_kwargs: {} + model: gpt-4o-mini + streaming_callback: null + system_prompt: null + type: haystack.components.generators.openai.OpenAIGenerator + + prompt: + init_parameters: + template: | + {% raw %} + "According to the contents of this website: + {% for document in documents %} + {{document.content}} + {% endfor %} + Answer the given question: {{query}} + Answer: + " + {% endraw %} + type: haystack.components.builders.prompt_builder.PromptBuilder + +connections: +- receiver: converter.sources + sender: fetcher.streams +- receiver: prompt.documents + sender: converter.documents +- receiver: llm.prompt + sender: prompt.prompt + +metadata: {} diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/generative_qa.yaml.jinja2 b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/generative_qa.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..456689d75c54c6b5c5d18c190358a569c5dd2dcb --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/generative_qa.yaml.jinja2 @@ -0,0 +1,24 @@ +--- + +components: + generator: + init_parameters: + api_key: + env_vars: [ "OPENAI_API_KEY" ] + strict: true + type: "env_var" + model: "gpt-4o-mini" + type: "haystack.components.generators.openai.OpenAIGenerator" + + prompt_builder: + init_parameters: + template: "{% raw %}Answer the question {{question}}.\n Answer:\n{% endraw %}" + type: "haystack.components.builders.prompt_builder.PromptBuilder" + + +connections: +- receiver: generator.prompt + sender: prompt_builder.prompt + +metadata: + {} diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/indexing.yaml.jinja2 b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/indexing.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..69f5008454e3d11277f74d8caa11e9ceec8f4c12 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/indexing.yaml.jinja2 @@ -0,0 +1,67 @@ +--- + +components: + cleaner: + init_parameters: + remove_empty_lines: true + remove_extra_whitespaces: true + remove_regex: null + remove_repeated_substrings: false + remove_substrings: null + type: haystack.components.preprocessors.document_cleaner.DocumentCleaner + + converter: + init_parameters: + encoding: utf-8 + type: haystack.components.converters.txt.TextFileToDocument + + embedder: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + batch_size: 32 + dimensions: null + embedding_separator: '\n' + meta_fields_to_embed: [] + model: text-embedding-ada-002 + organization: null + prefix: '' + progress_bar: true + suffix: '' + type: haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder + + splitter: + init_parameters: + split_by: word + split_length: 200 + split_overlap: 0 + type: haystack.components.preprocessors.document_splitter.DocumentSplitter + + writer: + init_parameters: + document_store: + init_parameters: + bm25_tokenization_regex: (?u)\b\w\w+\b + bm25_algorithm: BM25L + bm25_parameters: {} + embedding_similarity_function: dot_product + index: documents + type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore + policy: NONE + type: haystack.components.writers.document_writer.DocumentWriter + +connections: +- receiver: cleaner.documents + sender: converter.documents +- receiver: splitter.documents + sender: cleaner.documents +- receiver: embedder.documents + sender: splitter.documents +- receiver: writer.documents + sender: embedder.documents + +metadata: {} diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/rag.yaml.jinja2 b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/rag.yaml.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..cff8bbb84da670948e141a2a1b5c140b7f7211b6 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/predefined/rag.yaml.jinja2 @@ -0,0 +1,70 @@ +--- + +components: + llm: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + generation_kwargs: {} + model: gpt-4o-mini + streaming_callback: null + system_prompt: null + type: haystack.components.generators.openai.OpenAIGenerator + + prompt_builder: + init_parameters: + template: | + {% raw %} + "Given these documents, answer the question. + Documents: + {% for doc in documents %}\ + {{ doc.content }} + {% endfor %} + Question: {{query}} + + Answer:" + {% endraw %} + type: haystack.components.builders.prompt_builder.PromptBuilder + + retriever: + init_parameters: + document_store: + init_parameters: + bm25_tokenization_regex: (?u)\b\w\w+\b + bm25_algorithm: BM25L + bm25_parameters: {} + embedding_similarity_function: dot_product + index: documents + type: haystack.document_stores.in_memory.document_store.InMemoryDocumentStore + filters: null + top_k: 10 + type: haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever + + text_embedder: + init_parameters: + api_base_url: null + api_key: + env_vars: + - OPENAI_API_KEY + strict: true + type: env_var + dimensions: null + model: text-embedding-ada-002 + organization: null + prefix: '' + suffix: '' + type: haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder + +connections: +- receiver: retriever.query_embedding + sender: text_embedder.embedding +- receiver: prompt_builder.documents + sender: retriever.documents +- receiver: llm.prompt + sender: prompt_builder.prompt + +metadata: {} diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/template.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/template.py new file mode 100644 index 0000000000000000000000000000000000000000..338e6b3fbd1695e7bebaf558f92c236eb79a9184 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/template.py @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from pathlib import Path +from typing import Any, Dict, Optional, Union + +from jinja2 import PackageLoader, TemplateSyntaxError, meta +from jinja2.sandbox import SandboxedEnvironment + +TEMPLATE_FILE_EXTENSION = ".yaml.jinja2" +TEMPLATE_HOME_DIR = Path(__file__).resolve().parent / "predefined" + + +class PredefinedPipeline(Enum): + """ + Enumeration of predefined pipeline templates that can be used to create a `PipelineTemplate`. + """ + + # Maintain 1-to-1 mapping between the enum name and the template file name in templates directory + GENERATIVE_QA = "generative_qa" + RAG = "rag" + INDEXING = "indexing" + CHAT_WITH_WEBSITE = "chat_with_website" + + +class PipelineTemplate: + """ + The PipelineTemplate enables the creation of flexible and configurable pipelines. + + The PipelineTemplate class enables the straightforward creation of flexible and configurable pipelines using + Jinja2 templated YAML files. Specifically designed to simplify the setup of complex data processing pipelines for + a range of NLP tasks—including question answering, retriever augmented generation (RAG), document indexing, among + others - PipelineTemplate empowers users to dynamically generate pipeline configurations from templates and + customize components as necessary. Its design philosophy centers on providing an accessible, yet powerful, tool + for constructing pipelines that accommodate both common use cases and specialized requirements with ease. + + Examples of usage: + + - **Default Build**: Instantiating a pipeline with default settings for a "question answering" (qa) task. + ```python + from haystack.templates import PipelineTemplate, PredefinedPipeline + + # Create a pipeline with default components for an extractive QA task + pipe = PipelineTemplate.from_predefined(PredefinedPipeline.GENERATIVE_QA).build() + print(pipe.run(data={"question": "What's the capital of Bosnia and Herzegovina? Be brief"})) + ``` + + - **Customizing for Specific Tasks**: Building a pipeline for document indexing with specific components tailored + to the task. + ```python + from haystack.components.embedders import SentenceTransformersDocumentEmbedder + from haystack.templates import PipelineTemplate, PredefinedPipeline + + # Customize the pipeline for document indexing with specific components, include PDF file converter + pt = PipelineTemplate.from_predefined(PredefinedTemplate.INDEXING) + pipe = pt.build(template_params={"use_pdf_file_converter": True}) + + result = pipe.run(data={"sources": ["some_text_file.txt", "another_pdf_file.pdf"]}) + print(result) + ``` + + The `PipelineTemplate` is designed to offer both ease of use for common pipeline configurations and the + flexibility to customize and extend pipelines as required by advanced users and specific use cases. + """ + + def __init__(self, template_content: str): + """ + Initialize a PipelineTemplate. + + Besides calling the constructor directly, a set of utility methods is provided to conveniently create an + instance of `PipelineTemplate` from different sources. See `from_string`, `from_file`, `from_predefined` + and `from_url`. + + :param template_content: The raw template source to use in the template. + """ + env = SandboxedEnvironment( + loader=PackageLoader("haystack.core.pipeline", "predefined"), trim_blocks=True, lstrip_blocks=True + ) + try: + self._template = env.from_string(template_content) + except TemplateSyntaxError as e: + raise ValueError(f"Invalid pipeline template: {e.message}") from e + + # Store the list of undefined variables in the template. Components' names will be part of this list + self.template_variables = meta.find_undeclared_variables(env.parse(template_content)) + self._template_content = template_content + + def render(self, template_params: Optional[Dict[str, Any]] = None) -> str: + """ + Constructs a `Pipeline` instance based on the template. + + :param template_params: An optional dictionary of parameters to use when rendering the pipeline template. + + :returns: An instance of `Pipeline` constructed from the rendered template and custom component configurations. + """ + template_params = template_params or {} + return self._template.render(**template_params) + + @classmethod + def from_file(cls, file_path: Union[Path, str]) -> "PipelineTemplate": + """ + Create a PipelineTemplate from a file. + + :param file_path: The path to the file containing the template. Must contain valid Jinja2 syntax. + :returns: An instance of `PipelineTemplate`. + """ + with open(file_path, "r") as file: + return cls(file.read()) + + @classmethod + def from_predefined(cls, predefined_pipeline: PredefinedPipeline) -> "PipelineTemplate": + """ + Create a PipelineTemplate from a predefined template. + + See `PredefinedPipeline` for available options. + + :param predefined_pipeline: The predefined pipeline to use. + :returns: An instance of `PipelineTemplate `. + """ + template_path = f"{TEMPLATE_HOME_DIR}/{predefined_pipeline.value}{TEMPLATE_FILE_EXTENSION}" + return cls.from_file(template_path) + + @property + def template_content(self) -> str: + """ + Returns the raw template string as a read-only property. + """ + return self._template_content diff --git a/testbed/deepset-ai__haystack/haystack/core/pipeline/utils.py b/testbed/deepset-ai__haystack/haystack/core/pipeline/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f858a39d6851dc5365589feaf076b8eceda44b --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/pipeline/utils.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Optional, Tuple + + +def parse_connect_string(connection: str) -> Tuple[str, Optional[str]]: + """ + Returns component-connection pairs from a connect_to/from string. + + :param connection: + The connection string. + :returns: + A tuple containing the component name and the connection name. + """ + if "." in connection: + split_str = connection.split(".", maxsplit=1) + return (split_str[0], split_str[1]) + return connection, None diff --git a/testbed/deepset-ai__haystack/haystack/core/serialization.py b/testbed/deepset-ai__haystack/haystack/core/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..3477f0c806cd2c14425d90e2455d9a10e6acaafb --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/serialization.py @@ -0,0 +1,259 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import inspect +from collections.abc import Callable +from dataclasses import dataclass +from importlib import import_module +from typing import Any, Dict, Iterable, Optional, Type + +from haystack.core.component.component import _hook_component_init, logger +from haystack.core.errors import DeserializationError, SerializationError + + +@dataclass(frozen=True) +class DeserializationCallbacks: + """ + Callback functions that are invoked in specific stages of the pipeline deserialization process. + + :param component_pre_init: + Invoked just before a component instance is + initialized. Receives the following inputs: + `component_name` (`str`), `component_class` (`Type`), `init_params` (`Dict[str, Any]`). + + The callback is allowed to modify the `init_params` + dictionary, which contains all the parameters that + are passed to the component's constructor. + """ + + component_pre_init: Optional[Callable] = None + + +def component_to_dict(obj: Any, name: str) -> Dict[str, Any]: + """ + Converts a component instance into a dictionary. + + If a `to_dict` method is present in the component instance, that will be used instead of the default method. + + :param obj: + The component to be serialized. + :param name: + The name of the component. + :returns: + A dictionary representation of the component. + + :raises SerializationError: + If the component doesn't have a `to_dict` method. + If the values of the init parameters can't be determined. + If a non-basic Python type is used in the serialized data. + """ + if hasattr(obj, "to_dict"): + data = obj.to_dict() + else: + init_parameters = {} + for param_name, param in inspect.signature(obj.__init__).parameters.items(): + # Ignore `args` and `kwargs`, used by the default constructor + if param_name in ("args", "kwargs"): + continue + try: + # This only works if the Component constructor assigns the init + # parameter to an instance variable or property with the same name + param_value = getattr(obj, param_name) + except AttributeError as e: + # If the parameter doesn't have a default value, raise an error + if param.default is param.empty: + raise SerializationError( + f"Cannot determine the value of the init parameter '{param_name}' " + f"for the class {obj.__class__.__name__}." + f"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a " + f"custom serialization method 'to_dict' to the class." + ) from e + # In case the init parameter was not assigned, we use the default value + param_value = param.default + init_parameters[param_name] = param_value + + data = default_to_dict(obj, **init_parameters) + + _validate_component_to_dict_output(obj, name, data) + return data + + +def _validate_component_to_dict_output(component: Any, name: str, data: Dict[str, Any]) -> None: + # Ensure that only basic Python types are used in the serde data. + def is_allowed_type(obj: Any) -> bool: + return isinstance(obj, (str, int, float, bool, list, dict, set, tuple, type(None))) + + def check_iterable(l: Iterable[Any]): + for v in l: + if not is_allowed_type(v): + raise SerializationError( + f"Component '{name}' of type '{type(component).__name__}' has an unsupported value " + f"of type '{type(v).__name__}' in the serialized data." + ) + if isinstance(v, (list, set, tuple)): + check_iterable(v) + elif isinstance(v, dict): + check_dict(v) + + def check_dict(d: Dict[str, Any]): + if any(not isinstance(k, str) for k in data.keys()): + raise SerializationError( + f"Component '{name}' of type '{type(component).__name__}' has a non-string key in the serialized data." + ) + + for k, v in d.items(): + if not is_allowed_type(v): + raise SerializationError( + f"Component '{name}' of type '{type(component).__name__}' has an unsupported value " + f"of type '{type(v).__name__}' in the serialized data under key '{k}'." + ) + if isinstance(v, (list, set, tuple)): + check_iterable(v) + elif isinstance(v, dict): + check_dict(v) + + check_dict(data) + + +def generate_qualified_class_name(cls: Type[object]) -> str: + """ + Generates a qualified class name for a class. + + :param cls: + The class whose qualified name is to be generated. + :returns: + The qualified name of the class. + """ + return f"{cls.__module__}.{cls.__name__}" + + +def component_from_dict( + cls: Type[object], data: Dict[str, Any], name: str, callbacks: Optional[DeserializationCallbacks] = None +) -> Any: + """ + Creates a component instance from a dictionary. + + If a `from_dict` method is present in the component class, that will be used instead of the default method. + + :param cls: + The class to be used for deserialization. + :param data: + The serialized data. + :param name: + The name of the component. + :param callbacks: + Callbacks to invoke during deserialization. + :returns: + The deserialized component. + """ + + def component_pre_init_callback(component_cls, init_params): + assert callbacks is not None + assert callbacks.component_pre_init is not None + callbacks.component_pre_init(name, component_cls, init_params) + + def do_from_dict(): + if hasattr(cls, "from_dict"): + return cls.from_dict(data) + + return default_from_dict(cls, data) + + if callbacks is None or callbacks.component_pre_init is None: + return do_from_dict() + + with _hook_component_init(component_pre_init_callback): + return do_from_dict() + + +def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]: + """ + Utility function to serialize an object to a dictionary. + + This is mostly necessary for components but can be used by any object. + `init_parameters` are parameters passed to the object class `__init__`. + They must be defined explicitly as they'll be used when creating a new + instance of `obj` with `from_dict`. Omitting them might cause deserialisation + errors or unexpected behaviours later, when calling `from_dict`. + + An example usage: + + ```python + class MyClass: + def __init__(self, my_param: int = 10): + self.my_param = my_param + + def to_dict(self): + return default_to_dict(self, my_param=self.my_param) + + + obj = MyClass(my_param=1000) + data = obj.to_dict() + assert data == { + "type": "MyClass", + "init_parameters": { + "my_param": 1000, + }, + } + ``` + + :param obj: + The object to be serialized. + :param init_parameters: + The parameters used to create a new instance of the class. + :returns: + A dictionary representation of the instance. + """ + return {"type": generate_qualified_class_name(type(obj)), "init_parameters": init_parameters} + + +def default_from_dict(cls: Type[object], data: Dict[str, Any]) -> Any: + """ + Utility function to deserialize a dictionary to an object. + + This is mostly necessary for components but can be used by any object. + + The function will raise a `DeserializationError` if the `type` field in `data` is + missing or it doesn't match the type of `cls`. + + If `data` contains an `init_parameters` field it will be used as parameters to create + a new instance of `cls`. + + :param cls: + The class to be used for deserialization. + :param data: + The serialized data. + :returns: + The deserialized object. + + :raises DeserializationError: + If the `type` field in `data` is missing or it doesn't match the type of `cls`. + """ + init_params = data.get("init_parameters", {}) + if "type" not in data: + raise DeserializationError("Missing 'type' in serialization data") + if data["type"] != generate_qualified_class_name(cls): + raise DeserializationError(f"Class '{data['type']}' can't be deserialized as '{cls.__name__}'") + return cls(**init_params) + + +def import_class_by_name(fully_qualified_name: str) -> Type[object]: + """ + Utility function to import (load) a class object based on its fully qualified class name. + + This function dynamically imports a class based on its string name. + It splits the name into module path and class name, imports the module, + and returns the class object. + + :param fully_qualified_name: the fully qualified class name as a string + :returns: the class object. + :raises ImportError: If the class cannot be imported or found. + """ + try: + module_path, class_name = fully_qualified_name.rsplit(".", 1) + logger.debug(f"Attempting to import class '{class_name}' from module '{module_path}'") + module = import_module(module_path) + return getattr(module, class_name) + except (ImportError, AttributeError) as error: + logger.error(f"Failed to import class '{fully_qualified_name}'") + raise ImportError(f"Could not import class '{fully_qualified_name}'") from error diff --git a/testbed/deepset-ai__haystack/haystack/core/type_utils.py b/testbed/deepset-ai__haystack/haystack/core/type_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..06651cd568853377d741c492d497226b01aca60e --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/core/type_utils.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Union, get_args, get_origin + +from haystack import logging + +logger = logging.getLogger(__name__) + + +def _is_optional(type_: type) -> bool: + """ + Utility method that returns whether a type is Optional. + """ + return get_origin(type_) is Union and type(None) in get_args(type_) + + +def _types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements + """ + Checks whether the source type is equal or a subtype of the destination type. Used to validate pipeline connections. + + Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of + typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well + with "bare" types, so `List` is treated differently from `List[Any]`, even though they should be the same. + + Consider simplifying the typing of your components if you observe unexpected errors during component connection. + """ + if sender == receiver or receiver is Any: + return True + + if sender is Any: + return False + + try: + if issubclass(sender, receiver): + return True + except TypeError: # typing classes can't be used with issubclass, so we deal with them below + pass + + sender_origin = get_origin(sender) + receiver_origin = get_origin(receiver) + + if sender_origin is not Union and receiver_origin is Union: + return any(_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver)) + + if not sender_origin or not receiver_origin or sender_origin != receiver_origin: + return False + + sender_args = get_args(sender) + receiver_args = get_args(receiver) + if len(sender_args) > len(receiver_args): + return False + + return all(_types_are_compatible(*args) for args in zip(sender_args, receiver_args)) + + +def _type_name(type_): + """ + Util methods to get a nice readable representation of a type. + + Handles Optional and Literal in a special way to make it more readable. + """ + # Literal args are strings, so we wrap them in quotes to make it clear + if isinstance(type_, str): + return f"'{type_}'" + + name = getattr(type_, "__name__", str(type_)) + + if name.startswith("typing."): + name = name[7:] + if "[" in name: + name = name.split("[")[0] + args = get_args(type_) + if name == "Union" and type(None) in args and len(args) == 2: + # Optional is technically a Union of type and None + # but we want to display it as Optional + name = "Optional" + + if args: + args = ", ".join([_type_name(a) for a in args if a is not type(None)]) + return f"{name}[{args}]" + + return f"{name}" diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/__init__.py b/testbed/deepset-ai__haystack/haystack/dataclasses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..231ce8071347366c9116f7b9868f9fa1742470be --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/__init__.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.dataclasses.answer import Answer, ExtractedAnswer, GeneratedAnswer +from haystack.dataclasses.byte_stream import ByteStream +from haystack.dataclasses.chat_message import ChatMessage, ChatRole +from haystack.dataclasses.document import Document +from haystack.dataclasses.sparse_embedding import SparseEmbedding +from haystack.dataclasses.streaming_chunk import StreamingChunk + +__all__ = [ + "Document", + "ExtractedAnswer", + "GeneratedAnswer", + "Answer", + "ByteStream", + "ChatMessage", + "ChatRole", + "StreamingChunk", + "SparseEmbedding", +] diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/answer.py b/testbed/deepset-ai__haystack/haystack/dataclasses/answer.py new file mode 100644 index 0000000000000000000000000000000000000000..edf0092f55e1eff033897d1263c0962bf1603fd1 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/answer.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import io +from dataclasses import asdict, dataclass, field +from typing import Any, Dict, List, Optional, Protocol, runtime_checkable + +from pandas import DataFrame, read_json + +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.dataclasses.document import Document + + +@runtime_checkable +@dataclass +class Answer(Protocol): + data: Any + query: str + meta: Dict[str, Any] + + def to_dict(self) -> Dict[str, Any]: # noqa: D102 + ... + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Answer": # noqa: D102 + ... + + +@dataclass +class ExtractedAnswer: + query: str + score: float + data: Optional[str] = None + document: Optional[Document] = None + context: Optional[str] = None + document_offset: Optional["Span"] = None + context_offset: Optional["Span"] = None + meta: Dict[str, Any] = field(default_factory=dict) + + @dataclass + class Span: + start: int + end: int + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize the object to a dictionary. + + :returns: + Serialized dictionary representation of the object. + """ + document = self.document.to_dict(flatten=False) if self.document is not None else None + document_offset = asdict(self.document_offset) if self.document_offset is not None else None + context_offset = asdict(self.context_offset) if self.context_offset is not None else None + return default_to_dict( + self, + data=self.data, + query=self.query, + document=document, + context=self.context, + score=self.score, + document_offset=document_offset, + context_offset=context_offset, + meta=self.meta, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ExtractedAnswer": + """ + Deserialize the object from a dictionary. + + :param data: + Dictionary representation of the object. + :returns: + Deserialized object. + """ + init_params = data.get("init_parameters", {}) + if (doc := init_params.get("document")) is not None: + data["init_parameters"]["document"] = Document.from_dict(doc) + + if (offset := init_params.get("document_offset")) is not None: + data["init_parameters"]["document_offset"] = ExtractedAnswer.Span(**offset) + + if (offset := init_params.get("context_offset")) is not None: + data["init_parameters"]["context_offset"] = ExtractedAnswer.Span(**offset) + return default_from_dict(cls, data) + + +@dataclass +class ExtractedTableAnswer: + query: str + score: float + data: Optional[str] = None + document: Optional[Document] = None + context: Optional[DataFrame] = None + document_cells: List["Cell"] = field(default_factory=list) + context_cells: List["Cell"] = field(default_factory=list) + meta: Dict[str, Any] = field(default_factory=dict) + + @dataclass + class Cell: + row: int + column: int + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize the object to a dictionary. + + :returns: + Serialized dictionary representation of the object. + """ + document = self.document.to_dict(flatten=False) if self.document is not None else None + context = self.context.to_json() if self.context is not None else None + document_cells = [asdict(c) for c in self.document_cells] + context_cells = [asdict(c) for c in self.context_cells] + return default_to_dict( + self, + data=self.data, + query=self.query, + document=document, + context=context, + score=self.score, + document_cells=document_cells, + context_cells=context_cells, + meta=self.meta, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ExtractedTableAnswer": + """ + Deserialize the object from a dictionary. + + :param data: + Dictionary representation of the object. + + :returns: + Deserialized object. + """ + init_params = data.get("init_parameters", {}) + if (doc := init_params.get("document")) is not None: + data["init_parameters"]["document"] = Document.from_dict(doc) + + if (context := init_params.get("context")) is not None: + data["init_parameters"]["context"] = read_json(io.StringIO(context)) + + if (cells := init_params.get("document_cells")) is not None: + data["init_parameters"]["document_cells"] = [ExtractedTableAnswer.Cell(**c) for c in cells] + + if (cells := init_params.get("context_cells")) is not None: + data["init_parameters"]["context_cells"] = [ExtractedTableAnswer.Cell(**c) for c in cells] + return default_from_dict(cls, data) + + +@dataclass +class GeneratedAnswer: + data: str + query: str + documents: List[Document] + meta: Dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize the object to a dictionary. + + :returns: + Serialized dictionary representation of the object. + """ + documents = [doc.to_dict(flatten=False) for doc in self.documents] + return default_to_dict(self, data=self.data, query=self.query, documents=documents, meta=self.meta) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "GeneratedAnswer": + """ + Deserialize the object from a dictionary. + + :param data: + Dictionary representation of the object. + + :returns: + Deserialized object. + """ + init_params = data.get("init_parameters", {}) + if (documents := init_params.get("documents")) is not None: + data["init_parameters"]["documents"] = [Document.from_dict(d) for d in documents] + + return default_from_dict(cls, data) diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/byte_stream.py b/testbed/deepset-ai__haystack/haystack/dataclasses/byte_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..72a2648199503d6a186f13542e01e51ae4e17d59 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/byte_stream.py @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Dict, Optional + + +@dataclass +class ByteStream: + """ + Base data class representing a binary object in the Haystack API. + """ + + data: bytes + meta: Dict[str, Any] = field(default_factory=dict, hash=False) + mime_type: Optional[str] = field(default=None) + + def to_file(self, destination_path: Path): + """ + Write the ByteStream to a file. Note: the metadata will be lost. + + :param destination_path: The path to write the ByteStream to. + """ + with open(destination_path, "wb") as fd: + fd.write(self.data) + + @classmethod + def from_file_path( + cls, filepath: Path, mime_type: Optional[str] = None, meta: Optional[Dict[str, Any]] = None + ) -> "ByteStream": + """ + Create a ByteStream from the contents read from a file. + + :param filepath: A valid path to a file. + :param mime_type: The mime type of the file. + :param meta: Additional metadata to be stored with the ByteStream. + """ + with open(filepath, "rb") as fd: + return cls(data=fd.read(), mime_type=mime_type, meta=meta or {}) + + @classmethod + def from_string( + cls, text: str, encoding: str = "utf-8", mime_type: Optional[str] = None, meta: Optional[Dict[str, Any]] = None + ) -> "ByteStream": + """ + Create a ByteStream encoding a string. + + :param text: The string to encode + :param encoding: The encoding used to convert the string into bytes + :param mime_type: The mime type of the file. + :param meta: Additional metadata to be stored with the ByteStream. + """ + return cls(data=text.encode(encoding), mime_type=mime_type, meta=meta or {}) + + def to_string(self, encoding: str = "utf-8") -> str: + """ + Convert the ByteStream to a string, metadata will not be included. + + :param encoding: The encoding used to convert the bytes to a string. Defaults to "utf-8". + :returns: The string representation of the ByteStream. + :raises: UnicodeDecodeError: If the ByteStream data cannot be decoded with the specified encoding. + """ + return self.data.decode(encoding) diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/chat_message.py b/testbed/deepset-ai__haystack/haystack/dataclasses/chat_message.py new file mode 100644 index 0000000000000000000000000000000000000000..4bfbe55820d7664ca18350fb4a293bce2df72845 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/chat_message.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Dict, Optional + + +class ChatRole(str, Enum): + """Enumeration representing the roles within a chat.""" + + ASSISTANT = "assistant" + USER = "user" + SYSTEM = "system" + FUNCTION = "function" + + +@dataclass +class ChatMessage: + """ + Represents a message in a LLM chat conversation. + + :param content: The text content of the message. + :param role: The role of the entity sending the message. + :param name: The name of the function being called (only applicable for role FUNCTION). + :param meta: Additional metadata associated with the message. + """ + + content: str + role: ChatRole + name: Optional[str] + meta: Dict[str, Any] = field(default_factory=dict, hash=False) + + def is_from(self, role: ChatRole) -> bool: + """ + Check if the message is from a specific role. + + :param role: The role to check against. + :returns: True if the message is from the specified role, False otherwise. + """ + return self.role == role + + @classmethod + def from_assistant(cls, content: str, meta: Optional[Dict[str, Any]] = None) -> "ChatMessage": + """ + Create a message from the assistant. + + :param content: The text content of the message. + :param meta: Additional metadata associated with the message. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.ASSISTANT, None, meta or {}) + + @classmethod + def from_user(cls, content: str) -> "ChatMessage": + """ + Create a message from the user. + + :param content: The text content of the message. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.USER, None) + + @classmethod + def from_system(cls, content: str) -> "ChatMessage": + """ + Create a message from the system. + + :param content: The text content of the message. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.SYSTEM, None) + + @classmethod + def from_function(cls, content: str, name: str) -> "ChatMessage": + """ + Create a message from a function call. + + :param content: The text content of the message. + :param name: The name of the function being called. + :returns: A new ChatMessage instance. + """ + return cls(content, ChatRole.FUNCTION, name) + + def to_dict(self) -> Dict[str, Any]: + """ + Converts ChatMessage into a dictionary. + + :returns: + Serialized version of the object. + """ + data = asdict(self) + data["role"] = self.role.value + + return data + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ChatMessage": + """ + Creates a new ChatMessage object from a dictionary. + + :param data: + The dictionary to build the ChatMessage object. + :returns: + The created object. + """ + data["role"] = ChatRole(data["role"]) + + return cls(**data) diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/document.py b/testbed/deepset-ai__haystack/haystack/dataclasses/document.py new file mode 100644 index 0000000000000000000000000000000000000000..aed35964115b6ffbbaf3eba17ccc99b369958de4 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/document.py @@ -0,0 +1,207 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import hashlib +import io +from dataclasses import asdict, dataclass, field, fields +from typing import Any, Dict, List, Optional + +from numpy import ndarray +from pandas import DataFrame, read_json + +from haystack import logging +from haystack.dataclasses.byte_stream import ByteStream +from haystack.dataclasses.sparse_embedding import SparseEmbedding + +logger = logging.getLogger(__name__) + + +class _BackwardCompatible(type): + """ + Metaclass that handles Document backward compatibility. + """ + + def __call__(cls, *args, **kwargs): + """ + Called before Document.__init__, will remap legacy fields to new ones. + + Also handles building a Document from a flattened dictionary. + """ + # Move `content` to new fields depending on the type + content = kwargs.get("content") + if isinstance(content, DataFrame): + kwargs["dataframe"] = content + del kwargs["content"] + + # Not used anymore + if "content_type" in kwargs: + del kwargs["content_type"] + + # Embedding were stored as NumPy arrays in 1.x, so we convert it to the new type + if isinstance(embedding := kwargs.get("embedding"), ndarray): + kwargs["embedding"] = embedding.tolist() + + # id_hash_keys is not used anymore + if "id_hash_keys" in kwargs: + del kwargs["id_hash_keys"] + + return super().__call__(*args, **kwargs) + + +@dataclass +class Document(metaclass=_BackwardCompatible): + """ + Base data class containing some data to be queried. + + Can contain text snippets, tables, and file paths to images or audios. Documents can be sorted by score and saved + to/from dictionary and JSON. + + :param id: Unique identifier for the document. When not set, it's generated based on the Document fields' values. + :param content: Text of the document, if the document contains text. + :param dataframe: Pandas dataframe with the document's content, if the document contains tabular data. + :param blob: Binary data associated with the document, if the document has any binary data associated with it. + :param meta: Additional custom metadata for the document. Must be JSON-serializable. + :param score: Score of the document. Used for ranking, usually assigned by retrievers. + :param embedding: dense vector representation of the document. + :param sparse_embedding: sparse vector representation of the document. + """ + + id: str = field(default="") + content: Optional[str] = field(default=None) + dataframe: Optional[DataFrame] = field(default=None) + blob: Optional[ByteStream] = field(default=None) + meta: Dict[str, Any] = field(default_factory=dict) + score: Optional[float] = field(default=None) + embedding: Optional[List[float]] = field(default=None) + sparse_embedding: Optional[SparseEmbedding] = field(default=None) + + def __repr__(self): + fields = [] + if self.content is not None: + fields.append( + f"content: '{self.content}'" if len(self.content) < 100 else f"content: '{self.content[:100]}...'" + ) + if self.dataframe is not None: + fields.append(f"dataframe: {self.dataframe.shape}") + if self.blob is not None: + fields.append(f"blob: {len(self.blob.data)} bytes") + if len(self.meta) > 0: + fields.append(f"meta: {self.meta}") + if self.score is not None: + fields.append(f"score: {self.score}") + if self.embedding is not None: + fields.append(f"embedding: vector of size {len(self.embedding)}") + if self.sparse_embedding is not None: + fields.append(f"sparse_embedding: vector with {len(self.sparse_embedding.indices)} non-zero elements") + fields_str = ", ".join(fields) + return f"{self.__class__.__name__}(id={self.id}, {fields_str})" + + def __eq__(self, other): + """ + Compares Documents for equality. + + Two Documents are considered equals if their dictionary representation is identical. + """ + if type(self) != type(other): + return False + return self.to_dict() == other.to_dict() + + def __post_init__(self): + """ + Generate the ID based on the init parameters. + """ + # Generate an id only if not explicitly set + self.id = self.id or self._create_id() + + def _create_id(self): + """ + Creates a hash of the given content that acts as the document's ID. + """ + text = self.content or None + dataframe = self.dataframe.to_json() if self.dataframe is not None else None + blob = self.blob.data if self.blob is not None else None + mime_type = self.blob.mime_type if self.blob is not None else None + meta = self.meta or {} + embedding = self.embedding if self.embedding is not None else None + sparse_embedding = self.sparse_embedding.to_dict() if self.sparse_embedding is not None else "" + data = f"{text}{dataframe}{blob}{mime_type}{meta}{embedding}{sparse_embedding}" + return hashlib.sha256(data.encode("utf-8")).hexdigest() + + def to_dict(self, flatten=True) -> Dict[str, Any]: + """ + Converts Document into a dictionary. + + `dataframe` and `blob` fields are converted to JSON-serializable types. + + :param flatten: + Whether to flatten `meta` field or not. Defaults to `True` to be backward-compatible with Haystack 1.x. + """ + data = asdict(self) + if (dataframe := data.get("dataframe")) is not None: + data["dataframe"] = dataframe.to_json() + if (blob := data.get("blob")) is not None: + data["blob"] = {"data": list(blob["data"]), "mime_type": blob["mime_type"]} + + if flatten: + meta = data.pop("meta") + return {**data, **meta} + + return data + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Document": + """ + Creates a new Document object from a dictionary. + + The `dataframe` and `blob` fields are converted to their original types. + """ + if (dataframe := data.get("dataframe")) is not None: + data["dataframe"] = read_json(io.StringIO(dataframe)) + if blob := data.get("blob"): + data["blob"] = ByteStream(data=bytes(blob["data"]), mime_type=blob["mime_type"]) + if sparse_embedding := data.get("sparse_embedding"): + data["sparse_embedding"] = SparseEmbedding.from_dict(sparse_embedding) + + # Store metadata for a moment while we try un-flattening allegedly flatten metadata. + # We don't expect both a `meta=` keyword and flatten metadata keys so we'll raise a + # ValueError later if this is the case. + meta = data.pop("meta", {}) + # Unflatten metadata if it was flattened. We assume any keyword argument that's not + # a document field is a metadata key. We treat legacy fields as document fields + # for backward compatibility. + flatten_meta = {} + legacy_fields = ["content_type", "id_hash_keys"] + document_fields = legacy_fields + [f.name for f in fields(cls)] + for key in list(data.keys()): + if key not in document_fields: + flatten_meta[key] = data.pop(key) + + # We don't support passing both flatten keys and the `meta` keyword parameter + if meta and flatten_meta: + raise ValueError( + "You can pass either the 'meta' parameter or flattened metadata keys as keyword arguments, " + "but currently you're passing both. Pass either the 'meta' parameter or flattened metadata keys." + ) + + # Finally put back all the metadata + return cls(**data, meta={**meta, **flatten_meta}) + + @property + def content_type(self): + """ + Returns the type of the content for the document. + + This is necessary to keep backward compatibility with 1.x. + + :raises ValueError: + If both `text` and `dataframe` fields are set or both are missing. + """ + if self.content is not None and self.dataframe is not None: + raise ValueError("Both text and dataframe are set.") + + if self.content is not None: + return "text" + elif self.dataframe is not None: + return "table" + raise ValueError("Neither text nor dataframe is set.") diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/sparse_embedding.py b/testbed/deepset-ai__haystack/haystack/dataclasses/sparse_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3c18c80742acecc69ea3922f3f8f44ec58907c --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/sparse_embedding.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import asdict, dataclass +from typing import Any, Dict, List + + +@dataclass +class SparseEmbedding: + """ + Class representing a sparse embedding. + + :param indices: List of indices of non-zero elements in the embedding. + :param values: List of values of non-zero elements in the embedding. + """ + + indices: List[int] + values: List[float] + + def __post_init__(self): + """ + Checks if the indices and values lists are of the same length. + + Raises a ValueError if they are not. + """ + if len(self.indices) != len(self.values): + raise ValueError("Length of indices and values must be the same.") + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the SparseEmbedding object to a dictionary. + + :returns: + Serialized sparse embedding. + """ + return asdict(self) + + @classmethod + def from_dict(cls, sparse_embedding_dict: Dict[str, Any]) -> "SparseEmbedding": + """ + Deserializes the sparse embedding from a dictionary. + + :param sparse_embedding_dict: + Dictionary to deserialize from. + :returns: + Deserialized sparse embedding. + """ + return cls(**sparse_embedding_dict) diff --git a/testbed/deepset-ai__haystack/haystack/dataclasses/streaming_chunk.py b/testbed/deepset-ai__haystack/haystack/dataclasses/streaming_chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..455caa09e285fd4cf8c9c361e6a83a3fdd063ad8 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/dataclasses/streaming_chunk.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from typing import Any, Dict + + +@dataclass +class StreamingChunk: + """ + The StreamingChunk class encapsulates a segment of streamed content along with associated metadata. + + This structure facilitates the handling and processing of streamed data in a systematic manner. + + :param content: The content of the message chunk as a string. + :param meta: A dictionary containing metadata related to the message chunk. + """ + + content: str + meta: Dict[str, Any] = field(default_factory=dict, hash=False) diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/__init__.py b/testbed/deepset-ai__haystack/haystack/document_stores/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/errors/__init__.py b/testbed/deepset-ai__haystack/haystack/document_stores/errors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c22cc78c49a1ff850036d75fbb3580cebecfd6 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/errors/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .errors import DocumentStoreError, DuplicateDocumentError, MissingDocumentError + +__all__ = ["DocumentStoreError", "DuplicateDocumentError", "MissingDocumentError"] diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/errors/errors.py b/testbed/deepset-ai__haystack/haystack/document_stores/errors/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..cc24e2cad6037c302b4a942d8315c8687b78d917 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/errors/errors.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +class DocumentStoreError(Exception): + pass + + +class DuplicateDocumentError(DocumentStoreError): + pass + + +class MissingDocumentError(DocumentStoreError): + pass diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/in_memory/__init__.py b/testbed/deepset-ai__haystack/haystack/document_stores/in_memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94d0b2e97f3a3ffd25033c430e630a96f055843f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/in_memory/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.document_stores.in_memory.document_store import InMemoryDocumentStore + +__all__ = ["InMemoryDocumentStore"] diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/in_memory/document_store.py b/testbed/deepset-ai__haystack/haystack/document_stores/in_memory/document_store.py new file mode 100644 index 0000000000000000000000000000000000000000..245c55f78c9e0a18c430912b08c99cf83eb279f2 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/in_memory/document_store.py @@ -0,0 +1,645 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +import math +import re +import uuid +from collections import Counter +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple + +import numpy as np + +from haystack import default_from_dict, default_to_dict, logging +from haystack.dataclasses import Document +from haystack.document_stores.errors import DocumentStoreError, DuplicateDocumentError +from haystack.document_stores.types import DuplicatePolicy +from haystack.utils import expit +from haystack.utils.filters import document_matches_filter + +logger = logging.getLogger(__name__) + +# document scores are essentially unbounded and will be scaled to values between 0 and 1 if scale_score is set to +# True (default). Scaling uses the expit function (inverse of the logit function) after applying a scaling factor +# (e.g., BM25_SCALING_FACTOR for the bm25_retrieval method). +# Larger scaling factor decreases scaled scores. For example, an input of 10 is scaled to 0.99 with +# BM25_SCALING_FACTOR=2 but to 0.78 with BM25_SCALING_FACTOR=8 (default). The defaults were chosen empirically. +# Increase the default if most unscaled scores are larger than expected (>30) and otherwise would incorrectly all be +# mapped to scores ~1. +BM25_SCALING_FACTOR = 8 +DOT_PRODUCT_SCALING_FACTOR = 100 + + +@dataclass +class BM25DocumentStats: + """ + A dataclass for managing document statistics for BM25 retrieval. + + :param freq_token: A Counter of token frequencies in the document. + :param doc_len: Number of tokens in the document. + """ + + freq_token: Dict[str, int] + doc_len: int + + +# Global storage for all InMemoryDocumentStore instances, indexed by the index name. +_STORAGES: Dict[str, Dict[str, Document]] = {} +_BM25_STATS_STORAGES: Dict[str, Dict[str, BM25DocumentStats]] = {} +_AVERAGE_DOC_LEN_STORAGES: Dict[str, float] = {} +_FREQ_VOCAB_FOR_IDF_STORAGES: Dict[str, Counter] = {} + + +class InMemoryDocumentStore: + """ + Stores data in-memory. It's ephemeral and cannot be saved to disk. + """ + + def __init__( + self, + bm25_tokenization_regex: str = r"(?u)\b\w\w+\b", + bm25_algorithm: Literal["BM25Okapi", "BM25L", "BM25Plus"] = "BM25L", + bm25_parameters: Optional[Dict] = None, + embedding_similarity_function: Literal["dot_product", "cosine"] = "dot_product", + index: Optional[str] = None, + ): + """ + Initializes the DocumentStore. + + :param bm25_tokenization_regex: The regular expression used to tokenize the text for BM25 retrieval. + :param bm25_algorithm: The BM25 algorithm to use. One of "BM25Okapi", "BM25L", or "BM25Plus". + :param bm25_parameters: Parameters for BM25 implementation in a dictionary format. + For example: {'k1':1.5, 'b':0.75, 'epsilon':0.25} + You can learn more about these parameters by visiting https://github.com/dorianbrown/rank_bm25. + :param embedding_similarity_function: The similarity function used to compare Documents embeddings. + One of "dot_product" (default) or "cosine". To choose the most appropriate function, look for information + about your embedding model. + :param index: A specific index to store the documents. If not specified, a random UUID is used. + Using the same index allows you to store documents across multiple InMemoryDocumentStore instances. + """ + self.bm25_tokenization_regex = bm25_tokenization_regex + self.tokenizer = re.compile(bm25_tokenization_regex).findall + + if index is None: + index = str(uuid.uuid4()) + + self.index = index + if self.index not in _STORAGES: + _STORAGES[self.index] = {} + + self.bm25_algorithm = bm25_algorithm + self.bm25_algorithm_inst = self._dispatch_bm25() + self.bm25_parameters = bm25_parameters or {} + self.embedding_similarity_function = embedding_similarity_function + + # Per-document statistics + if self.index not in _BM25_STATS_STORAGES: + _BM25_STATS_STORAGES[self.index] = {} + + if self.index not in _AVERAGE_DOC_LEN_STORAGES: + _AVERAGE_DOC_LEN_STORAGES[self.index] = 0.0 + + if self.index not in _FREQ_VOCAB_FOR_IDF_STORAGES: + _FREQ_VOCAB_FOR_IDF_STORAGES[self.index] = Counter() + + @property + def storage(self) -> Dict[str, Document]: + """ + Utility property that returns the storage used by this instance of InMemoryDocumentStore. + """ + return _STORAGES.get(self.index, {}) + + @property + def _bm25_attr(self) -> Dict[str, BM25DocumentStats]: + return _BM25_STATS_STORAGES.get(self.index, {}) + + @property + def _avg_doc_len(self) -> float: + return _AVERAGE_DOC_LEN_STORAGES.get(self.index, 0.0) + + @_avg_doc_len.setter + def _avg_doc_len(self, value: float): + _AVERAGE_DOC_LEN_STORAGES[self.index] = value + + @property + def _freq_vocab_for_idf(self) -> Counter: + return _FREQ_VOCAB_FOR_IDF_STORAGES.get(self.index, Counter()) + + def _dispatch_bm25(self): + """ + Select the correct BM25 algorithm based on user specification. + + :returns: + The BM25 algorithm method. + """ + table = {"BM25Okapi": self._score_bm25okapi, "BM25L": self._score_bm25l, "BM25Plus": self._score_bm25plus} + + if self.bm25_algorithm not in table: + raise ValueError(f"BM25 algorithm '{self.bm25_algorithm}' is not supported.") + return table[self.bm25_algorithm] + + def _tokenize_bm25(self, text: str) -> List[str]: + """ + Tokenize text using the BM25 tokenization regex. + + Here we explicitly create a tokenization method to encapsulate + all pre-processing logic used to create BM25 tokens, such as + lowercasing. This helps track the exact tokenization process + used for BM25 scoring at any given time. + + :param text: + The text to tokenize. + :returns: + A list of tokens. + """ + text = text.lower() + return self.tokenizer(text) + + def _score_bm25l(self, query: str, documents: List[Document]) -> List[Tuple[Document, float]]: + """ + Calculate BM25L scores for the given query and filtered documents. + + :param query: + The query string. + :param documents: + The list of documents to score, should be produced by + the filter_documents method; may be an empty list. + :returns: + A list of tuples, each containing a Document and its BM25L score. + """ + k = self.bm25_parameters.get("k1", 1.5) + b = self.bm25_parameters.get("b", 0.75) + delta = self.bm25_parameters.get("delta", 0.5) + + def _compute_idf(tokens: List[str]) -> Dict[str, float]: + """Per-token IDF computation for all tokens.""" + idf = {} + n_corpus = len(self._bm25_attr) + for tok in tokens: + n = self._freq_vocab_for_idf.get(tok, 0) + idf[tok] = math.log((n_corpus + 1.0) / (n + 0.5)) * int(n != 0) + return idf + + def _compute_tf(token: str, freq: Dict[str, int], doc_len: int) -> float: + """Per-token BM25L computation.""" + freq_term = freq.get(token, 0.0) + ctd = freq_term / (1 - b + b * doc_len / self._avg_doc_len) + return (1.0 + k) * (ctd + delta) / (k + ctd + delta) + + idf = _compute_idf(self._tokenize_bm25(query)) + bm25_attr = {doc.id: self._bm25_attr[doc.id] for doc in documents} + + ret = [] + for doc in documents: + doc_stats = bm25_attr[doc.id] + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + score = 0.0 + for tok in idf.keys(): # pylint: disable=consider-using-dict-items + score += idf[tok] * _compute_tf(tok, freq, doc_len) + ret.append((doc, score)) + + return ret + + def _score_bm25okapi(self, query: str, documents: List[Document]) -> List[Tuple[Document, float]]: + """ + Calculate BM25Okapi scores for the given query and filtered documents. + + :param query: + The query string. + :param documents: + The list of documents to score, should be produced by + the filter_documents method; may be an empty list. + :returns: + A list of tuples, each containing a Document and its BM25L score. + """ + k = self.bm25_parameters.get("k1", 1.5) + b = self.bm25_parameters.get("b", 0.75) + epsilon = self.bm25_parameters.get("epsilon", 0.25) + + def _compute_idf(tokens: List[str]) -> Dict[str, float]: + """Per-token IDF computation for all tokens.""" + sum_idf = 0.0 + neg_idf_tokens = [] + + # Although this is a global statistic, we compute it here + # to make the computation more self-contained. And the + # complexity is O(vocab_size), which is acceptable. + idf = {} + for tok, n in self._freq_vocab_for_idf.items(): + idf[tok] = math.log((len(self._bm25_attr) - n + 0.5) / (n + 0.5)) + sum_idf += idf[tok] + if idf[tok] < 0: + neg_idf_tokens.append(tok) + + eps = epsilon * sum_idf / len(self._freq_vocab_for_idf) + for tok in neg_idf_tokens: + idf[tok] = eps + return {tok: idf.get(tok, 0.0) for tok in tokens} + + def _compute_tf(token: str, freq: Dict[str, int], doc_len: int) -> float: + """Per-token BM25L computation.""" + freq_term = freq.get(token, 0.0) + freq_norm = freq_term + k * (1 - b + b * doc_len / self._avg_doc_len) + return freq_term * (1.0 + k) / freq_norm + + idf = _compute_idf(self._tokenize_bm25(query)) + bm25_attr = {doc.id: self._bm25_attr[doc.id] for doc in documents} + + ret = [] + for doc in documents: + doc_stats = bm25_attr[doc.id] + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + score = 0.0 + for tok in idf.keys(): + score += idf[tok] * _compute_tf(tok, freq, doc_len) + ret.append((doc, score)) + + return ret + + def _score_bm25plus(self, query: str, documents: List[Document]) -> List[Tuple[Document, float]]: + """ + Calculate BM25+ scores for the given query and filtered documents. + + This implementation follows the document on BM25 Wikipedia page, + which add 1 (smoothing factor) to document frequency when computing IDF. + + :param query: + The query string. + :param documents: + The list of documents to score, should be produced by + the filter_documents method; may be an empty list. + :returns: + A list of tuples, each containing a Document and its BM25+ score. + """ + k = self.bm25_parameters.get("k1", 1.5) + b = self.bm25_parameters.get("b", 0.75) + delta = self.bm25_parameters.get("delta", 1.0) + + def _compute_idf(tokens: List[str]) -> Dict[str, float]: + """Per-token IDF computation.""" + idf = {} + n_corpus = len(self._bm25_attr) + for tok in tokens: + n = self._freq_vocab_for_idf.get(tok, 0) + idf[tok] = math.log(1 + (n_corpus - n + 0.5) / (n + 0.5)) * int(n != 0) + return idf + + def _compute_tf(token: str, freq: Dict[str, int], doc_len: float) -> float: + """Per-token normalized term frequency.""" + freq_term = freq.get(token, 0.0) + freq_damp = k * (1 - b + b * doc_len / self._avg_doc_len) + return freq_term * (1.0 + k) / (freq_term + freq_damp) + delta + + idf = _compute_idf(self._tokenize_bm25(query)) + bm25_attr = {doc.id: self._bm25_attr[doc.id] for doc in documents} + + ret = [] + for doc in documents: + doc_stats = bm25_attr[doc.id] + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + score = 0.0 + for tok in idf.keys(): # pylint: disable=consider-using-dict-items + score += idf[tok] * _compute_tf(tok, freq, doc_len) + ret.append((doc, score)) + + return ret + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ + return default_to_dict( + self, + bm25_tokenization_regex=self.bm25_tokenization_regex, + bm25_algorithm=self.bm25_algorithm, + bm25_parameters=self.bm25_parameters, + embedding_similarity_function=self.embedding_similarity_function, + index=self.index, + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "InMemoryDocumentStore": + """ + Deserializes the component from a dictionary. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized component. + """ + return default_from_dict(cls, data) + + def save_to_disk(self, path: str) -> None: + """ + Write the database and its' data to disk as a JSON file. + + :param path: The path to the JSON file. + """ + data: Dict[str, Any] = self.to_dict() + data["documents"] = [doc.to_dict(flatten=False) for doc in self.storage.values()] + with open(path, "w") as f: + json.dump(data, f) + + @classmethod + def load_from_disk(cls, path: str) -> "InMemoryDocumentStore": + """ + Load the database and its' data from disk as a JSON file. + + :param path: The path to the JSON file. + :returns: The loaded InMemoryDocumentStore. + """ + if Path(path).exists(): + try: + with open(path, "r") as f: + data = json.load(f) + except Exception as e: + raise Exception(f"Error loading InMemoryDocumentStore from disk. error: {e}") + + documents = data.pop("documents") + cls_object = default_from_dict(cls, data) + cls_object.write_documents( + documents=[Document(**doc) for doc in documents], policy=DuplicatePolicy.OVERWRITE + ) + return cls_object + + else: + raise FileNotFoundError(f"File {path} not found.") + + def count_documents(self) -> int: + """ + Returns the number of how many documents are present in the DocumentStore. + """ + return len(self.storage.keys()) + + def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]: + """ + Returns the documents that match the filters provided. + + For a detailed specification of the filters, refer to the DocumentStore.filter_documents() protocol + documentation. + + :param filters: The filters to apply to the document list. + :returns: A list of Documents that match the given filters. + """ + if filters: + if "operator" not in filters and "conditions" not in filters: + raise ValueError( + "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering " + "for details." + ) + return [doc for doc in self.storage.values() if document_matches_filter(filters=filters, document=doc)] + return list(self.storage.values()) + + def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int: + """ + Refer to the DocumentStore.write_documents() protocol documentation. + + If `policy` is set to `DuplicatePolicy.NONE` defaults to `DuplicatePolicy.FAIL`. + """ + if ( + not isinstance(documents, Iterable) + or isinstance(documents, str) + or any(not isinstance(doc, Document) for doc in documents) + ): + raise ValueError("Please provide a list of Documents.") + + if policy == DuplicatePolicy.NONE: + policy = DuplicatePolicy.FAIL + + written_documents = len(documents) + for document in documents: + if policy != DuplicatePolicy.OVERWRITE and document.id in self.storage.keys(): + if policy == DuplicatePolicy.FAIL: + raise DuplicateDocumentError(f"ID '{document.id}' already exists.") + if policy == DuplicatePolicy.SKIP: + logger.warning("ID '{document_id}' already exists", document_id=document.id) + written_documents -= 1 + continue + + # Since the statistics are updated in an incremental manner, + # we need to explicitly remove the existing document to revert + # the statistics before updating them with the new document. + if document.id in self.storage.keys(): + self.delete_documents([document.id]) + + # This processing logic is extracted from the original bm25_retrieval method. + # Since we are creating index incrementally before the first retrieval, + # we need to determine what content to use for indexing here, not at query time. + if document.content is not None: + if document.dataframe is not None: + logger.warning( + "Document '{document_id}' has both text and dataframe content. " + "Using text content for retrieval and skipping dataframe content.", + document_id=document.id, + ) + tokens = self._tokenize_bm25(document.content) + elif document.dataframe is not None: + str_content = document.dataframe.astype(str) + csv_content = str_content.to_csv(index=False) + tokens = self._tokenize_bm25(csv_content) + else: + tokens = [] + + self.storage[document.id] = document + + self._bm25_attr[document.id] = BM25DocumentStats(Counter(tokens), len(tokens)) + self._freq_vocab_for_idf.update(set(tokens)) + self._avg_doc_len = (len(tokens) + self._avg_doc_len * len(self._bm25_attr)) / (len(self._bm25_attr) + 1) + return written_documents + + def delete_documents(self, document_ids: List[str]) -> None: + """ + Deletes all documents with matching document_ids from the DocumentStore. + + :param document_ids: The object_ids to delete. + """ + for doc_id in document_ids: + if doc_id not in self.storage.keys(): + continue + del self.storage[doc_id] + + # Update statistics accordingly + doc_stats = self._bm25_attr.pop(doc_id) + freq = doc_stats.freq_token + doc_len = doc_stats.doc_len + + self._freq_vocab_for_idf.subtract(Counter(freq.keys())) + try: + self._avg_doc_len = (self._avg_doc_len * (len(self._bm25_attr) + 1) - doc_len) / len(self._bm25_attr) + except ZeroDivisionError: + self._avg_doc_len = 0 + + def bm25_retrieval( + self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: int = 10, scale_score: bool = False + ) -> List[Document]: + """ + Retrieves documents that are most relevant to the query using BM25 algorithm. + + :param query: The query string. + :param filters: A dictionary with filters to narrow down the search space. + :param top_k: The number of top documents to retrieve. Default is 10. + :param scale_score: Whether to scale the scores of the retrieved documents. Default is False. + :returns: A list of the top_k documents most relevant to the query. + """ + if not query: + raise ValueError("Query should be a non-empty string") + + content_type_filter = { + "operator": "OR", + "conditions": [ + {"field": "content", "operator": "!=", "value": None}, + {"field": "dataframe", "operator": "!=", "value": None}, + ], + } + if filters: + if "operator" not in filters: + raise ValueError( + "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering " + "for details." + ) + filters = {"operator": "AND", "conditions": [content_type_filter, filters]} + else: + filters = content_type_filter + + all_documents = self.filter_documents(filters=filters) + if len(all_documents) == 0: + logger.info("No documents found for BM25 retrieval. Returning empty list.") + return [] + + results = sorted(self.bm25_algorithm_inst(query, all_documents), key=lambda x: x[1], reverse=True)[:top_k] + + # BM25Okapi can return meaningful negative values, so they should not be filtered out when scale_score is False. + # It's the only algorithm supported by rank_bm25 at the time of writing (2024) that can return negative scores. + # see https://github.com/deepset-ai/haystack/pull/6889 for more context. + negatives_are_valid = self.bm25_algorithm == "BM25Okapi" and not scale_score + + # Create documents with the BM25 score to return them + return_documents = [] + for doc, score in results: + if scale_score: + score = expit(score / BM25_SCALING_FACTOR) + + if not negatives_are_valid and score <= 0.0: + continue + + doc_fields = doc.to_dict() + doc_fields["score"] = score + return_document = Document.from_dict(doc_fields) + return_documents.append(return_document) + + return return_documents + + def embedding_retrieval( + self, + query_embedding: List[float], + filters: Optional[Dict[str, Any]] = None, + top_k: int = 10, + scale_score: bool = False, + return_embedding: bool = False, + ) -> List[Document]: + """ + Retrieves documents that are most similar to the query embedding using a vector similarity metric. + + :param query_embedding: Embedding of the query. + :param filters: A dictionary with filters to narrow down the search space. + :param top_k: The number of top documents to retrieve. Default is 10. + :param scale_score: Whether to scale the scores of the retrieved Documents. Default is False. + :param return_embedding: Whether to return the embedding of the retrieved Documents. Default is False. + :returns: A list of the top_k documents most relevant to the query. + """ + if len(query_embedding) == 0 or not isinstance(query_embedding[0], float): + raise ValueError("query_embedding should be a non-empty list of floats.") + + filters = filters or {} + all_documents = self.filter_documents(filters=filters) + + documents_with_embeddings = [doc for doc in all_documents if doc.embedding is not None] + if len(documents_with_embeddings) == 0: + logger.warning( + "No Documents found with embeddings. Returning empty list. " + "To generate embeddings, use a DocumentEmbedder." + ) + return [] + elif len(documents_with_embeddings) < len(all_documents): + logger.info( + "Skipping some Documents that don't have an embedding. " + "To generate embeddings, use a DocumentEmbedder." + ) + + scores = self._compute_query_embedding_similarity_scores( + embedding=query_embedding, documents=documents_with_embeddings, scale_score=scale_score + ) + + # create Documents with the similarity score for the top k results + top_documents = [] + for doc, score in sorted(zip(documents_with_embeddings, scores), key=lambda x: x[1], reverse=True)[:top_k]: + doc_fields = doc.to_dict() + doc_fields["score"] = score + if return_embedding is False: + doc_fields["embedding"] = None + top_documents.append(Document.from_dict(doc_fields)) + + return top_documents + + def _compute_query_embedding_similarity_scores( + self, embedding: List[float], documents: List[Document], scale_score: bool = False + ) -> List[float]: + """ + Computes the similarity scores between the query embedding and the embeddings of the documents. + + :param embedding: Embedding of the query. + :param documents: A list of Documents. + :param scale_score: Whether to scale the scores of the Documents. Default is False. + :returns: A list of scores. + """ + + query_embedding = np.array(embedding) + if query_embedding.ndim == 1: + query_embedding = np.expand_dims(a=query_embedding, axis=0) + + try: + document_embeddings = np.array([doc.embedding for doc in documents]) + except ValueError as e: + if "inhomogeneous shape" in str(e): + raise DocumentStoreError( + "The embedding size of all Documents should be the same. " + "Please make sure that the Documents have been embedded with the same model." + ) from e + raise e + if document_embeddings.ndim == 1: + document_embeddings = np.expand_dims(a=document_embeddings, axis=0) + + if self.embedding_similarity_function == "cosine": + # cosine similarity is a normed dot product + query_embedding /= np.linalg.norm(x=query_embedding, axis=1, keepdims=True) + document_embeddings /= np.linalg.norm(x=document_embeddings, axis=1, keepdims=True) + + try: + scores = np.dot(a=query_embedding, b=document_embeddings.T)[0].tolist() + except ValueError as e: + if "shapes" in str(e) and "not aligned" in str(e): + raise DocumentStoreError( + "The embedding size of the query should be the same as the embedding size of the Documents. " + "Please make sure that the query has been embedded with the same model as the Documents." + ) from e + raise e + + if scale_score: + if self.embedding_similarity_function == "dot_product": + scores = [expit(float(score / DOT_PRODUCT_SCALING_FACTOR)) for score in scores] + elif self.embedding_similarity_function == "cosine": + scores = [(score + 1) / 2 for score in scores] + + return scores diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/types/__init__.py b/testbed/deepset-ai__haystack/haystack/document_stores/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6becf8b41f2075c68bf5d8827452bea3d2587c --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/types/__init__.py @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .filter_policy import FilterPolicy, apply_filter_policy +from .policy import DuplicatePolicy +from .protocol import DocumentStore + +__all__ = ["apply_filter_policy", "DocumentStore", "DuplicatePolicy", "FilterPolicy"] diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/types/filter_policy.py b/testbed/deepset-ai__haystack/haystack/document_stores/types/filter_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b0dc58d89563a02211a8e25db17df8f4e4de024c --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/types/filter_policy.py @@ -0,0 +1,319 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum +from typing import Any, Dict, Literal, Optional + +from haystack import logging + +logger = logging.getLogger(__name__) + + +class FilterPolicy(Enum): + """ + Policy to determine how filters are applied in retrievers interacting with document stores. + """ + + # Runtime filters replace init filters during retriever run invocation. + REPLACE = "replace" + + # Runtime filters are merged with init filters, with runtime filters overwriting init values. + MERGE = "merge" + + def __str__(self): + return self.value + + @staticmethod + def from_str(filter_policy: str) -> "FilterPolicy": + """ + Convert a string to a FilterPolicy enum. + + :param filter_policy: The string to convert. + :return: The corresponding FilterPolicy enum. + """ + enum_map = {e.value.lower(): e for e in FilterPolicy} + policy = enum_map.get(filter_policy.lower() if filter_policy else "") + if policy is None: + msg = f"Unknown FilterPolicy type '{filter_policy}'. Supported types are: {list(enum_map.keys())}" + raise ValueError(msg) + return policy + + +def is_comparison_filter(filter_item: Dict[str, Any]) -> bool: + """ + Check if the given filter is a comparison filter. + + :param filter_item: The filter to check. + :returns: True if the filter is a comparison filter, False otherwise. + """ + return all(key in filter_item for key in ["field", "operator", "value"]) + + +def is_logical_filter(filter_item: Dict[str, Any]) -> bool: + """ + Check if the given filter is a logical filter. + + :param filter_item: The filter to check. + :returns: True if the filter is a logical filter, False otherwise. + """ + return "operator" in filter_item and "conditions" in filter_item + + +def combine_two_logical_filters( + init_logical_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any] +) -> Dict[str, Any]: + """ + Combine two logical filters, they must have the same operator. + + If `init_logical_filter["operator"]` and `runtime_logical_filter["operator"]` are the same, the conditions + of both filters are combined. Otherwise, the `init_logical_filter` is ignored and ` + runtime_logical_filter` is returned. + + __Example__: + + ```python + init_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + runtime_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ] + } + new_filters = combine_two_logical_filters( + init_logical_filter, runtime_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ] + } + ``` + """ + if init_logical_filter["operator"] == runtime_logical_filter["operator"]: + return { + "operator": str(init_logical_filter["operator"]), + "conditions": init_logical_filter["conditions"] + runtime_logical_filter["conditions"], + } + + logger.warning( + "The provided logical operators, {parsed_operator} and {operator}, do not match so the parsed logical " + "filter, {init_logical_filter}, will be ignored and only the provided logical filter,{runtime_logical_filter}, " + "will be used. Update the logical operators to match to include the parsed filter.", + parsed_operator=init_logical_filter["operator"], + operator=runtime_logical_filter["operator"], + init_logical_filter=init_logical_filter, + runtime_logical_filter=runtime_logical_filter, + ) + runtime_logical_filter["operator"] = str(runtime_logical_filter["operator"]) + return runtime_logical_filter + + +def combine_init_comparison_and_runtime_logical_filters( + init_comparison_filter: Dict[str, Any], + runtime_logical_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine a runtime logical filter with the init comparison filter using the provided logical_operator. + + We only add the init_comparison_filter if logical_operator matches the existing + runtime_logical_filter["operator"]. Otherwise, we return the runtime_logical_filter unchanged. + + __Example__: + + ```python + runtime_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + new_filters = combine_init_comparison_and_runtime_logical_filters( + init_comparison_filter, runtime_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if runtime_logical_filter["operator"] == logical_operator: + conditions = runtime_logical_filter["conditions"] + fields = {c.get("field") for c in conditions} + if init_comparison_filter["field"] not in fields: + conditions.append(init_comparison_filter) + else: + logger.warning( + "The init filter, {init_filter}, is ignored as the field is already present in the existing " + "filters, {filters}.", + init_filter=init_comparison_filter, + filters=runtime_logical_filter, + ) + return {"operator": str(runtime_logical_filter["operator"]), "conditions": conditions} + + logger.warning( + "The provided logical_operator, {logical_operator}, does not match the logical operator found in " + "the runtime filters, {filters_logical_operator}, so the init filter will be ignored.", + logical_operator=logical_operator, + filters_logical_operator=runtime_logical_filter["operator"], + ) + runtime_logical_filter["operator"] = str(runtime_logical_filter["operator"]) + return runtime_logical_filter + + +def combine_runtime_comparison_and_init_logical_filters( + runtime_comparison_filter: Dict[str, Any], + init_logical_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine an init logical filter with the runtime comparison filter using the provided logical_operator. + + We only add the runtime_comparison_filter if logical_operator matches the existing + init_logical_filter["operator"]. Otherwise, we return the runtime_comparison_filter unchanged. + + __Example__: + + ```python + init_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + runtime_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + new_filters = combine_runtime_comparison_and_init_logical_filters( + runtime_comparison_filter, init_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if init_logical_filter["operator"] == logical_operator: + conditions = init_logical_filter["conditions"] + fields = {c.get("field") for c in conditions} + if runtime_comparison_filter["field"] in fields: + logger.warning( + "The runtime filter, {runtime_filter}, will overwrite the existing filter with the same " + "field in the init logical filter.", + runtime_filter=runtime_comparison_filter, + ) + conditions = [c for c in conditions if c.get("field") != runtime_comparison_filter["field"]] + conditions.append(runtime_comparison_filter) + return {"operator": str(init_logical_filter["operator"]), "conditions": conditions} + + logger.warning( + "The provided logical_operator, {logical_operator}, does not match the logical operator found in " + "the init logical filter, {filters_logical_operator}, so the init logical filter will be ignored.", + logical_operator=logical_operator, + filters_logical_operator=init_logical_filter["operator"], + ) + return runtime_comparison_filter + + +def combine_two_comparison_filters( + init_comparison_filter: Dict[str, Any], + runtime_comparison_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine a comparison filter with the `init_comparison_filter` using the provided `logical_operator`. + + If `runtime_comparison_filter` and `init_comparison_filter` target the same field, `init_comparison_filter` + is ignored and `runtime_comparison_filter` is returned unchanged. + + __Example__: + + ```python + runtime_comparison_filter = {"field": "meta.type", "operator": "==", "value": "article"}, + init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + new_filters = combine_two_comparison_filters( + init_comparison_filter, runtime_comparison_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if runtime_comparison_filter["field"] == init_comparison_filter["field"]: + logger.warning( + "The parsed filter, {parsed_filter}, is ignored as the field is already present in the existing " + "filters, {filters}.", + parsed_filter=init_comparison_filter, + filters=runtime_comparison_filter, + ) + return runtime_comparison_filter + + return {"operator": str(logical_operator), "conditions": [init_comparison_filter, runtime_comparison_filter]} + + +def apply_filter_policy( + filter_policy: FilterPolicy, + init_filters: Optional[Dict[str, Any]] = None, + runtime_filters: Optional[Dict[str, Any]] = None, + default_logical_operator: Literal["AND", "OR", "NOT"] = "AND", +) -> Optional[Dict[str, Any]]: + """ + Apply the filter policy to the given initial and runtime filters to determine the final set of filters used. + + The function combines or replaces the initial and runtime filters based on the specified filter policy. + + :param filter_policy: The policy to apply when handling the filters. It can be one of the following: + - `FilterPolicy.REPLACE`: Runtime filters will replace the initial filters. + - `FilterPolicy.MERGE`: Runtime filters will be merged with the initial filters. If there are overlapping keys, + values from the runtime filters will overwrite those from the initial filters. + :param init_filters: The initial filters set during the initialization of the relevant retriever. + :param runtime_filters: The filters provided at runtime, usually during a query operation execution. These filters + can change for each query/retriever run invocation. + :param default_logical_operator: The default logical operator to use when merging filters (non-legacy filters only). + :returns: A dictionary containing the resulting filters based on the provided policy. + """ + if filter_policy == FilterPolicy.MERGE and runtime_filters and init_filters: + # now we merge filters + if is_comparison_filter(init_filters) and is_comparison_filter(runtime_filters): + return combine_two_comparison_filters(init_filters, runtime_filters, default_logical_operator) + elif is_comparison_filter(init_filters) and is_logical_filter(runtime_filters): + return combine_init_comparison_and_runtime_logical_filters( + init_filters, runtime_filters, default_logical_operator + ) + elif is_logical_filter(init_filters) and is_comparison_filter(runtime_filters): + return combine_runtime_comparison_and_init_logical_filters( + runtime_filters, init_filters, default_logical_operator + ) + elif is_logical_filter(init_filters) and is_logical_filter(runtime_filters): + return combine_two_logical_filters(init_filters, runtime_filters) + + return runtime_filters or init_filters diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/types/policy.py b/testbed/deepset-ai__haystack/haystack/document_stores/types/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d392b4914bc63bfae97114494e8385880c5fdb6f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/types/policy.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from enum import Enum + + +class DuplicatePolicy(Enum): + NONE = "none" + SKIP = "skip" + OVERWRITE = "overwrite" + FAIL = "fail" diff --git a/testbed/deepset-ai__haystack/haystack/document_stores/types/protocol.py b/testbed/deepset-ai__haystack/haystack/document_stores/types/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ad3062cf857c462327fc9b61e308f65ba90bdf --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/document_stores/types/protocol.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Protocol + +from haystack import logging +from haystack.dataclasses import Document +from haystack.document_stores.types.policy import DuplicatePolicy + +# Ellipsis are needed for the type checker, it's safe to disable module-wide +# pylint: disable=unnecessary-ellipsis + +logger = logging.getLogger(__name__) + + +class DocumentStore(Protocol): + """ + Stores Documents to be used by the components of a Pipeline. + + Classes implementing this protocol often store the documents permanently and allow specialized components to + perform retrieval on them, either by embedding, by keyword, hybrid, and so on, depending on the backend used. + + In order to retrieve documents, consider using a Retriever that supports the DocumentStore implementation that + you're using. + """ + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes this store to a dictionary. + """ + ... + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentStore": + """ + Deserializes the store from a dictionary. + """ + ... + + def count_documents(self) -> int: + """ + Returns the number of documents stored. + """ + ... + + def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]: + """ + Returns the documents that match the filters provided. + + Filters are defined as nested dictionaries that can be of two types: + - Comparison + - Logic + + Comparison dictionaries must contain the keys: + + - `field` + - `operator` + - `value` + + Logic dictionaries must contain the keys: + + - `operator` + - `conditions` + + The `conditions` key must be a list of dictionaries, either of type Comparison or Logic. + + The `operator` value in Comparison dictionaries must be one of: + + - `==` + - `!=` + - `>` + - `>=` + - `<` + - `<=` + - `in` + - `not in` + + The `operator` values in Logic dictionaries must be one of: + + - `NOT` + - `OR` + - `AND` + + + A simple filter: + ```python + filters = {"field": "meta.type", "operator": "==", "value": "article"} + ``` + + A more complex filter: + ```python + filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.date", "operator": ">=", "value": 1420066800}, + {"field": "meta.date", "operator": "<", "value": 1609455600}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + { + "operator": "OR", + "conditions": [ + {"field": "meta.genre", "operator": "in", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + }, + ], + } + + :param filters: the filters to apply to the document list. + :returns: a list of Documents that match the given filters. + """ + ... + + def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int: + """ + Writes Documents into the DocumentStore. + + :param documents: a list of Document objects. + :param policy: the policy to apply when a Document with the same id already exists in the DocumentStore. + - `DuplicatePolicy.NONE`: Default policy, behaviour depends on the Document Store. + - `DuplicatePolicy.SKIP`: If a Document with the same id already exists, it is skipped and not written. + - `DuplicatePolicy.OVERWRITE`: If a Document with the same id already exists, it is overwritten. + - `DuplicatePolicy.FAIL`: If a Document with the same id already exists, an error is raised. + :raises DuplicateError: If `policy` is set to `DuplicatePolicy.FAIL` and a Document with the same id already + exists. + :returns: The number of Documents written. + If `DuplicatePolicy.OVERWRITE` is used, this number is always equal to the number of documents in input. + If `DuplicatePolicy.SKIP` is used, this number can be lower than the number of documents in the input list. + """ + ... + + def delete_documents(self, document_ids: List[str]) -> None: + """ + Deletes all documents with a matching document_ids from the DocumentStore. + + Fails with `MissingDocumentError` if no document with this id is present in the DocumentStore. + + :param document_ids: the object_ids to delete + """ + ... diff --git a/testbed/deepset-ai__haystack/haystack/errors.py b/testbed/deepset-ai__haystack/haystack/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..e18cb8d5ab9ef8ad0c4ccde660af4853c0b6b664 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/errors.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +class FilterError(Exception): + pass diff --git a/testbed/deepset-ai__haystack/haystack/evaluation/__init__.py b/testbed/deepset-ai__haystack/haystack/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..734699a03f2ca779a68e9ea8c8baae406b242d75 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/evaluation/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .base import BaseEvaluationRunResult +from .eval_run_result import EvaluationRunResult + +__all__ = ["BaseEvaluationRunResult", "EvaluationRunResult"] diff --git a/testbed/deepset-ai__haystack/haystack/evaluation/base.py b/testbed/deepset-ai__haystack/haystack/evaluation/base.py new file mode 100644 index 0000000000000000000000000000000000000000..617fa176381df53468e04dba85d75ee5f0237e70 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/evaluation/base.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from abc import ABC, abstractmethod +from typing import List, Optional + +from pandas import DataFrame + + +class BaseEvaluationRunResult(ABC): + """ + Represents the results of an evaluation run. + """ + + @abstractmethod + def to_pandas(self) -> "DataFrame": + """ + Creates a Pandas DataFrame containing the scores of each metric for every input sample. + + :returns: + Pandas DataFrame with the scores. + """ + + @abstractmethod + def score_report(self) -> "DataFrame": + """ + Transforms the results into a Pandas DataFrame with the aggregated scores for each metric. + + :returns: + Pandas DataFrame with the aggregated scores. + """ + + @abstractmethod + def comparative_individual_scores_report( + self, other: "BaseEvaluationRunResult", keep_columns: Optional[List[str]] = None + ) -> "DataFrame": + """ + Creates a Pandas DataFrame with the scores for each metric in the results of two different evaluation runs. + + The inputs to both evaluation runs is assumed to be the same. + + :param other: + Results of another evaluation run to compare with. + :param keep_columns: + List of common column names to keep from the inputs of the evaluation runs to compare. + :returns: + Pandas DataFrame with the score comparison. + """ diff --git a/testbed/deepset-ai__haystack/haystack/evaluation/eval_run_result.py b/testbed/deepset-ai__haystack/haystack/evaluation/eval_run_result.py new file mode 100644 index 0000000000000000000000000000000000000000..1d04419ebe38fbd4aa8c115618a212dce13dc0ce --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/evaluation/eval_run_result.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Dict, List, Optional +from warnings import warn + +from pandas import DataFrame +from pandas import concat as pd_concat + +from .base import BaseEvaluationRunResult + + +class EvaluationRunResult(BaseEvaluationRunResult): + """ + Contains the inputs and the outputs of an evaluation pipeline and provides methods to inspect them. + """ + + def __init__(self, run_name: str, inputs: Dict[str, List[Any]], results: Dict[str, Dict[str, Any]]): + """ + Initialize a new evaluation run result. + + :param run_name: + Name of the evaluation run. + :param inputs: + Dictionary containing the inputs used for the run. + Each key is the name of the input and its value is + a list of input values. The length of the lists should + be the same. + :param results: + Dictionary containing the results of the evaluators + used in the evaluation pipeline. Each key is the name + of the metric and its value is dictionary with the following + keys: + - 'score': The aggregated score for the metric. + - 'individual_scores': A list of scores for each input sample. + """ + self.run_name = run_name + self.inputs = deepcopy(inputs) + self.results = deepcopy(results) + + if len(inputs) == 0: + raise ValueError("No inputs provided.") + if len({len(l) for l in inputs.values()}) != 1: + raise ValueError("Lengths of the inputs should be the same.") + + expected_len = len(next(iter(inputs.values()))) + + for metric, outputs in results.items(): + if "score" not in outputs: + raise ValueError(f"Aggregate score missing for {metric}.") + if "individual_scores" not in outputs: + raise ValueError(f"Individual scores missing for {metric}.") + + if len(outputs["individual_scores"]) != expected_len: + raise ValueError( + f"Length of individual scores for '{metric}' should be the same as the inputs. " + f"Got {len(outputs['individual_scores'])} but expected {expected_len}." + ) + + def score_report(self) -> DataFrame: + """ + Transforms the results into a Pandas DataFrame with the aggregated scores for each metric. + + :returns: + Pandas DataFrame with the aggregated scores. + """ + results = {k: v["score"] for k, v in self.results.items()} + df = DataFrame.from_dict(results, orient="index", columns=["score"]).reset_index() + df.columns = ["metrics", "score"] + return df + + def to_pandas(self) -> DataFrame: + """ + Creates a Pandas DataFrame containing the scores of each metric for every input sample. + + :returns: + Pandas DataFrame with the scores. + """ + inputs_columns = list(self.inputs.keys()) + inputs_values = list(self.inputs.values()) + inputs_values = list(map(list, zip(*inputs_values))) # transpose the values + df_inputs = DataFrame(inputs_values, columns=inputs_columns) + + scores_columns = list(self.results.keys()) + scores_values = [v["individual_scores"] for v in self.results.values()] + scores_values = list(map(list, zip(*scores_values))) # transpose the values + df_scores = DataFrame(scores_values, columns=scores_columns) + + return df_inputs.join(df_scores) + + def comparative_individual_scores_report( + self, other: "BaseEvaluationRunResult", keep_columns: Optional[List[str]] = None + ) -> DataFrame: + """ + Creates a Pandas DataFrame with the scores for each metric in the results of two different evaluation runs. + + The inputs to both evaluation runs is assumed to be the same. + + :param other: + Results of another evaluation run to compare with. + :param keep_columns: + List of common column names to keep from the inputs of the evaluation runs to compare. + :returns: + Pandas DataFrame with the score comparison. + """ + if not isinstance(other, EvaluationRunResult): + raise ValueError("Comparative scores can only be computed between EvaluationRunResults.") + + this_name = self.run_name + other_name = other.run_name + if this_name == other_name: + warn(f"The run names of the two evaluation results are the same ('{this_name}')") + this_name = f"{this_name}_first" + other_name = f"{other_name}_second" + + if self.inputs.keys() != other.inputs.keys(): + warn(f"The input columns differ between the results; using the input columns of '{this_name}'.") + + pipe_a_df = self.to_pandas() + pipe_b_df = other.to_pandas() + + if keep_columns is None: + ignore = list(self.inputs.keys()) + else: + ignore = [col for col in list(self.inputs.keys()) if col not in keep_columns] + + pipe_b_df.drop(columns=ignore, inplace=True, errors="ignore") + pipe_b_df.columns = [f"{other_name}_{column}" for column in pipe_b_df.columns] # type: ignore + pipe_a_df.columns = [f"{this_name}_{col}" if col not in ignore else col for col in pipe_a_df.columns] # type: ignore + + results_df = pd_concat([pipe_a_df, pipe_b_df], axis=1) + + return results_df diff --git a/testbed/deepset-ai__haystack/haystack/lazy_imports.py b/testbed/deepset-ai__haystack/haystack/lazy_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a2688fb624c015e0438584497ab701a6e35560a1 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/lazy_imports.py @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from types import TracebackType +from typing import Optional, Type + +from lazy_imports.try_import import _DeferredImportExceptionContextManager + +DEFAULT_IMPORT_ERROR_MSG = "Try 'pip install {}'" + + +class LazyImport(_DeferredImportExceptionContextManager): + """ + Wrapper on top of lazy_import's _DeferredImportExceptionContextManager. + + It adds the possibility to customize the error messages. + """ + + def __init__(self, message: str = DEFAULT_IMPORT_ERROR_MSG) -> None: + super().__init__() + self.import_error_msg = message + + def __exit__( + self, exc_type: Optional[Type[Exception]], exc_value: Optional[Exception], traceback: Optional[TracebackType] + ) -> Optional[bool]: + """ + Exit the context manager. + + Args: + exc_type: + Raised exception type. :obj:`None` if nothing is raised. + exc_value: + Raised exception object. :obj:`None` if nothing is raised. + traceback: + Associated traceback. :obj:`None` if nothing is raised. + + Returns: + :obj:`None` if nothing is deferred, otherwise :obj:`True`. + :obj:`True` will suppress any exceptions avoiding them from propagating. + + """ + if isinstance(exc_value, ImportError): + message = ( + f"Failed to import '{exc_value.name}'. {self.import_error_msg.format(exc_value.name)}. " + f"Original error: {exc_value}" + ) + self._deferred = (exc_value, message) + return True + return None diff --git a/testbed/deepset-ai__haystack/haystack/logging.py b/testbed/deepset-ai__haystack/haystack/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0149a032b362813d3337fe8f66a109402656a7 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/logging.py @@ -0,0 +1,393 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import builtins +import functools +import logging +import os +import sys +import typing +from typing import Any, List, Optional + +if typing.TYPE_CHECKING: + from structlog.typing import EventDict, Processor, WrappedLogger + +HAYSTACK_LOGGING_USE_JSON_ENV_VAR = "HAYSTACK_LOGGING_USE_JSON" +HAYSTACK_LOGGING_IGNORE_STRUCTLOG_ENV_VAR = "HAYSTACK_LOGGING_IGNORE_STRUCTLOG" + + +class PatchedLogger(typing.Protocol): + """Class which enables using type checkers to find wrong logger usage.""" + + def debug( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log a debug message.""" + + def info( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log an info message.""" + + def warn( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log a warning message.""" + + def warning( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log a warning message.""" + + def error( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log an error message.""" + + def critical( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log a critical message.""" + + def exception( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log an exception message.""" + + def fatal( + self, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log a fatal message.""" + + def log( + self, + level: int, + msg: str, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, + ) -> None: + """Log a message.""" + + def setLevel(self, level: int) -> None: + """Set the logging level.""" + + +def patch_log_method_to_kwargs_only(func: typing.Callable) -> typing.Callable: + """A decorator to make sure that a function is only called with keyword arguments.""" + + @functools.wraps(func) + def _log_only_with_kwargs( + msg, *, _: Any = None, exc_info: Any = None, stack_info: Any = False, stacklevel: int = 1, **kwargs: Any + ) -> Any: # we need the `_` to avoid a syntax error + existing_extra = kwargs.pop("extra", {}) + return func( + # we need to increase the stacklevel by 1 to point to the correct caller + # (otherwise it points to this function) + msg, + exc_info=exc_info, + stack_info=stack_info, + stacklevel=stacklevel + 1, + extra={**existing_extra, **kwargs}, + ) + + return _log_only_with_kwargs + + +def patch_log_with_level_method_to_kwargs_only(func: typing.Callable) -> typing.Callable: + """A decorator to make sure that a function is only called with keyword arguments.""" + + @functools.wraps(func) + def _log_only_with_kwargs( + level, + msg, + *, + _: Any = None, + exc_info: Any = None, + stack_info: Any = False, + stacklevel: int = 1, + **kwargs: Any, # we need the `_` to avoid a syntax error + ) -> Any: + existing_extra = kwargs.pop("extra", {}) + + return func( + level, + msg, + exc_info=exc_info, + stack_info=stack_info, + # we need to increase the stacklevel by 1 to point to the correct caller + # (otherwise it points to this function) + stacklevel=stacklevel + 1, + extra={**existing_extra, **kwargs}, + ) + + return _log_only_with_kwargs + + +def patch_make_records_to_use_kwarg_string_interpolation(original_make_records: typing.Callable) -> typing.Callable: + """A decorator to ensure string interpolation is used.""" + + @functools.wraps(original_make_records) + def _wrapper(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None) -> Any: + safe_extra = extra or {} + try: + interpolated_msg = msg.format(**safe_extra) + except (KeyError, ValueError): + interpolated_msg = msg + return original_make_records(name, level, fn, lno, interpolated_msg, (), exc_info, func, extra, sinfo) + + return _wrapper + + +def _patch_structlog_call_information(logger: logging.Logger) -> None: + # structlog patches the findCaller to hide itself from the traceback. + # We need to patch their patch to hide `haystack.logging` from the traceback. + try: + from structlog._frames import _find_first_app_frame_and_name, _format_stack + from structlog.stdlib import _FixedFindCallerLogger + + if not isinstance(logger, _FixedFindCallerLogger): + return + + # completely copied from structlog. We only add `haystack.logging` to the list of ignored frames + # pylint: disable=unused-variable + def findCaller(stack_info: bool = False, stacklevel: int = 1) -> typing.Tuple[str, int, str, Optional[str]]: + try: + sinfo: Optional[str] + # we need to exclude `haystack.logging` from the stack + f, name = _find_first_app_frame_and_name(["logging", "haystack.logging"]) + sinfo = _format_stack(f) if stack_info else None + except Exception as error: + print(f"Error in findCaller: {error}") + + return f.f_code.co_filename, f.f_lineno, f.f_code.co_name, sinfo + + logger.findCaller = findCaller # type: ignore + except ImportError: + pass + + +def getLogger(name: str) -> PatchedLogger: + """ + Get the Haystack logger, a patched version of the one from the standard library. + + We patch the default logger methods to make sure that they are only called with keyword arguments. + We enforce keyword-arguments because + - it brings in consistency + - it makes structure logging effective, not just an available feature + """ + logger = logging.getLogger(name) + logger.debug = patch_log_method_to_kwargs_only(logger.debug) # type: ignore + logger.info = patch_log_method_to_kwargs_only(logger.info) # type: ignore + logger.warn = patch_log_method_to_kwargs_only(logger.warn) # type: ignore + logger.warning = patch_log_method_to_kwargs_only(logger.warning) # type: ignore + logger.error = patch_log_method_to_kwargs_only(logger.error) # type: ignore + logger.critical = patch_log_method_to_kwargs_only(logger.critical) # type: ignore + logger.exception = patch_log_method_to_kwargs_only(logger.exception) # type: ignore + logger.fatal = patch_log_method_to_kwargs_only(logger.fatal) # type: ignore + logger.log = patch_log_with_level_method_to_kwargs_only(logger.log) # type: ignore + + _patch_structlog_call_information(logger) + + # We also patch the `makeRecord` method to use keyword string interpolation + logger.makeRecord = patch_make_records_to_use_kwarg_string_interpolation(logger.makeRecord) # type: ignore + + return typing.cast(PatchedLogger, logger) + + +def add_line_and_file(_: "WrappedLogger", __: str, event_dict: "EventDict") -> "EventDict": + """Add line and file to log entries.""" + stdlib_record = event_dict.get("_record") + if not stdlib_record: + return event_dict + + event_dict["lineno"] = stdlib_record.lineno + event_dict["module"] = stdlib_record.name + + return event_dict + + +def correlate_logs_with_traces(_: "WrappedLogger", __: str, event_dict: "EventDict") -> "EventDict": + """ + Add correlation data for logs. + + This is useful if you want to correlate logs with traces. + """ + import haystack.tracing.tracer # to avoid circular imports + + if not haystack.tracing.is_tracing_enabled(): + return event_dict + + current_span = haystack.tracing.tracer.current_span() + if current_span: + event_dict.update(current_span.get_correlation_data_for_logs()) + + return event_dict + + +def configure_logging(use_json: Optional[bool] = None) -> None: + """ + Configure logging for Haystack. + + - If `structlog` is not installed, we keep everything as it is. The user is responsible for configuring logging + themselves. + - If `structlog` is installed, we configure it to format log entries including its key-value data. To disable this + behavior set the environment variable `HAYSTACK_LOGGING_IGNORE_STRUCTLOG` to `true`. + - If `structlog` is installed, you can JSON format all logs. Enable this by + - setting the `use_json` parameter to `True` when calling this function + - setting the environment variable `HAYSTACK_LOGGING_USE_JSON` to `true` + """ + import haystack.utils.jupyter # to avoid circular imports + + try: + import structlog + from structlog.processors import ExceptionRenderer + from structlog.tracebacks import ExceptionDictTransformer + + except ImportError: + # structlog is not installed - fall back to standard logging + return + + if os.getenv(HAYSTACK_LOGGING_IGNORE_STRUCTLOG_ENV_VAR, "false").lower() == "true": + # If the user wants to ignore structlog, we don't configure it and fall back to standard logging + return + + # We roughly follow the structlog documentation here: + # https://www.structlog.org/en/stable/standard-library.html#rendering-using-structlog-based-formatters-within-logging + # This means that we use structlog to format the log entries for entries emitted via `logging` and `structlog`. + + if use_json is None: # explicit parameter takes precedence over everything else + use_json_env_var = os.getenv(HAYSTACK_LOGGING_USE_JSON_ENV_VAR) + if use_json_env_var is None: + # We try to guess if we are in an interactive terminal or not + interactive_terminal = ( + sys.stderr.isatty() or hasattr(builtins, "__IPYTHON__") or haystack.utils.jupyter.is_in_jupyter() + ) + use_json = not interactive_terminal + else: + # User gave us an explicit value via environment variable + use_json = use_json_env_var.lower() == "true" + + shared_processors: List[Processor] = [ + # Add the log level to the event_dict for structlog to use + structlog.stdlib.add_log_level, + # Adds the current timestamp in ISO format to logs + structlog.processors.TimeStamper(fmt="iso"), + structlog.contextvars.merge_contextvars, + add_line_and_file, + ] + + if use_json: + # We only need that in sophisticated production setups where we want to correlate logs with traces + shared_processors.append(correlate_logs_with_traces) + + structlog.configure( + processors=shared_processors + [structlog.stdlib.ProcessorFormatter.wrap_for_formatter], + logger_factory=structlog.stdlib.LoggerFactory(ignore_frame_names=["haystack.logging"]), + cache_logger_on_first_use=True, + # This is a filter that will filter out log entries that are below the log level of the root logger. + wrapper_class=structlog.make_filtering_bound_logger(min_level=logging.root.getEffectiveLevel()), + ) + + renderers: List[Processor] + if use_json: + renderers = [ + ExceptionRenderer( + # don't show locals in production logs - this can be quite sensitive information + ExceptionDictTransformer(show_locals=False) + ), + structlog.processors.JSONRenderer(), + ] + else: + renderers = [structlog.dev.ConsoleRenderer()] + + formatter = structlog.stdlib.ProcessorFormatter( + # These run ONLY on `logging` entries that do NOT originate within + # structlog. + foreign_pre_chain=shared_processors + + [ + # Add the information from the `logging` `extras` to the event dictionary + structlog.stdlib.ExtraAdder() + ], + # These run on ALL entries after the pre_chain is done. + processors=[ + # Remove _record & _from_structlog. to avoid that this metadata is added to the final log record + structlog.stdlib.ProcessorFormatter.remove_processors_meta, + *renderers, + ], + ) + + handler = logging.StreamHandler() + handler.name = "HaystackLoggingHandler" + # Use OUR `ProcessorFormatter` to format all `logging` entries. + handler.setFormatter(formatter) + + root_logger = logging.getLogger() + # avoid adding our handler twice + old_handlers = [ + h + for h in root_logger.handlers + if not (isinstance(h, logging.StreamHandler) and h.name == "HaystackLoggingHandler") + ] + new_handlers = [handler, *old_handlers] + root_logger.handlers = new_handlers diff --git a/testbed/deepset-ai__haystack/haystack/marshal/__init__.py b/testbed/deepset-ai__haystack/haystack/marshal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f52f1aa598cfa8121738db47605d60a33403bb1 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/marshal/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.marshal.protocol import Marshaller +from haystack.marshal.yaml import YamlMarshaller + +__all__ = ["Marshaller", "YamlMarshaller"] diff --git a/testbed/deepset-ai__haystack/haystack/marshal/protocol.py b/testbed/deepset-ai__haystack/haystack/marshal/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..657f3cd67d19429105cd8def1acee19ed38159d4 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/marshal/protocol.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, Protocol, Union + +# Ellipsis are needed for the type checker, it's safe to disable module-wide +# pylint: disable=unnecessary-ellipsis + + +class Marshaller(Protocol): + def marshal(self, dict_: Dict[str, Any]) -> str: + "Convert a dictionary to its string representation" + ... + + def unmarshal(self, data_: Union[str, bytes, bytearray]) -> Dict[str, Any]: + """Convert a marshalled object to its dictionary representation""" + ... diff --git a/testbed/deepset-ai__haystack/haystack/marshal/yaml.py b/testbed/deepset-ai__haystack/haystack/marshal/yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..615cd1916a9838d700fac279744decd1d12c795e --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/marshal/yaml.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, Union + +import yaml + + +# Custom YAML safe loader that supports loading Python tuples +class YamlLoader(yaml.SafeLoader): # pylint: disable=too-many-ancestors + def construct_python_tuple(self, node: yaml.SequenceNode): + """Construct a Python tuple from the sequence.""" + return tuple(self.construct_sequence(node)) + + +class YamlDumper(yaml.SafeDumper): # pylint: disable=too-many-ancestors + def represent_tuple(self, data: tuple): + """Represent a Python tuple.""" + return self.represent_sequence("tag:yaml.org,2002:python/tuple", data) + + +YamlDumper.add_representer(tuple, YamlDumper.represent_tuple) +YamlLoader.add_constructor("tag:yaml.org,2002:python/tuple", YamlLoader.construct_python_tuple) + + +class YamlMarshaller: + def marshal(self, dict_: Dict[str, Any]) -> str: + """Return a YAML representation of the given dictionary.""" + try: + return yaml.dump(dict_, Dumper=YamlDumper) + except yaml.representer.RepresenterError as e: + raise TypeError( + "Error dumping pipeline to YAML - Ensure that all pipeline " + "components only serialize basic Python types" + ) from e + + def unmarshal(self, data_: Union[str, bytes, bytearray]) -> Dict[str, Any]: + """Return a dictionary from the given YAML data.""" + try: + return yaml.load(data_, Loader=YamlLoader) + except yaml.constructor.ConstructorError as e: + raise TypeError( + "Error loading pipeline from YAML - Ensure that all pipeline " + "components only serialize basic Python types" + ) from e diff --git a/testbed/deepset-ai__haystack/haystack/telemetry/__init__.py b/testbed/deepset-ai__haystack/haystack/telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa29de4d15cac65e6bc9c19146d3d9088b78385 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/telemetry/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.telemetry._telemetry import pipeline_running, tutorial_running diff --git a/testbed/deepset-ai__haystack/haystack/telemetry/_environment.py b/testbed/deepset-ai__haystack/haystack/telemetry/_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c92b9e45da1374b1cc35143d81c3cfe0e43f94 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/telemetry/_environment.py @@ -0,0 +1,114 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +import platform +import sys +from typing import Any, Dict, Optional + +from haystack import logging +from haystack.version import __version__ + +logger = logging.getLogger(__name__) + +# This value cannot change during the lifetime of the process +_IS_DOCKER_CACHE = None + + +def _in_podman() -> bool: + """ + Check if the code is running in a Podman container. + + Podman run would create the file /run/.containernv, see: + https://github.com/containers/podman/blob/main/docs/source/markdown/podman-run.1.md.in#L31 + """ + return os.path.exists("/run/.containerenv") + + +def _has_dockerenv() -> bool: + """ + Check if the code is running in a Docker container. + + This might not work anymore at some point (even if it's been a while now), see: + https://github.com/moby/moby/issues/18355#issuecomment-220484748 + """ + return os.path.exists("/.dockerenv") + + +def _has_docker_cgroup_v1() -> bool: + """ + This only works with cgroups v1. + """ + path = "/proc/self/cgroup" # 'self' should be always symlinked to the actual PID + return os.path.isfile(path) and any("docker" in line for line in open(path)) + + +def _has_docker_cgroup_v2() -> bool: + """ + Check if the code is running in a Docker container using the cgroups v2 version. + + inspired from: https://github.com/jenkinsci/docker-workflow-plugin/blob/master/src/main/java/org/jenkinsci/plugins/docker/workflow/client/DockerClient.java + """ + path = "/proc/self/mountinfo" # 'self' should be always symlinked to the actual PID + return os.path.isfile(path) and any("/docker/containers/" in line for line in open(path)) + + +def _is_containerized() -> Optional[bool]: + """ + This code is based on the popular 'is-docker' package for node.js + """ + global _IS_DOCKER_CACHE # pylint: disable=global-statement + + if _IS_DOCKER_CACHE is None: + _IS_DOCKER_CACHE = _in_podman() or _has_dockerenv() or _has_docker_cgroup_v1() or _has_docker_cgroup_v2() + + return _IS_DOCKER_CACHE + + +def collect_system_specs() -> Dict[str, Any]: + """ + Collects meta-data about the setup that is used with Haystack. + + Data collected includes: operating system, python version, Haystack version, transformers version, + pytorch version, number of GPUs, execution environment. + + These values are highly unlikely to change during the runtime of the pipeline, + so they're collected only once. + """ + specs = { + "libraries.haystack": __version__, + "os.containerized": _is_containerized(), + "os.version": platform.release(), + "os.family": platform.system(), + "os.machine": platform.machine(), + "python.version": platform.python_version(), + "hardware.cpus": os.cpu_count(), + "hardware.gpus": 0, + "libraries.transformers": False, + "libraries.torch": False, + "libraries.cuda": False, + "libraries.pytest": sys.modules["pytest"].__version__ if "pytest" in sys.modules.keys() else False, + "libraries.ipython": sys.modules["ipython"].__version__ if "ipython" in sys.modules.keys() else False, + "libraries.colab": sys.modules["google.colab"].__version__ if "google.colab" in sys.modules.keys() else False, + } + + # Try to find out transformer's version + try: + import transformers + + specs["libraries.transformers"] = transformers.__version__ + except ImportError: + pass + + # Try to find out torch's version and info on potential GPU(s) + try: + import torch + + specs["libraries.torch"] = torch.__version__ + if torch.cuda.is_available(): + specs["libraries.cuda"] = torch.version.cuda + specs["libraries.gpus"] = torch.cuda.device_count() + except ImportError: + pass + return specs diff --git a/testbed/deepset-ai__haystack/haystack/telemetry/_telemetry.py b/testbed/deepset-ai__haystack/haystack/telemetry/_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cfbf269b0f8782c042b93133d734558275beda --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/telemetry/_telemetry.py @@ -0,0 +1,190 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import datetime +import logging +import os +import uuid +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +import posthog +import yaml + +from haystack import logging as haystack_logging +from haystack.core.serialization import generate_qualified_class_name +from haystack.telemetry._environment import collect_system_specs + +if TYPE_CHECKING: + from haystack.core.pipeline import Pipeline + + +HAYSTACK_TELEMETRY_ENABLED = "HAYSTACK_TELEMETRY_ENABLED" +CONFIG_PATH = Path("~/.haystack/config.yaml").expanduser() + +#: Telemetry sends at most one event every number of seconds specified in this constant +MIN_SECONDS_BETWEEN_EVENTS = 60 + + +logger = haystack_logging.getLogger(__name__) + + +class Telemetry: + """ + Haystack reports anonymous usage statistics to support continuous software improvements for all its users. + + You can opt-out of sharing usage statistics by manually setting the environment + variable `HAYSTACK_TELEMETRY_ENABLED` as described for different operating systems on the + [documentation page](https://docs.haystack.deepset.ai/docs/telemetry#how-can-i-opt-out). + + Check out the documentation for more details: [Telemetry](https://docs.haystack.deepset.ai/docs/telemetry). + """ + + def __init__(self): + """ + Initializes the telemetry. + + Loads the user_id from the config file, or creates a new id and saves it if the file is not found. + + It also collects system information which cannot change across the lifecycle + of the process (for example `is_containerized()`). + """ + posthog.api_key = "phc_C44vUK9R1J6HYVdfJarTEPqVAoRPJzMXzFcj8PIrJgP" + posthog.host = "https://eu.posthog.com" + + # disable posthog logging + for module_name in ["posthog", "backoff"]: + logging.getLogger(module_name).setLevel(logging.CRITICAL) + # Prevent module from sending errors to stderr when an exception is encountered during an emit() call + logging.getLogger(module_name).addHandler(logging.NullHandler()) + logging.getLogger(module_name).propagate = False + + self.user_id = None + + if CONFIG_PATH.exists(): + # Load the config file + try: + with open(CONFIG_PATH, "r", encoding="utf-8") as config_file: + config = yaml.safe_load(config_file) + if "user_id" in config: + self.user_id = config["user_id"] + except Exception as e: + logger.debug( + "Telemetry could not read the config file {config_path}", config_path=CONFIG_PATH, exc_info=e + ) + else: + # Create the config file + logger.info( + "Haystack sends anonymous usage data to understand the actual usage and steer dev efforts " + "towards features that are most meaningful to users. You can opt-out at anytime by manually " + "setting the environment variable HAYSTACK_TELEMETRY_ENABLED as described for different " + "operating systems in the " + "[documentation page](https://docs.haystack.deepset.ai/docs/telemetry#how-can-i-opt-out). " + "More information at [Telemetry](https://docs.haystack.deepset.ai/docs/telemetry)." + ) + CONFIG_PATH.parents[0].mkdir(parents=True, exist_ok=True) + self.user_id = str(uuid.uuid4()) + try: + with open(CONFIG_PATH, "w") as outfile: + yaml.dump({"user_id": self.user_id}, outfile, default_flow_style=False) + except Exception as e: + logger.debug( + "Telemetry could not write config file to {config_path}", config_path=CONFIG_PATH, exc_info=e + ) + + self.event_properties = collect_system_specs() + + def send_event(self, event_name: str, event_properties: Optional[Dict[str, Any]] = None): + """ + Sends a telemetry event. + + :param event_name: The name of the event to show in PostHog. + :param event_properties: Additional event metadata. These are merged with the + system metadata collected in __init__, so take care not to overwrite them. + """ + event_properties = event_properties or {} + try: + posthog.capture( + distinct_id=self.user_id, event=event_name, properties={**self.event_properties, **event_properties} + ) + except Exception as e: + logger.debug("Telemetry couldn't make a POST request to PostHog.", exc_info=e) + + +def send_telemetry(func): + """ + Decorator that sends the output of the wrapped function to PostHog. + + The wrapped function is actually called only if telemetry is enabled. + """ + + # FIXME? Somehow, functools.wraps makes `telemetry` out of scope. Let's take care of it later. + def send_telemetry_wrapper(*args, **kwargs): + try: + if telemetry: + output = func(*args, **kwargs) + if output: + telemetry.send_event(*output) + except Exception as e: + # Never let telemetry break things + logger.debug("There was an issue sending a telemetry event", exc_info=e) + + return send_telemetry_wrapper + + +@send_telemetry +def pipeline_running(pipeline: "Pipeline") -> Optional[Tuple[str, Dict[str, Any]]]: + """ + Collects telemetry data for a pipeline run and sends it to Posthog. + + Collects name, type and the content of the _telemetry_data attribute, if present, for each component in the + pipeline and sends such data to Posthog. + + :param pipeline: the pipeline that is running. + """ + pipeline._telemetry_runs += 1 + if ( + pipeline._last_telemetry_sent + and (datetime.datetime.now() - pipeline._last_telemetry_sent).seconds < MIN_SECONDS_BETWEEN_EVENTS + ): + return None + + pipeline._last_telemetry_sent = datetime.datetime.now() + + # Collect info about components + components: Dict[str, List[Dict[str, Any]]] = defaultdict(list) + for component_name, instance in pipeline.walk(): + component_qualified_class_name = generate_qualified_class_name(type(instance)) + if hasattr(instance, "_get_telemetry_data"): + telemetry_data = getattr(instance, "_get_telemetry_data")() + if not isinstance(telemetry_data, dict): + raise TypeError( + f"Telemetry data for component {component_name} must be a dictionary but is {type(telemetry_data)}." + ) + components[component_qualified_class_name].append({"name": component_name, **telemetry_data}) + else: + components[component_qualified_class_name].append({"name": component_name}) + + # Data sent to Posthog + return "Pipeline run (2.x)", { + "pipeline_id": str(id(pipeline)), + "runs": pipeline._telemetry_runs, + "components": components, + } + + +@send_telemetry +def tutorial_running(tutorial_id: str) -> Tuple[str, Dict[str, Any]]: + """ + Send a telemetry event for a tutorial, if telemetry is enabled. + + :param tutorial_id: identifier of the tutorial + """ + return "Tutorial", {"tutorial.id": tutorial_id} + + +telemetry = None +if os.getenv("HAYSTACK_TELEMETRY_ENABLED", "true").lower() in ("true", "1"): + telemetry = Telemetry() diff --git a/testbed/deepset-ai__haystack/haystack/testing/__init__.py b/testbed/deepset-ai__haystack/haystack/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/haystack/testing/document_store.py b/testbed/deepset-ai__haystack/haystack/testing/document_store.py new file mode 100644 index 0000000000000000000000000000000000000000..095a89e2a848cccd5941497cba911453c64666fb --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/document_store.py @@ -0,0 +1,1349 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import random +from datetime import datetime +from typing import List + +import pandas as pd + +from haystack.dataclasses import Document +from haystack.document_stores.errors import DuplicateDocumentError +from haystack.document_stores.types import DocumentStore, DuplicatePolicy +from haystack.errors import FilterError +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install pytest'") as pytest_import: + import pytest + + +def _random_embeddings(n): + return [random.random() for _ in range(n)] + + +# pylint: disable=too-many-public-methods + + +# These are random embedding that are used to test filters. +# We declare them here as they're used both in the `filterable_docs` fixture +# and the body of several `filter_documents` tests. +TEST_EMBEDDING_1 = _random_embeddings(768) +TEST_EMBEDDING_2 = _random_embeddings(768) + + +class AssertDocumentsEqualMixin: + def assert_documents_are_equal(self, received: List[Document], expected: List[Document]): + """ + Assert that two lists of Documents are equal. + + This is used in every test, if a Document Store implementation has a different behaviour + it should override this method. This can happen for example when the Document Store sets + a score to returned Documents. Since we can't know what the score will be, we can't compare + the Documents reliably. + """ + assert received == expected + + +class CountDocumentsTest: + """ + Utility class to test a Document Store `count_documents` method. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(CountDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_count_empty(self, document_store: DocumentStore): + """Test count is zero for an empty document store""" + assert document_store.count_documents() == 0 + + def test_count_not_empty(self, document_store: DocumentStore): + """Test count is greater than zero if the document store contains documents""" + document_store.write_documents( + [Document(content="test doc 1"), Document(content="test doc 2"), Document(content="test doc 3")] + ) + assert document_store.count_documents() == 3 + + +class WriteDocumentsTest(AssertDocumentsEqualMixin): + """ + Utility class to test a Document Store `write_documents` method. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + The Document Store `filter_documents` method must be at least partly implemented to return all stored Documents + for this tests to work correctly. + Example usage: + + ```python + class MyDocumentStoreTest(WriteDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_write_documents(self, document_store: DocumentStore): + """ + Test write_documents() default behaviour. + """ + msg = ( + "Default write_documents() behaviour depends on the Document Store implementation, " + "as we don't enforce a default behaviour when no policy is set. " + "Override this test in your custom test class." + ) + raise NotImplementedError(msg) + + def test_write_documents_duplicate_fail(self, document_store: DocumentStore): + """Test write_documents() fails when writing documents with same id and `DuplicatePolicy.FAIL`.""" + doc = Document(content="test doc") + assert document_store.write_documents([doc], policy=DuplicatePolicy.FAIL) == 1 + with pytest.raises(DuplicateDocumentError): + document_store.write_documents(documents=[doc], policy=DuplicatePolicy.FAIL) + self.assert_documents_are_equal(document_store.filter_documents(), [doc]) + + def test_write_documents_duplicate_skip(self, document_store: DocumentStore): + """Test write_documents() skips writing when using DuplicatePolicy.SKIP.""" + doc = Document(content="test doc") + assert document_store.write_documents([doc], policy=DuplicatePolicy.SKIP) == 1 + assert document_store.write_documents(documents=[doc], policy=DuplicatePolicy.SKIP) == 0 + + def test_write_documents_duplicate_overwrite(self, document_store: DocumentStore): + """Test write_documents() overwrites when using DuplicatePolicy.OVERWRITE.""" + doc1 = Document(id="1", content="test doc 1") + doc2 = Document(id="1", content="test doc 2") + + assert document_store.write_documents([doc2], policy=DuplicatePolicy.OVERWRITE) == 1 + self.assert_documents_are_equal(document_store.filter_documents(), [doc2]) + assert document_store.write_documents(documents=[doc1], policy=DuplicatePolicy.OVERWRITE) == 1 + self.assert_documents_are_equal(document_store.filter_documents(), [doc1]) + + def test_write_documents_invalid_input(self, document_store: DocumentStore): + """Test write_documents() fails when providing unexpected input.""" + with pytest.raises(ValueError): + document_store.write_documents(["not a document for sure"]) # type: ignore + with pytest.raises(ValueError): + document_store.write_documents("not a list actually") # type: ignore + + +class DeleteDocumentsTest: + """ + Utility class to test a Document Store `delete_documents` method. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + The Document Store `write_documents` and `count_documents` methods must be implemented for this tests to work + correctly. + Example usage: + + ```python + class MyDocumentStoreTest(DeleteDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_delete_documents(self, document_store: DocumentStore): + """Test delete_documents() normal behaviour.""" + doc = Document(content="test doc") + document_store.write_documents([doc]) + assert document_store.count_documents() == 1 + + document_store.delete_documents([doc.id]) + assert document_store.count_documents() == 0 + + def test_delete_documents_empty_document_store(self, document_store: DocumentStore): + """Test delete_documents() doesn't fail when called using an empty Document Store.""" + document_store.delete_documents(["non_existing_id"]) + + def test_delete_documents_non_existing_document(self, document_store: DocumentStore): + """Test delete_documents() doesn't delete any Document when called with non existing id.""" + doc = Document(content="test doc") + document_store.write_documents([doc]) + assert document_store.count_documents() == 1 + + document_store.delete_documents(["non_existing_id"]) + + # No Document has been deleted + assert document_store.count_documents() == 1 + + +class FilterableDocsFixtureMixin: + """ + Mixin class that adds a filterable_docs() fixture to a test class. + """ + + @pytest.fixture + def filterable_docs(self) -> List[Document]: + """Fixture that returns a list of Documents that can be used to test filtering.""" + documents = [] + for i in range(3): + documents.append( + Document( + content=f"A Foo Document {i}", + meta={ + "name": f"name_{i}", + "page": "100", + "chapter": "intro", + "number": 2, + "date": "1969-07-21T20:17:40", + }, + embedding=_random_embeddings(768), + ) + ) + documents.append( + Document( + content=f"A Bar Document {i}", + meta={ + "name": f"name_{i}", + "page": "123", + "chapter": "abstract", + "number": -2, + "date": "1972-12-11T19:54:58", + }, + embedding=_random_embeddings(768), + ) + ) + documents.append( + Document( + content=f"A Foobar Document {i}", + meta={ + "name": f"name_{i}", + "page": "90", + "chapter": "conclusion", + "number": -10, + "date": "1989-11-09T17:53:00", + }, + embedding=_random_embeddings(768), + ) + ) + documents.append( + Document( + content=f"Document {i} without embedding", + meta={"name": f"name_{i}", "no_embedding": True, "chapter": "conclusion"}, + ) + ) + documents.append(Document(dataframe=pd.DataFrame([i]), meta={"name": f"table_doc_{i}"})) + documents.append( + Document(content=f"Doc {i} with zeros emb", meta={"name": "zeros_doc"}, embedding=TEST_EMBEDDING_1) + ) + documents.append( + Document(content=f"Doc {i} with ones emb", meta={"name": "ones_doc"}, embedding=TEST_EMBEDDING_2) + ) + return documents + + +class LegacyFilterDocumentsInvalidFiltersTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using invalid legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsInvalidFiltersTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_incorrect_filter_type(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(ValueError): + document_store.filter_documents(filters="something odd") # type: ignore + + def test_incorrect_filter_nesting(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"number": {"page": "100"}}) + + def test_deeper_incorrect_filter_nesting(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"number": {"page": {"chapter": "intro"}}}) + + +class LegacyFilterDocumentsEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using implicit and explicit '$eq' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_document_content(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"content": "A Foo Document 1"}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.content == "A Foo Document 1"]) + + def test_filter_simple_metadata_value(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": "100"}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_filter_document_dataframe(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": pd.DataFrame([1])}) + self.assert_documents_are_equal( + result, + [doc for doc in filterable_docs if doc.dataframe is not None and doc.dataframe.equals(pd.DataFrame([1]))], + ) + + def test_eq_filter_explicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$eq": "100"}}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_eq_filter_implicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": "100"}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_eq_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": pd.DataFrame([1])}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if isinstance(doc.dataframe, pd.DataFrame) and doc.dataframe.equals(pd.DataFrame([1])) + ], + ) + + def test_eq_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + embedding = [0.0] * 768 + result = document_store.filter_documents(filters={"embedding": embedding}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if embedding == doc.embedding]) + + +class LegacyFilterDocumentsNotEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$ne' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsNotEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_ne_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$ne": "100"}}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") != "100"]) + + def test_ne_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": {"$ne": pd.DataFrame([1])}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if not isinstance(doc.dataframe, pd.DataFrame) or not doc.dataframe.equals(pd.DataFrame([1])) + ], + ) + + def test_ne_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"embedding": {"$ne": TEST_EMBEDDING_1}}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.embedding != TEST_EMBEDDING_1]) + + +class LegacyFilterDocumentsInTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using implicit and explicit '$in' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsInTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_simple_list_single_element(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100"]}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") == "100"]) + + def test_filter_simple_list_one_value(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100"]}) + self.assert_documents_are_equal(result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100"]]) + + def test_filter_simple_list(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100", "123"]}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100", "123"]] + ) + + def test_incorrect_filter_name(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"non_existing_meta_field": ["whatever"]}) + self.assert_documents_are_equal(result, []) + + def test_incorrect_filter_value(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["nope"]}) + self.assert_documents_are_equal(result, []) + + def test_in_filter_explicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$in": ["100", "123", "n.a."]}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100", "123"]] + ) + + def test_in_filter_implicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": ["100", "123", "n.a."]}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") in ["100", "123"]] + ) + + def test_in_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"dataframe": {"$in": [pd.DataFrame([1]), pd.DataFrame([2])]}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if isinstance(doc.dataframe, pd.DataFrame) + and (doc.dataframe.equals(pd.DataFrame([1])) or doc.dataframe.equals(pd.DataFrame([2]))) + ], + ) + + def test_in_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + embedding_zero = [0.0] * 768 + embedding_one = [1.0] * 768 + result = document_store.filter_documents(filters={"embedding": {"$in": [embedding_zero, embedding_one]}}) + self.assert_documents_are_equal( + result, + [doc for doc in filterable_docs if (embedding_zero == doc.embedding or embedding_one == doc.embedding)], + ) + + +class LegacyFilterDocumentsNotInTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$nin' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsNotInTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_nin_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={"dataframe": {"$nin": [pd.DataFrame([1]), pd.DataFrame([0])]}} + ) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if not isinstance(doc.dataframe, pd.DataFrame) + or (not doc.dataframe.equals(pd.DataFrame([1])) and not doc.dataframe.equals(pd.DataFrame([0]))) + ], + ) + + def test_nin_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"embedding": {"$nin": [TEST_EMBEDDING_1, TEST_EMBEDDING_2]}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.embedding not in [TEST_EMBEDDING_1, TEST_EMBEDDING_2]] + ) + + def test_nin_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"page": {"$nin": ["100", "123", "n.a."]}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("page") not in ["100", "123"]] + ) + + +class LegacyFilterDocumentsGreaterThanTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$gt' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsGreaterThanTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_gt_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$gt": 0.0}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if "number" in doc.meta and doc.meta["number"] > 0] + ) + + def test_gt_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$gt": "100"}}) + + def test_gt_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$gt": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_gt_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$gt": TEST_EMBEDDING_1}}) + + +class LegacyFilterDocumentsGreaterThanEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$gte' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsGreaterThanEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_gte_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$gte": -2}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if "number" in doc.meta and doc.meta["number"] >= -2] + ) + + def test_gte_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$gte": "100"}}) + + def test_gte_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$gte": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_gte_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$gte": TEST_EMBEDDING_1}}) + + +class LegacyFilterDocumentsLessThanTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$lt' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsLessThanTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_lt_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lt": 0.0}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("number") is not None and doc.meta["number"] < 0] + ) + + def test_lt_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$lt": "100"}}) + + def test_lt_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$lt": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_lt_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$lt": TEST_EMBEDDING_2}}) + + +class LegacyFilterDocumentsLessThanEqualTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using explicit '$lte' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsLessThanEqualTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_lte_filter(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lte": 2.0}}) + self.assert_documents_are_equal( + result, [doc for doc in filterable_docs if doc.meta.get("number") is not None and doc.meta["number"] <= 2.0] + ) + + def test_lte_filter_non_numeric(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"page": {"$lte": "100"}}) + + def test_lte_filter_table(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"dataframe": {"$lte": pd.DataFrame([[1, 2, 3], [-1, -2, -3]])}}) + + def test_lte_filter_embedding(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"embedding": {"$lte": TEST_EMBEDDING_1}}) + + +class LegacyFilterDocumentsSimpleLogicalTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using '$and', '$or' and '$not' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsSimpleLogicalTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_simple_or(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters = {"$or": {"name": {"$in": ["name_0", "name_1"]}, "number": {"$lt": 1.0}}} + result = document_store.filter_documents(filters=filters) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if (doc.meta.get("number") is not None and doc.meta["number"] < 1) + or doc.meta.get("name") in ["name_0", "name_1"] + ], + ) + + def test_filter_simple_implicit_and_with_multi_key_dict( + self, document_store: DocumentStore, filterable_docs: List[Document] + ): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lte": 2.0, "$gte": 0.0}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if "number" in doc.meta and doc.meta["number"] >= 0.0 and doc.meta["number"] <= 2.0 + ], + ) + + def test_filter_simple_explicit_and_with_list(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$and": [{"$lte": 2}, {"$gte": 0}]}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if "number" in doc.meta and doc.meta["number"] <= 2.0 and doc.meta["number"] >= 0.0 + ], + ) + + def test_filter_simple_implicit_and(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"number": {"$lte": 2.0, "$gte": 0}}) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if "number" in doc.meta and doc.meta["number"] <= 2.0 and doc.meta["number"] >= 0.0 + ], + ) + + +class LegacyFilterDocumentsNestedLogicalTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test `filter_documents` using multiple nested logical '$and', '$or' and '$not' legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsNestedLogicalTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_filter_nested_implicit_and(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = {"number": {"$lte": 2, "$gte": 0}, "name": ["name_0", "name_1"]} + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + "number" in doc.meta + and doc.meta["number"] <= 2 + and doc.meta["number"] >= 0 + and doc.meta.get("name") in ["name_0", "name_1"] + ) + ], + ) + + def test_filter_nested_or(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters = {"$or": {"name": {"$or": [{"$eq": "name_0"}, {"$eq": "name_1"}]}, "number": {"$lt": 1.0}}} + result = document_store.filter_documents(filters=filters) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + doc.meta.get("name") in ["name_0", "name_1"] + or (doc.meta.get("number") is not None and doc.meta["number"] < 1) + ) + ], + ) + + def test_filter_nested_and_or_explicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = { + "$and": {"page": {"$eq": "123"}, "$or": {"name": {"$in": ["name_0", "name_1"]}, "number": {"$lt": 1.0}}} + } + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + doc.meta.get("page") in ["123"] + and ( + doc.meta.get("name") in ["name_0", "name_1"] + or ("number" in doc.meta and doc.meta["number"] < 1) + ) + ) + ], + ) + + def test_filter_nested_and_or_implicit(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = { + "page": {"$eq": "123"}, + "$or": {"name": {"$in": ["name_0", "name_1"]}, "number": {"$lt": 1.0}}, + } + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + doc.meta.get("page") in ["123"] + and ( + doc.meta.get("name") in ["name_0", "name_1"] + or ("number" in doc.meta and doc.meta["number"] < 1) + ) + ) + ], + ) + + def test_filter_nested_or_and(self, document_store: DocumentStore, filterable_docs: List[Document]): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters_simplified = { + "$or": { + "number": {"$lt": 1}, + "$and": {"name": {"$in": ["name_0", "name_1"]}, "$not": {"chapter": {"$eq": "intro"}}}, + } + } + result = document_store.filter_documents(filters=filters_simplified) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + (doc.meta.get("number") is not None and doc.meta["number"] < 1) + or (doc.meta.get("name") in ["name_0", "name_1"] and (doc.meta.get("chapter") != "intro")) + ) + ], + ) + + def test_filter_nested_multiple_identical_operators_same_level( + self, document_store: DocumentStore, filterable_docs: List[Document] + ): + """""" # noqa # pylint: disable=C0112 + document_store.write_documents(filterable_docs) + filters = { + "$or": [ + {"$and": {"name": {"$in": ["name_0", "name_1"]}, "page": "100"}}, + {"$and": {"chapter": {"$in": ["intro", "abstract"]}, "page": "123"}}, + ] + } + result = document_store.filter_documents(filters=filters) + self.assert_documents_are_equal( + result, + [ + doc + for doc in filterable_docs + if ( + (doc.meta.get("name") in ["name_0", "name_1"] and doc.meta.get("page") == "100") + or (doc.meta.get("chapter") in ["intro", "abstract"] and doc.meta.get("page") == "123") + ) + ], + ) + + +class LegacyFilterDocumentsTest( # pylint: disable=too-many-ancestors + LegacyFilterDocumentsInvalidFiltersTest, + LegacyFilterDocumentsEqualTest, + LegacyFilterDocumentsNotEqualTest, + LegacyFilterDocumentsInTest, + LegacyFilterDocumentsNotInTest, + LegacyFilterDocumentsGreaterThanTest, + LegacyFilterDocumentsGreaterThanEqualTest, + LegacyFilterDocumentsLessThanTest, + LegacyFilterDocumentsLessThanEqualTest, + LegacyFilterDocumentsSimpleLogicalTest, + LegacyFilterDocumentsNestedLogicalTest, +): + """ + Utility class to test a Document Store `filter_documents` method using different types of legacy filters + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(LegacyFilterDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_no_filter_empty(self, document_store: DocumentStore): + """""" # noqa # pylint: disable=C0112 + assert document_store.filter_documents() == [] + assert document_store.filter_documents(filters={}) == [] + + def test_no_filter_not_empty(self, document_store: DocumentStore): + """""" # noqa # pylint: disable=C0112 + docs = [Document(content="test doc")] + document_store.write_documents(docs) + assert document_store.filter_documents() == docs + assert document_store.filter_documents(filters={}) == docs + + +class FilterDocumentsTest(AssertDocumentsEqualMixin, FilterableDocsFixtureMixin): + """ + Utility class to test a Document Store `filter_documents` method using different types of filters. + + To use it create a custom test class and override the `document_store` fixture to return your Document Store. + Example usage: + + ```python + class MyDocumentStoreTest(FilterDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + """ + + def test_no_filters(self, document_store): + """Test filter_documents() with empty filters""" + self.assert_documents_are_equal(document_store.filter_documents(), []) + self.assert_documents_are_equal(document_store.filter_documents(filters={}), []) + docs = [Document(content="test doc")] + document_store.write_documents(docs) + self.assert_documents_are_equal(document_store.filter_documents(), docs) + self.assert_documents_are_equal(document_store.filter_documents(filters={}), docs) + + # == comparator + def test_comparison_equal(self, document_store, filterable_docs): + """Test filter_documents() with == comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "==", "value": 100}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") == 100]) + + def test_comparison_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with == comparator and dataframe""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={"field": "dataframe", "operator": "==", "value": pd.DataFrame([1])} + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.dataframe is not None and d.dataframe.equals(pd.DataFrame([1]))] + ) + + def test_comparison_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with == comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "==", "value": None}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") is None]) + + # != comparator + def test_comparison_not_equal(self, document_store, filterable_docs): + """Test filter_documents() with != comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "!=", "value": 100}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") != 100]) + + def test_comparison_not_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with != comparator and dataframe""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={"field": "dataframe", "operator": "!=", "value": pd.DataFrame([1])} + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.dataframe is None or not d.dataframe.equals(pd.DataFrame([1]))] + ) + + def test_comparison_not_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with != comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "!=", "value": None}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") is not None]) + + # > comparator + def test_comparison_greater_than(self, document_store, filterable_docs): + """Test filter_documents() with > comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": ">", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] > 0] + ) + + def test_comparison_greater_than_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": ">", "value": "1972-12-11T19:54:58"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) > datetime.fromisoformat("1972-12-11T19:54:58") + ], + ) + + def test_comparison_greater_than_with_string(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">", "value": "1"}) + + def test_comparison_greater_than_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "dataframe", "operator": ">", "value": pd.DataFrame([1])}) + + def test_comparison_greater_than_with_list(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">", "value": [1]}) + + def test_comparison_greater_than_with_none(self, document_store, filterable_docs): + """Test filter_documents() with > comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": ">", "value": None}) + self.assert_documents_are_equal(result, []) + + # >= comparator + def test_comparison_greater_than_equal(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": ">=", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] >= 0] + ) + + def test_comparison_greater_than_equal_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": ">=", "value": "1969-07-21T20:17:40"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) >= datetime.fromisoformat("1969-07-21T20:17:40") + ], + ) + + def test_comparison_greater_than_equal_with_string(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">=", "value": "1"}) + + def test_comparison_greater_than_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"field": "dataframe", "operator": ">=", "value": pd.DataFrame([1])} + ) + + def test_comparison_greater_than_equal_with_list(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": ">=", "value": [1]}) + + def test_comparison_greater_than_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with >= comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": ">=", "value": None}) + self.assert_documents_are_equal(result, []) + + # < comparator + def test_comparison_less_than(self, document_store, filterable_docs): + """Test filter_documents() with < comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "<", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] < 0] + ) + + def test_comparison_less_than_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": "<", "value": "1969-07-21T20:17:40"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) < datetime.fromisoformat("1969-07-21T20:17:40") + ], + ) + + def test_comparison_less_than_with_string(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<", "value": "1"}) + + def test_comparison_less_than_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "dataframe", "operator": "<", "value": pd.DataFrame([1])}) + + def test_comparison_less_than_with_list(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<", "value": [1]}) + + def test_comparison_less_than_with_none(self, document_store, filterable_docs): + """Test filter_documents() with < comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "<", "value": None}) + self.assert_documents_are_equal(result, []) + + # <= comparator + def test_comparison_less_than_equal(self, document_store, filterable_docs): + """Test filter_documents() with <=""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "<=", "value": 0}) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] <= 0] + ) + + def test_comparison_less_than_equal_with_iso_date(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and datetime""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + {"field": "meta.date", "operator": "<=", "value": "1969-07-21T20:17:40"} + ) + self.assert_documents_are_equal( + result, + [ + d + for d in filterable_docs + if d.meta.get("date") is not None + and datetime.fromisoformat(d.meta["date"]) <= datetime.fromisoformat("1969-07-21T20:17:40") + ], + ) + + def test_comparison_less_than_equal_with_string(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and string""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<=", "value": "1"}) + + def test_comparison_less_than_equal_with_dataframe(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and dataframe""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"field": "dataframe", "operator": "<=", "value": pd.DataFrame([1])} + ) + + def test_comparison_less_than_equal_with_list(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and list""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"field": "meta.number", "operator": "<=", "value": [1]}) + + def test_comparison_less_than_equal_with_none(self, document_store, filterable_docs): + """Test filter_documents() with <= comparator and None""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents(filters={"field": "meta.number", "operator": "<=", "value": None}) + self.assert_documents_are_equal(result, []) + + # in comparator + def test_comparison_in(self, document_store, filterable_docs): + """Test filter_documents() with 'in' comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "in", "value": [10, -10]}) + assert len(result) + expected = [d for d in filterable_docs if d.meta.get("number") is not None and d.meta["number"] in [10, -10]] + self.assert_documents_are_equal(result, expected) + + def test_comparison_in_with_with_non_list(self, document_store, filterable_docs): + """Test filter_documents() with 'in' comparator and non-iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "in", "value": 9}) + + def test_comparison_in_with_with_non_list_iterable(self, document_store, filterable_docs): + """Test filter_documents() with 'in' comparator and iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "in", "value": (10, 11)}) + + # not in comparator + def test_comparison_not_in(self, document_store, filterable_docs): + """Test filter_documents() with 'not in' comparator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents({"field": "meta.number", "operator": "not in", "value": [9, 10]}) + self.assert_documents_are_equal(result, [d for d in filterable_docs if d.meta.get("number") not in [9, 10]]) + + def test_comparison_not_in_with_with_non_list(self, document_store, filterable_docs): + """Test filter_documents() with 'not in' comparator and non-iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "not in", "value": 9}) + + def test_comparison_not_in_with_with_non_list_iterable(self, document_store, filterable_docs): + """Test filter_documents() with 'not in' comparator and iterable""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents({"field": "meta.number", "operator": "not in", "value": (10, 11)}) + + # Logical operator + def test_and_operator(self, document_store, filterable_docs): + """Test filter_documents() with 'AND' operator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={ + "operator": "AND", + "conditions": [ + {"field": "meta.number", "operator": "==", "value": 100}, + {"field": "meta.name", "operator": "==", "value": "name_0"}, + ], + } + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") == 100 and d.meta.get("name") == "name_0"] + ) + + def test_or_operator(self, document_store, filterable_docs): + """Test filter_documents() with 'OR' operator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={ + "operator": "OR", + "conditions": [ + {"field": "meta.number", "operator": "==", "value": 100}, + {"field": "meta.name", "operator": "==", "value": "name_0"}, + ], + } + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if d.meta.get("number") == 100 or d.meta.get("name") == "name_0"] + ) + + def test_not_operator(self, document_store, filterable_docs): + """Test filter_documents() with 'NOT' operator""" + document_store.write_documents(filterable_docs) + result = document_store.filter_documents( + filters={ + "operator": "NOT", + "conditions": [ + {"field": "meta.number", "operator": "==", "value": 100}, + {"field": "meta.name", "operator": "==", "value": "name_0"}, + ], + } + ) + self.assert_documents_are_equal( + result, [d for d in filterable_docs if not (d.meta.get("number") == 100 and d.meta.get("name") == "name_0")] + ) + + # Malformed filters + def test_missing_top_level_operator_key(self, document_store, filterable_docs): + """Test filter_documents() with top-level operator""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"conditions": [{"field": "meta.name", "operator": "==", "value": "test"}]} + ) + + def test_missing_top_level_conditions_key(self, document_store, filterable_docs): + """Test filter_documents() with missing top-level condition key""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents(filters={"operator": "AND"}) + + def test_missing_condition_field_key(self, document_store, filterable_docs): + """Test filter_documents() with missing condition key""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"operator": "AND", "conditions": [{"operator": "==", "value": "test"}]} + ) + + def test_missing_condition_operator_key(self, document_store, filterable_docs): + """Test filter_documents() with missing operator key""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"operator": "AND", "conditions": [{"field": "meta.name", "value": "test"}]} + ) + + def test_missing_condition_value_key(self, document_store, filterable_docs): + """Test filter_documents() with missing condition value""" + document_store.write_documents(filterable_docs) + with pytest.raises(FilterError): + document_store.filter_documents( + filters={"operator": "AND", "conditions": [{"field": "meta.name", "operator": "=="}]} + ) + + +class DocumentStoreBaseTests(CountDocumentsTest, WriteDocumentsTest, DeleteDocumentsTest, FilterDocumentsTest): + @pytest.fixture + def document_store(self) -> DocumentStore: + """Base fixture, to be reimplemented when deriving from DocumentStoreBaseTests""" + raise NotImplementedError() diff --git a/testbed/deepset-ai__haystack/haystack/testing/factory.py b/testbed/deepset-ai__haystack/haystack/testing/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..29d8fa7738109b536ba2d23ccfd2209cd0e593fd --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/factory.py @@ -0,0 +1,233 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict, List, Optional, Tuple, Type, Union + +from haystack.core.component import Component, component +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.dataclasses import Document +from haystack.document_stores.types import DocumentStore, DuplicatePolicy + + +def document_store_class( + name: str, + documents: Optional[List[Document]] = None, + documents_count: Optional[int] = None, + bases: Optional[Tuple[type, ...]] = None, + extra_fields: Optional[Dict[str, Any]] = None, +) -> Type[DocumentStore]: + """ + Utility function to create a DocumentStore class with the given name and list of documents. + + If `documents` is set but `documents_count` is not, `documents_count` will be the length + of `documents`. + If both are set explicitly they don't influence each other. + + `write_documents()` and `delete_documents()` are no-op. + You can override them using `extra_fields`. + + ### Usage + + Create a DocumentStore class that returns no documents: + ```python + MyFakeStore = document_store_class("MyFakeComponent") + document_store = MyFakeStore() + assert document_store.documents_count() == 0 + assert document_store.filter_documents() == [] + ``` + + Create a DocumentStore class that returns a single document: + ```python + doc = Document(id="fake_id", content="Fake content") + MyFakeStore = document_store_class("MyFakeComponent", documents=[doc]) + document_store = MyFakeStore() + assert document_store.documents_count() == 1 + assert document_store.filter_documents() == [doc] + ``` + + Create a DocumentStore class that returns no document but returns a custom count: + ```python + MyFakeStore = document_store_class("MyFakeComponent", documents_count=100) + document_store = MyFakeStore() + assert document_store.documents_count() == 100 + assert document_store.filter_documents() == [] + ``` + + Create a DocumentStore class that returns a document and a custom count: + ```python + doc = Document(id="fake_id", content="Fake content") + MyFakeStore = document_store_class("MyFakeComponent", documents=[doc], documents_count=100) + document_store = MyFakeStore() + assert document_store.documents_count() == 100 + assert document_store.filter_documents() == [doc] + ``` + + Create a DocumentStore class with a custom base class: + ```python + MyFakeStore = document_store_class( + "MyFakeStore", + bases=(MyBaseClass,) + ) + document_store = MyFakeStore() + assert isinstance(store, MyBaseClass) + ``` + + Create a DocumentStore class with an extra field `my_field`: + ```python + MyFakeStore = document_store_class( + "MyFakeStore", + extra_fields={"my_field": 10} + ) + document_store = MyFakeStore() + assert document_store.my_field == 10 + ``` + """ + if documents is not None and documents_count is None: + documents_count = len(documents) + elif documents_count is None: + documents_count = 0 + + def count_documents(self) -> Union[int, None]: + return documents_count + + def filter_documents(self, filters: Optional[Dict[str, Any]] = None) -> List[Document]: + if documents is not None: + return documents + return [] + + def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.FAIL) -> None: + return + + def delete_documents(self, document_ids: List[str]) -> None: + return + + def to_dict(self) -> Dict[str, Any]: + return default_to_dict(self) + + fields = { + "count_documents": count_documents, + "filter_documents": filter_documents, + "write_documents": write_documents, + "delete_documents": delete_documents, + "to_dict": to_dict, + "from_dict": classmethod(default_from_dict), + } + + if extra_fields is not None: + fields = {**fields, **extra_fields} + + if bases is None: + bases = (object,) + + cls = type(name, bases, fields) + return cls + + +def component_class( + name: str, + input_types: Optional[Dict[str, Any]] = None, + output_types: Optional[Dict[str, Any]] = None, + output: Optional[Dict[str, Any]] = None, + bases: Optional[Tuple[type, ...]] = None, + extra_fields: Optional[Dict[str, Any]] = None, +) -> Type[Component]: + """ + Utility class to create a Component class with the given name and input and output types. + + If `output` is set but `output_types` is not, `output_types` will be set to the types of the values in `output`. + Though if `output_types` is set but `output` is not the component's `run` method will return a dictionary + of the same keys as `output_types` all with a value of None. + + ### Usage + + Create a component class with default input and output types: + ```python + MyFakeComponent = component_class_factory("MyFakeComponent") + component = MyFakeComponent() + output = component.run(value=1) + assert output == {"value": None} + ``` + + Create a component class with an "value" input of type `int` and with a "value" output of `10`: + ```python + MyFakeComponent = component_class_factory( + "MyFakeComponent", + input_types={"value": int}, + output={"value": 10} + ) + component = MyFakeComponent() + output = component.run(value=1) + assert output == {"value": 10} + ``` + + Create a component class with a custom base class: + ```python + MyFakeComponent = component_class_factory( + "MyFakeComponent", + bases=(MyBaseClass,) + ) + component = MyFakeComponent() + assert isinstance(component, MyBaseClass) + ``` + + Create a component class with an extra field `my_field`: + ```python + MyFakeComponent = component_class_factory( + "MyFakeComponent", + extra_fields={"my_field": 10} + ) + component = MyFakeComponent() + assert component.my_field == 10 + ``` + + Args: + name: Name of the component class + input_types: Dictionary of string and type that defines the inputs of the component, + if set to None created component will expect a single input "value" of Any type. + Defaults to None. + output_types: Dictionary of string and type that defines the outputs of the component, + if set to None created component will return a single output "value" of NoneType and None value. + Defaults to None. + output: Actual output dictionary returned by the created component run, + is set to None it will return a dictionary of string and None values. + Keys will be the same as the keys of output_types. Defaults to None. + bases: Base classes for this component, if set to None only base is object. Defaults to None. + extra_fields: Extra fields for the Component, defaults to None. + + :return: A class definition that can be used as a component. + """ + if input_types is None: + input_types = {"value": Any} + if output_types is None and output is not None: + output_types = {key: type(value) for key, value in output.items()} + elif output_types is None: + output_types = {"value": type(None)} + + def init(self): + component.set_input_types(self, **input_types) + component.set_output_types(self, **output_types) + + # Both arguments are necessary to correctly define + # run but pylint doesn't like that we don't use them. + # It's fine ignoring the warning here. + def run(self, **kwargs): # pylint: disable=unused-argument + if output is not None: + return output + return {name: None for name in output_types.keys()} + + def to_dict(self): + return default_to_dict(self) + + def from_dict(cls, data: Dict[str, Any]): + return default_from_dict(cls, data) + + fields = {"__init__": init, "run": run, "to_dict": to_dict, "from_dict": classmethod(from_dict)} + if extra_fields is not None: + fields = {**fields, **extra_fields} + + if bases is None: + bases = (object,) + + cls = type(name, bases, fields) + return component(cls) diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/__init__.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..011ca2ddeae6a574ed970fa8238cd19df04a9483 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/__init__.py @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.testing.sample_components.accumulate import Accumulate +from haystack.testing.sample_components.add_value import AddFixedValue +from haystack.testing.sample_components.concatenate import Concatenate +from haystack.testing.sample_components.double import Double +from haystack.testing.sample_components.fstring import FString +from haystack.testing.sample_components.greet import Greet +from haystack.testing.sample_components.hello import Hello +from haystack.testing.sample_components.joiner import StringJoiner, StringListJoiner +from haystack.testing.sample_components.parity import Parity +from haystack.testing.sample_components.remainder import Remainder +from haystack.testing.sample_components.repeat import Repeat +from haystack.testing.sample_components.subtract import Subtract +from haystack.testing.sample_components.sum import Sum +from haystack.testing.sample_components.text_splitter import TextSplitter +from haystack.testing.sample_components.threshold import Threshold + +__all__ = [ + "Concatenate", + "Subtract", + "Parity", + "Remainder", + "Accumulate", + "Threshold", + "AddFixedValue", + "Repeat", + "Sum", + "Greet", + "Double", + "StringJoiner", + "Hello", + "TextSplitter", + "StringListJoiner", + "FString", +] diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/accumulate.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/accumulate.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d0acec300cbf91d2af0bce91d250484775b642 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/accumulate.py @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import builtins +import sys +from importlib import import_module +from typing import Any, Callable, Dict, Optional + +from haystack.core.component import component +from haystack.core.errors import ComponentDeserializationError +from haystack.core.serialization import default_to_dict + + +def _default_function(first: int, second: int) -> int: + return first + second + + +@component +class Accumulate: + """ + Accumulates the value flowing through the connection into an internal attribute. + + The sum function can be customized. Example of how to deal with serialization when some of the parameters + are not directly serializable. + """ + + def __init__(self, function: Optional[Callable] = None): + """ + Class constructor + + :param function: + the function to use to accumulate the values. + The function must take exactly two values. + If it's a callable, it's used as it is. + If it's a string, the component will look for it in sys.modules and + import it at need. This is also a parameter. + """ + self.state = 0 + self.function: Callable = _default_function if function is None else function # type: ignore + + def to_dict(self) -> Dict[str, Any]: + """Converts the component to a dictionary""" + module = sys.modules.get(self.function.__module__) + if not module: + raise ValueError("Could not locate the import module.") + if module == builtins: + function_name = self.function.__name__ + else: + function_name = f"{module.__name__}.{self.function.__name__}" + + return default_to_dict(self, function=function_name) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Accumulate": + """Loads the component from a dictionary""" + if "type" not in data: + raise ComponentDeserializationError("Missing 'type' in component serialization data") + if data["type"] != f"{cls.__module__}.{cls.__name__}": + raise ComponentDeserializationError(f"Class '{data['type']}' can't be deserialized as '{cls.__name__}'") + + init_params = data.get("init_parameters", {}) + + accumulator_function = None + if "function" in init_params: + parts = init_params["function"].split(".") + module_name = ".".join(parts[:-1]) + function_name = parts[-1] + module = import_module(module_name) + accumulator_function = getattr(module, function_name) + + return cls(function=accumulator_function) + + @component.output_types(value=int) + def run(self, value: int): + """ + Accumulates the value flowing through the connection into an internal attribute. + + The sum function can be customized. + """ + self.state = self.function(self.state, value) + return {"value": self.state} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/add_value.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/add_value.py new file mode 100644 index 0000000000000000000000000000000000000000..cc445a4cf6d4a2719f6c6064d11bf1540f42783a --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/add_value.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Optional + +from haystack.core.component import component + + +@component +class AddFixedValue: + """ + Adds two values together. + """ + + def __init__(self, add: int = 1): + self.add = add + + @component.output_types(result=int) + def run(self, value: int, add: Optional[int] = None): + """ + Adds two values together. + """ + if add is None: + add = self.add + return {"result": value + add} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/concatenate.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/concatenate.py new file mode 100644 index 0000000000000000000000000000000000000000..023237ea78b4614e442c6b400616bdd50e7d8468 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/concatenate.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List, Union + +from haystack.core.component import component + + +@component +class Concatenate: + """ + Concatenates two values + """ + + @component.output_types(value=List[str]) + def run(self, first: Union[List[str], str], second: Union[List[str], str]): + """ + Concatenates two values + """ + if isinstance(first, str) and isinstance(second, str): + res = [first, second] + elif isinstance(first, list) and isinstance(second, list): + res = first + second + elif isinstance(first, list) and isinstance(second, str): + res = first + [second] + elif isinstance(first, str) and isinstance(second, list): + res = [first] + second + else: + res = None + return {"value": res} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/double.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/double.py new file mode 100644 index 0000000000000000000000000000000000000000..42286ce141aa150c21818f9f7a4bc669165db0d2 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/double.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Double: + """ + Doubles the input value. + """ + + @component.output_types(value=int) + def run(self, value: int): + """ + Doubles the input value. + """ + return {"value": value * 2} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/fstring.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/fstring.py new file mode 100644 index 0000000000000000000000000000000000000000..a95bc3f41ba97b2828d4c0abbe7a3f6156c7888d --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/fstring.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, List, Optional + +from haystack.core.component import component + + +@component +class FString: + """ + Takes a template string and a list of variables in input and returns the formatted string in output. + """ + + def __init__(self, template: str, variables: Optional[List[str]] = None): + self.template = template + self.variables = variables or [] + if "template" in self.variables: + raise ValueError("The variable name 'template' is reserved and cannot be used.") + component.set_input_types(self, **{variable: Any for variable in self.variables}) + + @component.output_types(string=str) + def run(self, template: Optional[str] = None, **kwargs): + """ + Takes a template string and a list of variables in input and returns the formatted string in output. + + If the template is not given, the component will use the one given at initialization. + """ + if not template: + template = self.template + return {"string": template.format(**kwargs)} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/greet.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/greet.py new file mode 100644 index 0000000000000000000000000000000000000000..4deed973a30bef0c225b441bcb47be68ef6069d2 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/greet.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import logging +from typing import Optional + +import haystack.logging as haystack_logging +from haystack.core.component import component + +logger = haystack_logging.getLogger(__name__) + + +@component +class Greet: + """ + Logs a greeting message without affecting the value passing on the connection. + """ + + def __init__(self, message: str = "\nGreeting component says: Hi! The value is {value}\n", log_level: str = "INFO"): + """ + Class constructor + + :param message: the message to log. Can use `{value}` to embed the value. + :param log_level: the level to log at. + """ + if log_level and not getattr(logging, log_level): + raise ValueError(f"This log level does not exist: {log_level}") + self.message = message + self.log_level = log_level + + @component.output_types(value=int) + def run(self, value: int, message: Optional[str] = None, log_level: Optional[str] = None): + """ + Logs a greeting message without affecting the value passing on the connection. + """ + if not message: + message = self.message + if not log_level: + log_level = self.log_level + + level = getattr(logging, log_level, None) + if not level: + raise ValueError(f"This log level does not exist: {log_level}") + + logger.log(level=level, msg=message.format(value=value)) + return {"value": value} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/hello.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/hello.py new file mode 100644 index 0000000000000000000000000000000000000000..b60c57f3e839b3a546853fad6b7f1d4a4a5c1252 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/hello.py @@ -0,0 +1,13 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Hello: + @component.output_types(output=str) + def run(self, word: str): + """Takes a string in input and returns "Hello, !"in output.""" + return {"output": f"Hello, {word}!"} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/joiner.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..8912c2ac9fde4e500d1c156bf7b9c55893f3ba2f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/joiner.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack.core.component import component +from haystack.core.component.types import Variadic + + +@component +class StringJoiner: + @component.output_types(output=str) + def run(self, input_str: Variadic[str]): + """ + Take strings from multiple input nodes and join them into a single one returned in output. + + Since `input_str` is Variadic, we know we'll receive a List[str]. + """ + return {"output": " ".join(input_str)} + + +@component +class StringListJoiner: + @component.output_types(output=str) + def run(self, inputs: Variadic[List[str]]): + """ + Take list of strings from multiple input nodes and join them into a single one returned in output. + + Since `input_str` is Variadic, we know we'll receive a List[List[str]]. + """ + retval: List[str] = [] + for list_of_strings in inputs: + retval += list_of_strings + + return {"output": retval} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/parity.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/parity.py new file mode 100644 index 0000000000000000000000000000000000000000..5d219275abb39c4a745a82b7571599dfb00b84f9 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/parity.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Parity: # pylint: disable=too-few-public-methods + """ + Redirects the value, unchanged, along the 'even' connection if even, or along the 'odd' one if odd. + """ + + @component.output_types(even=int, odd=int) + def run(self, value: int): + """ + :param value: The value to check for parity + """ + remainder = value % 2 + if remainder: + return {"odd": value} + return {"even": value} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/remainder.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/remainder.py new file mode 100644 index 0000000000000000000000000000000000000000..89d74240bcfbf906a06eabb1c2c81bb983da0162 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/remainder.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Remainder: + def __init__(self, divisor=3): + if divisor == 0: + raise ValueError("Can't divide by zero") + self.divisor = divisor + component.set_output_types(self, **{f"remainder_is_{val}": int for val in range(divisor)}) + + def run(self, value: int): + """ + :param value: the value to check the remainder of. + """ + remainder = value % self.divisor + output = {f"remainder_is_{remainder}": value} + return output diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/repeat.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/repeat.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc41d742a9d76260a3a05b8e785bc0ea55bed07 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/repeat.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack.core.component import component + + +@component +class Repeat: + def __init__(self, outputs: List[str]): + self._outputs = outputs + component.set_output_types(self, **{k: int for k in outputs}) + + def run(self, value: int): + """ + :param value: the value to repeat. + """ + return {val: value for val in self._outputs} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/subtract.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/subtract.py new file mode 100644 index 0000000000000000000000000000000000000000..c0f8867f0158ff39aeb37699bcae26394fc9eef9 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/subtract.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component + + +@component +class Subtract: + """ + Compute the difference between two values. + """ + + @component.output_types(difference=int) + def run(self, first_value: int, second_value: int): + """ + Run the component. + + :param first_value: name of the connection carrying the value to subtract from. + :param second_value: name of the connection carrying the value to subtract. + """ + return {"difference": first_value - second_value} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/sum.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/sum.py new file mode 100644 index 0000000000000000000000000000000000000000..ca475f898b2229c7f6effac8512f3f7b0c8d771f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/sum.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.component import component +from haystack.core.component.types import Variadic + + +@component +class Sum: + @component.output_types(total=int) + def run(self, values: Variadic[int]): + """ + :param value: the values to sum. + """ + return {"total": sum(values)} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/text_splitter.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/text_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad00460b87f5a3b508c763f1789742f3c522717 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/text_splitter.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List + +from haystack.core.component import component + + +@component +class TextSplitter: + @component.output_types(output=List[str]) + def run(self, sentence: str): + """Takes a sentence in input and returns its words in output.""" + return {"output": sentence.split()} diff --git a/testbed/deepset-ai__haystack/haystack/testing/sample_components/threshold.py b/testbed/deepset-ai__haystack/haystack/testing/sample_components/threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..9cec4fa30fea1ceb81315924a5d6b730fd00a022 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/sample_components/threshold.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Optional + +from haystack.core.component import component + + +@component +class Threshold: # pylint: disable=too-few-public-methods + """ + Redirects the value, along a different connection whether the value is above or below the given threshold. + + :param threshold: the number to compare the input value against. This is also a parameter. + """ + + def __init__(self, threshold: int = 10): + """ + :param threshold: the number to compare the input value against. + """ + self.threshold = threshold + + @component.output_types(above=int, below=int) + def run(self, value: int, threshold: Optional[int] = None): + """ + Redirects the value, along a different connection whether the value is above or below the given threshold. + + :param threshold: the number to compare the input value against. This is also a parameter. + """ + if threshold is None: + threshold = self.threshold + + if value < threshold: + return {"below": value} + return {"above": value} diff --git a/testbed/deepset-ai__haystack/haystack/testing/test_utils.py b/testbed/deepset-ai__haystack/haystack/testing/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..247bb2e3b6d2024e8477023dbab52988b52b7d56 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/testing/test_utils.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +import random + +from haystack import logging + +logger = logging.getLogger(__name__) + + +def set_all_seeds(seed: int, deterministic_cudnn: bool = False) -> None: + """ + Setting multiple seeds to make runs reproducible. + + Important: Enabling `deterministic_cudnn` gives you full reproducibility with CUDA, + but might slow down your training (see https://pytorch.org/docs/stable/notes/randomness.html#cudnn) ! + + :param seed:number to use as seed + :param deterministic_cudnn: Enable for full reproducibility when using CUDA. Caution: might slow down training. + """ + random.seed(seed) + os.environ["PYTHONHASHSEED"] = str(seed) + + try: + import torch + + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + if deterministic_cudnn: + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + except (ImportError, ModuleNotFoundError) as exc: + logger.info("Could not set PyTorch seed because torch is not installed. Exception: {exception}", exception=exc) diff --git a/testbed/deepset-ai__haystack/haystack/tracing/__init__.py b/testbed/deepset-ai__haystack/haystack/tracing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce07a0471d8ffc4706c8a6aafa02a603b15cc46b --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/tracing/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.tracing.tracer import ( # noqa: I001 (otherwise we end up with partial imports) + Span, + Tracer, + auto_enable_tracing, + disable_tracing, + enable_tracing, + is_tracing_enabled, + tracer, +) +from haystack.tracing.opentelemetry import OpenTelemetryTracer diff --git a/testbed/deepset-ai__haystack/haystack/tracing/datadog.py b/testbed/deepset-ai__haystack/haystack/tracing/datadog.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d0808e55eff347eb126fb63463c5b60f02ca9b --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/tracing/datadog.py @@ -0,0 +1,79 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import contextlib +from typing import Any, Dict, Iterator, Optional + +from haystack.lazy_imports import LazyImport +from haystack.tracing import Span, Tracer +from haystack.tracing import utils as tracing_utils + +with LazyImport("Run 'pip install ddtrace'") as ddtrace_import: + import ddtrace + + +class DatadogSpan(Span): + def __init__(self, span: "ddtrace.Span") -> None: + self._span = span + + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + coerced_value = tracing_utils.coerce_tag_value(value) + self._span.set_tag(key, coerced_value) + + def raw_span(self) -> Any: + """ + Provides access to the underlying span object of the tracer. + + :return: The underlying span object. + """ + return self._span + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + """Return a dictionary with correlation data for logs.""" + raw_span = self.raw_span() + if not raw_span: + return {} + + # https://docs.datadoghq.com/tracing/other_telemetry/connect_logs_and_traces/python/#no-standard-library-logging + trace_id, span_id = (str((1 << 64) - 1 & raw_span.trace_id), raw_span.span_id) + + return { + "dd.trace_id": trace_id, + "dd.span_id": span_id, + "dd.service": ddtrace.config.service or "", + "dd.env": ddtrace.config.env or "", + "dd.version": ddtrace.config.version or "", + } + + +class DatadogTracer(Tracer): + def __init__(self, tracer: "ddtrace.Tracer") -> None: + ddtrace_import.check() + self._tracer = tracer + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + with self._tracer.trace(operation_name) as span: + custom_span = DatadogSpan(span) + if tags: + custom_span.set_tags(tags) + + yield custom_span + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + current_span = self._tracer.current_span() + if current_span is None: + return None + + return DatadogSpan(current_span) diff --git a/testbed/deepset-ai__haystack/haystack/tracing/logging_tracer.py b/testbed/deepset-ai__haystack/haystack/tracing/logging_tracer.py new file mode 100644 index 0000000000000000000000000000000000000000..166c484a903c6974ad11263f64a09f8d91aec6ed --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/tracing/logging_tracer.py @@ -0,0 +1,85 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import contextlib +import dataclasses +from typing import Any, Dict, Iterator, Optional + +from haystack import logging +from haystack.tracing import Span, Tracer + +logger = logging.getLogger(__name__) + +RESET_COLOR = "\033[0m" + + +@dataclasses.dataclass +class LoggingSpan(Span): + operation_name: str + tags: Dict[str, Any] = dataclasses.field(default_factory=dict) + + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + self.tags[key] = value + + +class LoggingTracer(Tracer): + """ + A simple tracer that logs the operation name and tags of a span. + """ + + def __init__(self, tags_color_strings: Optional[Dict[str, str]] = None) -> None: + """ + Initialize the LoggingTracer. + + :param tags_color_strings: + A dictionary that maps tag names to color strings that should be used when logging the tags. + The color strings should be in the format of + [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors). + For example, to color the tag "haystack.component.input" in red, you would pass + `tags_color_strings={"haystack.component.input": "\x1b[1;31m"}`. + """ + + self.tags_color_strings = tags_color_strings or {} + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """ + Trace the execution of a block of code. + + :param operation_name: the name of the operation being traced. + :param tags: tags to apply to the newly created span. + :param parent_span: the parent span to use for the newly created span. Not used in this simple tracer. + :returns: the newly created span. + """ + + custom_span = LoggingSpan(operation_name, tags=tags or {}) + + try: + yield custom_span + except Exception as e: + raise e + # we make sure to log the operation name and tags of the span when the context manager exits + # both in case of success and error + finally: + operation_name = custom_span.operation_name + tags = custom_span.tags or {} + logger.debug("Operation: {operation_name}", operation_name=operation_name) + for tag_name, tag_value in tags.items(): + color_string = self.tags_color_strings.get(tag_name, "") + logger.debug( + color_string + "{tag_name}={tag_value}" + RESET_COLOR, tag_name=tag_name, tag_value=tag_value + ) + + def current_span(self) -> Optional[Span]: + """Return the current active span, if any.""" + # we don't store spans in this simple tracer + return None diff --git a/testbed/deepset-ai__haystack/haystack/tracing/opentelemetry.py b/testbed/deepset-ai__haystack/haystack/tracing/opentelemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..88c61301cd60132cd1cac8f91573d2f08f68aa68 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/tracing/opentelemetry.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import contextlib +from typing import Any, Dict, Iterator, Optional + +from haystack.lazy_imports import LazyImport +from haystack.tracing import Span, Tracer +from haystack.tracing import utils as tracing_utils + +with LazyImport("Run 'pip install opentelemetry-sdk'") as opentelemetry_import: + import opentelemetry + import opentelemetry.trace + + +class OpenTelemetrySpan(Span): + def __init__(self, span: "opentelemetry.trace.Span") -> None: + self._span = span + + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + coerced_value = tracing_utils.coerce_tag_value(value) + self._span.set_attribute(key, coerced_value) + + def raw_span(self) -> Any: + """ + Provides access to the underlying span object of the tracer. + + :return: The underlying span object. + """ + return self._span + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + """Return a dictionary with correlation data for logs.""" + span_context = self._span.get_span_context() + return {"trace_id": span_context.trace_id, "span_id": span_context.span_id} + + +class OpenTelemetryTracer(Tracer): + def __init__(self, tracer: "opentelemetry.trace.Tracer") -> None: + opentelemetry_import.check() + self._tracer = tracer + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + with self._tracer.start_as_current_span(operation_name) as raw_span: + span = OpenTelemetrySpan(raw_span) + if tags: + span.set_tags(tags) + + yield span + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + current_span = opentelemetry.trace.get_current_span() + if isinstance(current_span, opentelemetry.trace.NonRecordingSpan): + return None + + return OpenTelemetrySpan(current_span) diff --git a/testbed/deepset-ai__haystack/haystack/tracing/tracer.py b/testbed/deepset-ai__haystack/haystack/tracing/tracer.py new file mode 100644 index 0000000000000000000000000000000000000000..4afe7e3db7cfdad73eba4abe7a164a5f89fbfaa9 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/tracing/tracer.py @@ -0,0 +1,239 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import abc +import contextlib +import os +from typing import Any, Dict, Iterator, Optional + +from haystack import logging + +HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR = "HAYSTACK_AUTO_TRACE_ENABLED" +HAYSTACK_CONTENT_TRACING_ENABLED_ENV_VAR = "HAYSTACK_CONTENT_TRACING_ENABLED" + +logger = logging.getLogger(__name__) + + +class Span(abc.ABC): + """Interface for an instrumented operation.""" + + @abc.abstractmethod + def set_tag(self, key: str, value: Any) -> None: + """ + Set a single tag on the span. + + Note that the value will be serialized to a string, so it's best to use simple types like strings, numbers, or + booleans. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + pass + + def set_tags(self, tags: Dict[str, Any]) -> None: + """ + Set multiple tags on the span. + + :param tags: a mapping of tag names to tag values. + """ + for key, value in tags.items(): + self.set_tag(key, value) + + def raw_span(self) -> Any: + """ + Provides access to the underlying span object of the tracer. + + Use this if you need full access to the underlying span object. + + :return: The underlying span object. + """ + return self + + def set_content_tag(self, key: str, value: Any) -> None: + """ + Set a single tag containing content information. + + Content is sensitive information such as + - the content of a query + - the content of a document + - the content of an answer + + By default, this behavior is disabled. To enable it + - set the environment variable `HAYSTACK_CONTENT_TRACING_ENABLED` to `true` or + - override the `set_content_tag` method in a custom tracer implementation. + + :param key: the name of the tag. + :param value: the value of the tag. + """ + if tracer.is_content_tracing_enabled: + self.set_tag(key, value) + + def get_correlation_data_for_logs(self) -> Dict[str, Any]: + """ + Return a dictionary with correlation data for logs. + + This is useful if you want to correlate logs with traces. + """ + return {} + + +class Tracer(abc.ABC): + """Interface for instrumenting code by creating and submitting spans.""" + + @abc.abstractmethod + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """ + Trace the execution of a block of code. + + :param operation_name: the name of the operation being traced. + :param tags: tags to apply to the newly created span. + :param parent_span: the parent span to use for the newly created span. + If `None`, the newly created span will be a root span. + :return: the newly created span. + """ + pass + + @abc.abstractmethod + def current_span(self) -> Optional[Span]: + """ + Returns the currently active span. If no span is active, returns `None`. + + :return: Currently active span or `None` if no span is active. + """ + pass + + +class ProxyTracer(Tracer): + """ + Container for the actual tracer instance. + + This eases + - replacing the actual tracer instance without having to change the global tracer instance + - implementing default behavior for the tracer + """ + + def __init__(self, provided_tracer: Tracer) -> None: + self.actual_tracer: Tracer = provided_tracer + self.is_content_tracing_enabled = os.getenv(HAYSTACK_CONTENT_TRACING_ENABLED_ENV_VAR, "false").lower() == "true" + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + with self.actual_tracer.trace(operation_name, tags=tags, parent_span=parent_span) as span: + yield span + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + return self.actual_tracer.current_span() + + +class NullSpan(Span): + """A no-op implementation of the `Span` interface. This is used when tracing is disabled.""" + + def set_tag(self, key: str, value: Any) -> None: + """Set a single tag on the span.""" + pass + + +class NullTracer(Tracer): + """A no-op implementation of the `Tracer` interface. This is used when tracing is disabled.""" + + @contextlib.contextmanager + def trace( + self, operation_name: str, tags: Optional[Dict[str, Any]] = None, parent_span: Optional[Span] = None + ) -> Iterator[Span]: + """Activate and return a new span that inherits from the current active span.""" + yield NullSpan() + + def current_span(self) -> Optional[Span]: + """Return the current active span""" + return NullSpan() + + +# We use the proxy pattern to allow for easy enabling and disabling of tracing without having to change the global +# tracer instance. That's especially convenient if users import the object directly +# (in that case we'd have to monkey-patch it in all of these modules). +tracer: ProxyTracer = ProxyTracer(provided_tracer=NullTracer()) + + +def enable_tracing(provided_tracer: Tracer) -> None: + """Enable tracing by setting the global tracer instance.""" + tracer.actual_tracer = provided_tracer + + +def disable_tracing() -> None: + """Disable tracing by setting the global tracer instance to a no-op tracer.""" + tracer.actual_tracer = NullTracer() + + +def is_tracing_enabled() -> bool: + """Return whether tracing is enabled.""" + return not isinstance(tracer.actual_tracer, NullTracer) + + +def auto_enable_tracing() -> None: + """ + Auto-enable the right tracing backend. + + This behavior can be disabled by setting the environment variable `HAYSTACK_AUTO_TRACE_ENABLED` to `false`. + Note that it will only work correctly if tracing was configured _before_ Haystack is imported. + """ + if os.getenv(HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR, "true").lower() == "false": + logger.info( + "Tracing disabled via environment variable '{env_key}'", env_key=HAYSTACK_AUTO_TRACE_ENABLED_ENV_VAR + ) + return + + if is_tracing_enabled(): + return # tracing already enabled + + tracer = _auto_configured_opentelemetry_tracer() or _auto_configured_datadog_tracer() + if tracer: + enable_tracing(tracer) + logger.info("Auto-enabled tracing for '{tracer}'", tracer=tracer.__class__.__name__) + + +def _auto_configured_opentelemetry_tracer() -> Optional[Tracer]: + # we implement this here and not in the `opentelemetry` module to avoid import warnings when OpenTelemetry is not + # installed + try: + import opentelemetry.trace + + # the safest way to check if tracing is enabled is to try to start a span and see if it's a no-op span + # alternatively we could of course check `opentelemetry.trace._TRACER_PROVIDER` + # but that's not part of the public API and could change in the future + with opentelemetry.trace.get_tracer("haystack").start_as_current_span("haystack.tracing.auto_enable") as span: + if isinstance(span, opentelemetry.trace.NonRecordingSpan): + return None + + from haystack.tracing.opentelemetry import OpenTelemetryTracer + + return OpenTelemetryTracer(opentelemetry.trace.get_tracer("haystack")) + except ImportError: + pass + + return None + + +def _auto_configured_datadog_tracer() -> Optional[Tracer]: + # we implement this here and not in the `datadog` module to avoid import warnings when Datadog is not installed + try: + from ddtrace import tracer + + from haystack.tracing.datadog import DatadogTracer + + if tracer.enabled: + return DatadogTracer(tracer=tracer) + except ImportError: + pass + + return None + + +auto_enable_tracing() diff --git a/testbed/deepset-ai__haystack/haystack/tracing/utils.py b/testbed/deepset-ai__haystack/haystack/tracing/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e87c63600848a70531b08877924f01774db1eeb --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/tracing/utils.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from typing import Any, Union + +from haystack import logging + +logger = logging.getLogger(__name__) + +PRIMITIVE_TYPES = (bool, str, int, float) + + +def coerce_tag_value(value: Any) -> Union[bool, str, int, float]: + """ + Coerces span tag values to compatible types for the tracing backend. + + Most tracing libraries don't support sending complex types to the backend. Hence, we need to convert them to + compatible types. + + :param value: an arbitrary value which should be coerced to a compatible type + :return: the value coerced to a compatible type + """ + if isinstance(value, PRIMITIVE_TYPES): + return value + + if value is None: + return "" + + try: + # do that with-in try-except because who knows what kind of objects are being passed + serializable = _serializable_value(value) + return json.dumps(serializable) + except Exception as error: + logger.debug("Failed to coerce tag value to string: {error}", error=error) + + # Our last resort is to convert the value to a string + return str(value) + + +def _serializable_value(value: Any) -> Any: + if isinstance(value, list): + return [_serializable_value(v) for v in value] + + if isinstance(value, dict): + return {k: _serializable_value(v) for k, v in value.items()} + + if getattr(value, "to_dict", None): + return _serializable_value(value.to_dict()) + + return value diff --git a/testbed/deepset-ai__haystack/haystack/utils/__init__.py b/testbed/deepset-ai__haystack/haystack/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc46f07f438832373b7bbabef6847606e2879446 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/__init__.py @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from .auth import Secret, deserialize_secrets_inplace +from .callable_serialization import deserialize_callable, serialize_callable +from .device import ComponentDevice, Device, DeviceMap, DeviceType +from .docstore_deserialization import deserialize_document_store_in_init_params_inplace +from .expit import expit +from .filters import document_matches_filter, raise_on_invalid_filter_syntax +from .jinja2_extensions import Jinja2TimeExtension +from .jupyter import is_in_jupyter +from .requests_utils import request_with_retry +from .type_serialization import deserialize_type, serialize_type + +__all__ = [ + "Secret", + "deserialize_secrets_inplace", + "ComponentDevice", + "Device", + "DeviceMap", + "DeviceType", + "expit", + "document_matches_filter", + "raise_on_invalid_filter_syntax", + "is_in_jupyter", + "request_with_retry", + "serialize_callable", + "deserialize_callable", + "serialize_type", + "deserialize_type", + "deserialize_document_store_in_init_params_inplace", + "Jinja2TimeExtension", +] diff --git a/testbed/deepset-ai__haystack/haystack/utils/auth.py b/testbed/deepset-ai__haystack/haystack/utils/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..61638f2057312a0668280dae009d47ef5d92629d --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/auth.py @@ -0,0 +1,229 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from abc import ABC, abstractmethod +from dataclasses import dataclass +from enum import Enum +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union + + +class SecretType(Enum): + TOKEN = "token" + ENV_VAR = "env_var" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "SecretType": + """ + Convert a string to a SecretType. + + :param string: The string to convert. + """ + mapping = {e.value: e for e in SecretType} + _type = mapping.get(string) + if _type is None: + raise ValueError(f"Unknown secret type '{string}'") + return _type + + +class Secret(ABC): + """ + Encapsulates a secret used for authentication. + + Usage example: + ```python + from haystack.components.generators import OpenAIGenerator + from haystack.utils import Secret + + generator = OpenAIGenerator(api_key=Secret.from_token("")) + ``` + """ + + @staticmethod + def from_token(token: str) -> "Secret": + """ + Create a token-based secret. Cannot be serialized. + + :param token: + The token to use for authentication. + """ + return TokenSecret(_token=token) + + @staticmethod + def from_env_var(env_vars: Union[str, List[str]], *, strict: bool = True) -> "Secret": + """ + Create an environment variable-based secret. Accepts one or more environment variables. + + Upon resolution, it returns a string token from the first environment variable that is set. + + :param env_vars: + A single environment variable or an ordered list of + candidate environment variables. + :param strict: + Whether to raise an exception if none of the environment + variables are set. + """ + if isinstance(env_vars, str): + env_vars = [env_vars] + return EnvVarSecret(_env_vars=tuple(env_vars), _strict=strict) + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the secret to a JSON-serializable dictionary. + + Some secrets may not be serializable. + + :returns: + The serialized policy. + """ + out = {"type": self.type.value} + inner = self._to_dict() + assert all(k not in inner for k in out.keys()) + out.update(inner) + return out + + @staticmethod + def from_dict(dict: Dict[str, Any]) -> "Secret": # noqa:A002 + """ + Create a secret from a JSON-serializable dictionary. + + :param dict: + The dictionary with the serialized data. + :returns: + The deserialized secret. + """ + secret_map = {SecretType.TOKEN: TokenSecret, SecretType.ENV_VAR: EnvVarSecret} + secret_type = SecretType.from_str(dict["type"]) + return secret_map[secret_type]._from_dict(dict) # type: ignore + + @abstractmethod + def resolve_value(self) -> Optional[Any]: + """ + Resolve the secret to an atomic value. The semantics of the value is secret-dependent. + + :returns: + The value of the secret, if any. + """ + pass + + @property + @abstractmethod + def type(self) -> SecretType: + """ + The type of the secret. + """ + pass + + @abstractmethod + def _to_dict(self) -> Dict[str, Any]: + pass + + @staticmethod + @abstractmethod + def _from_dict(_: Dict[str, Any]) -> "Secret": + pass + + +@dataclass(frozen=True) +class TokenSecret(Secret): + """ + A secret that uses a string token/API key. + + Cannot be serialized. + """ + + _token: str + _type: SecretType = SecretType.TOKEN + + def __post_init__(self): + super().__init__() + assert self._type == SecretType.TOKEN + + if len(self._token) == 0: + raise ValueError("Authentication token cannot be empty.") + + def _to_dict(self) -> Dict[str, Any]: + raise ValueError( + "Cannot serialize token-based secret. Use an alternative secret type like environment variables." + ) + + @staticmethod + def _from_dict(_: Dict[str, Any]) -> "Secret": + raise ValueError( + "Cannot deserialize token-based secret. Use an alternative secret type like environment variables." + ) + + def resolve_value(self) -> Optional[Any]: + """Return the token.""" + return self._token + + @property + def type(self) -> SecretType: + """The type of the secret.""" + return self._type + + +@dataclass(frozen=True) +class EnvVarSecret(Secret): + """ + A secret that accepts one or more environment variables. + + Upon resolution, it returns a string token from the first environment variable that is set. Can be serialized. + """ + + _env_vars: Tuple[str, ...] + _strict: bool = True + _type: SecretType = SecretType.ENV_VAR + + def __post_init__(self): + super().__init__() + assert self._type == SecretType.ENV_VAR + + if len(self._env_vars) == 0: + raise ValueError("One or more environment variables must be provided for the secret.") + + def _to_dict(self) -> Dict[str, Any]: + return {"env_vars": list(self._env_vars), "strict": self._strict} + + @staticmethod + def _from_dict(dictionary: Dict[str, Any]) -> "Secret": + return EnvVarSecret(tuple(dictionary["env_vars"]), _strict=dictionary["strict"]) + + def resolve_value(self) -> Optional[Any]: + """Resolve the secret to an atomic value. The semantics of the value is secret-dependent.""" + out = None + for env_var in self._env_vars: + value = os.getenv(env_var) + if value is not None: + out = value + break + if out is None and self._strict: + raise ValueError(f"None of the following authentication environment variables are set: {self._env_vars}") + return out + + @property + def type(self) -> SecretType: + """The type of the secret.""" + return self._type + + +def deserialize_secrets_inplace(data: Dict[str, Any], keys: Iterable[str], *, recursive: bool = False): + """ + Deserialize secrets in a dictionary inplace. + + :param data: + The dictionary with the serialized data. + :param keys: + The keys of the secrets to deserialize. + :param recursive: + Whether to recursively deserialize nested dictionaries. + """ + for k, v in data.items(): + if isinstance(v, dict) and recursive: + deserialize_secrets_inplace(v, keys) + elif k in keys and v is not None: + data[k] = Secret.from_dict(v) diff --git a/testbed/deepset-ai__haystack/haystack/utils/base_serialization.py b/testbed/deepset-ai__haystack/haystack/utils/base_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..f18f352a62316750621034cc0b24f2d619376fdd --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/base_serialization.py @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict + +from haystack.core.errors import DeserializationError, SerializationError +from haystack.core.serialization import generate_qualified_class_name, import_class_by_name + + +def serialize_class_instance(obj: Any) -> Dict[str, Any]: + """ + Serializes an object that has a `to_dict` method into a dictionary. + + :param obj: + The object to be serialized. + :returns: + A dictionary representation of the object. + :raises SerializationError: + If the object does not have a `to_dict` method. + """ + if not hasattr(obj, "to_dict"): + raise SerializationError(f"Object of class '{type(obj).__name__}' does not have a 'to_dict' method") + + output = obj.to_dict() + return {"type": generate_qualified_class_name(type(obj)), "data": output} + + +def deserialize_class_instance(data: Dict[str, Any]) -> Any: + """ + Deserializes an object from a dictionary representation generated by `auto_serialize_class_instance`. + + :param data: + The dictionary to deserialize from. + :returns: + The deserialized object. + :raises DeserializationError: + If the serialization data is malformed, the class type cannot be imported, or the + class does not have a `from_dict` method. + """ + if "type" not in data: + raise DeserializationError("Missing 'type' in serialization data") + if "data" not in data: + raise DeserializationError("Missing 'data' in serialization data") + + try: + obj_class = import_class_by_name(data["type"]) + except ImportError as e: + raise DeserializationError(f"Class '{data['type']}' not correctly imported") from e + + if not hasattr(obj_class, "from_dict"): + raise DeserializationError(f"Class '{data['type']}' does not have a 'from_dict' method") + + return obj_class.from_dict(data["data"]) diff --git a/testbed/deepset-ai__haystack/haystack/utils/callable_serialization.py b/testbed/deepset-ai__haystack/haystack/utils/callable_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..72a57c5ab395c25bbb09fa168da2f7523c5ac296 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/callable_serialization.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import inspect +import sys +from typing import Callable, Optional + +from haystack import DeserializationError + + +def serialize_callable(callable_handle: Callable) -> str: + """ + Serializes a callable to its full path. + + :param callable_handle: The callable to serialize + :return: The full path of the callable + """ + module = inspect.getmodule(callable_handle) + + # Get the full package path of the function + if module is not None: + full_path = f"{module.__name__}.{callable_handle.__name__}" + else: + full_path = callable_handle.__name__ + return full_path + + +def deserialize_callable(callable_handle: str) -> Optional[Callable]: + """ + Deserializes a callable given its full import path as a string. + + :param callable_handle: The full path of the callable_handle + :return: The callable + :raises DeserializationError: If the callable cannot be found + """ + parts = callable_handle.split(".") + module_name = ".".join(parts[:-1]) + function_name = parts[-1] + module = sys.modules.get(module_name, None) + if not module: + raise DeserializationError(f"Could not locate the module of the callable: {module_name}") + deserialized_callable = getattr(module, function_name, None) + if not deserialized_callable: + raise DeserializationError(f"Could not locate the callable: {function_name}") + return deserialized_callable diff --git a/testbed/deepset-ai__haystack/haystack/utils/device.py b/testbed/deepset-ai__haystack/haystack/utils/device.py new file mode 100644 index 0000000000000000000000000000000000000000..ab635184ed817d621e50fc8bb0c4fa914cb5f6c8 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/device.py @@ -0,0 +1,532 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, Optional, Tuple, Union + +from haystack import logging +from haystack.lazy_imports import LazyImport + +logger = logging.getLogger(__name__) + +with LazyImport( + message="PyTorch must be installed to use torch.device or use GPU support in HuggingFace transformers. " + "Run 'pip install \"transformers[torch]\"'" +) as torch_import: + import torch + + +class DeviceType(Enum): + """ + Represents device types supported by Haystack. + + This also includes devices that are not directly used by models - for example, the disk device is exclusively used + in device maps for frameworks that support offloading model weights to disk. + """ + + CPU = "cpu" + GPU = "cuda" + DISK = "disk" + MPS = "mps" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "DeviceType": + """ + Create a device type from a string. + + :param string: + The string to convert. + :returns: + The device type. + """ + mapping = {e.value: e for e in DeviceType} + _type = mapping.get(string) + if _type is None: + raise ValueError(f"Unknown device type string '{string}'") + return _type + + +@dataclass +class Device: + """ + A generic representation of a device. + + :param type: + The device type. + :param id: + The optional device id. + """ + + type: DeviceType + id: Optional[int] = field(default=None) + + def __init__(self, type: DeviceType, id: Optional[int] = None): # noqa:A002 + """ + Create a generic device. + + :param type: + The device type. + :param id: + The device id. + """ + if id is not None and id < 0: + raise ValueError(f"Device id must be >= 0, got {id}") + + self.type = type + self.id = id + + def __str__(self): + if self.id is None: + return str(self.type) + else: + return f"{self.type}:{self.id}" + + @staticmethod + def cpu() -> "Device": + """ + Create a generic CPU device. + + :returns: + The CPU device. + """ + return Device(DeviceType.CPU) + + @staticmethod + def gpu(id: int = 0) -> "Device": # noqa:A002 + """ + Create a generic GPU device. + + :param id: + The GPU id. + :returns: + The GPU device. + """ + return Device(DeviceType.GPU, id) + + @staticmethod + def disk() -> "Device": + """ + Create a generic disk device. + + :returns: + The disk device. + """ + return Device(DeviceType.DISK) + + @staticmethod + def mps() -> "Device": + """ + Create a generic Apple Metal Performance Shader device. + + :returns: + The MPS device. + """ + return Device(DeviceType.MPS) + + @staticmethod + def from_str(string: str) -> "Device": + """ + Create a generic device from a string. + + :returns: + The device. + + """ + device_type_str, device_id = _split_device_string(string) + return Device(DeviceType.from_str(device_type_str), device_id) + + +@dataclass +class DeviceMap: + """ + A generic mapping from strings to devices. + + The semantics of the strings are dependent on target framework. Primarily used to deploy HuggingFace models to + multiple devices. + + :param mapping: + Dictionary mapping strings to devices. + """ + + mapping: Dict[str, Device] = field(default_factory=dict, hash=False) + + def __getitem__(self, key: str) -> Device: + return self.mapping[key] + + def __setitem__(self, key: str, value: Device): + self.mapping[key] = value + + def __contains__(self, key: str) -> bool: + return key in self.mapping + + def __len__(self) -> int: + return len(self.mapping) + + def __iter__(self): + return iter(self.mapping.items()) + + def to_dict(self) -> Dict[str, str]: + """ + Serialize the mapping to a JSON-serializable dictionary. + + :returns: + The serialized mapping. + """ + return {key: str(device) for key, device in self.mapping.items()} + + @property + def first_device(self) -> Optional[Device]: + """ + Return the first device in the mapping, if any. + + :returns: + The first device. + """ + if not self.mapping: + return None + else: + return next(iter(self.mapping.values())) + + @staticmethod + def from_dict(dict: Dict[str, str]) -> "DeviceMap": # noqa:A002 + """ + Create a generic device map from a JSON-serialized dictionary. + + :param dict: + The serialized mapping. + :returns: + The generic device map. + """ + mapping = {} + for key, device_str in dict.items(): + mapping[key] = Device.from_str(device_str) + return DeviceMap(mapping) + + @staticmethod + def from_hf(hf_device_map: Dict[str, Union[int, str, "torch.device"]]) -> "DeviceMap": + """ + Create a generic device map from a HuggingFace device map. + + :param hf_device_map: + The HuggingFace device map. + :returns: + The deserialized device map. + """ + mapping = {} + for key, device in hf_device_map.items(): + if isinstance(device, int): + mapping[key] = Device(DeviceType.GPU, device) + elif isinstance(device, str): + device_type, device_id = _split_device_string(device) + mapping[key] = Device(DeviceType.from_str(device_type), device_id) + elif isinstance(device, torch.device): + device_type = device.type + device_id = device.index + mapping[key] = Device(DeviceType.from_str(device_type), device_id) + else: + raise ValueError( + f"Couldn't convert HuggingFace device map - unexpected device '{str(device)}' for '{key}'" + ) + return DeviceMap(mapping) + + +@dataclass(frozen=True) +class ComponentDevice: + """ + A representation of a device for a component. + + This can be either a single device or a device map. + """ + + _single_device: Optional[Device] = field(default=None) + _multiple_devices: Optional[DeviceMap] = field(default=None) + + @classmethod + def from_str(cls, device_str: str) -> "ComponentDevice": + """ + Create a component device representation from a device string. + + The device string can only represent a single device. + + :param device_str: + The device string. + :returns: + The component device representation. + """ + device = Device.from_str(device_str) + return cls.from_single(device) + + @classmethod + def from_single(cls, device: Device) -> "ComponentDevice": + """ + Create a component device representation from a single device. + + Disks cannot be used as single devices. + + :param device: + The device. + :returns: + The component device representation. + """ + if device.type == DeviceType.DISK: + raise ValueError("The disk device can only be used as a part of device maps") + + return cls(_single_device=device) + + @classmethod + def from_multiple(cls, device_map: DeviceMap) -> "ComponentDevice": + """ + Create a component device representation from a device map. + + :param device_map: + The device map. + :returns: + The component device representation. + """ + return cls(_multiple_devices=device_map) + + def _validate(self): + """ + Validate the component device representation. + """ + if not (self._single_device is not None) ^ (self._multiple_devices is not None): + raise ValueError( + "The component device can neither be empty nor contain both a single device and a device map" + ) + + def to_torch(self) -> "torch.device": + """ + Convert the component device representation to PyTorch format. + + Device maps are not supported. + + :returns: + The PyTorch device representation. + """ + self._validate() + + if self._single_device is None: + raise ValueError("Only single devices can be converted to PyTorch format") + + torch_import.check() + assert self._single_device is not None + return torch.device(str(self._single_device)) + + def to_torch_str(self) -> str: + """ + Convert the component device representation to PyTorch string format. + + Device maps are not supported. + + :returns: + The PyTorch device string representation. + """ + self._validate() + + if self._single_device is None: + raise ValueError("Only single devices can be converted to PyTorch format") + + assert self._single_device is not None + return str(self._single_device) + + def to_spacy(self) -> int: + """ + Convert the component device representation to spaCy format. + + Device maps are not supported. + + :returns: + The spaCy device representation. + """ + self._validate() + + if self._single_device is None: + raise ValueError("Only single devices can be converted to spaCy format") + + assert self._single_device is not None + if self._single_device.type == DeviceType.GPU: + assert self._single_device.id is not None + return self._single_device.id + else: + return -1 + + def to_hf(self) -> Union[Union[int, str], Dict[str, Union[int, str]]]: + """ + Convert the component device representation to HuggingFace format. + + :returns: + The HuggingFace device representation. + """ + self._validate() + + def convert_device(device: Device, *, gpu_id_only: bool = False) -> Union[int, str]: + if gpu_id_only and device.type == DeviceType.GPU: + assert device.id is not None + return device.id + else: + return str(device) + + if self._single_device is not None: + return convert_device(self._single_device) + + assert self._multiple_devices is not None + return {key: convert_device(device, gpu_id_only=True) for key, device in self._multiple_devices.mapping.items()} + + def update_hf_kwargs(self, hf_kwargs: Dict[str, Any], *, overwrite: bool) -> Dict[str, Any]: + """ + Convert the component device representation to HuggingFace format. + + Add them as canonical keyword arguments to the keyword arguments dictionary. + + :param hf_kwargs: + The HuggingFace keyword arguments dictionary. + :param overwrite: + Whether to overwrite existing device arguments. + :returns: + The HuggingFace keyword arguments dictionary. + """ + self._validate() + + if not overwrite and any(x in hf_kwargs for x in ("device", "device_map")): + return hf_kwargs + + converted = self.to_hf() + key = "device_map" if self.has_multiple_devices else "device" + hf_kwargs[key] = converted + return hf_kwargs + + @property + def has_multiple_devices(self) -> bool: + """ + Whether this component device representation contains multiple devices. + """ + self._validate() + + return self._multiple_devices is not None + + @property + def first_device(self) -> Optional["ComponentDevice"]: + """ + Return either the single device or the first device in the device map, if any. + + :returns: + The first device. + """ + self._validate() + + if self._single_device is not None: + return self.from_single(self._single_device) + + assert self._multiple_devices is not None + assert self._multiple_devices.first_device is not None + return self.from_single(self._multiple_devices.first_device) + + @staticmethod + def resolve_device(device: Optional["ComponentDevice"] = None) -> "ComponentDevice": + """ + Select a device for a component. If a device is specified, it's used. Otherwise, the default device is used. + + :param device: + The provided device, if any. + :returns: + The resolved device. + """ + if not isinstance(device, ComponentDevice) and device is not None: + raise ValueError( + f"Invalid component device type '{type(device).__name__}'. Must either be None or ComponentDevice." + ) + + if device is None: + device = ComponentDevice.from_single(_get_default_device()) + + return device + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the component device representation to a JSON-serializable dictionary. + + :returns: + The dictionary representation. + """ + if self._single_device is not None: + return {"type": "single", "device": str(self._single_device)} + elif self._multiple_devices is not None: + return {"type": "multiple", "device_map": self._multiple_devices.to_dict()} + else: + # Unreachable + assert False + + @classmethod + def from_dict(cls, dict: Dict[str, Any]) -> "ComponentDevice": # noqa:A002 + """ + Create a component device representation from a JSON-serialized dictionary. + + :param dict: + The serialized representation. + :returns: + The deserialized component device. + """ + if dict["type"] == "single": + return cls.from_str(dict["device"]) + elif dict["type"] == "multiple": + return cls.from_multiple(DeviceMap.from_dict(dict["device_map"])) + else: + raise ValueError(f"Unknown component device type '{dict['type']}' in serialized data") + + +def _get_default_device() -> Device: + """ + Return the default device for Haystack. + + Precedence: + GPU > MPS > CPU. If PyTorch is not installed, only CPU is available. + + :returns: + The default device. + """ + try: + torch_import.check() + + has_mps = ( + hasattr(torch.backends, "mps") + and torch.backends.mps.is_available() + and os.getenv("HAYSTACK_MPS_ENABLED", "true") != "false" + ) + has_cuda = torch.cuda.is_available() + except ImportError: + has_mps = False + has_cuda = False + + if has_cuda: + return Device.gpu() + elif has_mps: + return Device.mps() + else: + return Device.cpu() + + +def _split_device_string(string: str) -> Tuple[str, Optional[int]]: + """ + Split a device string into device type and device id. + + :param string: + The device string to split. + :returns: + The device type and device id, if any. + """ + if ":" in string: + device_type, device_id_str = string.split(":") + try: + device_id = int(device_id_str) + except ValueError: + raise ValueError(f"Device id must be an integer, got {device_id_str}") + else: + device_type = string + device_id = None + return device_type, device_id diff --git a/testbed/deepset-ai__haystack/haystack/utils/docstore_deserialization.py b/testbed/deepset-ai__haystack/haystack/utils/docstore_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..41d8b2714dd47d26f35f99d92e9063f712688176 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/docstore_deserialization.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, Dict + +from haystack import DeserializationError +from haystack.core.serialization import default_from_dict, import_class_by_name + + +def deserialize_document_store_in_init_params_inplace(data: Dict[str, Any], key: str = "document_store"): + """ + Deserializes a generic document store from the init_parameters of a serialized component in place. + + :param data: + The dictionary to deserialize from. + :param key: + The key in the `data["init_parameters"]` dictionary where the document store is specified. + :returns: + The dictionary, with the document store deserialized. + + :raises DeserializationError: + If the document store is not properly specified in the serialization data or its type cannot be imported. + """ + init_params = data.get("init_parameters", {}) + if key not in init_params: + raise DeserializationError(f"Missing '{key}' in serialization data") + if "type" not in init_params[key]: + raise DeserializationError(f"Missing 'type' in {key} serialization data") + + doc_store_data = data["init_parameters"][key] + try: + doc_store_class = import_class_by_name(doc_store_data["type"]) + except ImportError as e: + raise DeserializationError(f"Class '{doc_store_data['type']}' not correctly imported") from e + if hasattr(doc_store_class, "from_dict"): + data["init_parameters"][key] = doc_store_class.from_dict(doc_store_data) + else: + data["init_parameters"][key] = default_from_dict(doc_store_class, doc_store_data) diff --git a/testbed/deepset-ai__haystack/haystack/utils/expit.py b/testbed/deepset-ai__haystack/haystack/utils/expit.py new file mode 100644 index 0000000000000000000000000000000000000000..2f29ce99bd184f1a0a5e08955223d01dd69fd662 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/expit.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from numpy import exp + + +def expit(x) -> float: + """ + Compute logistic sigmoid function. Maps input values to a range between 0 and 1 + + :param x: input value. Can be a scalar or a numpy array. + """ + return 1 / (1 + exp(-x)) diff --git a/testbed/deepset-ai__haystack/haystack/utils/filters.py b/testbed/deepset-ai__haystack/haystack/utils/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a3133e3c63cef39a724090e7d8a67abbf70306 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/filters.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import fields +from datetime import datetime +from typing import Any, Dict, List, Optional + +import pandas as pd + +from haystack.dataclasses import Document +from haystack.errors import FilterError + + +def raise_on_invalid_filter_syntax(filters: Optional[Dict[str, Any]] = None): + """ + Raise an error if the filter syntax is invalid. + """ + if filters and ("operator" not in filters or "conditions" not in filters): + msg = "Invalid filter syntax. See https://docs.haystack.deepset.ai/docs/metadata-filtering for details." + raise FilterError(msg) + + +def document_matches_filter(filters: Dict[str, Any], document: Document) -> bool: + """ + Return whether `filters` match the Document. + + For a detailed specification of the filters, refer to the + `DocumentStore.filter_documents()` protocol documentation. + """ + if "field" in filters: + return _comparison_condition(filters, document) + return _logic_condition(filters, document) + + +def _and(document: Document, conditions: List[Dict[str, Any]]) -> bool: + return all(_comparison_condition(condition, document) for condition in conditions) + + +def _or(document: Document, conditions: List[Dict[str, Any]]) -> bool: + return any(_comparison_condition(condition, document) for condition in conditions) + + +def _not(document: Document, conditions: List[Dict[str, Any]]) -> bool: + return not _and(document, conditions) + + +LOGICAL_OPERATORS = {"NOT": _not, "OR": _or, "AND": _and} + + +def _equal(document_value: Any, filter_value: Any) -> bool: + if isinstance(document_value, pd.DataFrame): + document_value = document_value.to_json() + + if isinstance(filter_value, pd.DataFrame): + filter_value = filter_value.to_json() + + return document_value == filter_value + + +def _not_equal(document_value: Any, filter_value: Any) -> bool: + return not _equal(document_value=document_value, filter_value=filter_value) + + +def _greater_than(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + if isinstance(document_value, str) or isinstance(filter_value, str): + try: + document_value = datetime.fromisoformat(document_value) + filter_value = datetime.fromisoformat(filter_value) + except (ValueError, TypeError) as exc: + msg = ( + "Can't compare strings using operators '>', '>=', '<', '<='. " + "Strings are only comparable if they are ISO formatted dates." + ) + raise FilterError(msg) from exc + if type(filter_value) in [list, pd.DataFrame]: + msg = f"Filter value can't be of type {type(filter_value)} using operators '>', '>=', '<', '<='" + raise FilterError(msg) + return document_value > filter_value + + +def _greater_than_equal(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + return _equal(document_value=document_value, filter_value=filter_value) or _greater_than( + document_value=document_value, filter_value=filter_value + ) + + +def _less_than(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + return not _greater_than_equal(document_value=document_value, filter_value=filter_value) + + +def _less_than_equal(document_value: Any, filter_value: Any) -> bool: + if document_value is None or filter_value is None: + # We can't compare None values reliably using operators '>', '>=', '<', '<=' + return False + + return not _greater_than(document_value=document_value, filter_value=filter_value) + + +def _in(document_value: Any, filter_value: Any) -> bool: + if not isinstance(filter_value, list): + msg = ( + f"Filter value must be a `list` when using operator 'in' or 'not in', " + f"received type '{type(filter_value)}'" + ) + raise FilterError(msg) + return any(_equal(e, document_value) for e in filter_value) + + +def _not_in(document_value: Any, filter_value: Any) -> bool: + return not _in(document_value=document_value, filter_value=filter_value) + + +COMPARISON_OPERATORS = { + "==": _equal, + "!=": _not_equal, + ">": _greater_than, + ">=": _greater_than_equal, + "<": _less_than, + "<=": _less_than_equal, + "in": _in, + "not in": _not_in, +} + + +def _logic_condition(condition: Dict[str, Any], document: Document) -> bool: + if "operator" not in condition: + msg = f"'operator' key missing in {condition}" + raise FilterError(msg) + if "conditions" not in condition: + msg = f"'conditions' key missing in {condition}" + raise FilterError(msg) + operator: str = condition["operator"] + conditions: List[Dict[str, Any]] = condition["conditions"] + return LOGICAL_OPERATORS[operator](document, conditions) + + +def _comparison_condition(condition: Dict[str, Any], document: Document) -> bool: + if "field" not in condition: + # 'field' key is only found in comparison dictionaries. + # We assume this is a logic dictionary since it's not present. + return _logic_condition(condition, document) + field: str = condition["field"] + + if "operator" not in condition: + msg = f"'operator' key missing in {condition}" + raise FilterError(msg) + if "value" not in condition: + msg = f"'value' key missing in {condition}" + raise FilterError(msg) + + if "." in field: + # Handles fields formatted like so: + # 'meta.person.name' + parts = field.split(".") + document_value = getattr(document, parts[0]) + for part in parts[1:]: + if part not in document_value: + # If a field is not found we treat it as None + document_value = None + break + document_value = document_value[part] + elif field not in [f.name for f in fields(document)]: + # Converted legacy filters don't add the `meta.` prefix, so we assume + # that all filter fields that are not actual fields in Document are converted + # filters. + # + # We handle this to avoid breaking compatibility with converted legacy filters. + # This will be removed as soon as we stop supporting legacy filters. + document_value = document.meta.get(field) + else: + document_value = getattr(document, field) + operator: str = condition["operator"] + filter_value: Any = condition["value"] + return COMPARISON_OPERATORS[operator](filter_value=filter_value, document_value=document_value) diff --git a/testbed/deepset-ai__haystack/haystack/utils/hf.py b/testbed/deepset-ai__haystack/haystack/utils/hf.py new file mode 100644 index 0000000000000000000000000000000000000000..89f036a70545e54e337f1ff55842649fb2c2746f --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/hf.py @@ -0,0 +1,357 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import copy +import inspect +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Union + +from haystack import logging +from haystack.dataclasses import StreamingChunk +from haystack.lazy_imports import LazyImport +from haystack.utils.auth import Secret +from haystack.utils.device import ComponentDevice + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as torch_import: + import torch + +with LazyImport(message="Run 'pip install \"huggingface_hub>=0.23.0\"'") as huggingface_hub_import: + from huggingface_hub import HfApi, InferenceClient, model_info + from huggingface_hub.utils import RepositoryNotFoundError + +logger = logging.getLogger(__name__) + + +class HFGenerationAPIType(Enum): + """ + API type to use for Hugging Face API Generators. + """ + + # HF [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference). + TEXT_GENERATION_INFERENCE = "text_generation_inference" + + # HF [Inference Endpoints](https://huggingface.co/inference-endpoints). + INFERENCE_ENDPOINTS = "inference_endpoints" + + # HF [Serverless Inference API](https://huggingface.co/inference-api). + SERVERLESS_INFERENCE_API = "serverless_inference_api" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "HFGenerationAPIType": + """ + Convert a string to a HFGenerationAPIType enum. + + :param string: The string to convert. + :return: The corresponding HFGenerationAPIType enum. + + """ + enum_map = {e.value: e for e in HFGenerationAPIType} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown Hugging Face API type '{string}'. Supported types are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +class HFEmbeddingAPIType(Enum): + """ + API type to use for Hugging Face API Embedders. + """ + + # HF [Text Embeddings Inference (TEI)](https://github.com/huggingface/text-embeddings-inference). + TEXT_EMBEDDINGS_INFERENCE = "text_embeddings_inference" + + # HF [Inference Endpoints](https://huggingface.co/inference-endpoints). + INFERENCE_ENDPOINTS = "inference_endpoints" + + # HF [Serverless Inference API](https://huggingface.co/inference-api). + SERVERLESS_INFERENCE_API = "serverless_inference_api" + + def __str__(self): + return self.value + + @staticmethod + def from_str(string: str) -> "HFEmbeddingAPIType": + """ + Convert a string to a HFEmbeddingAPIType enum. + + :param string: + :return: The corresponding HFEmbeddingAPIType enum. + """ + enum_map = {e.value: e for e in HFEmbeddingAPIType} + mode = enum_map.get(string) + if mode is None: + msg = f"Unknown Hugging Face API type '{string}'. Supported types are: {list(enum_map.keys())}" + raise ValueError(msg) + return mode + + +class HFModelType(Enum): + EMBEDDING = 1 + GENERATION = 2 + + +def serialize_hf_model_kwargs(kwargs: Dict[str, Any]): + """ + Recursively serialize HuggingFace specific model keyword arguments in-place to make them JSON serializable. + + :param kwargs: The keyword arguments to serialize + """ + torch_import.check() + + for k, v in kwargs.items(): + # torch.dtype + if isinstance(v, torch.dtype): + kwargs[k] = str(v) + + if isinstance(v, dict): + serialize_hf_model_kwargs(v) + + +def deserialize_hf_model_kwargs(kwargs: Dict[str, Any]): + """ + Recursively deserialize HuggingFace specific model keyword arguments in-place to make them JSON serializable. + + :param kwargs: The keyword arguments to deserialize + """ + torch_import.check() + + for k, v in kwargs.items(): + # torch.dtype + if isinstance(v, str) and v.startswith("torch."): + dtype_str = v.split(".")[1] + dtype = getattr(torch, dtype_str, None) + if dtype is not None and isinstance(dtype, torch.dtype): + kwargs[k] = dtype + + if isinstance(v, dict): + deserialize_hf_model_kwargs(v) + + +def resolve_hf_device_map(device: Optional[ComponentDevice], model_kwargs: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """ + Update `model_kwargs` to include the keyword argument `device_map`. + + This method is useful you want to force loading a transformers model when using `AutoModel.from_pretrained` to + use `device_map`. + + We handle the edge case where `device` and `device_map` is specified by ignoring the `device` parameter and printing + a warning. + + :param device: The device on which the model is loaded. If `None`, the default device is automatically + selected. + :param model_kwargs: Additional HF keyword arguments passed to `AutoModel.from_pretrained`. + For details on what kwargs you can pass, see the model's documentation. + """ + model_kwargs = copy.copy(model_kwargs) or {} + if model_kwargs.get("device_map"): + if device is not None: + logger.warning( + "The parameters `device` and `device_map` from `model_kwargs` are both provided. " + "Ignoring `device` and using `device_map`." + ) + # Resolve device if device_map is provided in model_kwargs + device_map = model_kwargs["device_map"] + else: + device_map = ComponentDevice.resolve_device(device).to_hf() + + # Set up device_map which allows quantized loading and multi device inference + # requires accelerate which is always installed when using `pip install transformers[torch]` + model_kwargs["device_map"] = device_map + + return model_kwargs + + +def resolve_hf_pipeline_kwargs( + huggingface_pipeline_kwargs: Dict[str, Any], + model: str, + task: Optional[str], + supported_tasks: List[str], + device: Optional[ComponentDevice], + token: Optional[Secret], +) -> Dict[str, Any]: + """ + Resolve the HuggingFace pipeline keyword arguments based on explicit user inputs. + + :param huggingface_pipeline_kwargs: Dictionary containing keyword arguments used to initialize a + Hugging Face pipeline. + :param model: The name or path of a Hugging Face model for on the HuggingFace Hub. + :param task: The task for the Hugging Face pipeline. + :param supported_tasks: The list of supported tasks to check the task of the model against. If the task of the model + is not present within this list then a ValueError is thrown. + :param device: The device on which the model is loaded. If `None`, the default device is automatically + selected. If a device/device map is specified in `huggingface_pipeline_kwargs`, it overrides this parameter. + :param token: The token to use as HTTP bearer authorization for remote files. + If the token is also specified in the `huggingface_pipeline_kwargs`, this parameter will be ignored. + """ + huggingface_hub_import.check() + + token = token.resolve_value() if token else None + # check if the huggingface_pipeline_kwargs contain the essential parameters + # otherwise, populate them with values from other init parameters + huggingface_pipeline_kwargs.setdefault("model", model) + huggingface_pipeline_kwargs.setdefault("token", token) + + device = ComponentDevice.resolve_device(device) + device.update_hf_kwargs(huggingface_pipeline_kwargs, overwrite=False) + + # task identification and validation + task = task or huggingface_pipeline_kwargs.get("task") + if task is None and isinstance(huggingface_pipeline_kwargs["model"], str): + task = model_info(huggingface_pipeline_kwargs["model"], token=huggingface_pipeline_kwargs["token"]).pipeline_tag + + if task not in supported_tasks: + raise ValueError(f"Task '{task}' is not supported. " f"The supported tasks are: {', '.join(supported_tasks)}.") + huggingface_pipeline_kwargs["task"] = task + return huggingface_pipeline_kwargs + + +def check_valid_model(model_id: str, model_type: HFModelType, token: Optional[Secret]) -> None: + """ + Check if the provided model ID corresponds to a valid model on HuggingFace Hub. + + Also check if the model is an embedding or generation model. + + :param model_id: A string representing the HuggingFace model ID. + :param model_type: the model type, HFModelType.EMBEDDING or HFModelType.GENERATION + :param token: The optional authentication token. + :raises ValueError: If the model is not found or is not a embedding model. + """ + huggingface_hub_import.check() + + api = HfApi() + try: + model_info = api.model_info(model_id, token=token.resolve_value() if token else None) + except RepositoryNotFoundError as e: + raise ValueError( + f"Model {model_id} not found on HuggingFace Hub. Please provide a valid HuggingFace model_id." + ) from e + + if model_type == HFModelType.EMBEDDING: + allowed_model = model_info.pipeline_tag in ["sentence-similarity", "feature-extraction"] + error_msg = f"Model {model_id} is not a embedding model. Please provide a embedding model." + elif model_type == HFModelType.GENERATION: + allowed_model = model_info.pipeline_tag in ["text-generation", "text2text-generation"] + error_msg = f"Model {model_id} is not a text generation model. Please provide a text generation model." + else: + allowed_model = False + error_msg = f"Unknown model type for {model_id}" + + if not allowed_model: + raise ValueError(error_msg) + + +def check_generation_params(kwargs: Optional[Dict[str, Any]], additional_accepted_params: Optional[List[str]] = None): + """ + Check the provided generation parameters for validity. + + :param kwargs: A dictionary containing the generation parameters. + :param additional_accepted_params: An optional list of strings representing additional accepted parameters. + :raises ValueError: If any unknown text generation parameters are provided. + """ + huggingface_hub_import.check() + + if kwargs: + accepted_params = { + param + for param in inspect.signature(InferenceClient.text_generation).parameters.keys() + if param not in ["self", "prompt"] + } + if additional_accepted_params: + accepted_params.update(additional_accepted_params) + unknown_params = set(kwargs.keys()) - accepted_params + if unknown_params: + raise ValueError( + f"Unknown text generation parameters: {unknown_params}. The valid parameters are: {accepted_params}." + ) + + +with LazyImport(message="Run 'pip install \"transformers[torch]\"'") as transformers_import: + from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast, StoppingCriteria, TextStreamer + + torch_import.check() + transformers_import.check() + + class StopWordsCriteria(StoppingCriteria): + """ + Stops text generation in HuggingFace generators if any one of the stop words is generated. + + Note: When a stop word is encountered, the generation of new text is stopped. + However, if the stop word is in the prompt itself, it can stop generating new text + prematurely after the first token. This is particularly important for LLMs designed + for dialogue generation. For these models, like for example mosaicml/mpt-7b-chat, + the output includes both the new text and the original prompt. Therefore, it's important + to make sure your prompt has no stop words. + """ + + def __init__( + self, + tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], + stop_words: List[str], + device: Union[str, torch.device] = "cpu", + ): + super().__init__() + # check if tokenizer is a valid tokenizer + if not isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)): + raise ValueError( + f"Invalid tokenizer provided for StopWordsCriteria - {tokenizer}. " + f"Please provide a valid tokenizer from the HuggingFace Transformers library." + ) + if not tokenizer.pad_token: + if tokenizer.eos_token: + tokenizer.pad_token = tokenizer.eos_token + else: + tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + encoded_stop_words = tokenizer(stop_words, add_special_tokens=False, padding=True, return_tensors="pt") + self.stop_ids = encoded_stop_words.input_ids.to(device) + + def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: + """Check if any of the stop words are generated in the current text generation step.""" + for stop_id in self.stop_ids: + found_stop_word = self.is_stop_word_found(input_ids, stop_id) + if found_stop_word: + return True + return False + + @staticmethod + def is_stop_word_found(generated_text_ids: torch.Tensor, stop_id: torch.Tensor) -> bool: + """ + Performs phrase matching. + + Checks if a sequence of stop tokens appears in a continuous or sequential order within the generated text. + """ + generated_text_ids = generated_text_ids[-1] + len_generated_text_ids = generated_text_ids.size(0) + len_stop_id = stop_id.size(0) + result = all(generated_text_ids[len_generated_text_ids - len_stop_id :].eq(stop_id)) + return result + + class HFTokenStreamingHandler(TextStreamer): + """ + Streaming handler for HuggingFaceLocalGenerator and HuggingFaceLocalChatGenerator. + + Note: This is a helper class for HuggingFaceLocalGenerator & HuggingFaceLocalChatGenerator enabling streaming + of generated text via Haystack Callable[StreamingChunk, None] callbacks. + + Do not use this class directly. + """ + + def __init__( + self, + tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast], + stream_handler: Callable[[StreamingChunk], None], + stop_words: Optional[List[str]] = None, + ): + super().__init__(tokenizer=tokenizer, skip_prompt=True) # type: ignore + self.token_handler = stream_handler + self.stop_words = stop_words or [] + + def on_finalized_text(self, word: str, stream_end: bool = False): + """Callback function for handling the generated text.""" + word_to_send = word + "\n" if stream_end else word + if word_to_send.strip() not in self.stop_words: + self.token_handler(StreamingChunk(content=word_to_send)) diff --git a/testbed/deepset-ai__haystack/haystack/utils/jinja2_extensions.py b/testbed/deepset-ai__haystack/haystack/utils/jinja2_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..94d0dc8fdd869b48a4f3583260fbc0f9ac7d3c68 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/jinja2_extensions.py @@ -0,0 +1,96 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import Any, List, Optional, Union + +from jinja2 import Environment, nodes +from jinja2.ext import Extension + +from haystack.lazy_imports import LazyImport + +with LazyImport(message='Run "pip install arrow>=1.3.0"') as arrow_import: + import arrow + + +class Jinja2TimeExtension(Extension): + # Syntax for current date + tags = {"now"} + + def __init__(self, environment: Environment): # pylint: disable=useless-parent-delegation + """ + Initializes the JinjaTimeExtension object. + + :param environment: The Jinja2 environment to initialize the extension with. + It provides the context where the extension will operate. + """ + arrow_import.check() + super().__init__(environment) + + @staticmethod + def _get_datetime( + timezone: str, + operator: Optional[str] = None, + offset: Optional[str] = None, + datetime_format: Optional[str] = None, + ) -> str: + """ + Get the current datetime based on timezone, apply any offset if provided, and format the result. + + :param timezone: The timezone string (e.g., 'UTC' or 'America/New_York') for which the current + time should be fetched. + :param operator: The operator ('+' or '-') to apply to the offset (used for adding/subtracting intervals). + Defaults to None if no offset is applied, otherwise default is '+'. + :param offset: The offset string in the format 'interval=value' (e.g., 'hours=2,days=1') specifying how much + to adjust the datetime. The intervals can be any valid interval accepted + by Arrow (e.g., hours, days, weeks, months). Defaults to None if no adjustment is needed. + :param datetime_format: The format string to use for formatting the output datetime. + Defaults to '%Y-%m-%d %H:%M:%S' if not provided. + """ + try: + dt = arrow.now(timezone) + except Exception as e: + raise ValueError(f"Invalid timezone {timezone}: {e}") + + if offset and operator: + try: + # Parse the offset and apply it to the datetime object + replace_params = { + interval.strip(): float(operator + value.strip()) + for param in offset.split(",") + for interval, value in [param.split("=")] + } + # Shift the datetime fields based on the parsed offset + dt = dt.shift(**replace_params) + except (ValueError, AttributeError) as e: + raise ValueError(f"Invalid offset or operator {offset}, {operator}: {e}") + + # Use the provided format or fallback to the default one + datetime_format = datetime_format or "%Y-%m-%d %H:%M:%S" + + return dt.strftime(datetime_format) + + def parse(self, parser: Any) -> Union[nodes.Node, List[nodes.Node]]: + """ + Parse the template expression to determine how to handle the datetime formatting. + + :param parser: The parser object that processes the template expressions and manages the syntax tree. + It's used to interpret the template's structure. + """ + lineno = next(parser.stream).lineno + node = parser.parse_expression() + # Check if a custom datetime format is provided after a comma + datetime_format = parser.parse_expression() if parser.stream.skip_if("comma") else nodes.Const(None) + + # Default Add when no operator is provided + operator = "+" if isinstance(node, nodes.Add) else "-" + # Call the _get_datetime method with the appropriate operator and offset, if exist + call_method = self.call_method( + "_get_datetime", + [node.left, nodes.Const(operator), node.right, datetime_format] + if isinstance(node, (nodes.Add, nodes.Sub)) + else [node, nodes.Const(None), nodes.Const(None), datetime_format], + lineno=lineno, + ) + + return nodes.Output([call_method], lineno=lineno) diff --git a/testbed/deepset-ai__haystack/haystack/utils/jupyter.py b/testbed/deepset-ai__haystack/haystack/utils/jupyter.py new file mode 100644 index 0000000000000000000000000000000000000000..95de65b7900f2237726adda36630d86897b1551b --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/jupyter.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + + +def is_in_jupyter() -> bool: + """ + Returns `True` if in Jupyter or Google Colab, `False` otherwise. + """ + # Inspired by: + # https://github.com/explosion/spaCy/blob/e1249d3722765aaca56f538e830add7014d20e2a/spacy/util.py#L1079 + try: + # We don't need to import `get_ipython` as it's always present in Jupyter notebooks + if get_ipython().__class__.__name__ == "ZMQInteractiveShell": # type: ignore[name-defined] + return True # Jupyter notebook or qtconsole + if get_ipython().__class__.__module__ == "google.colab._shell": # type: ignore[name-defined] + return True # Colab notebook + except NameError: + pass # Probably standard Python interpreter + return False diff --git a/testbed/deepset-ai__haystack/haystack/utils/requests_utils.py b/testbed/deepset-ai__haystack/haystack/utils/requests_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..07893934e463f9be015b31bd90816856ae381dde --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/requests_utils.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import logging +from typing import List, Optional + +import requests +from tenacity import after_log, before_log, retry, retry_if_exception_type, stop_after_attempt, wait_exponential + +logger = logging.getLogger(__file__) + + +def request_with_retry( + attempts: int = 3, status_codes_to_retry: Optional[List[int]] = None, **kwargs +) -> requests.Response: + """ + Executes an HTTP request with a configurable exponential backoff retry on failures. + + Usage example: + ```python + from haystack.utils import request_with_retry + + # Sending an HTTP request with default retry configs + res = request_with_retry(method="GET", url="https://example.com") + + # Sending an HTTP request with custom number of attempts + res = request_with_retry(method="GET", url="https://example.com", attempts=10) + + # Sending an HTTP request with custom HTTP codes to retry + res = request_with_retry(method="GET", url="https://example.com", status_codes_to_retry=[408, 503]) + + # Sending an HTTP request with custom timeout in seconds + res = request_with_retry(method="GET", url="https://example.com", timeout=5) + + # Sending an HTTP request with custom authorization handling + class CustomAuth(requests.auth.AuthBase): + def __call__(self, r): + r.headers["authorization"] = "Basic " + return r + + res = request_with_retry(method="GET", url="https://example.com", auth=CustomAuth()) + + # All of the above combined + res = request_with_retry( + method="GET", + url="https://example.com", + auth=CustomAuth(), + attempts=10, + status_codes_to_retry=[408, 503], + timeout=5 + ) + + # Sending a POST request + res = request_with_retry(method="POST", url="https://example.com", data={"key": "value"}, attempts=10) + + # Retry all 5xx status codes + res = request_with_retry(method="GET", url="https://example.com", status_codes_to_retry=list(range(500, 600))) + ``` + + :param attempts: + Maximum number of attempts to retry the request. + :param status_codes_to_retry: + List of HTTP status codes that will trigger a retry. + When param is `None`, HTTP 408, 418, 429 and 503 will be retried. + :param kwargs: + Optional arguments that `request` accepts. + :returns: + The `Response` object. + """ + + if status_codes_to_retry is None: + status_codes_to_retry = [408, 418, 429, 503] + + @retry( + reraise=True, + wait=wait_exponential(), + retry=retry_if_exception_type((requests.HTTPError, TimeoutError)), + stop=stop_after_attempt(attempts), + before=before_log(logger, logging.DEBUG), + after=after_log(logger, logging.DEBUG), + ) + def run(): + timeout = kwargs.pop("timeout", 10) + res = requests.request(**kwargs, timeout=timeout) + + if res.status_code in status_codes_to_retry: + # We raise only for the status codes that must trigger a retry + res.raise_for_status() + + return res + + res = run() + # We raise here too in case the request failed with a status code that + # won't trigger a retry, this way the call will still cause an explicit exception + res.raise_for_status() + return res diff --git a/testbed/deepset-ai__haystack/haystack/utils/type_serialization.py b/testbed/deepset-ai__haystack/haystack/utils/type_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..b2dd319d52fe48e245392ee1beb7edee30816d0e --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/type_serialization.py @@ -0,0 +1,143 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import importlib +import inspect +import sys +import typing +from typing import Any, get_args, get_origin + +from haystack import DeserializationError + + +def serialize_type(target: Any) -> str: + """ + Serializes a type or an instance to its string representation, including the module name. + + This function handles types, instances of types, and special typing objects. + It assumes that non-typing objects will have a '__name__' attribute and raises + an error if a type cannot be serialized. + + :param target: + The object to serialize, can be an instance or a type. + :return: + The string representation of the type. + :raises ValueError: + If the type cannot be serialized. + """ + # If the target is a string and contains a dot, treat it as an already serialized type + if isinstance(target, str) and "." in target: + return target + + # Determine if the target is a type or an instance of a typing object + is_type_or_typing = isinstance(target, type) or bool(get_origin(target)) + type_obj = target if is_type_or_typing else type(target) + type_obj_repr = repr(type_obj) + + if type_obj_repr.startswith("typing."): + # e.g., typing.List[int] -> List[int], we'll add the module below + type_name = type_obj_repr.split(".", 1)[1] + elif origin := get_origin(type_obj): # get the origin (base type of the parameterized generic type) + # get the arguments of the generic type + args = get_args(type_obj) + args_repr = ", ".join(serialize_type(arg) for arg in args) + type_name = f"{origin.__name__}[{args_repr}]" + elif hasattr(type_obj, "__name__"): + type_name = type_obj.__name__ + else: + # If type cannot be serialized, raise an error + raise ValueError(f"Could not serialize type: {type_obj_repr}") + + module = inspect.getmodule(type_obj) + if module and hasattr(module, "__name__"): + if module.__name__ == "builtins": + # omit the module name for builtins, it just clutters the output + # e.g. instead of 'builtins.str', we'll just return 'str' + full_path = type_name + else: + full_path = f"{module.__name__}.{type_name}" + else: + full_path = type_name + + return full_path + + +def deserialize_type(type_str: str) -> Any: + """ + Deserializes a type given its full import path as a string, including nested generic types. + + This function will dynamically import the module if it's not already imported + and then retrieve the type object from it. It also handles nested generic types like + `typing.List[typing.Dict[int, str]]`. + + :param type_str: + The string representation of the type's full import path. + :returns: + The deserialized type object. + :raises DeserializationError: + If the type cannot be deserialized due to missing module or type. + """ + + type_mapping = { + list: typing.List, + dict: typing.Dict, + set: typing.Set, + tuple: typing.Tuple, + frozenset: typing.FrozenSet, + } + + def parse_generic_args(args_str): + args = [] + bracket_count = 0 + current_arg = "" + + for char in args_str: + if char == "[": + bracket_count += 1 + elif char == "]": + bracket_count -= 1 + + if char == "," and bracket_count == 0: + args.append(current_arg.strip()) + current_arg = "" + else: + current_arg += char + + if current_arg: + args.append(current_arg.strip()) + + return args + + if "[" in type_str and type_str.endswith("]"): + # Handle generics + main_type_str, generics_str = type_str.split("[", 1) + generics_str = generics_str[:-1] + + main_type = deserialize_type(main_type_str) + generic_args = tuple(deserialize_type(arg) for arg in parse_generic_args(generics_str)) + + # Reconstruct + if sys.version_info >= (3, 9) or repr(main_type).startswith("typing."): + return main_type[generic_args] + else: + return type_mapping[main_type][generic_args] # type: ignore + + else: + # Handle non-generics + parts = type_str.split(".") + module_name = ".".join(parts[:-1]) or "builtins" + type_name = parts[-1] + + module = sys.modules.get(module_name) + if not module: + try: + module = importlib.import_module(module_name) + except ImportError as e: + raise DeserializationError(f"Could not import the module: {module_name}") from e + + deserialized_type = getattr(module, type_name, None) + if not deserialized_type: + raise DeserializationError(f"Could not locate the type: {type_name} in the module: {module_name}") + + return deserialized_type diff --git a/testbed/deepset-ai__haystack/haystack/utils/url_validation.py b/testbed/deepset-ai__haystack/haystack/utils/url_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..06b6cf2ed7c62a07b07d50a30454937cc965c8af --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/utils/url_validation.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from urllib.parse import urlparse + + +def is_valid_http_url(url: str) -> bool: + """Check if a URL is a valid HTTP/HTTPS URL.""" + r = urlparse(url) + return all([r.scheme in ["http", "https"], r.netloc]) diff --git a/testbed/deepset-ai__haystack/haystack/version.py b/testbed/deepset-ai__haystack/haystack/version.py new file mode 100644 index 0000000000000000000000000000000000000000..a3133d5b2441a09819eaaf244303082cf0b5d034 --- /dev/null +++ b/testbed/deepset-ai__haystack/haystack/version.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from importlib import metadata + +try: + __version__ = str(metadata.version("haystack-ai")) +except metadata.PackageNotFoundError: + __version__ = "main" diff --git a/testbed/deepset-ai__haystack/releasenotes/config.yaml b/testbed/deepset-ai__haystack/releasenotes/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4ab01a3de79ab705ef79543ba0f8e6c0077c3bd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/config.yaml @@ -0,0 +1,47 @@ +default_branch: main +collapse_pre_releases: true +pre_release_tag_re: (?P-(?:[ab]|rc)+\d*)$ +prelude_section_name: highlights +template: | + --- + highlights: > + Replace this text with content to appear at the top of the section for this + release. The highlights might repeat some details that are also present in other notes + from the same release, that's ok. Not every release note requires highlights, + use this section only to describe major features or notable changes. + upgrade: + - | + List upgrade notes here, or remove this section. + Upgrade notes should be rare: only list known/potential breaking changes, + or major changes that require user action before the upgrade. + Notes here must include steps that users can follow to 1. know if they're + affected and 2. handle the change gracefully on their end. + features: + - | + List new features here, or remove this section. + enhancements: + - | + List new behavior that is too small to be + considered a new feature, or remove this section. + issues: + - | + List known issues here, or remove this section. For example, if some change is experimental or known to not work in some cases, it should be mentioned here. + deprecations: + - | + List deprecations notes here, or remove this section. Deprecations should not be used for something that is removed in the release, use upgrade section instead. Deprecation should allow time for users to make necessary changes for the removal to happen in a future release. + security: + - | + Add security notes here, or remove this section. + fixes: + - | + Add normal bug fixes here, or remove this section. + +sections: + # The prelude section is implicitly included. + - [upgrade, Upgrade Notes] + - [features, New Features] + - [enhancements, Enhancement Notes] + - [issues, Known Issues] + - [deprecations, Deprecation Notes] + - [security, Security Notes] + - [fixes, Bug Fixes] diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/adapt-gpt-generator-bb7f52bd67f6b197.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/adapt-gpt-generator-bb7f52bd67f6b197.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8382ecf14f89280430e1957f6aba4392c06c2033 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/adapt-gpt-generator-bb7f52bd67f6b197.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adapt GPTGenerator to use strings for input and output diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-CohereGenerator-ca55e5b8e46df754.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-CohereGenerator-ca55e5b8e46df754.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd639cceb20672efbf5ed3b83e82624bd830b540 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-CohereGenerator-ca55e5b8e46df754.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add CohereGenerator compatible with Cohere generate endpoint diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-MarkdownToTextDocument-f97ec6c5fb35527d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-MarkdownToTextDocument-f97ec6c5fb35527d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ceedb7eaaa98ec6b17c1be04539df3f639de2ad3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-MarkdownToTextDocument-f97ec6c5fb35527d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add MarkdownToTextDocument, a file converter that converts Markdown files into a text Documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7547ee187a315b748433c4acc45d0214979a7c16 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-TEI-embedders-8c76593bc25a7219.yaml @@ -0,0 +1,28 @@ +--- +features: + - | + Add HuggingFace TEI Embedders - `HuggingFaceTEITextEmbedder` and `HuggingFaceTEIDocumentEmbedder`. + + An example using `HuggingFaceTEITextEmbedder` to embed a string: + ```python + from haystack.components.embedders import HuggingFaceTEITextEmbedder + text_to_embed = "I love pizza!" + text_embedder = HuggingFaceTEITextEmbedder( + model="BAAI/bge-small-en-v1.5", url="", token="" + ) + print(text_embedder.run(text_to_embed)) + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + ``` + + An example using `HuggingFaceTEIDocumentEmbedder` to create Document embeddings: + ```python + from haystack.dataclasses import Document + from haystack.components.embedders import HuggingFaceTEIDocumentEmbedder + doc = Document(content="I love pizza!") + document_embedder = HuggingFaceTEIDocumentEmbedder( + model="BAAI/bge-small-en-v1.5", url="", token="" + ) + result = document_embedder.run([doc]) + print(result["documents"][0].embedding) + # [0.017020374536514282, -0.023255806416273117, ...] + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60e79ba40de041c8af265259845e8b31eb071bfb --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-answerbuilder-2.0-5dd255eeba68041f.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add the `AnswerBuilder` component for Haystack 2.0 that creates Answer objects from the string output of Generators. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml new file mode 100644 index 0000000000000000000000000000000000000000..10df92afb2c03837137230a76c07bcd3bab40109 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-apple-silicon-gpu-acceleration-38bf69781a933b95.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added support for Apple Silicon GPU acceleration through "mps pytorch", enabling better performance on Apple M1 hardware. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c890a442977a404d6bbac07322ae0c1e250c054d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added the apply_filter_policy function to standardize the application of filter policies across all document store-specific retrievers, allowing for consistent handling of initial and runtime filters based on the chosen policy (replace or merge). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-azure-embedders-fd5f4fbcab0e1c48.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-azure-embedders-fd5f4fbcab0e1c48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d66d3207d22c697b97f780e3ebfbb422bc0eb2de --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-azure-embedders-fd5f4fbcab0e1c48.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Adds AzureOpenAIDocumentEmbedder and AzureOpenAITextEmbedder as new embedders. These embedders are very similar to + their OpenAI counterparts, but they use the Azure API instead of the OpenAI API. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-azure-generators-a30c786204b22e48.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-azure-generators-a30c786204b22e48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2a3422cfebbdcf47c4bdafbaee9dfae11678cfc5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-azure-generators-a30c786204b22e48.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds support for Azure OpenAI models with AzureOpenAIGenerator and AzureOpenAIChatGenerator components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a259261574d843a412f2430690ee51d6d175d7f9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-azure_ocr_doc_converter-935130b3b243d236.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add AzureOCRDocumentConverter to convert files of different types using Azure's Document Intelligence Service. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..163d9631efa635f49252a7c39a16794d3576d4e8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-blob-type-2a9476a39841f54d.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add ByteStream type to send binary raw data across components + in a pipeline. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml new file mode 100644 index 0000000000000000000000000000000000000000..75893aa537c83f707a7de0964d81d198f9cf9438 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-branch-joiner-037298459ca74077.yaml @@ -0,0 +1,14 @@ +--- +highlights: > + The `Multiplexer` component proved to be hard to explain and to understand. After reviewing its use cases, the documentation + was rewritten and the component was renamed to `BranchJoiner` to better explain its functionalities. +upgrade: + - | + `BranchJoiner` has the very same interface as `Multiplexer`. To upgrade your code, just rename any occurrence + of `Multiplexer` to `BranchJoiner` and ajdust the imports accordingly. +features: + - | + Add `BranchJoiner` to eventually replace `Multiplexer` +deprecations: + - | + `Mulitplexer` is now deprecated. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab163705b764f61e6c145369a7438cde55fe2bf2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-calculate-metrics-metricsresults-03bf27ce8b16cff5.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Adds `calculate_metrics()` function to EvaluationResult for computation of evaluation metrics. + Adds `Metric` class to store list of available metrics. + Adds `MetricsResult` class to store the metric values computed during the evaluation. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-chat-message-c456e4603529ae85.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-chat-message-c456e4603529ae85.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d15712852058cb14823add1d33fb4a934918616 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-chat-message-c456e4603529ae85.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Introduce ChatMessage data class to facilitate structured handling and processing of message content + within LLM chat interactions. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d80cb47d106dfc36f0f6958658010b87449b248 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-chatpromptbuilder-19acd18a6486909d.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + `ChatPromptBuilder` now supports changing its template at runtime. This allows you to define a default template and then change it based on your needs at runtime. +deprecations: + - | + `DynamicChatPromptBuilder` has been deprecated as `ChatPromptBuilder` fully covers its functionality. Use `ChatPromptBuilder` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-current-date-promptbuilder-ff60c846f5a70dc6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-current-date-promptbuilder-ff60c846f5a70dc6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07dacf43a8d296df2048d1f10cf72fe26d625786 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-current-date-promptbuilder-ff60c846f5a70dc6.yaml @@ -0,0 +1,16 @@ +--- +enhancements: + - | + Allow the ability to add the current date inside a template in `PromptBuilder` using the following syntax: + + - `{% now 'UTC' %}`: Get the current date for the UTC timezone. + + - `{% now 'America/Chicago' + 'hours=2' %}`: Add two hours to the current date in the Chicago timezone. + + - `{% now 'Europe/Berlin' - 'weeks=2' %}`: Subtract two weeks from the current date in the Berlin timezone. + + - `{% now 'Pacific/Fiji' + 'hours=2', '%H' %}`: Display only the number of hours after adding two hours to the Fiji timezone. + + - `{% now 'Etc/GMT-4', '%I:%M %p' %}`: Change the date format to AM/PM for the GMT-4 timezone. + + Note that if no date format is provided, the default will be `%Y-%m-%d %H:%M:%S`. Please refer to [list of tz database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) for a list of timezones. \ No newline at end of file diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-custom-converter-hook-to-pypdf-cc7c333a6e7fc5f7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-custom-converter-hook-to-pypdf-cc7c333a6e7fc5f7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e8ec760a62f1737f6f2a33d777ffd52b659d6e9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-custom-converter-hook-to-pypdf-cc7c333a6e7fc5f7.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add callable hook to PyPDFToDocument to enable easier customization of pdf to Document conversion. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9f4cdde9f78d57359f43cfb3c346da8e9d07a7ec --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-custom-filters-to-conditional-router-631eba8bab3c2ae7.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added custom filters support to ConditionalRouter. Users can now pass in + one or more custom Jinja2 filter callables and be able to access those + filters when defining condition expressions in routes. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2cb22f98a058ba4e3ccf0c8836e41c6730a7874 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-default-value-to-input-socket-2e62116fc4be5214.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add a field called `default_value` to the `InputSocket` dataclass. + Derive `is_mandatory` value from the presence of `default_value`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-deprecation-warning-context-relevance-937df7e807ac1a8d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-deprecation-warning-context-relevance-937df7e807ac1a8d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5942aced037736f9afc5ab97d7102ea30e68f4e3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-deprecation-warning-context-relevance-937df7e807ac1a8d.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + The output of the ContextRelevanceEvaluator will change in Haystack 2.4.0. Contexts will be scored as a whole instead of individual statements and only the relevant sentences will be returned. A score of 1 is now returned if a relevant sentence is found, and 0 otherwise. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-dimensions-parameter-to-OpenAI-Embedders-to-fully-support-the-new-models-1393cc235e457733.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-dimensions-parameter-to-OpenAI-Embedders-to-fully-support-the-new-models-1393cc235e457733.yaml new file mode 100644 index 0000000000000000000000000000000000000000..777047af0b641be56c5b5b86378935661cf4eeac --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-dimensions-parameter-to-OpenAI-Embedders-to-fully-support-the-new-models-1393cc235e457733.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + add dimensions parameter to OpenAI Embedders to fully support new embedding models like text-embedding-3-small, text-embedding-3-large and upcoming ones diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7bb46a8a5bb03b903fd1582c8fa0734a79d8bf2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-distribution-based-rank-fusion-mode-JoinDocuments-6fca30b82fd535ce.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added a new mode in JoinDocuments, + Distribution-based rank fusion as + [the article](https://medium.com/plain-simple-software/distribution-based-score-fusion-dbsf-a-new-approach-to-vector-search-ranking-f87c37488b18) diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f742601594f4a64d4af706dbf2eb59fa60200480 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-document-writer-number-of-documents-written-2c57f3a5d6ae2131.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Document writer returns the number of documents written. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-docx-file-to-document-47b603755a00fbe6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-docx-file-to-document-47b603755a00fbe6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb52b968f7681930e7be324b124d736de971192e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-docx-file-to-document-47b603755a00fbe6.yaml @@ -0,0 +1,6 @@ +--- +highlights: > + Adding the `DocxToDocument` component to convert Docx files to Documents. +features: + - | + Adding the `DocxToDocument` component inside the `converters` category. It uses the `python-docx` library to convert Docx files to haystack Documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-dynamic-per-message-templating-908468226c5e3d45.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-dynamic-per-message-templating-908468226c5e3d45.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce3f40f6f1e92a3d32e71fcc1cdd1e27bdac723c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-dynamic-per-message-templating-908468226c5e3d45.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds `ChatMessage` templating in `PromptBuilder` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5d6c53c00fb39cdb65a86494bd32323f7e08fc5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-dynamic-prompt-builder-e61c4b11405b8d80.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add `DynamicPromptBuilder` to dynamically generate prompts from either a list of ChatMessage instances or a string + template, leveraging Jinja2 templating for flexible and efficient prompt construction. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-eval-and-evaluation-result-5e9ac742e323bda8.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-eval-and-evaluation-result-5e9ac742e323bda8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b270143ed12348d8a6f296659be6719cc2f19a40 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-eval-and-evaluation-result-5e9ac742e323bda8.yaml @@ -0,0 +1,4 @@ +preview: + - | + Add eval function for evaluation of components and Pipelines. + Adds EvaluationResult to store results of evaluation. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f553cac7aa92f278ef18d2122e83f3c730d1c4bc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-exact-match-a7df21717238b771.yaml @@ -0,0 +1,8 @@ +--- +features: + - | + Adds support for the Exact Match metric to `EvaluationResult.calculate_metrics(...)`: + ```python + from haystack.evaluation.metrics import Metric + exact_match_metric = eval_result.calculate_metrics(Metric.EM, output_key="answers") + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c6fcabdcd95c86fa7c098c69df58efde0536f81 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-f1-d54cc900bec753f7.yaml @@ -0,0 +1,8 @@ +--- +features: + - | + Adds support for the F1 metric to `EvaluationResult.calculate_metrics(...)`: + ```python + from haystack.evaluation.metrics import Metric + f1_metric = eval_result.calculate_metrics(Metric.F1, output_key="answers") + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-failsafe-for-LLM-based-evaluators-34cdc183ab545315.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-failsafe-for-LLM-based-evaluators-34cdc183ab545315.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a97d33c8a2b70718e74f5286d5608fc8efd41e2f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-failsafe-for-LLM-based-evaluators-34cdc183ab545315.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + If an LLM-based evaluator (e.g., `Faithfulness` or `ContextRelevance`) is initialised with `raise_on_failure=False`, and if a call to an LLM fails or an LLM outputs an invalid JSON, the score of the sample is set to `NaN` instead of raising an exception. + The user is notified with a warning indicating the number of requests that failed. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-file-extension-classifier-preview-40f31c27bbd7cff9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-file-extension-classifier-preview-40f31c27bbd7cff9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a9d6f9c9b2f38c7bf1a01546840602741b9913bd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-file-extension-classifier-preview-40f31c27bbd7cff9.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds FileExtensionClassifier to preview components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-haystack-experimental-dependency-96ff02e71bc2af13.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-haystack-experimental-dependency-96ff02e71bc2af13.yaml new file mode 100644 index 0000000000000000000000000000000000000000..caa98d0d0a4ecb50db4bcd030079e44b9a54995b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-haystack-experimental-dependency-96ff02e71bc2af13.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Added haystack-experimental to the project's dependencies to enable automatic use of cutting-edge features from Haystack. Users can now access components from haystack-experimental by simply importing them from haystack_experimental instead of haystack. For more information, visit https://github.com/deepset-ai/haystack-experimental. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-html-to-document-21fe38b244388f4d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-html-to-document-21fe38b244388f4d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ff9b25b6b3b2e9f050e72abaf4f14e238b88ffe --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-html-to-document-21fe38b244388f4d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds HTMLToDocument component to convert HTML to a Document. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-hugging-face-chat-local-5fe7a88e24fde11b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-hugging-face-chat-local-5fe7a88e24fde11b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4722814426ded4d0331688aa815310531780196a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-hugging-face-chat-local-5fe7a88e24fde11b.yaml @@ -0,0 +1,19 @@ +--- +features: + - | + Introducing the HuggingFaceLocalChatGenerator, a new chat-based generator designed for leveraging chat models from + Hugging Face's (HF) model hub. Users can now perform inference with chat-based models in a local runtime, utilizing + familiar HF generation parameters, stop words, and even employing custom chat templates for custom message formatting. + This component also supports streaming responses and is optimized for compatibility with a variety of devices. + + Here is an example of how to use the HuggingFaceLocalChatGenerator: + + ```python + from haystack.components.generators.chat import HuggingFaceLocalChatGenerator + from haystack.dataclasses import ChatMessage + + generator = HuggingFaceLocalChatGenerator(model="HuggingFaceH4/zephyr-7b-beta") + generator.warm_up() + messages = [ChatMessage.from_user("What's Natural Language Processing? Be brief.")] + print(generator.run(messages)) + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-huggingface-tgi-chat-c63f4879a5d81342.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-huggingface-tgi-chat-c63f4879a5d81342.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d5b17782868054f6f180ba76b8538f2ad553e133 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-huggingface-tgi-chat-c63f4879a5d81342.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Adds `HuggingFaceTGIChatGenerator` for text and chat generation. This components support remote inferencing for + Hugging Face LLMs via text-generation-inference (TGI) protocol. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..838351608dfba42f1ada9fa39fea74e66bb6e055 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-huggingface-tgi-generator-9d7eed86f5246ea9.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Adds `HuggingFaceTGIGenerator` for text generation. This components support remote inferencing for + Hugging Face LLMs via text-generation-inference (TGI) protocol. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e4e0d25c98595864c03a1fe49516ddf6e4be722 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-indexing-ready-made-pipeline-85c1da2f8f910f9d.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add a indexing `build_indexing_pipeline` utility function diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-inf-mode-reader-e6eb79920e73c956.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-inf-mode-reader-e6eb79920e73c956.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dbe549f133e29c415bcb59c387bae589a13b3c0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-inf-mode-reader-e6eb79920e73c956.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adds inference mode to model call of the ExtractiveReader. This prevents gradients from being calculated during inference time in pytorch. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-keep-columns-to-EvalRunResult-comparative-be3e15ce45de3e0b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-keep-columns-to-EvalRunResult-comparative-be3e15ce45de3e0b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3720a0ca7dfec15d74bff519376420719781dbdf --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-keep-columns-to-EvalRunResult-comparative-be3e15ce45de3e0b.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + Added a new parameter to `EvaluationRunResult.comparative_individual_scores_report()` to specify columns to keep in the comparative DataFrame. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml new file mode 100644 index 0000000000000000000000000000000000000000..805c811d507d36b7930d306aa04ec57138660de2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-keep-id-to-document-cleaner-2a9854b5f195bb78.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + The `DocumentCleaner` class has the optional attribute `keep_id` that if set to True it keeps the document ids unchanged after cleanup. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f2699d40519097e161686b5754ac51006f5b5e51 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-link-content-fetcher-145915976f38e1e0.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Introduced the LinkContentFetcher in Haystack 2.0. This component fetches content from specified + URLs and converts them into ByteStream objects for further processing in Haystack pipelines. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2588daf593eb5265181b6a9defc9be78af4e0e21 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-lost-in-the-middle-ranker-6ad7dda754fad5a9.yaml @@ -0,0 +1,18 @@ +--- +prelude: > + We're excited to introduce a new ranker to Haystack - LostInTheMiddleRanker. + It reorders documents based on the "Lost in the Middle" order, a strategy that + places the most relevant paragraphs at the beginning or end of the context, + while less relevant paragraphs are positioned in the middle. This ranker, + based on the research paper "Lost in the Middle: How Language Models Use Long + Contexts" by Liu et al., can be leveraged in Retrieval-Augmented Generation + (RAG) pipelines. +features: + - | + The LostInTheMiddleRanker can be used like other rankers in Haystack. After + initializing LostInTheMiddleRanker with the desired parameters, it can be + used to rank/reorder a list of documents based on the "Lost in the Middle" + order - the most relevant documents are located at the top and bottom of + the returned list, while the least relevant documents are found in the + middle. We advise that you use this ranker in combination with other rankers, + and to place it towards the end of the pipeline. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9cf3e7dda8f4b120c182f00c5dc65921dd6e8a8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-markdown-file-type-router-support-39a607faa5c1436f.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adds markdown mimetype support to the file type router i.e. `FileTypeRouter` class. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..709a9c0f663b69bd19d11060b2cc8be975eb0ffe --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata-HTMLToDocument-42dbd074a46c979e.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds support for adding additional metadata and utilizing metadata received from ByteStream sources when creating documents using HTMLToDocument. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata-field-ranker-a8afd5bf15f29a0a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata-field-ranker-a8afd5bf15f29a0a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8f3110f4842e902eeeafe5430ff539307012aa3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata-field-ranker-a8afd5bf15f29a0a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds MetaFieldRanker, a component that ranks a list of Documents based on the value of a metadata field of choice. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58330ba0c1e06b0944bae84ba11dc7666766ca46 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-metadata_router-2.0-63829ac5a0528e9d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add `MetadataRouter`, a component that routes documents to different edges based on the content of their fields diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-model-kwargs-extractive-reader-c0b65ab34572408f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-model-kwargs-extractive-reader-c0b65ab34572408f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b647329e79036ab95727a29c49b7a6c2b7b0ebbd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-model-kwargs-extractive-reader-c0b65ab34572408f.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add new variable model_kwargs to the ExtractiveReader so we can pass different loading options supported by + HuggingFace. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-most-diverse-ranker-21cf310be4554551.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-most-diverse-ranker-21cf310be4554551.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f475dd609b1a4fee84d6e317104db9a90173104 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-most-diverse-ranker-21cf310be4554551.yaml @@ -0,0 +1,17 @@ +--- +prelude: > + We're introducing a new ranker to Haystack - DiversityRanker. This + ranker aims to maximize the overall diversity of the given documents. + It leverages sentence-transformer models to calculate semantic embeddings + for each document. It orders documents so that the next one, on average, + is least similar to the already selected documents. Such ranking results in a + list where each subsequent document contributes the most to the overall + diversity of the selected document set. +features: + - | + The DiversityRanker can be used like other rankers in Haystack and + it can be particularly helpful in cases where you have highly relevant + yet similar sets of documents. By ensuring a diversity of documents, + this new ranker facilitates a more comprehensive utilization of the + documents and, particularly in RAG pipelines, potentially contributes + to more accurate and rich model responses. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-new-rankers-schema-generation-7ad92fd5c5de8937.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-new-rankers-schema-generation-7ad92fd5c5de8937.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b77bdf0ccb85ef9ff0b6d955d46b40359cdf35f0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-new-rankers-schema-generation-7ad92fd5c5de8937.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Adds LostInTheMiddleRanker, DiversityRanker, and RecentnessRanker to `haystack/nodes/__init__.py` and thus + ensures that they are included in JSON schema generation. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-on_agent_final_answer_to_agent_base-7798ea8de2f43af0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-on_agent_final_answer_to_agent_base-7798ea8de2f43af0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..347fe8a0be07c3473221018c05b79c0666a70cf0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-on_agent_final_answer_to_agent_base-7798ea8de2f43af0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + added support for using `on_final_answer` trough `Agent` `callback_manager` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-openai-async-1f65701142f77181.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-openai-async-1f65701142f77181.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d97d8064eed5bc9cb5ea663b5a2b9380cc57a88 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-openai-async-1f65701142f77181.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add asyncio support to the OpenAI invocation layer. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-page-number-to-answer-1b6d68dc93508314.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-page-number-to-answer-1b6d68dc93508314.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6a834919a7107f285aafe34ba3d7af2c042cda8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-page-number-to-answer-1b6d68dc93508314.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + The ExtractiveReader can now add page numbers to the meta data of ExtractedAnswers. + It's done automatically if the source document of the ExtractedAnswer contains a page number in its meta data. + The ExtractedAnswer will then contain a key "answer_page_number" in its meta data. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-page-number-to-document-splitter-162e9dc7443575f0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-page-number-to-document-splitter-162e9dc7443575f0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8c97663cf1fb134ba2fa126e039dd7da3fa1a147 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-page-number-to-document-splitter-162e9dc7443575f0.yaml @@ -0,0 +1,7 @@ +--- +highlights: > + Add the "page_number" field to the metadata of all output documents. + +enhancements: + - | + Now the DocumentSplitter adds the "page_number" field to the metadata of all output documents to keep track of the page of the original document it belongs to. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7eb656a571eea4e871b57f947f203304ccbaf2c2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-pdfminer-converter-f08f68e38ef82f4a.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Provides users the ability to customize text extraction from PDF files. It is particularly useful for PDFs with unusual layouts, such as those containing multiple text columns. For instance, users can configure the object to retain the reading order. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-pptx-converter-625b745d64b3c939.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-pptx-converter-625b745d64b3c939.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a7aa5f9622e327a66d48862219149713266b40e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-pptx-converter-625b745d64b3c939.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add a PPTX to Document converter using the python-pptx library. Extracts all text from each slide. Each slide is separated with a page break "\f" + so a Document Splitter could split by slide. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-promptnode-arun-bc4c2bcc9c653015.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-promptnode-arun-bc4c2bcc9c653015.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9e3305eab50575219caeef287ffe516bf2c88f8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-promptnode-arun-bc4c2bcc9c653015.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + PromptNode can now be run asynchronously by calling the `arun` method. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-pypdf-to-document-converter-4a39c29abc4da7ba.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-pypdf-to-document-converter-4a39c29abc4da7ba.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8fe874d51fddecbc31e671712e3166572c3a65f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-pypdf-to-document-converter-4a39c29abc4da7ba.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds support for PDF files to the Document converter via pypdf library. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-rag-openapi-services-f3e377c49ff0f258.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-rag-openapi-services-f3e377c49ff0f258.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dab28853aaf39d45bfb714e17501f16e04f8cb08 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-rag-openapi-services-f3e377c49ff0f258.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds RAG OpenAPI services integration. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-remove-method-to-pipeline-base-c7ca1aa68b0f396b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-remove-method-to-pipeline-base-c7ca1aa68b0f396b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bfc1dc44260608fd924a3ce1b8a65679fc73591c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-remove-method-to-pipeline-base-c7ca1aa68b0f396b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added the 'remove_component' method in 'PipelineBase' to delete components and its connections. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-reno-e284cb173ab45ab3.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-reno-e284cb173ab45ab3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7008e1c37bf1368babb401e271bc4fd7f2b9e213 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-reno-e284cb173ab45ab3.yaml @@ -0,0 +1,11 @@ +--- +prelude: > + Release notes are now managed by `reno`. The main difference is that + every contributor is responsible for adding release notes for the feature or bugfix they're + introducing in Haystack in the very same Pull Request containing the code changes. The + goal is to encourage detailed and accurate notes for every release, especially when it comes + to complex features or breaking changes. +upgrade: + - | + If you're a Haystack contributor, you need a new tool called `reno` to manage the release notes. + Please run `pip install -e .[dev]` to ensure you have `reno` available in your environment. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-required-flag-for-prompt-builder-inputs-f5d3ffb3cb7df8d0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-required-flag-for-prompt-builder-inputs-f5d3ffb3cb7df8d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9aad19db92bd2bea8950e00f8edee242cc6904e5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-required-flag-for-prompt-builder-inputs-f5d3ffb3cb7df8d0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced PromptBuilder to specify and enforce required variables in prompt templates. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-router-f1f0cec79b1efe9a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-router-f1f0cec79b1efe9a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d6084f508647831313491210cd1697d6e297e07 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-router-f1f0cec79b1efe9a.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add `ConditionalRouter` component to enhance the conditional pipeline routing capabilities. + The `ConditionalRouter` component orchestrates the flow of data by evaluating specified route conditions + to determine the appropriate route among a set of provided route alternatives. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-sas-b8dbf61c0d78ba19.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-sas-b8dbf61c0d78ba19.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5078a4c93b5a8a11cd8b012c97167b6f9aab6012 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-sas-b8dbf61c0d78ba19.yaml @@ -0,0 +1,10 @@ +--- +features: + - | + Adds support for the Semantic Answer Similarity (SAS) metric to `EvaluationResult.calculate_metrics(...)`: + ```python + from haystack.evaluation.metrics import Metric + sas_metric = eval_result.calculate_metrics( + Metric.SAS, output_key="answers", model="sentence-transformers/paraphrase-multilingual-mpnet-base-v2" + ) + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-search_engine_kwargs-to-web-retriever-67fac44ef0039b7f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-search_engine_kwargs-to-web-retriever-67fac44ef0039b7f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3dcf8c96aad7eb8fb9aaf88e8c0e9517a4cbc3a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-search_engine_kwargs-to-web-retriever-67fac44ef0039b7f.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Add `search_engine_kwargs` param to WebRetriever so it can be propagated + to WebSearch. This is useful, for example, to pass the engine id when + using Google Custom Search. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-searchapi-integration-bb9130485c3c9429.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-searchapi-integration-bb9130485c3c9429.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1cd3e046dffb98e589bf0c4098c84d5a48f49e8e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-searchapi-integration-bb9130485c3c9429.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Integrate SearchApi as an additional websearch provider. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-transformers-document-embedder-f1e8612b8eaf9b7f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-transformers-document-embedder-f1e8612b8eaf9b7f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15689050b03b0458a0fa940e69b6eed5cb0b545a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-transformers-document-embedder-f1e8612b8eaf9b7f.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add Sentence Transformers Document Embedder. + It computes embeddings of Documents. The embedding of each Document is stored in the `embedding` field of the Document. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-transformers-text-embedder-2ce0de6f7a1149e1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-transformers-text-embedder-2ce0de6f7a1149e1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15d65d00a1816270a04294ae0f3272d568009116 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-transformers-text-embedder-2ce0de6f7a1149e1.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add Sentence Transformers Text Embedder. + It is a simple component that embeds strings into vectors. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-window-retrieval-5de4b0d6b2e8b0d6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-window-retrieval-5de4b0d6b2e8b0d6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6679d84757bc306bea9c45baa233d0f510f63433 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-sentence-window-retrieval-5de4b0d6b2e8b0d6.yaml @@ -0,0 +1,7 @@ +--- + +features: + - | + Adding a new component allowing to perform sentence-window retrieval, i.e. retrieves surrounding documents of a + given document from the document store. This is useful when a document is split into multiple chunks and you want to + retrieve the surrounding context of a given chunk. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48e3c8e427e09c7efb0b67da4e6eff1d99da7ffc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-serialization-to-inmemorydocumentstore-2aa4d9ac85b961c5.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added serialization methods save_to_disk and write_to_disk to InMemoryDocumentStore. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-serper-dev-8c582749728e3699.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-serper-dev-8c582749728e3699.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ce2fd9bba9224c9bfa38e8a07c56f3acbeb96ca --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-serper-dev-8c582749728e3699.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Adds SerperDevWebSearch component to retrieve URLs from the web. See https://serper.dev/ for more information. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-similarity-ranker-401bf595cea7318a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-similarity-ranker-401bf595cea7318a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0d3217a6703613bf98e3ee2f2052760cf8837a8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-similarity-ranker-401bf595cea7318a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds SimilarityRanker, a component that ranks a list of Documents based on their similarity to the query. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-skip-prompt-for-hf-model-agent-89aef2838edb907c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-skip-prompt-for-hf-model-agent-89aef2838edb907c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51760da92480c05bec44c3fb3ef15db1561ab830 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-skip-prompt-for-hf-model-agent-89aef2838edb907c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix the bug that the responses of Agents using local HF models contain the prompt text. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-split-by-page-to-DocumentSplitter-63232c17d858d787.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-split-by-page-to-DocumentSplitter-63232c17d858d787.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fccae32cc420be0a1baecde5d9592f2c899f026 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-split-by-page-to-DocumentSplitter-63232c17d858d787.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added split by page to DocumentSplitter, which will split the document at \f diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3eba2d57bca8eca3b91a6c1ce7acb1c1fbd92a7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + The `DocumentSplitter` now has support for the `split_id` and `split_overlap` to allow for more control over the splitting process. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-streaming-chunk-67897d7cb2c0d7c0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-streaming-chunk-67897d7cb2c0d7c0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..428d2c77e658fe014c3ed92d2fed65c3928bd6a0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-streaming-chunk-67897d7cb2c0d7c0.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Introduce the StreamingChunk dataclass for efficiently handling chunks of data streamed from a language model, + encapsulating both the content and associated metadata for systematic processing. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-tikaconverter-2.0-ef637f93114e6c96.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-tikaconverter-2.0-ef637f93114e6c96.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1ec435153d9e26691e0045d618a0405875e483c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-tikaconverter-2.0-ef637f93114e6c96.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add TikaDocumentConverter component to convert files of different types to Documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-timeout-arg-to-promptnode-de11f17733344052.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-timeout-arg-to-promptnode-de11f17733344052.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c1ff4630c74f19663c71f4217fbe8078111bdb10 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-timeout-arg-to-promptnode-de11f17733344052.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Introduces a new timeout keyword argument in PromptNode, addressing and fixing the issue #5380 for enhanced control over individual calls to OpenAI. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-top-p-sampler-ad6e0f5d623a6bb5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-top-p-sampler-ad6e0f5d623a6bb5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..729c8b624540c47e0bb933d740dfc71594fd5285 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-top-p-sampler-ad6e0f5d623a6bb5.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds TopPSampler, a component selects documents based on the cumulative probability of the Document scores using top p (nucleus) sampling. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-transformers-text-router-5542b9d13a3c91c9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-transformers-text-router-5542b9d13a3c91c9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf0d7c8e82dc72768cc82f2ac2d64421e0f68cb4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-transformers-text-router-5542b9d13a3c91c9.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Introduces the TransformersTextRouter! This component uses a transformers text classification pipeline to route text inputs onto different output connections based on the labels of the chosen text classification model. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-v2-answer-class-31bc8d3116922594.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-v2-answer-class-31bc8d3116922594.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e719652b49b7406bfe0bc1d8b764ac5ae25a0122 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-v2-answer-class-31bc8d3116922594.yaml @@ -0,0 +1,4 @@ +--- +preview: + - Add Answer base class for haystack v2 + - Add GeneratedAnswer and ExtractedAnswer diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-v2-extractive-reader-a2158d38781803ec.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-v2-extractive-reader-a2158d38781803ec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..75854604b62a4d9e800afbfffa4aebe2cc64d820 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-v2-extractive-reader-a2158d38781803ec.yaml @@ -0,0 +1,7 @@ +--- +preview: + - | + This adds an ExtractiveReader for v2. It should be a replacement where + FARMReader would have been used before for inference. + The confidence scores are calculated differently from FARMReader because + each span is considered to be an independent binary classification task. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/add-yaml-marshaller-030e889f46484573.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/add-yaml-marshaller-030e889f46484573.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fa9663c27087e4c9d0840c3054f2b637833afa0c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/add-yaml-marshaller-030e889f46484573.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add `dumps`, `dump`, `loads` and `load` methods to save + and load pipelines in Yaml format. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/adding-metadata-info-from-OpenAI-f5309af5f59bb6a7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/adding-metadata-info-from-OpenAI-f5309af5f59bb6a7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f8de43bb1d780ccbb5e42bb8b1efc6e26955362c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/adding-metadata-info-from-OpenAI-f5309af5f59bb6a7.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + When using "openai" for the LLM-based evaluators the metadata from OpenAI will be in the output dictionary, under the key "meta". diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/adjust-web-retriever-caching-logic-2e05fbc972a86f29.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/adjust-web-retriever-caching-logic-2e05fbc972a86f29.yaml new file mode 100644 index 0000000000000000000000000000000000000000..41f6bc498569262b923a0715bf8294d35ad4b541 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/adjust-web-retriever-caching-logic-2e05fbc972a86f29.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + The WebRetriever now employs an enhanced caching mechanism that caches web page content based on search engine + results rather than the query. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/adopt-hf-token-770edaccf6278ad9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/adopt-hf-token-770edaccf6278ad9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a0f1e63e4baebf3e5ca05d39a04b55273e5a636 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/adopt-hf-token-770edaccf6278ad9.yaml @@ -0,0 +1,8 @@ +--- +preview: + - | + Adopt Hugging Face `token` instead of the deprecated `use_auth_token`. + Add this parameter to `ExtractiveReader` and `SimilarityRanker` to allow + loading private models. + Proper handling of `token` during serialization: if it is a string (a possible valid token) + it is not serialized. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/allow-connecting-same-components-again-e63cf719b9bf2a14.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/allow-connecting-same-components-again-e63cf719b9bf2a14.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b97c2674c6a558cd16fefe91a30518a5650eebb5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/allow-connecting-same-components-again-e63cf719b9bf2a14.yaml @@ -0,0 +1,5 @@ +--- +issues: + - | + Make `connect` idempotent, allowing connecting the same components more than once. Specially useful + in Jupiter notebooks. Fixes https://github.com/deepset-ai/haystack/issues/6359. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/allow-parameters-for-openai-generator-8ce86ba1bac80817.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/allow-parameters-for-openai-generator-8ce86ba1bac80817.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c5e2b93b7ab1c27890c5c42019fde9be5d7f7d5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/allow-parameters-for-openai-generator-8ce86ba1bac80817.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + LLM based evaluators can pass in supported OpenAIGenerator parameters via api_params. + This allows for custom generation_kwargs, changing the api_base_url (for local evaluation), + and all other supported parameters as described in the OpenAIGenerator docs. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/allow-simplified-pipeline-run-input-e3dd98ff38f0bc01.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/allow-simplified-pipeline-run-input-e3dd98ff38f0bc01.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6badfe24edf10c3fb19f92e632c17d020df1f982 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/allow-simplified-pipeline-run-input-e3dd98ff38f0bc01.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Adds option to run pipelines without specifying component inputs and their corresponding key/value pairs. Instead, + provide the input keys/values directly, and the pipeline's internal mechanisms will automatically determine the + appropriate components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/answer-refactoring-b617afa946311ac8.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/answer-refactoring-b617afa946311ac8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c2f609804f6e1e773c10d65f61d9a4cbe7db679 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/answer-refactoring-b617afa946311ac8.yaml @@ -0,0 +1,8 @@ +--- +enhancements: + - | + Refactor `Answer` dataclass and classes that inherited it. + Now `Answer` is a Protocol, classes that used to inherit it now respect that interface. + We also added a new `ExtractiveTableAnswer` to be used for table question answering. + + All classes now are easily serializable using `to_dict()` and `from_dict()` like `Document` and components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/async-pipeline-20649b54ecff2706.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/async-pipeline-20649b54ecff2706.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58d689fff2a9f2bb5c03d66b1decef5aa8e44303 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/async-pipeline-20649b54ecff2706.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add experimental support for asynchronous `Pipeline` run diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/avoid-LLM-based-evaluators-returning-NaN-579bc4593febb691.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/avoid-LLM-based-evaluators-returning-NaN-579bc4593febb691.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5245f35260efe45aa65ee69de9ed8483bc5f3280 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/avoid-LLM-based-evaluators-returning-NaN-579bc4593febb691.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + `FaithfullnessEvaluator` and `ContextRelevanceEvaluator` now return `0` instead of `NaN` when applied to an empty context or empty statements. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/azure-openai-generator-timeout-c39ecd6d4b0cdb4b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/azure-openai-generator-timeout-c39ecd6d4b0cdb4b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49217671fce8cf5a72cd942ad994ab6721f78c71 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/azure-openai-generator-timeout-c39ecd6d4b0cdb4b.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + `AzureOpenAIGenerator` and `AzureOpenAIChatGenerator` can now be configured passing a timeout for the underlying `AzureOpenAI` client. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/bedrock-support-bce28e3078c85c12.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/bedrock-support-bce28e3078c85c12.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d31ec387c491cfbff25ea54ff20d2a51902b17ef --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/bedrock-support-bce28e3078c85c12.yaml @@ -0,0 +1,16 @@ +--- +prelude: > + Haystack now supports Amazon Bedrock models, including all existing and previously announced + models, like Llama-2-70b-chat. To use these models, simply pass the model ID in the + model_name_or_path parameter, like you do for any other model. For details, see + [Amazon Bedrock Docmentation](https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html). + + For example, the following code loads the Llama 2 Chat 13B model: + ```python + from haystack.nodes import PromptNode + + prompt_node = PromptNode(model_name_or_path="meta.llama2-13b-chat-v1") + ``` +features: + - | + You can use Amazon Bedrock models in Haystack. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/better-doc-repr-6d35de1cf4b25697.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/better-doc-repr-6d35de1cf4b25697.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4515c7f272043be40cac281b2ef1d35b8a64bf3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/better-doc-repr-6d35de1cf4b25697.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Introduce a new Document representation, which includes meta, score and + embedding size. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/better-error-FileExtensionClassifier-4defc51ed116c2a2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/better-error-FileExtensionClassifier-4defc51ed116c2a2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7177606cb487558352745d26412355ccf0fc3291 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/better-error-FileExtensionClassifier-4defc51ed116c2a2.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Improve error messaging in the FileExtensionClassifier constructor + to avoid common mistakes. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-32-1-5b800ceff440b871.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-32-1-5b800ceff440b871.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad1991e6b92f949774dff5702dd1a1edbdee88ba --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-32-1-5b800ceff440b871.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Upgrade transformers to the latest version 4.32.1 so that Haystack benefits from Llama and T5 bugfixes: https://github.com/huggingface/transformers/releases/tag/v4.32.1 diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-32-341a42ff09796725.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-32-341a42ff09796725.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59be09fac8bf5465c81d0f375cfaf78d4bb7ec45 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-32-341a42ff09796725.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgrade Transformers to the latest version 4.32.0. + This version adds support for the GPTQ quantization and integrates MPT models. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-34-38d045d8e42ea0a2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-34-38d045d8e42ea0a2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a147f7ef95b78b36163c93637772bccca9983ec3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/bump-transformers-to-4-34-38d045d8e42ea0a2.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgrade Transformers to the latest version 4.34.1. + This version adds support for the new Mistral, Persimmon, BROS, ViTMatte, and Nougat models. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/byte-stream-mime-type-b060e96791c4993a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/byte-stream-mime-type-b060e96791c4993a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3771e5bd774e12ef59ea7baa62351d35ad12286c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/byte-stream-mime-type-b060e96791c4993a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add `mime_type` field to `ByteStream` dataclass. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/cache_checker_output_type-0b05e75ca41aab61.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/cache_checker_output_type-0b05e75ca41aab61.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c14d75c9acb74beed7fe9e8a41fd05f4f570473 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/cache_checker_output_type-0b05e75ca41aab61.yaml @@ -0,0 +1,3 @@ +--- +enhancements: + - Modify the output type of `CacheChecker` from `List[Any]` to `List` to make it possible to connect it in a Pipeline. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/canals-0.10.0-bfa4020a8cf207c4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/canals-0.10.0-bfa4020a8cf207c4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..34ea124b34ded291d4c4bb1c837ffd6b3c78753c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/canals-0.10.0-bfa4020a8cf207c4.yaml @@ -0,0 +1,2 @@ +preview: + - Upgrade Canals to 0.10.0 diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/canals-0.4.0-b69b19069c4a9e0f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/canals-0.4.0-b69b19069c4a9e0f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da1aeb54be8de83e0ccd95c92b3699f777a75b2b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/canals-0.4.0-b69b19069c4a9e0f.yaml @@ -0,0 +1,4 @@ +--- +preview: + - "Migrate existing v2 components to Canals 0.4.0" + - "Fix TextFileToDocument using wrong Document class" diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/change-context-relevance-evaluator-da770bf05c83cfbd.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/change-context-relevance-evaluator-da770bf05c83cfbd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b530ce460022c1caec6d63c6471af106d3401869 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/change-context-relevance-evaluator-da770bf05c83cfbd.yaml @@ -0,0 +1,6 @@ +--- + +upgrade: + - | + The `ContextRelevanceEvaluator` now returns a list of relevant sentences for each context, instead of all the sentences in a context. + Also, a score of 1 is now returned if a relevant sentence is found, and 0 otherwise. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/change-import-paths-3d4eae690412e545.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/change-import-paths-3d4eae690412e545.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a285a6d68d21794886f2d358895f42fd93d9ef77 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/change-import-paths-3d4eae690412e545.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Change import paths under the "preview" package to minimize + module namespace pollution. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/change-localwhispertranscriber-run-3b0a818060867720.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/change-localwhispertranscriber-run-3b0a818060867720.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b32d880caba9162de5f64ca0bfb683467b7d5075 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/change-localwhispertranscriber-run-3b0a818060867720.yaml @@ -0,0 +1,10 @@ +--- +upgrade: + - | + If you have a `LocalWhisperTranscriber` in a pipeline, change the `audio_files` + input name to `sources`. Similarly for standalone invocation of the component, + pass `sources` instead of `audio_files` to the `run()` method. +enhancements: + - | + Add support for `ByteStream` to `LocalWhisperTranscriber` and uniform the + input socket names to the other components in Haystack. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/change-metadata-to-meta-0fada93f04628c79.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/change-metadata-to-meta-0fada93f04628c79.yaml new file mode 100644 index 0000000000000000000000000000000000000000..339c6536c354a9d9e3c223724e372802579e786a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/change-metadata-to-meta-0fada93f04628c79.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Rename `metadata` to `meta`. + Rename `metadata_fields_to_embed` to `meta_fields_to_embed` in all Embedders. + Rename `metadata_field` to `meta_field` in `MetaFieldRanker`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/change-trafilatura-dependency-575985a2271c8370.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/change-trafilatura-dependency-575985a2271c8370.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff158a6c61f5a59c3f33538edc6218e38266b88f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/change-trafilatura-dependency-575985a2271c8370.yaml @@ -0,0 +1,7 @@ +--- +upgrade: + - | + `trafilatura` must now be manually installed with `pip install trafilatura` to use the `HTMLToDocument` Component. +enhancements: + - | + Remove `trafilatura` as direct dependency and make it a lazily imported one diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/changed-metadata-to-meta-64cceb9ed19722fe.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/changed-metadata-to-meta-64cceb9ed19722fe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5710841bab5624d210184d8dd2cca46e25fc7a7c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/changed-metadata-to-meta-64cceb9ed19722fe.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Rename all metadata references to meta. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/chatgpt-llm-generator-d043532654efe684.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/chatgpt-llm-generator-d043532654efe684.yaml new file mode 100644 index 0000000000000000000000000000000000000000..db9a092492cf46958e69856e84020b00c5343c4d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/chatgpt-llm-generator-d043532654efe684.yaml @@ -0,0 +1,2 @@ +preview: + - Introduce `GPTGenerator`, a class that can generate completions using OpenAI Chat models like GPT3.5 and GPT4. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/check-for-None-SAS-eval-0b982ccc1491ee83.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/check-for-None-SAS-eval-0b982ccc1491ee83.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d12adfde0cbc3d89c040664df0c95fc394bc3958 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/check-for-None-SAS-eval-0b982ccc1491ee83.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + `SASEvaluator` now raises a `ValueError` if a `None` value is contained in the `predicted_answers` input. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/check-id-hash-keys-postinit-28b012cdeada2c1e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/check-id-hash-keys-postinit-28b012cdeada2c1e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95dd463dc21e864e60f26ca7289a7385b85ad812 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/check-id-hash-keys-postinit-28b012cdeada2c1e.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + The Document dataclass checks if `id_hash_keys` is None or empty in + __post_init__. If so, it uses the default factory to set a default valid value. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/codespell-d4a32b9c589ca26e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/codespell-d4a32b9c589ca26e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9fb4efa0ddee324fae5f8f8458de73f958c3296c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/codespell-d4a32b9c589ca26e.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + ci: Fix typos discovered by codespell running in pre-commit. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/component-kw-only-run-args-eedee8907232d2d4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/component-kw-only-run-args-eedee8907232d2d4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68ef50fbffae8249c0a723298b52ed6f6ccbc775 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/component-kw-only-run-args-eedee8907232d2d4.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix ComponentMeta ignoring keyword-only parameters in the `run` method. ComponentMeta.__call__ handles the creation of InputSockets for the component's inputs when the latter has not explicitly called _Component.set_input_types(). This logic was not correctly handling keyword-only parameters. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/components-reuse-ccc5f2d4b9d7f9ff.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/components-reuse-ccc5f2d4b9d7f9ff.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ef055441178b398614510e8414ca82afe4aa345 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/components-reuse-ccc5f2d4b9d7f9ff.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Change `Pipeline.add_component()` to fail if the `Component` instance has already been added in another `Pipeline`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/connect-return-pipeline-dcc1e0786b19861e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/connect-return-pipeline-dcc1e0786b19861e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..686acfa039d0ce0426773861b1227bc746aa7dcf --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/connect-return-pipeline-dcc1e0786b19861e.yaml @@ -0,0 +1,12 @@ +--- +enhancements: + - | + Change `Pipeline.connect()` to return the instance of `Pipeline`. + This way we can chain multiple `connect()` like so: + ```python + pipeline.connect("fetcher", "converter") \ + .connect("converter", "splitter") \ + .connect("splitter", "ranker") \ + .connect("ranker", "prompt_builder") \ + .connect("prompt_builder", "llm") + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/context-relevance-04063b9dc9fe7379.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/context-relevance-04063b9dc9fe7379.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ab79f87cfe4e901c8822da8d8db5d91ecdc769e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/context-relevance-04063b9dc9fe7379.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add a new ContextRelevanceEvaluator component that can be used to evaluate whether retrieved documents are relevant to answer a question with a RAG pipeline. + Given a question and a list of retrieved document contents (contexts), an LLM is used to score to what extent the provided context is relevant. The score ranges from 0 to 1. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/converters-allow-passing-meta-70fb498b6eb80468.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/converters-allow-passing-meta-70fb498b6eb80468.yaml new file mode 100644 index 0000000000000000000000000000000000000000..839fe16a7336e3ffd22131fe472acd5417b6523b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/converters-allow-passing-meta-70fb498b6eb80468.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Make all Converters accept `meta` in the `run` method, so that users can + provide their own metadata. + The length of this list should match the number of `sources`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/converters-standardize-inputs-ed2ba9c97b762974.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/converters-standardize-inputs-ed2ba9c97b762974.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b1724da3cd9de31233ace160027de26406051b2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/converters-standardize-inputs-ed2ba9c97b762974.yaml @@ -0,0 +1,22 @@ +--- +upgrade: + - | + If you are using `AzureOCRDocumentConverter` or `TikaDocumentConverter`, + you need to change `paths` to `sources` in the `run` method. + + An example: + ```python + from haystack.components.converters import TikaDocumentConverter + converter = TikaDocumentConverter() + converter.run(paths=["paths/to/file1.pdf", "path/to/file2.pdf"]) + ``` + + The last line should be changed to: + ```python + converter.run(sources=["paths/to/file1.pdf", "path/to/file2.pdf"]) + ``` + +enhancements: + - | + Make all the Converters accept the `sources` parameter in the `run` method. + `sources` is a list that can contain str, Path or ByteStream objects. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/custom-query-dynamic-filters-dd83ec358d2f64a6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/custom-query-dynamic-filters-dd83ec358d2f64a6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dc69accde0b808f62fcd430975374ff3c169143 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/custom-query-dynamic-filters-dd83ec358d2f64a6.yaml @@ -0,0 +1,82 @@ +--- +upgrade: + - | + The Opensearch custom query syntax changes: the old filter placeholders for ``custom_query`` are no longer supported. + Replace your custom filter expressions with the new ``${filters}`` placeholder: + + **Old:** + ```python + retriever = BM25Retriever( + custom_query=""" + { + "query": { + "bool": { + "should": [{"multi_match": { + "query": ${query}, + "type": "most_fields", + "fields": ["content", "title"]}} + ], + "filter": [ + {"terms": {"year": ${years}}}, + {"terms": {"quarter": ${quarters}}}, + {"range": {"date": {"gte": ${date}}}} + ] + } + } + } + """ + ) + + retriever.retrieve( + query="What is the meaning of life?", + filters={"years": [2019, 2020], "quarters": [1, 2, 3], "date": "2019-03-01"} + ) + ``` + + **New:** + ```python + retriever = BM25Retriever( + custom_query=""" + { + "query": { + "bool": { + "should": [{"multi_match": { + "query": ${query}, + "type": "most_fields", + "fields": ["content", "title"]}} + ], + "filter": ${filters} + } + } + } + """ + ) + + retriever.retrieve( + query="What is the meaning of life?", + filters={"year": [2019, 2020], "quarter": [1, 2, 3], "date": {"$gte": "2019-03-01"}} + ) + ``` +features: + - | + When using ``custom_query`` in ``BM25Retriever`` along with ``OpenSearch`` + or ``Elasticsearch``, we added support for dynamic ``filters``, like in regular queries. + With this change, you can pass filters at query-time without having to modify the ``custom_query``: + Instead of defining filter expressions and field placeholders, all you have to do + is setting the ``${filters}`` placeholder analogous to the ``${query}`` placeholder into + your ``custom_query``. + **For example:** + ```python + { + "query": { + "bool": { + "should": [{"multi_match": { + "query": ${query}, // mandatory query placeholder + "type": "most_fields", + "fields": ["content", "title"]}} + ], + "filter": ${filters} // optional filters placeholder + } + } + } + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/deepset-cloud-document-store-search-fields-40b2322466f808a3.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/deepset-cloud-document-store-search-fields-40b2322466f808a3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..679a14276d45122b797395da0dcb6e63bca7d2d3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/deepset-cloud-document-store-search-fields-40b2322466f808a3.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + `DeepsetCloudDocumentStore` supports searching multiple fields in sparse queries. This enables you to search meta fields as well when using `BM25Retriever`. For example set `search_fields=["content", "title"]` to search the `title` meta field along with the document `content`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/default-to-from-dict-7f7d89b6c36e2ab8.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/default-to-from-dict-7f7d89b6c36e2ab8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3592483606a2f4f4a02dff8c19d6bab12d59a105 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/default-to-from-dict-7f7d89b6c36e2ab8.yaml @@ -0,0 +1,4 @@ +--- +preview: + - Migrate all components to Canals==0.7.0 + - Add serialization and deserialization methods for all Haystack components diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/default-write-documents-policy-95afe5fb34fc73ad.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/default-write-documents-policy-95afe5fb34fc73ad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d04a960ebc6420641c5bfbd02e30a2097ba7f7fd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/default-write-documents-policy-95afe5fb34fc73ad.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Change the default `DuplicatePolicy` for the `DocumentStore.write_documents()` protocol from `DuplicatePolicy.FAIL` to `DuplicatePolicy.NONE`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-dynamic-promptbuilders-14de431d98ae3e39.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-dynamic-promptbuilders-14de431d98ae3e39.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aed37439b0ba5e9d1aad6adbff6be3ad1a8aad26 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-dynamic-promptbuilders-14de431d98ae3e39.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Removed the deprecated `DynamicPromptBuilder` and `DynamicChatPromptBuilder` components. Use `PromptBuilder` and `ChatPromptBuilder` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-openai-answergenerator-537266612ba1ffff.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-openai-answergenerator-537266612ba1ffff.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e42dfacab7b3cfb2a4d000ff0926f3fc6b6bbc0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-openai-answergenerator-537266612ba1ffff.yaml @@ -0,0 +1,5 @@ +--- +deprecations: + - | + Deprecate `OpenAIAnswerGenerator` in favor of `PromptNode`. + `OpenAIAnswerGenerator` will be removed in Haystack 1.23. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-pipeline-run-debug-param-e69190338a8e041b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-pipeline-run-debug-param-e69190338a8e041b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6a72b8728f6670c55b9496c9d2b7d840a2b057a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/deprecate-pipeline-run-debug-param-e69190338a8e041b.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + Deprecate the unused `debug` parameter in the `Pipeline.run` method. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/device-management-eed64f411c48fbc7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/device-management-eed64f411c48fbc7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72caefc41caad47de918eb1ef8092dedfccdd12f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/device-management-eed64f411c48fbc7.yaml @@ -0,0 +1,31 @@ +--- +upgrade: + - | + Implement framework-agnostic device representations. The main impetus behind this change is to move away from stringified representations + of devices that are not portable between different frameworks. It also enables support for multi-device inference in a generic manner. + + Going forward, components can expose a single, optional device parameter in their constructor (`Optional[ComponentDevice]`): + ```python + import haystack.utils import ComponentDevice, Device, DeviceMap + class MyComponent(Component): + def __init__(self, device: Optional[ComponentDevice] = None): + # If device is None, automatically select a device. + self.device = ComponentDevice.resolve_device(device) + + def warm_up(self): + # Call the framework-specific conversion method. + self.model = AutoModel.from_pretrained("deepset/bert-base-cased-squad2", device=self.device.to_hf()) + + # Automatically selects a device. + c = MyComponent(device=None) + # Uses the first GPU available. + c = MyComponent(device=ComponentDevice.from_str("cuda:0")) + # Uses the CPU. + c = MyComponent(device=ComponentDevice.from_single(Device.cpu())) + # Allow the component to use multiple devices using a device map. + c = MyComponent(device=ComponentDevice.from_multiple(DeviceMap({ + "layer1": Device.cpu(), + "layer2": Device.gpu(1), + "layer3": Device.disk() + }))) + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/device-map-2ced24b510e45774.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/device-map-2ced24b510e45774.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e2317df42ecd40e4a3351de471d1e988960171a6 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/device-map-2ced24b510e45774.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Use `device_map` when loading a TransformersSimilarityRanker and ExtractiveReader. + This allows for multi-device inference and for loading quantized models (e.g. load_in_8bit=True) diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/diversity-ranker-add-topk-24f23136f316129a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/diversity-ranker-add-topk-24f23136f316129a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5fba39f330bd4b7fdf578354b8e981c42c4c27bf --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/diversity-ranker-add-topk-24f23136f316129a.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add top_k parameter to the DiversityRanker init method. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/doc-id-rework-85e82b5359282f7e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/doc-id-rework-85e82b5359282f7e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3d87ba2c6e08da50428f1ac4e9ef056d17eef54 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/doc-id-rework-85e82b5359282f7e.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Rework `Document.id` generation, if an `id` is not explicitly set it's generated + using all `Document` field' values, `score` is not used. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-backward-compatible-07c4151e98ef8511.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-backward-compatible-07c4151e98ef8511.yaml new file mode 100644 index 0000000000000000000000000000000000000000..23e883d22502a907d2e0940f8668492000572791 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-backward-compatible-07c4151e98ef8511.yaml @@ -0,0 +1,20 @@ +--- +prelude: > + The `Document` serialisation has been changed quite a bit, this will make it easier to implement + new Document Stores. + + The most notable change is that the `Document.flatten()` method has been removed. + `Document.to_dict()` now has a `flatten` parameter, that defaults to `True` for backward compatibility. + It will flatten metadata keys at the same level of other `Document` fields when converting to `dict`. + + `to_json` and `from_json` have been removed, as `to_dict` and `from_dict` already handle serialisation + of `dataframe` and `blob` fields. + Now `metadata` must only contain primitives that can be serialised to JSON with no custom encoders. + If any Document Store needs custom serialisation they can implement their own logic. + + `Document` has also been made backward compatible so that it can be created using dictionaries + structured as the legacy 1.x `Document`. The legacy fields will be converted automatically to + their new counterparts, or ignored if there's none. +preview: + - | + Refactor Document serialisation and make it backward compatible with Haystack 1.x diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-blob-ae28734c5be561d9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-blob-ae28734c5be561d9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..596917d4301752376620a896877221f666966ca8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-blob-ae28734c5be561d9.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Change `Document.blob` field type from `bytes` to `ByteStream` and remove `Document.mime_type` field. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-embedding-type-d66c44ac6878fbdd.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-embedding-type-d66c44ac6878fbdd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c01c4a250169fbe095bc7f08c36a15509d1e46e3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-embedding-type-d66c44ac6878fbdd.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Change `Document`'s `embedding` field type from `numpy.ndarray` to `List[float]` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-equality-4bc1b5273bd5b7f1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-equality-4bc1b5273bd5b7f1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..880fb9ebb64a13a3a99d7a6153c81894bf783db7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-equality-4bc1b5273bd5b7f1.yaml @@ -0,0 +1,14 @@ +--- +preview: + - | + Refactor `Document.__eq__()` so it compares the `Document`s dictionary + representation instead of only their `id`. + Previously this comparison would have unexpectedly worked: + ```python + first_doc = Document(id="1", content="Hey!") + second_doc = Document(id="1", content="Hello!") + assert first_doc == second_doc + first_doc.content = "Howdy!" + assert first_doc == second_doc + ``` + With this change the last comparison would rightly fail. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-joiner-2-126bd60c84be6efa.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-joiner-2-126bd60c84be6efa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..13029d0ede64f4a38dc851104912cbda6953dc3e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-joiner-2-126bd60c84be6efa.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Added a new DocumentJoiner component so that hybrid retrieval pipelines can merge the document result lists of multiple retrievers. + Similarly, indexing pipelines can use DocumentJoiner to merge multiple lists of documents created by different file converters. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-language-classifier-1ec0b3c4d08989c0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-language-classifier-1ec0b3c4d08989c0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07372290f3ddce8a2f6c3abc12e101fd1738d793 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-language-classifier-1ec0b3c4d08989c0.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Added DocumentLanguageClassifier component so that Documents can be routed to different components based on the detected language for example during preprocessing. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-map-evaluator-de896c94b54fe3fa.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-map-evaluator-de896c94b54fe3fa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7b8532379d4b3f1cd50c53115cd28e665e2c4f9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-map-evaluator-de896c94b54fe3fa.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add DocumentMAPEvaluator, it can be used to calculate mean average precision of retrieved documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-metadata-to-meta-8564aa3c045bb526.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-metadata-to-meta-8564aa3c045bb526.yaml new file mode 100644 index 0000000000000000000000000000000000000000..577b69a91e878f201dbfaa1b8fb6a34ce3ed2068 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-metadata-to-meta-8564aa3c045bb526.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Rename `Document`'s `metadata` field to `meta` to enhance backward compatibility diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-mrr-evaluator-fa7c266cc91201a7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-mrr-evaluator-fa7c266cc91201a7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..152fea593a7472df319e89a145a3d0812e980828 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-mrr-evaluator-fa7c266cc91201a7.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add DocumentMRREvaluator, it can be used to calculate mean reciprocal rank of retrieved documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-splitter-accept-split-threshold-467abb9fcd1c316b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-splitter-accept-split-threshold-467abb9fcd1c316b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37f6bda3e70860201191dd1ce3c1f2472cf94518 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-splitter-accept-split-threshold-467abb9fcd1c316b.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + DocumentSplitter now has an optional split_threshold parameter. Use this parameter if you want to rather not split inputs that are only slightly longer than the allowed split_length. + If when chunking one of the chunks is smaller than the split_threshold, the chunk will be concatenated with the previous one. This avoids having too small chunks that are not meaningful. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-store-testing-c1a8050f06ff3e97.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-store-testing-c1a8050f06ff3e97.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3bf89ac7fb11d22452de057dfc4d2b1fd9501e50 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-store-testing-c1a8050f06ff3e97.yaml @@ -0,0 +1,25 @@ +--- +prelude: > + The `testing.DocumentStoreBaseTests` has been heavily overhauled. + It has been split into multiple classes so developers can gradually test their Document Store as they're implemented. + `DocumentStoreBaseTests` now inherits from this classes: + - `CountDocumentsTest`, to test `DocumentStore.count_documents()` + - `WriteDocumentsTest`, to test `DocumentStore.write_documents()` + - `DeleteDocumentsTest`, to test `DocumentStore.delete_documents()` + - `FilterDocumentsTest`, to test `DocumentStore.filter_documents()` + + To use each class it's enough to inherit from it and define the `document_store` fixture to return an instance of the Document Store we're implementing. + ```python + class MyDocumentStoreCountDocumentTest(CountDocumentsTest): + @pytest.fixture + def document_store(self): + return MyDocumentStore() + ``` + + There's also another class that tests `DocumentStore.filter_documents()` using legacy filters. + This is not inherited by `DocumentStoreBaseTests` but can be added as a base class to verify the support of legacy filters. + - `LegacyFilterDocumentsTest` + +preview: + - | + Rework the `testing.DocumentStoreBaseTests` class to ease Document Stores development and testing diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-text-to-content-39b5439480af5c41.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-text-to-content-39b5439480af5c41.yaml new file mode 100644 index 0000000000000000000000000000000000000000..95e7d818e6aa38e1aa8ba2ac6b008b0884ffebd8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-text-to-content-39b5439480af5c41.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Rename `Document`'s `text` field to `content` to enhance backward compatibility diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-writer-default-policy-693027781629fc73.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-writer-default-policy-693027781629fc73.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b90629fe8be3da9cbed2f879fe518e4e9448a2ed --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-writer-default-policy-693027781629fc73.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Change `DocumentWriter` default `policy` from `DuplicatePolicy.FAIL` to `DuplicatePolicy.NONE`. + The `DocumentStore` protocol uses the same default so that different Document Stores can choose + the default policy that better fit. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/document-writer-v2-bbe0a62b3066f9cf.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/document-writer-v2-bbe0a62b3066f9cf.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7423892b84e148d8d746302f14f589895cf3fe56 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/document-writer-v2-bbe0a62b3066f9cf.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Added new DocumentWriter component to Haystack v2 preview so that documents can be written to stores. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/docxtodocument-rename-3acf592c89aea430.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/docxtodocument-rename-3acf592c89aea430.yaml new file mode 100644 index 0000000000000000000000000000000000000000..706a244142165b13fc05abb6b75730e38c260593 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/docxtodocument-rename-3acf592c89aea430.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Renamed component from DocxToDocument to DOCXToDocument to follow the naming convention of other converter components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/embedding-instructions-4feb216cbf796678.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/embedding-instructions-4feb216cbf796678.yaml new file mode 100644 index 0000000000000000000000000000000000000000..612a3160cdf895051543193d8b886b09c5622344 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/embedding-instructions-4feb216cbf796678.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Support for dense embedding instructions, used in retrieval models such as BGE and LLM-Embedder. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/enable-set-max-length-during-runtime-097d65e537bf800b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/enable-set-max-length-during-runtime-097d65e537bf800b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..32c5219fd2b3713317d519c22e7ee1925a5d9cfd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/enable-set-max-length-during-runtime-097d65e537bf800b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enable setting the `max_length` value when running PromptNodes using local HF text2text-generation models. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/enable_pass_use_fast_to_transformers-b5fdf14d69aa58ec.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/enable_pass_use_fast_to_transformers-b5fdf14d69aa58ec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33aacb3987ffb553c9ee3e1590ba134b9c0cf516 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/enable_pass_use_fast_to_transformers-b5fdf14d69aa58ec.yaml @@ -0,0 +1,3 @@ +--- +enhancements: + - enable passing use_fast to the underlying transformers' pipeline diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/enhance-inmemorydocumentstore-bm25-incremental-indexing-ebaf43b7163f3a24.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/enhance-inmemorydocumentstore-bm25-incremental-indexing-ebaf43b7163f3a24.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1c8d3f380018f8b7720bf0bb9d35faf2c0862984 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/enhance-inmemorydocumentstore-bm25-incremental-indexing-ebaf43b7163f3a24.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + Re-implement `InMemoryDocumentStore` BM25 search with incremental indexing by avoiding re-creating + the entire inverse index for every new query. This change also removes the dependency on + `haystack_bm25`. Please refer to [PR #7549](https://github.com/deepset-ai/haystack/pull/7549) + for the full context. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/enhanced-htmltodocument-content-extraction-229d63e7c7119807.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/enhanced-htmltodocument-content-extraction-229d63e7c7119807.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7aab3e330f4b62fb72da9d8a2c4d6c3064d37f4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/enhanced-htmltodocument-content-extraction-229d63e7c7119807.yaml @@ -0,0 +1,3 @@ +enhancements: + - | + Improved HTML content extraction by attempting to use multiple extractors in order of priority until successful. An additional try_others parameter in HTMLToDocument, which is true by default, determines whether subsequent extractors are used after a failure. This enhancement decreases extraction failures, ensuring more dependable content retrieval. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/enhanced-mime-type-handling-182fb64a0f5fb852.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/enhanced-mime-type-handling-182fb64a0f5fb852.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0e7d07445353a4924ea4d3d57a88f238875d2eb --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/enhanced-mime-type-handling-182fb64a0f5fb852.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improved MIME type management by directly setting MIME types on ByteStreams, enhancing the overall handling and routing of different file types. This update makes MIME type data more consistently accessible and simplifies the process of working with various document formats. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/exact-match-evaluator-197bb87b65e19d0c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/exact-match-evaluator-197bb87b65e19d0c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c872542bee3f14482eb45a3663ed805923443f2d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/exact-match-evaluator-197bb87b65e19d0c.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Add `AnswerExactMatchEvaluator`, a component that can be used to calculate the Exact Match metric + comparing a list of expected answers with a list of predicted answers. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/extend-promptbuilder-0322790d82248039.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/extend-promptbuilder-0322790d82248039.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff6e5bfaa01ebc85a81cfe8dce64ccaba86738f0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/extend-promptbuilder-0322790d82248039.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + `PromptBuilder` now supports changing its template at runtime (e.g. for Prompt Engineering). This allows you to define a default template and then change it based on your needs at runtime. +deprecations: + - | + `DynamicPromptBuilder` has been deprecated as `PromptBuilder` fully covers its functionality. Use `PromptBuilder` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/extend-write-documents-855ffc315974f03b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/extend-write-documents-855ffc315974f03b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e29d345423dc307db33d18a90058ca35e2701333 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/extend-write-documents-855ffc315974f03b.yaml @@ -0,0 +1,2 @@ +preview: + - Change `write_documents()` method in `DocumentStore` protocol to return the number of document written diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/extract_type_serialization-fc3ea6418ba5632d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/extract_type_serialization-fc3ea6418ba5632d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b380f9ec8d492c2ad527d1f8e963f47cdeb65196 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/extract_type_serialization-fc3ea6418ba5632d.yaml @@ -0,0 +1,3 @@ +enhancements: + - | + Move `serialize_type` and `deserialize_type` in the `utils` module. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/extractive-qa-answer-dedup-7ca3b94b79b38854.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/extractive-qa-answer-dedup-7ca3b94b79b38854.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12b79fa2aa4887f5595a5b5c3e5ea7a125bd4234 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/extractive-qa-answer-dedup-7ca3b94b79b38854.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Introduces answer deduplication on the Document level based on an overlap threshold. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/extractive-reader-invalid-ans-a88e6b1d1ee897aa.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/extractive-reader-invalid-ans-a88e6b1d1ee897aa.yaml new file mode 100644 index 0000000000000000000000000000000000000000..edec36fc43f1fa6776cb916fd8043ea980d30140 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/extractive-reader-invalid-ans-a88e6b1d1ee897aa.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix issue with `ExtractiveReader` picking invalid answers when `answers_per_seq` > num of valid answers diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/feat-widen-support-of-envars-vars-on-openai-components-efe6203c0c6bd7b3.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/feat-widen-support-of-envars-vars-on-openai-components-efe6203c0c6bd7b3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b2b47a6cdf2078e4e4a7665189ef4a8b638cc33 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/feat-widen-support-of-envars-vars-on-openai-components-efe6203c0c6bd7b3.yaml @@ -0,0 +1,6 @@ +--- +highlights: > + Add the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' to the OpenAI components. +enhancements: + - | + Now you can set the timeout and max_retries parameters on OpenAI components by setting the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES' environment vars or passing them at __init__. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/file-classifier-add-media-files-support-e970524f726dd844.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/file-classifier-add-media-files-support-e970524f726dd844.yaml new file mode 100644 index 0000000000000000000000000000000000000000..97a42ee98281085e905fdaabfbbfbc6c56ce884f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/file-classifier-add-media-files-support-e970524f726dd844.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhance FileTypeClassifier to detect media file types like mp3, mp4, mpeg, m4a, and similar. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/filters-converter-485cd24cf38407d0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/filters-converter-485cd24cf38407d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49cca08828237da1a79d82d0632d571edc3365b2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/filters-converter-485cd24cf38407d0.yaml @@ -0,0 +1,42 @@ +--- +prelude: > + Following the proposal to introduce a new way of declaring filters + in Haystack 2.x for Document Stores and all Components that use them, + we introduce a utility function to convert the legacy style to the new style. + + This will make life easier for developers when implementing new Document Stores + as it will only be necessary for filtering logic for the new style filters, as + conversion will be completely handled by the utility function. + + An example usage would be something similar to this: + ```python + legacy_filter = { + "$and": { + "type": {"$eq": "article"}, + "date": {"$gte": "2015-01-01", "$lt": "2021-01-01"}, + "rating": {"$gte": 3}, + "$or": {"genre": {"$in": ["economy", "politics"]}, "publisher": {"$eq": "nytimes"}}, + } + } + assert convert(legacy_filter) == { + "operator": "AND", + "conditions": [ + {"field": "type", "operator": "==", "value": "article"}, + {"field": "date", "operator": ">=", "value": "2015-01-01"}, + {"field": "date", "operator": "<", "value": "2021-01-01"}, + {"field": "rating", "operator": ">=", "value": 3}, + { + "operator": "OR", + "conditions": [ + {"field": "genre", "operator": "in", "value": ["economy", "politics"]}, + {"field": "publisher", "operator": "==", "value": "nytimes"}, + ], + }, + ], + } + ``` + + For more information on the new filters technical specification see [proposal #6001](https://github.com/deepset-ai/haystack/blob/main/proposals/text/6001-document-store-filter-rework.md) +preview: + - | + Introduce a function to convert legacy filters to the new style diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-auto-tracing-51ed3a590000d6c8.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-auto-tracing-51ed3a590000d6c8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..63dc2645ad82d97bbaf81ed9e37695412e234bb5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-auto-tracing-51ed3a590000d6c8.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Auto enable tracing upon import if `ddtrace` or `opentelemetry` is installed. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-azure-generators-serialization-18fcdc9cbcb3732e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-azure-generators-serialization-18fcdc9cbcb3732e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..071969e62ed8568d8bae5ba634f823b848c63bce --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-azure-generators-serialization-18fcdc9cbcb3732e.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Azure generators components fixed, they were missing the `@component` decorator. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-azure-ocr-bytestream-meta-0d2c8e6ea761b791.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-azure-ocr-bytestream-meta-0d2c8e6ea761b791.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b0f6ad9c85702af18a3c9d90aef4eca7947f1fa2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-azure-ocr-bytestream-meta-0d2c8e6ea761b791.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Meta handling of bytestreams in Azure OCR has been fixed. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-caching-filters-syntax-d4c165ce0b0f258f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-caching-filters-syntax-d4c165ce0b0f258f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c7cf8df4068c979992fe82875f728db5867f957 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-caching-filters-syntax-d4c165ce0b0f258f.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Use new filter syntax in the CacheChecker component instead of legacy one. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-chat-prompt-builder-serialization-345605337ca2584e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-chat-prompt-builder-serialization-345605337ca2584e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9df38134df6585543dc9ab41be4dc7c37867411 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-chat-prompt-builder-serialization-345605337ca2584e.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Solve serialization bug on 'ChatPromptBuilder' by creating 'to_dict' and 'from_dict' methods on 'ChatMessage' and 'ChatPromptBuilder'. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-chatgpt-invocation-layer-bc25d0ea5f77f05c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-chatgpt-invocation-layer-bc25d0ea5f77f05c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2be3084dd78477fc9964c4bd6059fcaefa3691d2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-chatgpt-invocation-layer-bc25d0ea5f77f05c.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Fixed the bug that prevented the correct usage of ChatGPT invocation layer + in 1.21.1. + Added async support for ChatGPT invocation layer. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-conditional-branching-a0f0d65c7ac97f71.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-conditional-branching-a0f0d65c7ac97f71.yaml new file mode 100644 index 0000000000000000000000000000000000000000..426ad87140b63e4e2e9b1ef4d7b54d012a9e60b5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-conditional-branching-a0f0d65c7ac97f71.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Fix some bugs running a Pipeline that has Components with conditional outputs. + Some branches that were expected not to run would run anyway, even if they received no inputs. + Some branches instead would cause the Pipeline to get stuck waiting to run that branch, even if they received no inputs. + The behaviour would depend whether the Component not receiving the input has a optional input or not. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-connect-with-same-name-5ce470f7f0451362.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-connect-with-same-name-5ce470f7f0451362.yaml new file mode 100644 index 0000000000000000000000000000000000000000..529cd69a108be66d02e405caa3ad5f7db16a2d54 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-connect-with-same-name-5ce470f7f0451362.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix `Pipeline.connect()` so it connects sockets with same name if multiple sockets with compatible types are found. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-descriptor-__dict__-doesnt-apply-to-bf6d47872345ed24.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-descriptor-__dict__-doesnt-apply-to-bf6d47872345ed24.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a3ff8d07a5a6bc39761bbec1d05562d84e85f09 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-descriptor-__dict__-doesnt-apply-to-bf6d47872345ed24.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixes the error `descriptor '__dict__' for 'ComponentClassX' objects doesn't apply to a 'ComponentClassX' object` when calling + `dir()` on a component instance. This fix should allow auto-completion in code editors. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-device-deserialization-st-embedder-c4efad96dd3869d5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-device-deserialization-st-embedder-c4efad96dd3869d5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6bb0a4d2b90fb72edd332007eaa6539ed4f06e2e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-device-deserialization-st-embedder-c4efad96dd3869d5.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Updates the from_dict method of SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder, NamedEntityExtractor, SentenceTransformersDiversityRanker and LocalWhisperTranscriber to allow None as a valid value for device when deserializing from a YAML file. + This allows a deserialized pipeline to auto-determine what device to use using the ComponentDevice.resolve_device logic. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-constructor-18b9e5dd9522a918.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-constructor-18b9e5dd9522a918.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0227063156e61823f6056826e3f381314acd4d28 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-constructor-18b9e5dd9522a918.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Remove `id` parameter from `Document` constructor as it was ignored and a new one was generated anyway. + This is a backwards incompatible change. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-flatten-metadata-ef61dbbae08b1db7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-flatten-metadata-ef61dbbae08b1db7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad516ff400fde9ef02096c0899d02e9d9461930c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-flatten-metadata-ef61dbbae08b1db7.yaml @@ -0,0 +1,8 @@ +--- + +preview: + - | + Fix a failure that occurred when creating a document passing the 'meta' keyword + to the constructor. Raise a specific ValueError if the 'meta' keyword is passed + along with metadata as keyword arguments, the two options are mutually exclusive + now. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-init-09c1cbb14202be7d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-init-09c1cbb14202be7d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1fc6a6cb208e97e9b423a8421c74eab25be362d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-init-09c1cbb14202be7d.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Make Document's constructor fail when is passed fields that are not present in the dataclass. An exception is made for "content_type" and "id_hash_keys": they are accepted in order to keep backward compatibility. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-splitter-split-info-1704f16c8b0f374a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-splitter-split-info-1704f16c8b0f374a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..87108281ba96589fc12f392bf5104b166106523d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-document-splitter-split-info-1704f16c8b0f374a.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + The DocumentSplitter was incorrectly calculating the `split_start_idx` and `_split_overlap` information due to slight miscalculations of appropriate indices. + This fixes those so the `split_start_idx` and `_split_overlap` information is correct. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-documentjoiner-topk-173141a894e5c093.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-documentjoiner-topk-173141a894e5c093.yaml new file mode 100644 index 0000000000000000000000000000000000000000..665186022ab26dffcdea3321c7a291004188be3e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-documentjoiner-topk-173141a894e5c093.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + The `DocumentJoiner` component's `run` method now accepts a `top_k` parameter, allowing users to specify the maximum number of documents to return at query time. This fixes issue #7702. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-e2e-test-preprocessing-7b24f848e074c48a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-e2e-test-preprocessing-7b24f848e074c48a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99e6d5242bef804b007d5640f1f65c6ea1b9eb6d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-e2e-test-preprocessing-7b24f848e074c48a.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Updated end-to-end test to use the DocumentLanguageClassifier with a MetadataRouter in a preprocessing pipeline. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-embedders-docs-examples-72119352572012d7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-embedders-docs-examples-72119352572012d7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed812f99c84da961d90773422267239d18839de2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-embedders-docs-examples-72119352572012d7.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Fix usage examples for OpenAIDocumentEmbedder and SentenceTransformersDocumentEmbedder. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-entityextractor-json-serialzable-b7d643eb83a3e58c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-entityextractor-json-serialzable-b7d643eb83a3e58c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ad1415b8faa0ec2cea2fdb58cd023ef17bc9eb9d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-entityextractor-json-serialzable-b7d643eb83a3e58c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix EntityExtractor output not JSON serializable. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-execution-order-1121cedd9c68c560.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-execution-order-1121cedd9c68c560.yaml new file mode 100644 index 0000000000000000000000000000000000000000..77dd7796796a3d5c508cf492115bac27e0a79543 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-execution-order-1121cedd9c68c560.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix bug in Pipeline.run() executing Components in a wrong and unexpected order diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-hf-api-serialization-026b84de29827c57.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-hf-api-serialization-026b84de29827c57.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5fa7d9c3cf04a091891aba635d93215a33290bfe --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-hf-api-serialization-026b84de29827c57.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fix the broken serialization of HuggingFaceAPITextEmbedder, HuggingFaceAPIDocumentEmbedder, + HuggingFaceAPIGenerator, and HuggingFaceAPIChatGenerator. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-issue-#5485-efa4486a414ce584.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-issue-#5485-efa4486a414ce584.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc91785920c44181f12fdd865ce6ea1d805d6e86 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-issue-#5485-efa4486a414ce584.yaml @@ -0,0 +1,2 @@ +fixes: + - fix issue 5485, TransformersImageToText.generate_captions accepts "str" diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-issue-7758-d35b687ca226a707.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-issue-7758-d35b687ca226a707.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b1accdd2ac6c927e33dd74dcb34d50092f6aa80b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-issue-7758-d35b687ca226a707.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed the calculation for MRR and MAP scores. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-jinja-env-81c98225b22dc827.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-jinja-env-81c98225b22dc827.yaml new file mode 100644 index 0000000000000000000000000000000000000000..328fae81416907eb681c2f3971b30967fd034f78 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-jinja-env-81c98225b22dc827.yaml @@ -0,0 +1,14 @@ +--- +upgrade: + - | + `OutputAdapter` and `ConditionalRouter` can't return users inputs anymore. +security: + - | + Fix issue that could lead to remote code execution when using insecure Jinja template in the following Components: + + - `PromptBuilder` + - `ChatPromptBuilder` + - `OutputAdapter` + - `ConditionalRouter` + + The same issue has been fixed in the `PipelineTemplate` class too. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-join-docs-null-score-746c392a87adffcc.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-join-docs-null-score-746c392a87adffcc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33d2e9311d4fdbd32e4a90efd15363a4bb9701b2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-join-docs-null-score-746c392a87adffcc.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + When using `JoinDocuments` with `join_mode=concatenate` (default) and + passing duplicate documents, including some with a null score, this + node raised an exception. + Now this case is handled correctly and the documents are joined as expected. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-joinDocuments-concatenate-56a7cdba00a7248e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-joinDocuments-concatenate-56a7cdba00a7248e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e282f7b9fb1cef12d49763947171b98a964cbc2a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-joinDocuments-concatenate-56a7cdba00a7248e.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Make JoinDocuments return only the document with the highest score if there are duplicate documents in the list. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-llmevaluator-subclass-deserialization-c633b2f95c84fe4b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-llmevaluator-subclass-deserialization-c633b2f95c84fe4b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a2adbca7886f24632ae60b84aeb070e3336b967 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-llmevaluator-subclass-deserialization-c633b2f95c84fe4b.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix the deserialization of pipelines containing evaluator components that were subclasses of `LLMEvaluator`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-model_max_length-prompt_handler-7f34c40c62a8c55b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-model_max_length-prompt_handler-7f34c40c62a8c55b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2fe468663855baa2158e45597ecca38ceceb8ca --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-model_max_length-prompt_handler-7f34c40c62a8c55b.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix model_max_length not being set in the Tokenizer in DefaultPromptHandler. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-named-entity-entity-extractor-backend-enum-2e64e25f8d7f1b08.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-named-entity-entity-extractor-backend-enum-2e64e25f8d7f1b08.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0df95101c8557d8b835517b1e727ef6613d8954e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-named-entity-entity-extractor-backend-enum-2e64e25f8d7f1b08.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix `NamedEntityExtractor` crashing in Python 3.12 if constructed using a string backend argument. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-pdfminer-converter-54e6d7e1a82d6e7b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pdfminer-converter-54e6d7e1a82d6e7b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42aa1e70318c135bf966e0964a1a9550ea8c6f35 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pdfminer-converter-54e6d7e1a82d6e7b.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed the PdfMinerToDocument converter's outputs to be properly wired up to 'documents'. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-pipeline-deserialization-a3909bb6b623c588.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pipeline-deserialization-a3909bb6b623c588.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8f91d5e5b0b013c655573ea279a3c7d98e731d9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pipeline-deserialization-a3909bb6b623c588.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Prevent `Pipeline.from_dict` from modifying the dictionary parameter passed to it. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-pipeline-run-loop-99f7ff9db16544d4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pipeline-run-loop-99f7ff9db16544d4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61ad81c7824ba24cbbb5b53befc3b26889837bef --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pipeline-run-loop-99f7ff9db16544d4.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix a bug when running a Pipeline that would cause it to get stuck in an infinite loop diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-pypdf-serialization-93744fd01ef5b841.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pypdf-serialization-93744fd01ef5b841.yaml new file mode 100644 index 0000000000000000000000000000000000000000..04d042c6fdb8885f53abc5fbd5889296c5157271 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-pypdf-serialization-93744fd01ef5b841.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Make `PyPDFToDocument` accept a `converter_name` parameter instead of + a `converter` instance, to allow a smooth serialization of the component. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-reader-top-k-b4f7e29be5ba5ee1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-reader-top-k-b4f7e29be5ba5ee1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb017358e9dc974fbbc07fcbe9ac3045bf8eed2c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-reader-top-k-b4f7e29be5ba5ee1.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Update Reader documentation to explain that top_k+1 answers are returned if no_answer is enabled (default). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-recursive-json-schema-validator-cdb7684de3c75e4e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-recursive-json-schema-validator-cdb7684de3c75e4e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c24e687005d93e3fce6ce056c9aebafcb4369aaf --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-recursive-json-schema-validator-cdb7684de3c75e4e.yaml @@ -0,0 +1,8 @@ +--- +enhancements: + - | + Made JSON schema validator compatible with all LLM by switching error template handling to a single user message. + Also reduce cost by only including last error instead of full message history. +fixes: + - | + Fix recursive JSON type conversion in the schema validator to be less aggressive (no infinite recursion). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-serialization-docrecallevaluator-91ad772ffed119ed.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-serialization-docrecallevaluator-91ad772ffed119ed.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c98eb79ccdae45dede94844a35e1ce83eb2f70ad --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-serialization-docrecallevaluator-91ad772ffed119ed.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Add `to_dict` method to `DocumentRecallEvaluator` to allow proper serialization of the component. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-serialization-openai-generator-cf7e9a04562dde75.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-serialization-openai-generator-cf7e9a04562dde75.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e815b68b0115460204480beff41b75d13140b80 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-serialization-openai-generator-cf7e9a04562dde75.yaml @@ -0,0 +1,3 @@ +fixes: + - | + Adds the missing 'organization' parameter to the serialization function. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-splitter-cleaner-hash-key-3b6f042af7da9ab4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-splitter-cleaner-hash-key-3b6f042af7da9ab4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33708f0b4dd5fd6113ff6d94be898cf4c54e12de --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-splitter-cleaner-hash-key-3b6f042af7da9ab4.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Fixed a bug that caused TextDocumentSplitter and DocumentCleaner to ignore id_hash_keys and create Documents with duplicate ids if the documents differed only in their metadata. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-stop-words-criteria-check-order-bug-4badfcc021dfc92a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-stop-words-criteria-check-order-bug-4badfcc021dfc92a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6f06db3c980f5004bbb995440f298975296df4ce --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-stop-words-criteria-check-order-bug-4badfcc021dfc92a.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix StopWordsCriteria not checking stop word tokens in a continuous and sequential order diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-stop-words-strip-issue-22ce51306e7b91e4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-stop-words-strip-issue-22ce51306e7b91e4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dab779ede30cd4775552cc527c5b373f5adc77f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-stop-words-strip-issue-22ce51306e7b91e4.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Ensure the leading whitespace in the generated text is preserved when using `stop_words` in the Hugging Face invocation layer of the PromptNode. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-text-splitter-65870db474338749.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-text-splitter-65870db474338749.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6633117e4a97282d2dffde5c77f538a12a42f70a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-text-splitter-65870db474338749.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Fix TextDocumentSplitter failing when run with an empty list diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-transformersranker-single-doc-12448c3d7bc8dc6c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-transformersranker-single-doc-12448c3d7bc8dc6c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5dffe1ebfaf660372624b808e4554c26e35a1c0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-transformersranker-single-doc-12448c3d7bc8dc6c.yaml @@ -0,0 +1,3 @@ +--- +fixes: + - Make `TransformersSimilarityRanker` run with a list containing a single document as input. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-version-47afaec913788a01.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-version-47afaec913788a01.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e657c7a529a06c154ade025c20dcfc2f9c51af6 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-version-47afaec913788a01.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fix Haystack imports failing when using local development environment that doesn't have `haystack-ai` installed. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/fix-weaviate-date-fields-request-bottleneck-d9784b7e1044cacd.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/fix-weaviate-date-fields-request-bottleneck-d9784b7e1044cacd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d40fe7c5bae3bd46da74169b42d7b7b496f60bf4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/fix-weaviate-date-fields-request-bottleneck-d9784b7e1044cacd.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed a bottleneck in Weaviate document store which was slowing down the indexing. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/flexible-hf-api-token-env-vars-5fe383cdc1a9cc29.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/flexible-hf-api-token-env-vars-5fe383cdc1a9cc29.yaml new file mode 100644 index 0000000000000000000000000000000000000000..506fa0513f552e6491dcb78661c382cb5a4c1fcd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/flexible-hf-api-token-env-vars-5fe383cdc1a9cc29.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced flexibility in HuggingFace API environment variable names across all related components to support both 'HF_API_TOKEN' and 'HF_TOKEN', improving compatibility with the widely used HF environmental variable naming conventions. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/force-valid-JSON-OpeanAI-LLM-based-evaluators-64816e68f137739b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/force-valid-JSON-OpeanAI-LLM-based-evaluators-64816e68f137739b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19e1ddb15ca93f46a26fae831b4ac5ee90bea596 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/force-valid-JSON-OpeanAI-LLM-based-evaluators-64816e68f137739b.yaml @@ -0,0 +1,6 @@ +--- + +enhancements: + - | + Enforce JSON mode on OpenAI LLM-based evaluators so that the they always return valid JSON output. + This is to ensure that the output is always in a consistent format, regardless of the input. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/generators-module-261376beb9c031cc.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/generators-module-261376beb9c031cc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0c57e6bc7b0181ebc9a0b35469ce787f93691149 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/generators-module-261376beb9c031cc.yaml @@ -0,0 +1,2 @@ +preview: + - Add generators module for LLM generator components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/gpt4-llm-generator-60708087ec42211f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/gpt4-llm-generator-60708087ec42211f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb67de3ccda1c4090be57c21f3f4110bd689ceab --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/gpt4-llm-generator-60708087ec42211f.yaml @@ -0,0 +1,3 @@ + +preview: + - Adds `GPT4Generator`, an LLM component based on `GPT35Generator` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/gptgenerator-api-key-b9a648301a67bb37.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/gptgenerator-api-key-b9a648301a67bb37.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1e7b085c18c7695b43cd0c7ed9b19414a653f45e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/gptgenerator-api-key-b9a648301a67bb37.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Better management of API key in GPT Generator. The API key is never serialized. + Make the `api_base_url` parameter really used (previously it was ignored). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/hfapichatgenerator-51772e1f0d679b1c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/hfapichatgenerator-51772e1f0d679b1c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd32439c9ba5229212243a1b5eaf252650ac655f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/hfapichatgenerator-51772e1f0d679b1c.yaml @@ -0,0 +1,14 @@ +--- +features: + - | + Introduce `HuggingFaceAPIChatGenerator`. + This text-generation component uses the ChatMessage format and supports different Hugging Face APIs: + - free Serverless Inference API + - paid Inference Endpoints + - self-hosted Text Generation Inference. + + This generator will replace the `HuggingFaceTGIChatGenerator` in the future. +deprecations: + - | + Deprecate `HuggingFaceTGIChatGenerator`. This component will be removed in Haystack 2.3.0. + Use `HuggingFaceAPIChatGenerator` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/hfapitextembedder-97bf5f739f413f3e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/hfapitextembedder-97bf5f739f413f3e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f8ac29deef7c5d16e1098f8c1b58050a52e123e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/hfapitextembedder-97bf5f739f413f3e.yaml @@ -0,0 +1,13 @@ +--- +features: + - | + Introduce `HuggingFaceAPITextEmbedder`. + This component can be used to embed strings using different Hugging Face APIs: + - free Serverless Inference API + - paid Inference Endpoints + - self-hosted Text Embeddings Inference. + This embedder will replace the `HuggingFaceTEITextEmbedder` in the future. +deprecations: + - | + Deprecate `HuggingFaceTEITextEmbedder`. This component will be removed in Haystack 2.3.0. + Use `HuggingFaceAPITextEmbedder` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/hflocalgenerator-generation-kwargs-in-run-2bde10d398a3712a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/hflocalgenerator-generation-kwargs-in-run-2bde10d398a3712a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf605f9c38faab82e0d762bfccce023b49abe220 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/hflocalgenerator-generation-kwargs-in-run-2bde10d398a3712a.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Allow passing `generation_kwargs` in the `run` method of the `HuggingFaceLocalGenerator`. + This makes this common operation faster. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/highlight-optional-conns-in-draw-cf107ee210b7b8e7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/highlight-optional-conns-in-draw-cf107ee210b7b8e7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ce9133fe286b44b071c6805d47e81ff544d941b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/highlight-optional-conns-in-draw-cf107ee210b7b8e7.yaml @@ -0,0 +1,3 @@ +--- +enhancements: + - Highlight optional connections in the `Pipeline.draw()` output. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/htmlconverter-allow-extractor-customizability-730ae129db17327a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/htmlconverter-allow-extractor-customizability-730ae129db17327a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a77b947505b7557a364a8c5bee8936b1b4bf100e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/htmlconverter-allow-extractor-customizability-730ae129db17327a.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + The `HTMLToDocument` converter now allows choosing the boilerpy3 extractor + to extract the content from the HTML document. + The default extractor has been changed to `DefaultExtractor`, which is better + for generic use cases than the previous default (`ArticleExtractor`). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/hugging-face-local-generator-a9a0ba011506f932.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/hugging-face-local-generator-a9a0ba011506f932.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2038626f3dedaf3a3517d55fbcdef12d8d9fe591 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/hugging-face-local-generator-a9a0ba011506f932.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add a minimal version of HuggingFaceLocalGenerator, a component that can run + Hugging Face models locally to generate text. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/hybrid_search_faq_pipeline.py-815df846dca7e872.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/hybrid_search_faq_pipeline.py-815df846dca7e872.yaml new file mode 100644 index 0000000000000000000000000000000000000000..660f7d692b3e9010cbe42d7f1ac0bc6ef17d9e35 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/hybrid_search_faq_pipeline.py-815df846dca7e872.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Added documents_store.update_embeddings call to pipeline examples so that embeddings are calculated for newly added documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/implemeting-eval-results-API-25b2f8707495bea0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/implemeting-eval-results-API-25b2f8707495bea0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2cec7bbd617b32f79278ffcd6c6a3624940aaacb --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/implemeting-eval-results-API-25b2f8707495bea0.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Added a new EvaluationRunResult dataclass that wraps the results of an evaluation pipeline, + allowing for its transformation and visualization. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/improve-ContextRelevance-evaluator-prompt-6b80229c99e3bc38.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/improve-ContextRelevance-evaluator-prompt-6b80229c99e3bc38.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dd7e8342b62a04beaed49d3ee8da2f15fe3a146 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/improve-ContextRelevance-evaluator-prompt-6b80229c99e3bc38.yaml @@ -0,0 +1,5 @@ +--- + +enhancements: + - | + Updated the ContextRelevance evaluator prompt, explicitly asking to score each statement. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/improve-hf-invocation-layer-tests-c42250d11d1d06c1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/improve-hf-invocation-layer-tests-c42250d11d1d06c1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e1329af398ce253b78b48f2b2098ba3e8a72377 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/improve-hf-invocation-layer-tests-c42250d11d1d06c1.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Minor PromptNode HFLocalInvocationLayer test improvements diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/improve-link-content-fetcher-512d039e3c7684f1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/improve-link-content-fetcher-512d039e3c7684f1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afb84eae28f9b02f9e10131a2a4704da01b3d93e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/improve-link-content-fetcher-512d039e3c7684f1.yaml @@ -0,0 +1,8 @@ +--- +enhancements: + - | + Several minor enhancements for LinkContentFetcher: + - Dynamic content handler resolution + - Custom User-Agent header (optional, minimize blocking) + - PDF support + - Register new content handlers diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/improve-pipeline-run-tracing-1d80aa7810df4205.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/improve-pipeline-run-tracing-1d80aa7810df4205.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c25257fd3730e6f7e6e3f65c65fdaead1aefe2ea --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/improve-pipeline-run-tracing-1d80aa7810df4205.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improved pipeline run tracing to include pipeline input/output data. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/improve-type-serialization-support-18822a5b978b1e77.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/improve-type-serialization-support-18822a5b978b1e77.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2c96fe48867bdec7106d87069da2685ba7576ce --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/improve-type-serialization-support-18822a5b978b1e77.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Improves/fixes type serialization of PEP 585 types (e.g. list[Document], and their nested version). This improvement enables better serialization of generics and nested types and improves/fixes matching of list[X] and List[X] types in component connections after serialization. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/in-memory-docstore-memory-share-82b75d018b3545fc.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/in-memory-docstore-memory-share-82b75d018b3545fc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d60997a41c95b509e2da7bbcf588f6e64d8b29be --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/in-memory-docstore-memory-share-82b75d018b3545fc.yaml @@ -0,0 +1,19 @@ +--- +features: + - | + Add memory sharing between different instances of InMemoryDocumentStore. + Setting the same `index` argument as another instance will make sure that the memory is shared. + e.g. + ```python + index = "my_personal_index" + document_store_1 = InMemoryDocumentStore(index=index) + document_store_2 = InMemoryDocumentStore(index=index) + + assert document_store_1.count_documents() == 0 + assert document_store_2.count_documents() == 0 + + document_store_1.write_documents([Document(content="Hello world")]) + + assert document_store_1.count_documents() == 1 + assert document_store_2.count_documents() == 1 + ``` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/inmemory-return-written-documents-488b7f90df84bc59.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/inmemory-return-written-documents-488b7f90df84bc59.yaml new file mode 100644 index 0000000000000000000000000000000000000000..632f2b6fb66c11e9c130b5921f3dc8d2cfe70818 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/inmemory-return-written-documents-488b7f90df84bc59.yaml @@ -0,0 +1,2 @@ +preview: + - Make `InMemoryDocumentStore.write_documents()` return the number of docs actually written diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/inmemorybm25retriever-zero-score-docs-67406062a76aa7f4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/inmemorybm25retriever-zero-score-docs-67406062a76aa7f4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ae440162aa8bfdea777651791f0d87a29d9479f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/inmemorybm25retriever-zero-score-docs-67406062a76aa7f4.yaml @@ -0,0 +1,3 @@ +--- +fixes: + - Prevent InMemoryBM25Retriever from returning documents with a score of 0.0. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/issue-5616-convert-files-to-docs-list-f75a057249ba8992.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/issue-5616-convert-files-to-docs-list-f75a057249ba8992.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1f05697db3f6901b98d2bae5a475172af66cfa8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/issue-5616-convert-files-to-docs-list-f75a057249ba8992.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Add `list_of_paths` argument to `utils.convert_files_to_docs` to allow + input of list of file paths to be converted, instead of, or as well as, + the current `dir_path` argument. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/lazy-import-v2-82902270867d9899.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/lazy-import-v2-82902270867d9899.yaml new file mode 100644 index 0000000000000000000000000000000000000000..36543095ebc7cbe60ab892f346460fa700fb1611 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/lazy-import-v2-82902270867d9899.yaml @@ -0,0 +1,2 @@ +preview: + - copy lazy_imports.py to preview diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6a7d2428582b1f63bd922c303382bce3b5bb9d5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improve LinkContentFetcher to support a broader range of content types, including glob patterns for text, application, audio, and video types. This update introduces a more flexible content handler resolution mechanism, allowing for direct matches and pattern matching, thereby greatly improving the handler's adaptability to various content types encountered on the web. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/link-content-include-snippet-if-blocked-53b0e3108f010315.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/link-content-include-snippet-if-blocked-53b0e3108f010315.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8291f1c3529b98b44f2bac28419c164918761a4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/link-content-include-snippet-if-blocked-53b0e3108f010315.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + If LinkContentFetcher encounters a block or receives any response code other than HTTPStatus.OK, return the search + engine snippet as content, if it's available. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/llm-evaluator-serde-fix-aa5b27d2524db9c5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/llm-evaluator-serde-fix-aa5b27d2524db9c5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aabfaaa6c722903d488307b54ed4e7d895702040 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/llm-evaluator-serde-fix-aa5b27d2524db9c5.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Correctly serialize tuples and types in the init parameters of the `LLMEvaluator` component and its subclasses. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/load-tokenizer-if-not-load-by-transformers-5841cdc9ff69bcc2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/load-tokenizer-if-not-load-by-transformers-5841cdc9ff69bcc2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3904010f980cc84517cc2d9afc8b28c02f7a35d8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/load-tokenizer-if-not-load-by-transformers-5841cdc9ff69bcc2.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Allow loading Tokenizers for prompt models not natively supported by transformers by setting `trust_remote_code` to `True`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/make-urlcachechecker-generic-e159d40bbd943081.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/make-urlcachechecker-generic-e159d40bbd943081.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7395748dd5f1f4fbee897b919c1eff5bc89c9a57 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/make-urlcachechecker-generic-e159d40bbd943081.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Improve the URLCacheChecker so that it can work with any type of data in the DocumentStore, not just URL caching. + Rename the component to CacheChecker. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/make-warm-up-consistent-0247da81b155b136.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/make-warm-up-consistent-0247da81b155b136.yaml new file mode 100644 index 0000000000000000000000000000000000000000..49cc2a91a120c23e1ad9850c7d93ad0bc48e9833 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/make-warm-up-consistent-0247da81b155b136.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Make `warm_up()` usage consistent across the codebase. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/max-retries-for-AzureOpenAIGenerator-0f1a1807dd2af041.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/max-retries-for-AzureOpenAIGenerator-0f1a1807dd2af041.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a00710c33512d749f9075b135b5434e437cc2f0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/max-retries-for-AzureOpenAIGenerator-0f1a1807dd2af041.yaml @@ -0,0 +1,9 @@ +--- +enhancements: + - | + Add max_retries to AzureOpenAIGenerator. + AzureOpenAIGenerator can now be initialised by setting max_retries. + If not set, it is inferred from the `OPENAI_MAX_RETRIES` + environment variable or set to 5. + The timeout for AzureOpenAIGenerator, if not set, it is inferred + from the `OPENAI_TIMEOUT` environment variable or set to 30. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..888a53a8dbd488e6d2871fbff9186f2a88ecdc4b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/max_retries-for-AzureOpenAIChatGenerator-9e49b4c7bec5c72b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add `max_retries` and `timeout` parameters to the AzureOpenAIChatGenerator initializations. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/memory-embedding-retrieval-06f384baa04a63f7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/memory-embedding-retrieval-06f384baa04a63f7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d5b374c75a8ed7f3cf9bd333fa476bf68ae13c5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/memory-embedding-retrieval-06f384baa04a63f7.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add `embedding_retrieval` method to `MemoryDocumentStore`, + which allows to retrieve the relevant Documents, given a query embedding. + It will be called by the `MemoryEmbeddingRetriever`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/memory-embedding-retriever-dde22dedc83d1603.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/memory-embedding-retriever-dde22dedc83d1603.yaml new file mode 100644 index 0000000000000000000000000000000000000000..946dc4fda79b30996fa66099a0a014c9e63cba9d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/memory-embedding-retriever-dde22dedc83d1603.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Rename `MemoryRetriever` to `MemoryBM25Retriever` + Add `MemoryEmbeddingRetriever`, which takes as input a query embedding and + retrieves the most relevant Documents from a `MemoryDocumentStore`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/merge-hf-utils-modules-5c16e04025123568.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/merge-hf-utils-modules-5c16e04025123568.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d57cdfcd70fd8634b473d204c96ccb03b07178d0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/merge-hf-utils-modules-5c16e04025123568.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Code from different "hf_utils.py" modules spread across different packages was + merged into `haystack.utils.hf`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/metadata_enhancement_for_SQuAD_files-2247c72f07760465.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/metadata_enhancement_for_SQuAD_files-2247c72f07760465.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed90d46a25f8a8460d599cf7ccce902a5e4571c8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/metadata_enhancement_for_SQuAD_files-2247c72f07760465.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Make it possible to load additional fields from the SQUAD format file into the meta field of the Labels diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/metafieldranker_sort-order_refactor-2000d89dc40dc15a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/metafieldranker_sort-order_refactor-2000d89dc40dc15a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..18a792c2323414a40201ee9bebdfddaf1f5c1876 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/metafieldranker_sort-order_refactor-2000d89dc40dc15a.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Prevent the `MetaFieldRanker` from throwing an error if one or more of the documents doesn't contain the specific meta data field. Now those documents will be ignored for ranking purposes and placed at the end of the ranked list so we don't completely throw them away. + Adding a sort_order that can have values of descending or ascending. + Added more runtime parameters. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/metaranker-missing-meta-options-1a969008d632a523.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/metaranker-missing-meta-options-1a969008d632a523.yaml new file mode 100644 index 0000000000000000000000000000000000000000..46cb0c82abb3f717118fbc09eb7125772894c57b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/metaranker-missing-meta-options-1a969008d632a523.yaml @@ -0,0 +1,7 @@ +--- +features: + - | + Add a new `missing_meta` param to `MetaFieldRanker`, which determines what to do with + documents that lack the ranked meta field. Supported values are `"bottom"` (which + puts documents with missing meta at the bottom of the sorted list), `"top"` (which puts them + at the top), and `"drop"` (which removes them from the results entirely). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/migrate-gpt-generator-for-chat-generator-b1edb394f3d6c9ef.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/migrate-gpt-generator-for-chat-generator-b1edb394f3d6c9ef.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e781c8302d3cc7997b8b1cb698eccedb193f553 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/migrate-gpt-generator-for-chat-generator-b1edb394f3d6c9ef.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Adds GPTChatGenerator, a chat-based OpenAI LLM component, ChatMessage(s) are used for input and output diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml new file mode 100644 index 0000000000000000000000000000000000000000..98e61e5f4986279c989ffb07c892f554948c35f8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/migrate-remote-whisper-transcriber-to-openai-sdk-980ae6f54ddfd7df.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Migrate RemoteWhisperTranscriber to OpenAI SDK. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/move-classifiers-943d9d52b4bfc49f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/move-classifiers-943d9d52b4bfc49f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae1e2b1ca158270c7dca84295ee399cec1a84a59 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/move-classifiers-943d9d52b4bfc49f.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Move Text Language Classifier and Document Language Classifier to the + classifiers package. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/move-documentjoiner-to-joiners-7fe188d18d65ffcd.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/move-documentjoiner-to-joiners-7fe188d18d65ffcd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59948c915fb5d71eda128e03e0d75137cc39321b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/move-documentjoiner-to-joiners-7fe188d18d65ffcd.yaml @@ -0,0 +1,10 @@ +--- +upgrade: + - | + Change any occurrence of: + from haystack.components.routers.document_joiner import DocumentJoiner + to: + from haystack.components.joiners.document_joiner import DocumentJoiner +enhancements: + - | + Create a new package called `joiners` and move `DocumentJoiner` there for clarity. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/multiplexer-a7b1259bd20c144c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/multiplexer-a7b1259bd20c144c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ef1fbaa4246b3c51bf125ff32e4f6352c8b4ffa --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/multiplexer-a7b1259bd20c144c.yaml @@ -0,0 +1,3 @@ +features: + - | + Add `Multiplexer`. For an example of its usage, see https://github.com/deepset-ai/haystack/pull/6420. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/named-entity-extractor-component-8fd647ee748892ca.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/named-entity-extractor-component-8fd647ee748892ca.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d9adfead0088bc7c922b3db37eda34306323ad5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/named-entity-extractor-component-8fd647ee748892ca.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added a new extractor component, namely NamedEntityExtractor. This component accepts a list of Documents as its input - the raw text in the documents are annotated by the extractor and the annotations are stored in the document's meta dictionary (under the key named_entities). + + The component is designed to support multiple NER backends, and the current implementations support two at the moment: Hugging Face and spaCy. These two backends implement support for any HF/spaCy model that supports token classification/NER respectively. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/named-entity-extractor-serde-improvements-28b594be5a38f175.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/named-entity-extractor-serde-improvements-28b594be5a38f175.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af37a9c369117bc034727995f2772d6b131f66f9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/named-entity-extractor-serde-improvements-28b594be5a38f175.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Fixed (de)serialization of NamedEntityExtractor. Includes updated tests verifying these fixes when NamedEntityExtractor is used in pipelines. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/new-document-f7072e3f6d93e10f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/new-document-f7072e3f6d93e10f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..66774e25f16e424643af6819556c09f65f118c72 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/new-document-f7072e3f6d93e10f.yaml @@ -0,0 +1,3 @@ +preview: + - Adds proposal for an extended Document class in Haystack 2.0. + - Adds the implementation of said class. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/openai-document-embedder-d2f59ba1f21babcb.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/openai-document-embedder-d2f59ba1f21babcb.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaf44199c6d9a21685f8bb43304cfc9de989d3ea --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/openai-document-embedder-d2f59ba1f21babcb.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add OpenAI Document Embedder. + It computes embeddings of Documents using OpenAI models. + The embedding of each Document is stored in the `embedding` field of the Document. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/openai-text-embedder-8f06cf0bf29e6752.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/openai-text-embedder-8f06cf0bf29e6752.yaml new file mode 100644 index 0000000000000000000000000000000000000000..35ade4a2b8b37e9ac592affdb327ed31edae212e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/openai-text-embedder-8f06cf0bf29e6752.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add OpenAI Text Embedder. + It is a component that uses OpenAI models to embed strings into vectors. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/optimize-pinecone-document-store.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/optimize-pinecone-document-store.yaml new file mode 100644 index 0000000000000000000000000000000000000000..664e789a9b86c12b7d872724a36ffd43797f4603 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/optimize-pinecone-document-store.yaml @@ -0,0 +1,11 @@ +--- +enhancements: + - | + Optimize particular methods from PineconeDocumentStore (delete_documents and _get_vector_count) +upgrade: + - | + This update enables all Pinecone index types to be used, including Starter. + Previously, Pinecone Starter index type couldn't be used as document store. Due to limitations of this index type + (https://docs.pinecone.io/docs/starter-environment), in current implementation fetching documents is limited to + Pinecone query vector limit (10000 vectors). Accordingly, if the number of documents in the index is above this limit, + some of PineconeDocumentStore functions will be limited. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pass-id-to-doc-init-c6b44d30978f2d9f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pass-id-to-doc-init-c6b44d30978f2d9f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8318be9f8b2952a057fe09a5c06d7d795fce413 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pass-id-to-doc-init-c6b44d30978f2d9f.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Revert #5826 and optionally take the `id` in the Document + class constructor. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pin-numpy-2304f88504d5041a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pin-numpy-2304f88504d5041a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00a876e0906e4a263ed653e74fbc3866d2b7ba23 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pin-numpy-2304f88504d5041a.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Pin numpy<2 to avoid breaking changes that cause several core integrations to fail. + Pin tenacity too (8.4.0 is broken). diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-hierarchy-b980efcf8ac6b122.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-hierarchy-b980efcf8ac6b122.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b0fd4a2e133b52b9733f3c6fbeef9775bb5c3b9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-hierarchy-b980efcf8ac6b122.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Create a class hierarchy for pipeline classes, and move the run logic into the child class. + Preparation work for introducing multiple run stratgegies. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-intermediate-outputs-7cb8e71f79532ec1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-intermediate-outputs-7cb8e71f79532ec1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..38a0a9ab8fba7891f016ec7425d8e6ebef0b2a39 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-intermediate-outputs-7cb8e71f79532ec1.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + `pipeline.run` accepts a set of component names whose intermediate outputs are returned in the final + pipeline output dictionary. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-io-connected-sockets-db862d045944f788.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-io-connected-sockets-db862d045944f788.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ccfa63324b753df820149eabfa83445c5ddbdcb --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-io-connected-sockets-db862d045944f788.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + `Pipeline.inputs` and `Pipeline.outputs` can optionally include components input/output sockets that are connected. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-run-fix-extra-outputs-a6c750a91faaa8fd.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-run-fix-extra-outputs-a6c750a91faaa8fd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..00d23f64ef55171956b2d2e9646400a0fbe73d28 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pipeline-run-fix-extra-outputs-a6c750a91faaa8fd.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + The `include_outputs_from` parameter in `Pipeline.run` correctly returns outputs of components with multiple outputs. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pptx-file-converter-3e494d2747637eb2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pptx-file-converter-3e494d2747637eb2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6090da6d44e77e21263283974e29eaee2fe1a2fb --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pptx-file-converter-3e494d2747637eb2.yaml @@ -0,0 +1,4 @@ +--- + features: + - | + Add PptxConverter: a node to convert pptx files to Haystack Documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/preprocessor-2-0-9828d930562fa3f5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/preprocessor-2-0-9828d930562fa3f5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb58645d6d6fc0921a36451d1e31bae7365eda9a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/preprocessor-2-0-9828d930562fa3f5.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add the `TextDocumentSplitter` component for Haystack 2.0 that splits a Document with long text into multiple Documents with shorter texts. Thereby the texts match the maximum length that the language models in Embedders or other components can process. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/preview-extra-6dfdca55d17cbc7f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/preview-extra-6dfdca55d17cbc7f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..223e2cbef37c807f1d4f24d2f005c1d6475a5dc8 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/preview-extra-6dfdca55d17cbc7f.yaml @@ -0,0 +1,4 @@ +preview: + - | + Create a dedicated dependency list for the preview package, `farm-haystack[preview]`. + Using `haystack-ai` is still the recommended way to test Haystack 2.0. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/prompt-builder-d22954ef9c4a2a7b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/prompt-builder-d22954ef9c4a2a7b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e9561c44e876dc88da6eb08cdff2c431224cb51 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/prompt-builder-d22954ef9c4a2a7b.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Add PromptBuilder component to render prompts from template strings diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pypdf-page-breaks-b6842d93f4c69185.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pypdf-page-breaks-b6842d93f4c69185.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b57856dbbf462a5f75b6a7cc3cbb1e5e018ecad7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pypdf-page-breaks-b6842d93f4c69185.yaml @@ -0,0 +1,7 @@ +--- +upgrade: + - | + Upgraded the default converter in PyPDFToDocument to insert page breaks "\f" + between each extracted page. + This allows for downstream components and applications to better be able to + keep track of the original PDF page a portion of text comes from. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/pypdf-rm-deprecated-params-6c4c51489305bb85.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/pypdf-rm-deprecated-params-6c4c51489305bb85.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dcd6978e8edc690bc698849d04d4eb6b9872d2ef --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/pypdf-rm-deprecated-params-6c4c51489305bb85.yaml @@ -0,0 +1,10 @@ +--- +upgrade: + - | + The deprecated `converter_name` parameter has been removed from `PyPDFToDocument`. + + To specify a custom converter for `PyPDFToDocument`, use the `converter` initialization parameter and + pass an instance of a class that implements the `PyPDFConverter` protocol. + + The `PyPDFConverter` protocol defines the methods `convert`, `to_dict` and `from_dict`. + A default implementation of `PyPDFConverter` is provided in the `DefaultConverter` class. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rag-e2e-test-rename-3e2c7265dbb6ba9e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rag-e2e-test-rename-3e2c7265dbb6ba9e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b741ae61dee5af056316be29cee24ada29d4841 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rag-e2e-test-rename-3e2c7265dbb6ba9e.yaml @@ -0,0 +1,3 @@ +--- +fixes: + - Fix `pytest` breaking in VSCode due to a name collision in the RAG pipeline tests. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rag_pipeline-4e9dfc82a4402935.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rag_pipeline-4e9dfc82a4402935.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa9049a2e2d6def65d9db122db31ee150f1023cc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rag_pipeline-4e9dfc82a4402935.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add a `build_rag_pipeline` utility function diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/ranker-prefix-bfaf09cd7da0852d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/ranker-prefix-bfaf09cd7da0852d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9431fda1bbad3f58e0f68532bc18d5195a392c40 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/ranker-prefix-bfaf09cd7da0852d.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add query and document prefix options for the TransformerSimilarityRanker diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/reader-crash-no-docs-53085ce48baaae81.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/reader-crash-no-docs-53085ce48baaae81.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf0cd02a89c21040bd4da7ce7b47162cebf03480 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/reader-crash-no-docs-53085ce48baaae81.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + Return an empty list of answers when `ExtractiveReader` receives an empty list of documents instead of raising an exception. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/refactor-documentjoiner-992e662bee8ca219.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-documentjoiner-992e662bee8ca219.yaml new file mode 100644 index 0000000000000000000000000000000000000000..de31f8feadca42d7d08dda3b2da4fce18c6874b6 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-documentjoiner-992e662bee8ca219.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Refactor DocumentJoiner to use enum pattern for the 'join_mode' parameter instead of bare string. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/refactor-generator-public-interface-b588e9f23778e0ee.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-generator-public-interface-b588e9f23778e0ee.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0cab7eed5ad6c7fa2e23b481fe6c5bfd095046e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-generator-public-interface-b588e9f23778e0ee.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Improve the public interface of the Generators: + - make `generation_kwargs` a dictionary + - rename `pipeline_kwargs` (in `HuggingFaceLocalGenerator`) to `huggingface_pipeline_kwargs` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/refactor-openai-document-embedder.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-openai-document-embedder.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3c337c89ce23d80f452aee4908b365394a4abe7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-openai-document-embedder.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Refactor OpenAIDocumentEmbedder to enrich documents with embeddings instead of recreating them. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/refactor-pinecone-document-store.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-pinecone-document-store.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8145ac50b89b9850053733e27e9c3131009ec12 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-pinecone-document-store.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Refactor PineconeDocumentStore to use metadata instead of namespaces + for distinction between documents with embeddings, documents without + embeddings and labels diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/refactor-sentense-transformers-document-embedder-f4ed8d10aaccd08c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-sentense-transformers-document-embedder-f4ed8d10aaccd08c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..325a7f8951f0f1a998aa0457ff9901bf84168505 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-sentense-transformers-document-embedder-f4ed8d10aaccd08c.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Refactor SentenceTransformersDocumentEmbedder to enrich documents with embeddings instead of recreating them. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/refactor-web-retriever-a0604ead72b84fdc.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-web-retriever-a0604ead72b84fdc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c2eaf51200271239b3f00a8bbb3c04e90829e8ef --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/refactor-web-retriever-a0604ead72b84fdc.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Refactor and simplify WebRetriever to use LinkContentFetcher component diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remotetranscriber-input-type-aae9a255435a3507.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remotetranscriber-input-type-aae9a255435a3507.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ca8b5bcd19af8eb4c5ab18b784a7154c54b3488 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remotetranscriber-input-type-aae9a255435a3507.yaml @@ -0,0 +1,2 @@ +preview: + - Extends input types of RemoteWhisperTranscriber from List[ByteStream] to List[Union[str, Path, ByteStream]] to make possible to connect it to FileTypeRouter. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-api-key-from-serialization-2474a1539b86e233.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-api-key-from-serialization-2474a1539b86e233.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e1a879816eab75496f9e31efcad31f40cd9a3803 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-api-key-from-serialization-2474a1539b86e233.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Remove "api_key" from serialization of AzureOCRDocumentConverter and SerperDevWebSearch. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-base-test-component-ee1986a2bbbace46.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-base-test-component-ee1986a2bbbace46.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3932d0aed0ae701b38213650d7ca43ac81e29846 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-base-test-component-ee1986a2bbbace46.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Remove `BaseTestComponent` class used to test `Component`s diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-canals-mentions-eac7f95df99d39b9.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-canals-mentions-eac7f95df99d39b9.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5651352324c7fc36ecb1acb8fbfb4310a6b5fad --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-canals-mentions-eac7f95df99d39b9.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Remove all mentions of Canals by renaming some variables. + `__canals_input__` and `__canals_ouput__` have been renamed respectively to `__haystack_input__` and `__haystack_ouput__`. + `CANALS_VARIADIC_ANNOTATION` has been renamed to `HAYSTACK_VARIADIC_ANNOTATION` and it's value changed from `__canals__variadic_t` to `__haystack__variadic_t`. + Default Pipeline `debug_path` has been changed from `.canals_debug` to `.haystack_debug`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-default-from-dict-reimplementation-2db4c32153c1e7af.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-default-from-dict-reimplementation-2db4c32153c1e7af.yaml new file mode 100644 index 0000000000000000000000000000000000000000..852eaa8f0b31a0857d745a4429f363338b22bd2f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-default-from-dict-reimplementation-2db4c32153c1e7af.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Removed implementations of from_dict and to_dict from all components where they had the same effect as the default implementation from Canals: https://github.com/deepset-ai/canals/blob/main/canals/serialization.py#L12-L13 This refactoring does not change the behavior of the components. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-deprecated-pypdf-default-converter-4e06aa946c3a89f1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-deprecated-pypdf-default-converter-4e06aa946c3a89f1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f9a81250fc7d5d79d8febae02e3a6283ca62c53a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-deprecated-pypdf-default-converter-4e06aa946c3a89f1.yaml @@ -0,0 +1,25 @@ +--- +upgrade: + - | + The deprecated default converter class `haystack.components.converters.pypdf.DefaultConverter` used by `PyPDFToDocument` has been removed. + + Pipeline YAMLs from `haystack<2.7.0` that use the default converter must be updated in the following manner: + ```yaml + # Old + components: + Comp1: + init_parameters: + converter: + type: haystack.components.converters.pypdf.DefaultConverter + type: haystack.components.converters.pypdf.PyPDFToDocument + + # New + components: + Comp1: + init_parameters: + converter: null + type: haystack.components.converters.pdf.PDFToTextConverter + ``` + + Pipeline YAMLs from `haystack<2.7.0` that use custom converter classes can be upgraded by simply loading + them with `haystack==2.6.x` and saving them to YAML again. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-document-array-fe70fd2cbb269add.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-document-array-fe70fd2cbb269add.yaml new file mode 100644 index 0000000000000000000000000000000000000000..64a326e21d55e613df1cb1e87d892395aa553c08 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-document-array-fe70fd2cbb269add.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Remove `array` field from `Document` dataclass. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-document-store-aware-mixin-8eef714844ee04f2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-document-store-aware-mixin-8eef714844ee04f2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..01ca9ccce357b9f4556f4c46d693fcb242d35041 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-document-store-aware-mixin-8eef714844ee04f2.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Remove `DocumentStoreAwareMixin` as it's not necessary anymore diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-id-hash-document-93e4a589b3fd2aad.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-id-hash-document-93e4a589b3fd2aad.yaml new file mode 100644 index 0000000000000000000000000000000000000000..707b8f642a3957abbeae8fceadee2fc21aa6b5fc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-id-hash-document-93e4a589b3fd2aad.yaml @@ -0,0 +1,12 @@ +--- +preview: + - | + Remove `id_hash_keys` field from `Document` dataclass. + `id_hash_keys` has been also removed from Components that were using it: + * `DocumentCleaner` + * `TextDocumentSplitter` + * `PyPDFToDocument` + * `AzureOCRDocumentConverter` + * `HTMLToDocument` + * `TextFileToDocument` + * `TikaDocumentConverter` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-image-from-debug-c83d61db92bcbfc2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-image-from-debug-c83d61db92bcbfc2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c817bd84238967effcf9fb5ec8d1154b82c18a4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-image-from-debug-c83d61db92bcbfc2.yaml @@ -0,0 +1,5 @@ +--- +issues: + - | + Fix "TypeError: descriptor '__dict__' for 'XXX' objects doesn't apply to a 'XXX' object" when running + pipelines with `debug=True` by removing the graph image from the debug payload. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-pipeline-c02067516c387f0b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-pipeline-c02067516c387f0b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8be791c6ffda8813ba18d0d5e46b6eab74701762 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-pipeline-c02067516c387f0b.yaml @@ -0,0 +1,3 @@ +--- +preview: + - Remove Pipeline specialisation to support DocumentStores. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-query-param-MetaFieldRanker-56883ab0377b7605.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-query-param-MetaFieldRanker-56883ab0377b7605.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6ad905b4ca943554e54dddb0862c1196cb0fb0a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-query-param-MetaFieldRanker-56883ab0377b7605.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Removes the unused query parameter from the run method of MetaFieldRanker. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-sklearnqueryclassifier-a95382808d99cb58.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-sklearnqueryclassifier-a95382808d99cb58.yaml new file mode 100644 index 0000000000000000000000000000000000000000..016449275babf957ac77a3cc9507c27d4747a237 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-sklearnqueryclassifier-a95382808d99cb58.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + SklearnQueryClassifier is removed and users should switch to the more powerful TransformersQueryClassifier instead. https://github.com/deepset-ai/haystack/discussions/5447 diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/remove-template-vars-invocation-kwargs-060f186fd1250fe4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/remove-template-vars-invocation-kwargs-060f186fd1250fe4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..43dec0f76517502970587f3e927c5e85ed99c4b3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/remove-template-vars-invocation-kwargs-060f186fd1250fe4.yaml @@ -0,0 +1,11 @@ +--- +upgrade: + - | + This update impacts only those who have created custom invocation layers by subclassing PromptModelInvocationLayer. + Previously, the invoke() method in your custom layer received all prompt template parameters (like query, + documents, etc.) as keyword arguments. With this change, these parameters will no longer be passed in as keyword + arguments. If you've implemented such a custom layer, you'll need to potentially update your code to accommodate + this change. +enhancements: + - | + Remove template variables from invocation layer kwargs diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-confidence-score-3ba604b8f9bd0454.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-confidence-score-3ba604b8f9bd0454.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b449fad3c70250e9105ae35a1b2152779b69656 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-confidence-score-3ba604b8f9bd0454.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Renamed the confidence_threshold parameter of the ExtractiveReader to score_threshold as ExtractedAnswers have a score and this is what the threshold is for. + For consistency, the term confidence is not mentioned anymore in favor of score. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-file-extension-router-9125028ec2c55e98.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-file-extension-router-9125028ec2c55e98.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76f9cf840fbc8960e2751ce2b7e084b7331884c3 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-file-extension-router-9125028ec2c55e98.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Enhanced file routing capabilities with the introduction of `ByteStream` handling, and + improved clarity by renaming the router to `FileTypeRouter`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-gpt-generators-f25011d251fafd6d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-gpt-generators-f25011d251fafd6d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72f40559fe0cabe0edada881820d6484d717093b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-gpt-generators-f25011d251fafd6d.yaml @@ -0,0 +1,4 @@ +--- +deprecations: + - | + Deprecate GPTGenerator and GPTChatGenerator. Replace them with OpenAIGenerator and OpenAIChatGenerator. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-memory-doc-store-2a9960d11d2aa492.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-memory-doc-store-2a9960d11d2aa492.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5672821554dc3954f8b02360b928d8e41a4b1c51 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-memory-doc-store-2a9960d11d2aa492.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Rename `MemoryDocumentStore` to `InMemoryDocumentStore` + Rename `MemoryBM25Retriever` to `InMemoryBM25Retriever` + Rename `MemoryEmbeddingRetriever` to `InMemoryEmbeddingRetriever` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param--transcribers-71dbe7cfb86950e0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param--transcribers-71dbe7cfb86950e0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e120da5c2a60c08953d69c522a3f1cd4b90cda95 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param--transcribers-71dbe7cfb86950e0.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + Rename the transcriber parameters `model_name` and `model_name_or_path` to `model`. This change affects both + `LocalWhisperTranscriber` and `RemoteWhisperTranscriber` classes. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-embedders-7cc87a768554724d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-embedders-7cc87a768554724d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5a25873213e0d4fcb413c86c19ec4e1fb9a7f47 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-embedders-7cc87a768554724d.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename the embedder parameters `model_name` and `model_name_or_path` to `model`. This change affects all Embedder classes. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-ner-dce7536f2e7866fe.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-ner-dce7536f2e7866fe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae6e36ed0ac15cf64b7326e594f059f47c459e8e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-ner-dce7536f2e7866fe.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename `model_name_or_path` to `model` in `NamedEntityExtractor`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-rankers-be3d6163597e0a9b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-rankers-be3d6163597e0a9b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afc85b5fd9c0c2595cf818301ed272bb90b209d2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-rankers-be3d6163597e0a9b.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename `model_name_or_path` to `model` in `TransformersSimilarityRanker`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-reader-b8cbb0d638e3b8c2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-reader-b8cbb0d638e3b8c2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a5bd3eef63155987b2ce92f8266299478907957 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-model-param-reader-b8cbb0d638e3b8c2.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename parameter `model_name_or_path` to `model` in `ExtractiveReader`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-reader-input-af739955bf4f71b5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-reader-input-af739955bf4f71b5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eec29c3e1b2e24d729127d6cc28b7ee33b062e12 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-reader-input-af739955bf4f71b5.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Renamed ExtractiveReader's input from `document` to `documents` to match its type List[Document]. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename-text-document-splitter-1e9fcd292c4591dd.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename-text-document-splitter-1e9fcd292c4591dd.yaml new file mode 100644 index 0000000000000000000000000000000000000000..363da072d4915c9671a4e7375ccead8e626ed127 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename-text-document-splitter-1e9fcd292c4591dd.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + rename `TextDocumentSplitter` to `DocumentSplitter`, to allow a better + distinction between Components that operate on text and those that operate + on Documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rename_similarity_ranker-d755c2cd00449ecc.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rename_similarity_ranker-d755c2cd00449ecc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a899742830e4121d5a02e6254bf643666e2adb53 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rename_similarity_ranker-d755c2cd00449ecc.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Rename `SimilarityRanker` to `TransformersSimilarityRanker`, + as there will be more similarity rankers in the future. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/renamed-model_name-or-model_name_or_path-to-model-184490cbb66c4d7c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/renamed-model_name-or-model_name_or_path-to-model-184490cbb66c4d7c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..992bffaf81e3412de0e022dc04f722eb3cbb9791 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/renamed-model_name-or-model_name_or_path-to-model-184490cbb66c4d7c.yaml @@ -0,0 +1,3 @@ +--- +upgrade: + - Rename the generator parameters `model_name` and `model_name_or_path` to `model`. This change affects all Generator classes. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/restrict-openai-supports-method-fb126583e4beb057.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/restrict-openai-supports-method-fb126583e4beb057.yaml new file mode 100644 index 0000000000000000000000000000000000000000..88e17d0ab273e3c9c34e65c139b8e501a12ab541 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/restrict-openai-supports-method-fb126583e4beb057.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Restricts the criteria for identifying an OpenAI model in the PromptNode and in the EmbeddingRetriever. + Previously, the criteria were quite loose, leading to more false positives. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f9b023339fb2693d278df353f9f9d9af77b3f36 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/retrievers-filter-policy-enhancement-af52d026c346e9c0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Introduced a 'filter_policy' init parameter for both InMemoryBM25Retriever and InMemoryEmbeddingRetriever, allowing users to define how runtime filters should be applied with options to either 'replace' the initial filters or 'merge' them, providing greater flexibility in filtering query results. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/review-all-extras-42d5a3a3d61f5393.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/review-all-extras-42d5a3a3d61f5393.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80a9fcddc1d1cb6066ca16fb78237b50d97be9d7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/review-all-extras-42d5a3a3d61f5393.yaml @@ -0,0 +1,3 @@ +upgrade: + - | + Removes the `audio`, `ray`, `onnx` and `beir` extras from the extra group `all`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rework-document-writer-4958db2024070f6f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rework-document-writer-4958db2024070f6f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce10a4b9fb3c57b624f78fd357d3752eea91b701 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rework-document-writer-4958db2024070f6f.yaml @@ -0,0 +1,4 @@ +--- +features: + - Rework `DocumentWriter` to remove `DocumentStoreAwareMixin`. + Now we require a generic `DocumentStore` when initialisating the writer. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rework-filters-1bb103d196a1912b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rework-filters-1bb103d196a1912b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..57509ec3342fc34ee9c8989eb8d02896921ee2ce --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rework-filters-1bb103d196a1912b.yaml @@ -0,0 +1,87 @@ +--- +prelude: > + With proposal [#6001](https://github.com/deepset-ai/haystack/pull/6001) we introduced a better specification to declare filters in Haystack 2.x. + The new syntax is a bit more verbose but less confusing and ambiguous as there are no implicit operators. + This will simplify conversion from this common syntax to a Document Store specific filtering logic, so it will ease + development of new Document Store. + Since everything must be declared explicitly it will also make it easier for user to understand the filters just + by reading them. + + The full specification is as follow. + + --- + + Filters top level must be a dictionary. + + There are two types of dictionaries: + + - Comparison + - Logic + + Top level can be either be a Comparison or Logic dictionary. + + Comparison dictionaries must contain the keys: + + - `field` + - `operator` + - `value` + + Logic dictionaries must contain the keys: + + - `operator` + - `conditions` + + `conditions` key must be a list of dictionaries, either Comparison or Logic. + + `operator` values in Comparison dictionaries must be: + + - `==` + - `!=` + - `>` + - `>=` + - `<` + - `<=` + - `in` + - `not in` + + `operator` values in Logic dictionaries must be: + + - `NOT` + - `OR` + - `AND` + + --- + + A simple filter: + + ```python + filters = {"field": "meta.type", "operator": "==", "value": "article"} + ``` + + A more complex filter: + ```python + filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.date", "operator": ">=", "value": 1420066800}, + {"field": "meta.date", "operator": "<", "value": 1609455600}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + { + "operator": "OR", + "conditions": [ + {"field": "meta.genre", "operator": "in", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + }, + ], + } + ``` + + --- + + To avoid causing too much disruption for users using legacy filters we'll keep supporting them for the time being. + We also provide a utility `convert` function for developers implementing their Document Store to do the same. +preview: + - | + Refactored `InMemoryDocumentStore` and `MetadataRouter` filtering logic to support new filters declaration. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rework-memory-retriever-73c5d3221bd96759.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rework-memory-retriever-73c5d3221bd96759.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0824e17a7c2f1b11703706aa850e97d6d953869f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rework-memory-retriever-73c5d3221bd96759.yaml @@ -0,0 +1,4 @@ +--- +features: + - Rework `MemoryRetriever` to remove `DocumentStoreAwareMixin`. + Now we require a `MemoryDocumentStore` when initialisating the retriever. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rm-deprecated-tei-embedders-cfcd660c906ba69e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rm-deprecated-tei-embedders-cfcd660c906ba69e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7cdc857950e91e388f430bbbc78c24fbd021fbf0 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rm-deprecated-tei-embedders-cfcd660c906ba69e.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + Deprecated `HuggingFaceTEITextEmbedder` and `HuggingFaceTEIDocumentEmbedder` have been removed. + Use `HuggingFaceAPITextEmbedder` and `HuggingFaceAPIDocumentEmbedder` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rm-deprecated-tgi-generators-6086bbb36417c0d8.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rm-deprecated-tgi-generators-6086bbb36417c0d8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a635630e67e32d95c4b540551668d9bf4ae306a4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rm-deprecated-tgi-generators-6086bbb36417c0d8.yaml @@ -0,0 +1,5 @@ +--- +upgrade: + - | + Deprecated `HuggingFaceTGIGenerator` and `HuggingFaceTGIChatGenerator` have been removed. + Use `HuggingFaceAPIGenerator` and `HuggingFaceAPIChatGenerator` instead. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/rm-docstore-decorator-d8d2ebfdf1d9702e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/rm-docstore-decorator-d8d2ebfdf1d9702e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b35d3b376d0173105c9f79c852ef4408e3ccd3e7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/rm-docstore-decorator-d8d2ebfdf1d9702e.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Improve the deserialization logic for components that use a Document Store. + Remove the @document_store decorator and the registry of Document Stores. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/route-meta-to-converters-ed85acc43b5aa96a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/route-meta-to-converters-ed85acc43b5aa96a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..73f67d99b4ac0d5ca3aa654bb6f541604abd08b2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/route-meta-to-converters-ed85acc43b5aa96a.yaml @@ -0,0 +1,3 @@ +--- +enhancements: + - Add example script about how to use Multiplexer to route meta to file converters. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/sas-evaluator-6970865787557e83.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/sas-evaluator-6970865787557e83.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d7aa24c734b8596f27b2fab7cb0d8e8e2f113a4f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/sas-evaluator-6970865787557e83.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add SASEvaluator, it can be used to calculate Semantic Answer Similarity of generated answers from an LLM diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/scale-score-false-h2-3c8e4e7e543e8cce.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/scale-score-false-h2-3c8e4e7e543e8cce.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b79085958ddc79dec10248f02968d664ebd3a8e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/scale-score-false-h2-3c8e4e7e543e8cce.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Change the default value of `scale_score` to False for Retrievers. + Users can still explicitly set `scale_score` to True to get relevance + scores in the range [0, 1]. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/scale-score-similarity-ranker-2deacff999265b9e.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/scale-score-similarity-ranker-2deacff999265b9e.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8b7f26d2922193d00a5ec664ff2d95fa933d556a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/scale-score-similarity-ranker-2deacff999265b9e.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Adds scale_score, which allows users to toggle if they would like their document scores to be raw logits or scaled between 0 and 1 (using the sigmoid function). This is a feature that already existed in Haystack v1 that is being moved over. + Adds calibration_factor. This follows the example from the ExtractiveReader which allows the user to better control the spread of scores when scaling the score using sigmoid. + Adds score_threshold. Also copied from the ExtractiveReader. This optionally allows users to set a score threshold where only documents with a score above this threshold are returned. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/self-correcting-rag-2e77ac94b89dfe5b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/self-correcting-rag-2e77ac94b89dfe5b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0d3c1f92b4c12a264fd43567447611f6e1e288c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/self-correcting-rag-2e77ac94b89dfe5b.yaml @@ -0,0 +1,2 @@ +enhancements: + - Add RAG self correction loop example diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/sentence-transformers-doc-embedder-prefix-suffix-442412c553135406.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/sentence-transformers-doc-embedder-prefix-suffix-442412c553135406.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5f88f83f1ce83c7780e088cea2f51b006fb5f61 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/sentence-transformers-doc-embedder-prefix-suffix-442412c553135406.yaml @@ -0,0 +1,7 @@ +--- +preview: + - | + Add `prefix` and `suffix` attributes to `SentenceTransformersDocumentEmbedder`. + They can be used to add a prefix and suffix to the Document text before + embedding it. This is necessary to take full advantage of modern embedding + models, such as E5. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/sentence-transformers-embedding-backend-69bd9410ede08c8f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/sentence-transformers-embedding-backend-69bd9410ede08c8f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b5e647fa7ea29a7d1614a491345eddc647be581d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/sentence-transformers-embedding-backend-69bd9410ede08c8f.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Add Sentence Transformers Embedding Backend. + It will be used by Embedder components and is responsible for computing embeddings. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/separate-classifiers-from-routers-96a37c76820385d6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/separate-classifiers-from-routers-96a37c76820385d6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e785ff96004c2fef0e8bfe0a307bdbb1710e9058 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/separate-classifiers-from-routers-96a37c76820385d6.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Remove routing functionality from DocumentLanguageClassifier and rename TextLanguageClassifer to TextLanguageRouter. + Classifiers in Haystack 2.x change metadata values but do not route inputs to multiple outputs. The latter is reserved for routers. + Use DocumentLanguageClassifier in combination with MetaDataRouter to classify and route documents in indexing pipelines. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/serialization-tuple-support-ffe176417e7099f5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/serialization-tuple-support-ffe176417e7099f5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3053ee6f2c2827c3523e6ff8bbe759c0301cb32 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/serialization-tuple-support-ffe176417e7099f5.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Pipeline serialization to YAML now supports tuples as field values. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/serialize-torch-dtype-57c6c94f6114fc00.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/serialize-torch-dtype-57c6c94f6114fc00.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba54d199dcfae77f947fe8c990a744ece8f85a82 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/serialize-torch-dtype-57c6c94f6114fc00.yaml @@ -0,0 +1,6 @@ +--- +fixes: + - | + Correctly handle the serialization and deserialization of torch.dtype. + This concerns the following components: + ExtractiveReader, HuggingFaceLocalGenerator, and TransformersSimilarityRanker. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/serperdev-more-robust-229ba25c8fc9306d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/serperdev-more-robust-229ba25c8fc9306d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9717400095a1f328497cd656594fb75fb0f5686a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/serperdev-more-robust-229ba25c8fc9306d.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Make the `SerperDevWebSearch` more robust when `snippet` is not present in the request response. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/set-input-type-328589ee51ffa21b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/set-input-type-328589ee51ffa21b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dfb95d711948edc70064d179e8d6e3f658084e08 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/set-input-type-328589ee51ffa21b.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Add `component.set_input_type()` function to set a Component input name, type and default value. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/ship-boilerpy3-0bffbd7955c89dd4.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/ship-boilerpy3-0bffbd7955c89dd4.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9349165ca6eeaa5d421945b67cc09384b1ff56f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/ship-boilerpy3-0bffbd7955c89dd4.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Include 'boilerpy3' in the 'haystack-ai' dependencies. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/simplify-textfiletodocument-c9d2fb7ed2c848ed.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/simplify-textfiletodocument-c9d2fb7ed2c848ed.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a533f6e8ae1e12300daeb30ba43bb3b676c5c6bc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/simplify-textfiletodocument-c9d2fb7ed2c848ed.yaml @@ -0,0 +1,3 @@ +preview: + - Remove most parameters from TextFileToDocument to make it match all other converters. + - Add support for ByteStreams diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/simplify-whisper-installation-1e347e2527cbf913.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/simplify-whisper-installation-1e347e2527cbf913.yaml new file mode 100644 index 0000000000000000000000000000000000000000..93b7ecb772231f90d1eb33c6bd11ece6a121e264 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/simplify-whisper-installation-1e347e2527cbf913.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgraded openai-whisper to version 20231106 and simplified installation through re-introduced audio extra. + The latest openai-whisper version unpins its tiktoken dependency, which resolved a version conflict with Haystack's dependencies. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-azureconverter-ce1cc196a9b161f3.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-azureconverter-ce1cc196a9b161f3.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccc96750020f20df2a685aaa2e3f6ca2907146a2 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-azureconverter-ce1cc196a9b161f3.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Adds support for single metadata dictionary input in `AzureOCRDocumentConverter`. In this way, additional metadata can be added to all files processed by this component even when the length of the list of sources is unknown. + diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-htm2document-199ea44a4ae5c02b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-htm2document-199ea44a4ae5c02b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c4067ec60b27e27d684e12d4b2146aa38fca311a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-htm2document-199ea44a4ae5c02b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Adds support for single metadata dictionary input in `HTMLToDocument`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-markdown2document-082bae7b20bd605d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-markdown2document-082bae7b20bd605d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e692cce4297ddd792dcc50d69e2aff5f4c624ffd --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-markdown2document-082bae7b20bd605d.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds support for single metadata dictionary input in `MarkdownToDocument``. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-pypdf2document-99e15f1cb9f65892.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-pypdf2document-99e15f1cb9f65892.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee7397321b7220b6158db3e5d428d2a8b3fa44fa --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/single-meta-in-pypdf2document-99e15f1cb9f65892.yaml @@ -0,0 +1,5 @@ + +--- +enhancements: + - | + Adds support for single metadata dictionary input in `PyPDFToDocument`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/single-metadata-txt-converter-a02bf90c60262701.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/single-metadata-txt-converter-a02bf90c60262701.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68c90c59cbd3f2837cb657f931f95ca5b4beca1b --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/single-metadata-txt-converter-a02bf90c60262701.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + Adds support for single metadata dictionary input in `TextFileToDocument``. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/sparse-emb-eq-773ef04ae3ed83ea.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/sparse-emb-eq-773ef04ae3ed83ea.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4074680bcf45b29116be22306effdee12d2cf84d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/sparse-emb-eq-773ef04ae3ed83ea.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add an `__eq__` method to `SparseEmbedding` class to compare two `SparseEmbedding` objects. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/sparse-embedding-dataclass-d75ae1ee6d75e646.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/sparse-embedding-dataclass-d75ae1ee6d75e646.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd20c43899e36f8bd4f9f73c595888f5d5807bee --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/sparse-embedding-dataclass-d75ae1ee6d75e646.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Make SparseEmbedding a dataclass, this makes it easier to use the class with Pydantic diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/speedup-import-b542f7a8323ef376.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/speedup-import-b542f7a8323ef376.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80ddc299a86b87834f067a7f35b582695f70dea6 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/speedup-import-b542f7a8323ef376.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Speed up import of Document dataclass. + Importing Document was slowed down cause we were importing the whole `pandas` and `numpy` packages. + This has now been changed to import only the necessary classes and functions. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/split-by-token-b9a4f954d4077ecc.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/split-by-token-b9a4f954d4077ecc.yaml new file mode 100644 index 0000000000000000000000000000000000000000..643793b7bc5d9b0fcf3e2d9d2d1045603ff1ff86 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/split-by-token-b9a4f954d4077ecc.yaml @@ -0,0 +1,2 @@ +features: + - Add `split_length` by token in PreProcessor diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/split-dynamic-prompt-builder-798e5a74caf7a2e8.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/split-dynamic-prompt-builder-798e5a74caf7a2e8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaf57ba3fce7512891143a13c34d3159532b4149 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/split-dynamic-prompt-builder-798e5a74caf7a2e8.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Split DynamicPromptBuilder into DynamicPromptBuilder and DynamicChatPromptBuilder diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/stop-using-canals-bfc26ad25e472652.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/stop-using-canals-bfc26ad25e472652.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7f4cd8fbf33f3c16b32bdb9733ccfe81f34f439 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/stop-using-canals-bfc26ad25e472652.yaml @@ -0,0 +1,7 @@ +--- +upgrade: + - | + Any import from `canals` should be rewritten to import from `haystack.core` +enhancements: + - | + Use the code formerly in `canals` from the `haystack.core` package across the whole codebase. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/stopwords-hf-generator-dab4b5827bae1492.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/stopwords-hf-generator-dab4b5827bae1492.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5ee9e9a0f87d9ab90765d76aab1765ace68749fc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/stopwords-hf-generator-dab4b5827bae1492.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Allow specifying stopwords to stop text generation for `HuggingFaceLocalGenerator`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/store-factory-91e7da46aeb7ff21.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/store-factory-91e7da46aeb7ff21.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7fc978a83f59df646a45d035ce47e852e4ad245c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/store-factory-91e7da46aeb7ff21.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add utility function `store_class` factory to create `Store`s for testing purposes. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/stores-serialisation-a09398d158b01ae6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/stores-serialisation-a09398d158b01ae6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2dc9f1e000b052263d071befc73faa76ab16720c --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/stores-serialisation-a09398d158b01ae6.yaml @@ -0,0 +1,4 @@ +--- +preview: + - Add `from_dict` and `to_dict` methods to `Store` `Protocol` + - Add default `from_dict` and `to_dict` implementations to classes decorated with `@store` diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/structlog-contextvars-c13bb3c59a6a92c7.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/structlog-contextvars-c13bb3c59a6a92c7.yaml new file mode 100644 index 0000000000000000000000000000000000000000..053d1f3cd78368602f1855a8a8283b4d3bd5b1ab --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/structlog-contextvars-c13bb3c59a6a92c7.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Add support for [structlog context variables](https://www.structlog.org/en/24.2.0/contextvars.html) to structured logging. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/support-azure-3.5-gpt-16k-model-ece0cfe03260748c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/support-azure-3.5-gpt-16k-model-ece0cfe03260748c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9fc499418cb96f2a6a60db660355fe9b58c213f9 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/support-azure-3.5-gpt-16k-model-ece0cfe03260748c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + gpt-35-turbo-16k model from Azure can integrate correctly diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/support-dates-in-filters-2.0-15785cc3776d2210.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/support-dates-in-filters-2.0-15785cc3776d2210.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99c84a4c13838e4564ef3f079bc26024ba796de4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/support-dates-in-filters-2.0-15785cc3776d2210.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add support for dates in filters. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/support-gpt-3.5-turbo-instruct-79236835a8be143c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/support-gpt-3.5-turbo-instruct-79236835a8be143c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48dede7f00e088e62cb7502996633531fb49c714 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/support-gpt-3.5-turbo-instruct-79236835a8be143c.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Support OpenAI's new `gpt-3.5-turbo-instruct` model diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/support-gpt-4-1106-preview-ce8e551b11d96471.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/support-gpt-4-1106-preview-ce8e551b11d96471.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8180ab3a52615f657746e5d6c63624117e2ef589 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/support-gpt-4-1106-preview-ce8e551b11d96471.yaml @@ -0,0 +1,2 @@ +enhancements: + - Add new token limit for gpt-4-1106-preview model diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/switch-bm25-dep-9b9d1c596f5ff4d0.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/switch-bm25-dep-9b9d1c596f5ff4d0.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3abeffa5a3081732fb3a44f76bc6b4f7720849a4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/switch-bm25-dep-9b9d1c596f5ff4d0.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Depend on our own rank_bm25 fork. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/telemetry-2.0-92c34c81563ff0e1.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/telemetry-2.0-92c34c81563ff0e1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..31fddfdf42008a7f71e699999cf619ceb586935d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/telemetry-2.0-92c34c81563ff0e1.yaml @@ -0,0 +1,3 @@ + +preview: + - Add basic telemetry to Haystack 2.0 pipelines diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/text-cleaner-eee0eecbdec21427.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/text-cleaner-eee0eecbdec21427.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e28b27ca5423cf0227e92db2f157efe16092ca7 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/text-cleaner-eee0eecbdec21427.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Add `TextCleaner` Component to clean list of strings. It can remove substrings matching a list of regular expressions, + convert text to lowercase, remove punctuation, and remove numbers. + This is mostly useful to clean generator predictions before evaluation. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/text-document-cleaner-8afce831a2ac31ae.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/text-document-cleaner-8afce831a2ac31ae.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cde155a938da6bde15f1413abb14a4391d8ea564 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/text-document-cleaner-8afce831a2ac31ae.yaml @@ -0,0 +1,5 @@ +--- +preview: + - | + Added DocumentCleaner, which removes extra whitespace, empty lines, headers, etc. from Documents containing text. + Useful as a preprocessing step before splitting into shorter text documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/text-language-classifier-0d1e1a97f1bb8ac6.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/text-language-classifier-0d1e1a97f1bb8ac6.yaml new file mode 100644 index 0000000000000000000000000000000000000000..84430525e21b40ceeffcbd96fd8597a4ca3e4506 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/text-language-classifier-0d1e1a97f1bb8ac6.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add TextLanguageClassifier component so that an input string, for example a query, can be routed to different components based on the detected language. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/textfile-to-document-v2-341987623765ec95.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/textfile-to-document-v2-341987623765ec95.yaml new file mode 100644 index 0000000000000000000000000000000000000000..41fd5150412ba607c38114e4ffd7e3abd417025f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/textfile-to-document-v2-341987623765ec95.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Add new TextFileToDocument component to Haystack v2 preview so that text files can be converted to Haystack Documents. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/tgi-chat-missing-decorator-799b2a133ee4708c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/tgi-chat-missing-decorator-799b2a133ee4708c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5437a83b5d934eea043353733f570a629bf9fd45 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/tgi-chat-missing-decorator-799b2a133ee4708c.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Add the `@component` decorator to `HuggingFaceTGIChatGenerator`. + The lack of this decorator made it impossible to use the `HuggingFaceTGIChatGenerator` in a pipeline. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/tracing-with-concurrency-5daadfde0a36f94a.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/tracing-with-concurrency-5daadfde0a36f94a.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d319c98091ea198b7cb42be2ef02ef84cbcd94c4 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/tracing-with-concurrency-5daadfde0a36f94a.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Each tracing span of a component run is now attached with the pipeline run span object. This allows users to trace + the execution of multiple pipeline runs concurrently. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/trafilatura-html-conversion-e9b9044d31fec794.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/trafilatura-html-conversion-e9b9044d31fec794.yaml new file mode 100644 index 0000000000000000000000000000000000000000..903e0d15cd123be7a14430fe0a3cc6beab9aec15 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/trafilatura-html-conversion-e9b9044d31fec794.yaml @@ -0,0 +1,9 @@ +--- +enhancements: + - | + `HTMLToDocument`: change the HTML conversion backend from `boilerpy3` to `trafilatura`, + which is more robust and better maintained. +deprecations: + - | + The following parameters of `HTMLToDocument` are ignored and will be removed in Haystack 2.4.0: + `extractor_type` and `try_others`. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/transformers-4-35-2-1739bbaa8c6f0111.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/transformers-4-35-2-1739bbaa8c6f0111.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b3c9b169986f71d5d23781135daa84107321110a --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/transformers-4-35-2-1739bbaa8c6f0111.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Upgrade Transformers to the latest version 4.35.2 + This version adds support for DistilWhisper, Fuyu, Kosmos-2, SeamlessM4T, Owl-v2. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/transformers-similarity-embed-meta-7f2b15988549f805.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/transformers-similarity-embed-meta-7f2b15988549f805.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4630bc2bdf73b4fed4a8caa50f5979eceea415c5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/transformers-similarity-embed-meta-7f2b15988549f805.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add meta_fields_to_embed following the implementation in SentenceTransformersDocumentEmbedder to be able to + embed meta fields along with the content of the document. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/transformers-similarity-update-53a840b31bac4c3d.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/transformers-similarity-update-53a840b31bac4c3d.yaml new file mode 100644 index 0000000000000000000000000000000000000000..92d61c48855119ddab959f49f83a51566d9b6072 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/transformers-similarity-update-53a840b31bac4c3d.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Add new variable model_kwargs to the TransformersSimilarityRanker so we can pass different loading options supported by + HuggingFace. Add device availability checking if the user passes in None to the device init param. Ranking goes, GPU, MPS, CPU. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/update-crawler-selenium-4.11-30fec9f6e345834f.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/update-crawler-selenium-4.11-30fec9f6e345834f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5db8222cc0f1f175a3d394117fea14b7566756de --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/update-crawler-selenium-4.11-30fec9f6e345834f.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Make the Crawler work properly with Selenium>=4.11.0. + Simplify the Crawler, as the new version of Selenium automatically finds or installs the necessary drivers. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/update-deepset-cloud-sdk-save-pipeline-config-ff820838846f5f38.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/update-deepset-cloud-sdk-save-pipeline-config-ff820838846f5f38.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5ca3ac5e473480ecf0687d85e8c9b0999b40384 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/update-deepset-cloud-sdk-save-pipeline-config-ff820838846f5f38.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Update the deepset Cloud SDK to the new endpoint format for new saving pipeline configs. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/update-openai-chat-tools-3d3636b2ffea9736.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/update-openai-chat-tools-3d3636b2ffea9736.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b30ee675e0207a5ade3701489c3de8dc34d8004 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/update-openai-chat-tools-3d3636b2ffea9736.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Update OpenAIChatGenerator to handle both tools and functions calling. OpenAIChatGenerator now supports both tools + and functions `generation_kwargs` parameters that enable function/tools invocation. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/update-sentence-transformers-import-error-msg-895b8ed2355ae2fe.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/update-sentence-transformers-import-error-msg-895b8ed2355ae2fe.yaml new file mode 100644 index 0000000000000000000000000000000000000000..89932da9a4fbd4033fbf900a73a2cd76156d3ddb --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/update-sentence-transformers-import-error-msg-895b8ed2355ae2fe.yaml @@ -0,0 +1,5 @@ +--- +enhancements: + - | + Update the error message when the `sentence-transformers` library is not installed + and the used component requires it. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/update-supported-cohere-models-68f17fa70051fc90.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/update-supported-cohere-models-68f17fa70051fc90.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19a1edc1c79f00e86f358072da48838cc3dfa929 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/update-supported-cohere-models-68f17fa70051fc90.yaml @@ -0,0 +1,7 @@ +--- +enhancements: + - | + Add alias names for Cohere embed models for an easier map between names +fixes: + - | + Remove unsupported `medium` and `finance-sentiment` models from supported Cohere embed model list diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-canals-0-9-0-2bed4670885e998b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-canals-0-9-0-2bed4670885e998b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6888127caf9e6c53f9bd192cc197b05d7c2a402d --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-canals-0-9-0-2bed4670885e998b.yaml @@ -0,0 +1,4 @@ +--- +preview: + - | + Upgrade canals to 0.9.0 to support variadic inputs for Joiner components and "/" in connection names like "text/plain" diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-huggingface-hub-dependency-9b8a89d50eb88fea.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-huggingface-hub-dependency-9b8a89d50eb88fea.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4113e2e91797aebbeac316a8099cfeb717d24a4e --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-huggingface-hub-dependency-9b8a89d50eb88fea.yaml @@ -0,0 +1,4 @@ +--- +upgrade: + - | + Upgraded the required version of `huggingface_hub` to `>=0.23.0` across various modules to ensure compatibility and leverage the latest features. This update includes modifications to error handling for token generation details and introduces adjustments in the chat and text generation interfaces to enhance functionality and developer experience. Users are advised to upgrade their `huggingface_hub` dependency. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-openai-client-15fda68fc769f95b.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-openai-client-15fda68fc769f95b.yaml new file mode 100644 index 0000000000000000000000000000000000000000..40b039a9ead91a723ad721f77affcfe77c20c8dc --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-openai-client-15fda68fc769f95b.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Upgrade to OpenAI client version 1.x diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-tiktoken-0.5.1-3cea9bf90fddb2f2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-tiktoken-0.5.1-3cea9bf90fddb2f2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f371e5f58c7b3c41ab6f5e35ad91e74f8095241f --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/upgrade-tiktoken-0.5.1-3cea9bf90fddb2f2.yaml @@ -0,0 +1,2 @@ +fixes: + - Upgrades tiktoken to 0.5.1 to account for a breaking release. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/url-cache-checker-a0fb3d7ad0bdb8c2.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/url-cache-checker-a0fb3d7ad0bdb8c2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d872c8b8015be2c7b35fd7d112207145ac3937e5 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/url-cache-checker-a0fb3d7ad0bdb8c2.yaml @@ -0,0 +1,6 @@ +--- +preview: + - | + Add `UrlCacheChecker` to support Web retrieval pipelines. + Check if documents coming from a given list of URLs are already present in the store and if so, returns them. + All URLs with no matching documents are returned on a separate connection. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/web-retriever-add-domain-scoping-6594425e0c0ace3c.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/web-retriever-add-domain-scoping-6594425e0c0ace3c.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51b1b4ed4d207bc260ef6b712f3f0eeda2819553 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/web-retriever-add-domain-scoping-6594425e0c0ace3c.yaml @@ -0,0 +1,5 @@ +--- +features: + - | + Introduced `allowed_domains` parameter in `WebRetriever` for domain-specific searches, + thus enabling "talk to a website" and "talk to docs" scenarios. diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/web-retriever-allow-custom-link-content-fetcher-8728141d81d7a5e5.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/web-retriever-allow-custom-link-content-fetcher-8728141d81d7a5e5.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fff5904a143a7e2d7bdef03f44c9c98a6eb41447 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/web-retriever-allow-custom-link-content-fetcher-8728141d81d7a5e5.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Allow WebRetriever users to specify a custom LinkContentFetcher instance diff --git a/testbed/deepset-ai__haystack/releasenotes/notes/weights-normalize-docjoin-rrf-v2-9cad33012fe90a55.yaml b/testbed/deepset-ai__haystack/releasenotes/notes/weights-normalize-docjoin-rrf-v2-9cad33012fe90a55.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e732906c98de31dc2842b71349adb6ac0b3f8f92 --- /dev/null +++ b/testbed/deepset-ai__haystack/releasenotes/notes/weights-normalize-docjoin-rrf-v2-9cad33012fe90a55.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Introduces weighted score normalization for the DocumentJoiner's reciprocal rank fusion, enhancing the relevance of document sorting by allowing customizable influence on the final scores diff --git a/testbed/deepset-ai__haystack/test/components/audio/test_whisper_local.py b/testbed/deepset-ai__haystack/test/components/audio/test_whisper_local.py new file mode 100644 index 0000000000000000000000000000000000000000..28463c4ce6575f881722ba371e2dea7d15177e12 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/audio/test_whisper_local.py @@ -0,0 +1,225 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import sys +from pathlib import Path +from unittest.mock import patch, MagicMock + +import pytest +import torch + +from haystack import Pipeline +from haystack.components.fetchers import LinkContentFetcher +from haystack.dataclasses import Document, ByteStream +from haystack.components.audio import LocalWhisperTranscriber +from haystack.utils.device import ComponentDevice, Device + + +SAMPLES_PATH = Path(__file__).parent.parent.parent / "test_files" + + +class TestLocalWhisperTranscriber: + def test_init(self): + transcriber = LocalWhisperTranscriber( + model="large-v2" + ) # Doesn't matter if it's huge, the model is not loaded in init. + assert transcriber.model == "large-v2" + assert transcriber.device == ComponentDevice.resolve_device(None) + assert transcriber._model is None + + def test_init_wrong_model(self): + with pytest.raises(ValueError, match="Model name 'whisper-1' not recognized"): + LocalWhisperTranscriber(model="whisper-1") + + def test_to_dict(self): + transcriber = LocalWhisperTranscriber() + data = transcriber.to_dict() + assert data == { + "type": "haystack.components.audio.whisper_local.LocalWhisperTranscriber", + "init_parameters": { + "model": "large", + "device": ComponentDevice.resolve_device(None).to_dict(), + "whisper_params": {}, + }, + } + + def test_to_dict_with_custom_init_parameters(self): + transcriber = LocalWhisperTranscriber( + model="tiny", + device=ComponentDevice.from_str("cuda:0"), + whisper_params={"return_segments": True, "temperature": [0.1, 0.6, 0.8]}, + ) + data = transcriber.to_dict() + assert data == { + "type": "haystack.components.audio.whisper_local.LocalWhisperTranscriber", + "init_parameters": { + "model": "tiny", + "device": ComponentDevice.from_str("cuda:0").to_dict(), + "whisper_params": {"return_segments": True, "temperature": [0.1, 0.6, 0.8]}, + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.audio.whisper_local.LocalWhisperTranscriber", + "init_parameters": { + "model": "tiny", + "device": ComponentDevice.from_single(Device.cpu()).to_dict(), + "whisper_params": {}, + }, + } + transcriber = LocalWhisperTranscriber.from_dict(data) + assert transcriber.model == "tiny" + assert transcriber.device == ComponentDevice.from_single(Device.cpu()) + assert transcriber.whisper_params == {} + assert transcriber._model is None + + def test_from_dict_no_default_parameters(self): + data = {"type": "haystack.components.audio.whisper_local.LocalWhisperTranscriber", "init_parameters": {}} + transcriber = LocalWhisperTranscriber.from_dict(data) + assert transcriber.model == "large" + assert transcriber.device == ComponentDevice.resolve_device(None) + assert transcriber.whisper_params == {} + + def test_from_dict_none_device(self): + data = { + "type": "haystack.components.audio.whisper_local.LocalWhisperTranscriber", + "init_parameters": {"model": "tiny", "device": None, "whisper_params": {}}, + } + transcriber = LocalWhisperTranscriber.from_dict(data) + assert transcriber.model == "tiny" + assert transcriber.device == ComponentDevice.resolve_device(None) + assert transcriber.whisper_params == {} + assert transcriber._model is None + + def test_warmup(self): + with patch("haystack.components.audio.whisper_local.whisper") as mocked_whisper: + transcriber = LocalWhisperTranscriber(model="large-v2", device=ComponentDevice.from_str("cpu")) + mocked_whisper.load_model.assert_not_called() + transcriber.warm_up() + mocked_whisper.load_model.assert_called_once_with("large-v2", device=torch.device(type="cpu")) + + def test_warmup_doesnt_reload(self): + with patch("haystack.components.audio.whisper_local.whisper") as mocked_whisper: + transcriber = LocalWhisperTranscriber(model="large-v2") + transcriber.warm_up() + transcriber.warm_up() + mocked_whisper.load_model.assert_called_once() + + def test_run_with_path(self): + comp = LocalWhisperTranscriber(model="large-v2") + comp._model = MagicMock() + comp._model.transcribe.return_value = { + "text": "test transcription", + "other_metadata": ["other", "meta", "data"], + } + results = comp.run(sources=[SAMPLES_PATH / "audio" / "this is the content of the document.wav"]) + expected = Document( + content="test transcription", + meta={ + "audio_file": SAMPLES_PATH / "audio" / "this is the content of the document.wav", + "other_metadata": ["other", "meta", "data"], + }, + ) + assert results["documents"] == [expected] + + def test_run_with_str(self): + comp = LocalWhisperTranscriber(model="large-v2") + comp._model = MagicMock() + comp._model.transcribe.return_value = { + "text": "test transcription", + "other_metadata": ["other", "meta", "data"], + } + results = comp.run( + sources=[str((SAMPLES_PATH / "audio" / "this is the content of the document.wav").absolute())] + ) + expected = Document( + content="test transcription", + meta={ + "audio_file": (SAMPLES_PATH / "audio" / "this is the content of the document.wav").absolute(), + "other_metadata": ["other", "meta", "data"], + }, + ) + assert results["documents"] == [expected] + + def test_transcribe(self): + comp = LocalWhisperTranscriber(model="large-v2") + comp._model = MagicMock() + comp._model.transcribe.return_value = { + "text": "test transcription", + "other_metadata": ["other", "meta", "data"], + } + results = comp.transcribe(sources=[SAMPLES_PATH / "audio" / "this is the content of the document.wav"]) + expected = Document( + content="test transcription", + meta={ + "audio_file": SAMPLES_PATH / "audio" / "this is the content of the document.wav", + "other_metadata": ["other", "meta", "data"], + }, + ) + assert results == [expected] + + def test_transcribe_stream(self): + comp = LocalWhisperTranscriber(model="large-v2") + comp._model = MagicMock() + comp._model.transcribe.return_value = { + "text": "test transcription", + "other_metadata": ["other", "meta", "data"], + } + path = SAMPLES_PATH / "audio" / "this is the content of the document.wav" + bs = ByteStream.from_file_path(path) + bs.meta["file_path"] = path + results = comp.transcribe(sources=[bs]) + expected = Document( + content="test transcription", meta={"audio_file": path, "other_metadata": ["other", "meta", "data"]} + ) + assert results == [expected] + + @pytest.mark.integration + @pytest.mark.skipif(sys.platform in ["win32", "cygwin"], reason="ffmpeg not installed on Windows CI") + def test_whisper_local_transcriber(self, test_files_path): + comp = LocalWhisperTranscriber(model="tiny", whisper_params={"language": "english"}) + comp.warm_up() + output = comp.run( + sources=[ + test_files_path / "audio" / "this is the content of the document.wav", + str((test_files_path / "audio" / "the context for this answer is here.wav").absolute()), + ByteStream.from_file_path(test_files_path / "audio" / "answer.wav", "rb"), + ] + ) + docs = output["documents"] + assert len(docs) == 3 + + assert all( + word in docs[0].content.strip().lower() for word in {"content", "the", "document"} + ), f"Expected words not found in: {docs[0].content.strip().lower()}" + assert test_files_path / "audio" / "this is the content of the document.wav" == docs[0].meta["audio_file"] + + assert all( + word in docs[1].content.strip().lower() for word in {"context", "answer"} + ), f"Expected words not found in: {docs[1].content.strip().lower()}" + path = test_files_path / "audio" / "the context for this answer is here.wav" + assert path.absolute() == docs[1].meta["audio_file"] + + assert docs[2].content.strip().lower() == "answer." + # meta.audio_file should contain the temp path where we dumped the audio bytes + assert docs[2].meta["audio_file"] + + @pytest.mark.integration + @pytest.mark.skipif(sys.platform in ["win32", "cygwin"], reason="ffmpeg not installed on Windows CI") + def test_whisper_local_transcriber_pipeline_and_url_source(self): + pipe = Pipeline() + pipe.add_component("fetcher", LinkContentFetcher()) + pipe.add_component("transcriber", LocalWhisperTranscriber(model="tiny")) + + pipe.connect("fetcher", "transcriber") + result = pipe.run( + data={ + "fetcher": { + "urls": [ + "https://github.com/deepset-ai/haystack/raw/refs/heads/main/test/test_files/audio/MLK_Something_happening.mp3" # noqa: E501 + ] + } + } + ) + assert "masses of people" in result["transcriber"]["documents"][0].content diff --git a/testbed/deepset-ai__haystack/test/components/builders/__init__.py b/testbed/deepset-ai__haystack/test/components/builders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/builders/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/builders/test_answer_builder.py b/testbed/deepset-ai__haystack/test/components/builders/test_answer_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..46c40e3422a23085f8c210459fe44f10fb046733 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/builders/test_answer_builder.py @@ -0,0 +1,274 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +import pytest + +from haystack import Document, GeneratedAnswer +from haystack.components.builders.answer_builder import AnswerBuilder +from haystack.dataclasses.chat_message import ChatMessage, ChatRole + + +class TestAnswerBuilder: + def test_run_unmatching_input_len(self): + component = AnswerBuilder() + with pytest.raises(ValueError): + component.run(query="query", replies=["reply1"], meta=[{"test": "meta"}, {"test": "meta2"}]) + + def test_run_without_meta(self): + component = AnswerBuilder() + output = component.run(query="query", replies=["reply1"]) + answers = output["answers"] + assert answers[0].data == "reply1" + assert answers[0].meta == {} + assert answers[0].query == "query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_meta_is_an_empty_list(self): + component = AnswerBuilder() + output = component.run(query="query", replies=["reply1"], meta=[]) + answers = output["answers"] + assert answers[0].data == "reply1" + assert answers[0].meta == {} + assert answers[0].query == "query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_without_pattern(self): + component = AnswerBuilder() + output = component.run(query="test query", replies=["Answer: AnswerString"], meta=[{}]) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_with_pattern_with_capturing_group(self): + component = AnswerBuilder(pattern=r"Answer: (.*)") + output = component.run(query="test query", replies=["Answer: AnswerString"], meta=[{}]) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "AnswerString" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_with_pattern_without_capturing_group(self): + component = AnswerBuilder(pattern=r"'.*'") + output = component.run(query="test query", replies=["Answer: 'AnswerString'"], meta=[{}]) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "'AnswerString'" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_with_pattern_with_more_than_one_capturing_group(self): + with pytest.raises(ValueError, match="contains multiple capture groups"): + AnswerBuilder(pattern=r"Answer: (.*), (.*)") + + def test_run_with_pattern_set_at_runtime(self): + component = AnswerBuilder(pattern="unused pattern") + output = component.run(query="test query", replies=["Answer: AnswerString"], meta=[{}], pattern=r"Answer: (.*)") + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "AnswerString" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_with_documents_without_reference_pattern(self): + component = AnswerBuilder() + output = component.run( + query="test query", + replies=["Answer: AnswerString"], + meta=[{}], + documents=[Document(content="test doc 1"), Document(content="test doc 2")], + ) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert len(answers[0].documents) == 2 + assert answers[0].documents[0].content == "test doc 1" + assert answers[0].documents[1].content == "test doc 2" + + def test_run_with_documents_with_reference_pattern(self): + component = AnswerBuilder(reference_pattern="\\[(\\d+)\\]") + output = component.run( + query="test query", + replies=["Answer: AnswerString[2]"], + meta=[{}], + documents=[Document(content="test doc 1"), Document(content="test doc 2")], + ) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString[2]" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert len(answers[0].documents) == 1 + assert answers[0].documents[0].content == "test doc 2" + + def test_run_with_documents_with_reference_pattern_and_no_match(self, caplog): + component = AnswerBuilder(reference_pattern="\\[(\\d+)\\]") + with caplog.at_level(logging.WARNING): + output = component.run( + query="test query", + replies=["Answer: AnswerString[3]"], + meta=[{}], + documents=[Document(content="test doc 1"), Document(content="test doc 2")], + ) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString[3]" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert len(answers[0].documents) == 0 + assert "Document index '3' referenced in Generator output is out of range." in caplog.text + + def test_run_with_reference_pattern_set_at_runtime(self): + component = AnswerBuilder(reference_pattern="unused pattern") + output = component.run( + query="test query", + replies=["Answer: AnswerString[2][3]"], + meta=[{}], + documents=[Document(content="test doc 1"), Document(content="test doc 2"), Document(content="test doc 3")], + reference_pattern="\\[(\\d+)\\]", + ) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString[2][3]" + assert answers[0].meta == {} + assert answers[0].query == "test query" + assert len(answers[0].documents) == 2 + assert answers[0].documents[0].content == "test doc 2" + assert answers[0].documents[1].content == "test doc 3" + + def test_run_with_chat_message_replies_without_pattern(self): + component = AnswerBuilder() + replies = [ + ChatMessage( + content="Answer: AnswerString", + role=ChatRole.ASSISTANT, + name=None, + meta={ + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + }, + ) + ] + output = component.run(query="test query", replies=replies, meta=[{}]) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString" + assert answers[0].meta == { + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + } + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_with_chat_message_replies_with_pattern(self): + component = AnswerBuilder(pattern=r"Answer: (.*)") + replies = [ + ChatMessage( + content="Answer: AnswerString", + role=ChatRole.ASSISTANT, + name=None, + meta={ + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + }, + ) + ] + output = component.run(query="test query", replies=replies, meta=[{}]) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "AnswerString" + assert answers[0].meta == { + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + } + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) + + def test_run_with_chat_message_replies_with_documents(self): + component = AnswerBuilder(reference_pattern="\\[(\\d+)\\]") + replies = [ + ChatMessage( + content="Answer: AnswerString[2]", + role=ChatRole.ASSISTANT, + name=None, + meta={ + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + }, + ) + ] + output = component.run( + query="test query", + replies=replies, + meta=[{}], + documents=[Document(content="test doc 1"), Document(content="test doc 2")], + ) + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "Answer: AnswerString[2]" + assert answers[0].meta == { + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + } + assert answers[0].query == "test query" + assert len(answers[0].documents) == 1 + assert answers[0].documents[0].content == "test doc 2" + + def test_run_with_chat_message_replies_with_pattern_set_at_runtime(self): + component = AnswerBuilder(pattern="unused pattern") + replies = [ + ChatMessage( + content="Answer: AnswerString", + role=ChatRole.ASSISTANT, + name=None, + meta={ + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + }, + ) + ] + output = component.run(query="test query", replies=replies, meta=[{}], pattern=r"Answer: (.*)") + answers = output["answers"] + assert len(answers) == 1 + assert answers[0].data == "AnswerString" + assert answers[0].meta == { + "model": "gpt-4o-mini", + "index": 0, + "finish_reason": "stop", + "usage": {"prompt_tokens": 32, "completion_tokens": 153, "total_tokens": 185}, + } + assert answers[0].query == "test query" + assert answers[0].documents == [] + assert isinstance(answers[0], GeneratedAnswer) diff --git a/testbed/deepset-ai__haystack/test/components/builders/test_chat_prompt_builder.py b/testbed/deepset-ai__haystack/test/components/builders/test_chat_prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..e40b47b5081e666a89b8e5c18635b4a0f82b11ed --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/builders/test_chat_prompt_builder.py @@ -0,0 +1,560 @@ +from typing import Any, Dict, List, Optional +from jinja2 import TemplateSyntaxError +import pytest + +from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder +from haystack import component +from haystack.core.pipeline.pipeline import Pipeline +from haystack.dataclasses.chat_message import ChatMessage, ChatRole +from haystack.dataclasses.document import Document + + +class TestChatPromptBuilder: + def test_init(self): + builder = ChatPromptBuilder( + template=[ + ChatMessage.from_user(content="This is a {{ variable }}"), + ChatMessage.from_system(content="This is a {{ variable2 }}"), + ] + ) + assert builder.required_variables == [] + assert builder.template[0].content == "This is a {{ variable }}" + assert builder.template[1].content == "This is a {{ variable2 }}" + assert builder._variables is None + assert builder._required_variables is None + + # we have inputs that contain: template, template_variables + inferred variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "variable", "variable2"} + assert inputs["template"].type == Optional[List[ChatMessage]] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["variable"].type == Any + assert inputs["variable2"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == List[ChatMessage] + + def test_init_without_template(self): + variables = ["var1", "var2"] + builder = ChatPromptBuilder(variables=variables) + assert builder.template is None + assert builder.required_variables == [] + assert builder._variables == variables + assert builder._required_variables is None + + # we have inputs that contain: template, template_variables + variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "var1", "var2"} + assert inputs["template"].type == Optional[List[ChatMessage]] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["var1"].type == Any + assert inputs["var2"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == List[ChatMessage] + + def test_init_with_required_variables(self): + builder = ChatPromptBuilder( + template=[ChatMessage.from_user("This is a {{ variable }}")], required_variables=["variable"] + ) + assert builder.required_variables == ["variable"] + assert builder.template[0].content == "This is a {{ variable }}" + assert builder._variables is None + assert builder._required_variables == ["variable"] + + # we have inputs that contain: template, template_variables + inferred variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "variable"} + assert inputs["template"].type == Optional[List[ChatMessage]] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["variable"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == List[ChatMessage] + + def test_init_with_custom_variables(self): + variables = ["var1", "var2", "var3"] + template = [ChatMessage.from_user("Hello, {{ var1 }}, {{ var2 }}!")] + builder = ChatPromptBuilder(template=template, variables=variables) + assert builder.required_variables == [] + assert builder._variables == variables + assert builder.template[0].content == "Hello, {{ var1 }}, {{ var2 }}!" + assert builder._required_variables is None + + # we have inputs that contain: template, template_variables + variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "var1", "var2", "var3"} + assert inputs["template"].type == Optional[List[ChatMessage]] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["var1"].type == Any + assert inputs["var2"].type == Any + assert inputs["var3"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == List[ChatMessage] + + def test_run(self): + builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")]) + res = builder.run(variable="test") + assert res == {"prompt": [ChatMessage.from_user("This is a test")]} + + def test_run_template_variable(self): + builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")]) + res = builder.run(template_variables={"variable": "test"}) + assert res == {"prompt": [ChatMessage.from_user("This is a test")]} + + def test_run_template_variable_overrides_variable(self): + builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")]) + res = builder.run(template_variables={"variable": "test_from_template_var"}, variable="test") + assert res == {"prompt": [ChatMessage.from_user("This is a test_from_template_var")]} + + def test_run_without_input(self): + builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a template without input")]) + res = builder.run() + assert res == {"prompt": [ChatMessage.from_user("This is a template without input")]} + + def test_run_with_missing_input(self): + builder = ChatPromptBuilder(template=[ChatMessage.from_user("This is a {{ variable }}")]) + res = builder.run() + assert res == {"prompt": [ChatMessage.from_user("This is a ")]} + + def test_run_with_missing_required_input(self): + builder = ChatPromptBuilder( + template=[ChatMessage.from_user("This is a {{ foo }}, not a {{ bar }}")], required_variables=["foo", "bar"] + ) + with pytest.raises(ValueError, match="foo"): + builder.run(bar="bar") + with pytest.raises(ValueError, match="bar"): + builder.run(foo="foo") + with pytest.raises(ValueError, match="foo, bar"): + builder.run() + + def test_run_with_variables(self): + variables = ["var1", "var2", "var3"] + template = [ChatMessage.from_user("Hello, {{ name }}! {{ var1 }}")] + + builder = ChatPromptBuilder(template=template, variables=variables) + + template_variables = {"name": "John"} + expected_result = {"prompt": [ChatMessage.from_user("Hello, John! How are you?")]} + + assert builder.run(template_variables=template_variables, var1="How are you?") == expected_result + + def test_run_with_variables_and_runtime_template(self): + variables = ["var1", "var2", "var3"] + + builder = ChatPromptBuilder(variables=variables) + + template = [ChatMessage.from_user("Hello, {{ name }}! {{ var1 }}")] + template_variables = {"name": "John"} + expected_result = {"prompt": [ChatMessage.from_user("Hello, John! How are you?")]} + + assert ( + builder.run(template=template, template_variables=template_variables, var1="How are you?") + == expected_result + ) + + def test_run_overwriting_default_template(self): + default_template = [ChatMessage.from_user("Hello, {{ name }}!")] + + builder = ChatPromptBuilder(template=default_template) + + template = [ChatMessage.from_user("Hello, {{ var1 }}{{ name }}!")] + expected_result = {"prompt": [ChatMessage.from_user("Hello, John!")]} + + assert builder.run(template, name="John") == expected_result + + def test_run_overwriting_default_template_with_template_variables(self): + default_template = [ChatMessage.from_user("Hello, {{ name }}!")] + + builder = ChatPromptBuilder(template=default_template) + + template = [ChatMessage.from_user("Hello, {{ var1 }} {{ name }}!")] + template_variables = {"var1": "Big"} + expected_result = {"prompt": [ChatMessage.from_user("Hello, Big John!")]} + + assert builder.run(template, template_variables, name="John") == expected_result + + def test_run_overwriting_default_template_with_variables(self): + variables = ["var1", "var2", "name"] + default_template = [ChatMessage.from_user("Hello, {{ name }}!")] + + builder = ChatPromptBuilder(template=default_template, variables=variables) + + template = [ChatMessage.from_user("Hello, {{ var1 }} {{ name }}!")] + expected_result = {"prompt": [ChatMessage.from_user("Hello, Big John!")]} + + assert builder.run(template, name="John", var1="Big") == expected_result + + def test_run_with_meta(self): + """ + Test that the ChatPromptBuilder correctly handles meta data. + It should render the message and copy the meta data from the original message. + """ + m = ChatMessage(content="This is a {{ variable }}", role=ChatRole.USER, name=None, meta={"test": "test"}) + builder = ChatPromptBuilder(template=[m]) + res = builder.run(variable="test") + res_msg = ChatMessage(content="This is a test", role=ChatRole.USER, name=None, meta={"test": "test"}) + assert res == {"prompt": [res_msg]} + + def test_run_with_invalid_template(self): + builder = ChatPromptBuilder() + + template = [ChatMessage.from_user("Hello, {{ name }!")] + template_variables = {"name": "John"} + with pytest.raises(TemplateSyntaxError): + builder.run(template, template_variables) + + def test_init_with_invalid_template(self): + template = [ChatMessage.from_user("Hello, {{ name }!")] + with pytest.raises(TemplateSyntaxError): + ChatPromptBuilder(template) + + def test_run_without_template(self): + prompt_builder = ChatPromptBuilder() + with pytest.raises( + ValueError, match="The ChatPromptBuilder requires a non-empty list of ChatMessage instances" + ): + prompt_builder.run() + + def test_run_with_empty_chat_message_list(self): + prompt_builder = ChatPromptBuilder(template=[], variables=["documents"]) + with pytest.raises( + ValueError, match="The ChatPromptBuilder requires a non-empty list of ChatMessage instances" + ): + prompt_builder.run() + + def test_chat_message_list_with_mixed_object_list(self): + prompt_builder = ChatPromptBuilder( + template=[ChatMessage.from_user("Hello"), "there world"], variables=["documents"] + ) + with pytest.raises( + ValueError, match="The ChatPromptBuilder expects a list containing only ChatMessage instances" + ): + prompt_builder.run() + + def test_provided_template_variables(self): + prompt_builder = ChatPromptBuilder(variables=["documents"], required_variables=["city"]) + + # both variables are provided + prompt_builder._validate_variables({"name", "city"}) + + # provided variables are a superset of the required variables + prompt_builder._validate_variables({"name", "city", "age"}) + + with pytest.raises(ValueError): + prompt_builder._validate_variables({"name"}) + + def test_example_in_pipeline(self): + default_template = [ + ChatMessage.from_user("Here is the document: {{documents[0].content}} \\n Answer: {{query}}") + ] + prompt_builder = ChatPromptBuilder(template=default_template, variables=["documents"]) + + @component + class DocumentProducer: + @component.output_types(documents=List[Document]) + def run(self, doc_input: str): + return {"documents": [Document(content=doc_input)]} + + pipe = Pipeline() + pipe.add_component("doc_producer", DocumentProducer()) + pipe.add_component("prompt_builder", prompt_builder) + pipe.connect("doc_producer.documents", "prompt_builder.documents") + + template = [ChatMessage.from_user("Here is the document: {{documents[0].content}} \n Query: {{query}}")] + result = pipe.run( + data={ + "doc_producer": {"doc_input": "Hello world, I live in Berlin"}, + "prompt_builder": { + "template": template, + "template_variables": {"query": "Where does the speaker live?"}, + }, + } + ) + + assert result == { + "prompt_builder": { + "prompt": [ + ChatMessage.from_user( + "Here is the document: Hello world, I live in Berlin \n Query: Where does the speaker live?" + ) + ] + } + } + + def test_example_in_pipeline_simple(self): + default_template = [ChatMessage.from_user("This is the default prompt:\n Query: {{query}}")] + prompt_builder = ChatPromptBuilder(template=default_template) + + pipe = Pipeline() + pipe.add_component("prompt_builder", prompt_builder) + + # using the default prompt + result = pipe.run(data={"query": "Where does the speaker live?"}) + expected_default = { + "prompt_builder": { + "prompt": [ChatMessage.from_user("This is the default prompt:\n Query: Where does the speaker live?")] + } + } + assert result == expected_default + + # using the dynamic prompt + result = pipe.run( + data={ + "query": "Where does the speaker live?", + "template": [ChatMessage.from_user("This is the dynamic prompt:\n Query: {{query}}")], + } + ) + expected_dynamic = { + "prompt_builder": { + "prompt": [ChatMessage.from_user("This is the dynamic prompt:\n Query: Where does the speaker live?")] + } + } + assert result == expected_dynamic + + +class TestChatPromptBuilderDynamic: + def test_multiple_templated_chat_messages(self): + prompt_builder = ChatPromptBuilder() + language = "French" + location = "Berlin" + messages = [ + ChatMessage.from_system("Write your response in this language:{{language}}"), + ChatMessage.from_user("Tell me about {{location}}"), + ] + + result = prompt_builder.run(template_variables={"language": language, "location": location}, template=messages) + assert result["prompt"] == [ + ChatMessage.from_system("Write your response in this language:French"), + ChatMessage.from_user("Tell me about Berlin"), + ], "The templated messages should match the expected output." + + def test_multiple_templated_chat_messages_in_place(self): + prompt_builder = ChatPromptBuilder() + language = "French" + location = "Berlin" + messages = [ + ChatMessage.from_system("Write your response ins this language:{{language}}"), + ChatMessage.from_user("Tell me about {{location}}"), + ] + + res = prompt_builder.run(template_variables={"language": language, "location": location}, template=messages) + assert res == { + "prompt": [ + ChatMessage.from_system("Write your response ins this language:French"), + ChatMessage.from_user("Tell me about Berlin"), + ] + }, "The templated messages should match the expected output." + + def test_some_templated_chat_messages(self): + prompt_builder = ChatPromptBuilder() + language = "English" + location = "Paris" + messages = [ + ChatMessage.from_system("Please, respond in the following language: {{language}}."), + ChatMessage.from_user("I would like to learn more about {{location}}."), + ChatMessage.from_assistant("Yes, I can help you with that {{subject}}"), + ChatMessage.from_user("Ok so do so please, be elaborate."), + ] + + result = prompt_builder.run(template_variables={"language": language, "location": location}, template=messages) + + expected_messages = [ + ChatMessage.from_system("Please, respond in the following language: English."), + ChatMessage.from_user("I would like to learn more about Paris."), + ChatMessage.from_assistant( + "Yes, I can help you with that {{subject}}" + ), # assistant message should not be templated + ChatMessage.from_user("Ok so do so please, be elaborate."), + ] + + assert result["prompt"] == expected_messages, "The templated messages should match the expected output." + + def test_example_in_pipeline(self): + prompt_builder = ChatPromptBuilder() + + pipe = Pipeline() + pipe.add_component("prompt_builder", prompt_builder) + + location = "Berlin" + system_message = ChatMessage.from_system( + "You are a helpful assistant giving out valuable information to tourists." + ) + messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")] + + res = pipe.run(data={"prompt_builder": {"template_variables": {"location": location}, "template": messages}}) + assert res == { + "prompt_builder": { + "prompt": [ + ChatMessage.from_system("You are a helpful assistant giving out valuable information to tourists."), + ChatMessage.from_user("Tell me about Berlin"), + ] + } + } + + messages = [ + system_message, + ChatMessage.from_user("What's the weather forecast for {{location}} in the next {{day_count}} days?"), + ] + + res = pipe.run( + data={ + "prompt_builder": {"template_variables": {"location": location, "day_count": "5"}, "template": messages} + } + ) + assert res == { + "prompt_builder": { + "prompt": [ + ChatMessage.from_system("You are a helpful assistant giving out valuable information to tourists."), + ChatMessage.from_user("What's the weather forecast for Berlin in the next 5 days?"), + ] + } + } + + def test_example_in_pipeline_with_multiple_templated_messages(self): + # no parameter init, we don't use any runtime template variables + prompt_builder = ChatPromptBuilder() + + pipe = Pipeline() + pipe.add_component("prompt_builder", prompt_builder) + + location = "Berlin" + system_message = ChatMessage.from_system( + "You are a helpful assistant giving out valuable information to tourists in {{language}}." + ) + messages = [system_message, ChatMessage.from_user("Tell me about {{location}}")] + + res = pipe.run( + data={ + "prompt_builder": { + "template_variables": {"location": location, "language": "German"}, + "template": messages, + } + } + ) + assert res == { + "prompt_builder": { + "prompt": [ + ChatMessage.from_system( + "You are a helpful assistant giving out valuable information to tourists in German." + ), + ChatMessage.from_user("Tell me about Berlin"), + ] + } + } + + messages = [ + system_message, + ChatMessage.from_user("What's the weather forecast for {{location}} in the next {{day_count}} days?"), + ] + + res = pipe.run( + data={ + "prompt_builder": { + "template_variables": {"location": location, "day_count": "5", "language": "English"}, + "template": messages, + } + } + ) + assert res == { + "prompt_builder": { + "prompt": [ + ChatMessage.from_system( + "You are a helpful assistant giving out valuable information to tourists in English." + ), + ChatMessage.from_user("What's the weather forecast for Berlin in the next 5 days?"), + ] + } + } + + def test_pipeline_complex(self): + @component + class ValueProducer: + def __init__(self, value_to_produce: str): + self.value_to_produce = value_to_produce + + @component.output_types(value_output=str) + def run(self): + return {"value_output": self.value_to_produce} + + pipe = Pipeline() + pipe.add_component("prompt_builder", ChatPromptBuilder(variables=["value_output"])) + pipe.add_component("value_producer", ValueProducer(value_to_produce="Berlin")) + pipe.connect("value_producer.value_output", "prompt_builder") + + messages = [ + ChatMessage.from_system("You give valuable information to tourists."), + ChatMessage.from_user("Tell me about {{value_output}}"), + ] + + res = pipe.run(data={"template": messages}) + assert res == { + "prompt_builder": { + "prompt": [ + ChatMessage.from_system("You give valuable information to tourists."), + ChatMessage.from_user("Tell me about Berlin"), + ] + } + } + + def test_to_dict(self): + component = ChatPromptBuilder( + template=[ChatMessage.from_user("text and {var}"), ChatMessage.from_assistant("content {required_var}")], + variables=["var", "required_var"], + required_variables=["required_var"], + ) + + assert component.to_dict() == { + "type": "haystack.components.builders.chat_prompt_builder.ChatPromptBuilder", + "init_parameters": { + "template": [ + {"content": "text and {var}", "role": "user", "name": None, "meta": {}}, + {"content": "content {required_var}", "role": "assistant", "name": None, "meta": {}}, + ], + "variables": ["var", "required_var"], + "required_variables": ["required_var"], + }, + } + + def test_from_dict(self): + component = ChatPromptBuilder.from_dict( + data={ + "type": "haystack.components.builders.chat_prompt_builder.ChatPromptBuilder", + "init_parameters": { + "template": [ + {"content": "text and {var}", "role": "user", "name": None, "meta": {}}, + {"content": "content {required_var}", "role": "assistant", "name": None, "meta": {}}, + ], + "variables": ["var", "required_var"], + "required_variables": ["required_var"], + }, + } + ) + + assert component.template == [ + ChatMessage.from_user("text and {var}"), + ChatMessage.from_assistant("content {required_var}"), + ] + assert component._variables == ["var", "required_var"] + assert component._required_variables == ["required_var"] + + def test_from_dict_template_none(self): + component = ChatPromptBuilder.from_dict( + data={ + "type": "haystack.components.builders.chat_prompt_builder.ChatPromptBuilder", + "init_parameters": {"template": None}, + } + ) + + assert component.template is None + assert component._variables is None + assert component._required_variables is None diff --git a/testbed/deepset-ai__haystack/test/components/builders/test_prompt_builder.py b/testbed/deepset-ai__haystack/test/components/builders/test_prompt_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..7461327f4ea3a0002df9de94046252231b2bb0f0 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/builders/test_prompt_builder.py @@ -0,0 +1,323 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Any, Dict, List, Optional +from unittest.mock import patch + +import arrow +import pytest +from jinja2 import TemplateSyntaxError + +from haystack import component +from haystack.components.builders.prompt_builder import PromptBuilder +from haystack.core.pipeline.pipeline import Pipeline +from haystack.dataclasses.document import Document + + +class TestPromptBuilder: + def test_init(self): + builder = PromptBuilder(template="This is a {{ variable }}") + assert builder.template is not None + assert builder.required_variables == [] + assert builder._template_string == "This is a {{ variable }}" + assert builder._variables is None + assert builder._required_variables is None + + # we have inputs that contain: template, template_variables + inferred variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "variable"} + assert inputs["template"].type == Optional[str] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["variable"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == str + + def test_init_with_required_variables(self): + builder = PromptBuilder(template="This is a {{ variable }}", required_variables=["variable"]) + assert builder.template is not None + assert builder.required_variables == ["variable"] + assert builder._template_string == "This is a {{ variable }}" + assert builder._variables is None + assert builder._required_variables == ["variable"] + + # we have inputs that contain: template, template_variables + inferred variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "variable"} + assert inputs["template"].type == Optional[str] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["variable"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == str + + def test_init_with_custom_variables(self): + variables = ["var1", "var2", "var3"] + template = "Hello, {{ var1 }}, {{ var2 }}!" + builder = PromptBuilder(template=template, variables=variables) + assert builder.template is not None + assert builder.required_variables == [] + assert builder._variables == variables + assert builder._template_string == "Hello, {{ var1 }}, {{ var2 }}!" + assert builder._required_variables is None + + # we have inputs that contain: template, template_variables + variables + inputs = builder.__haystack_input__._sockets_dict + assert set(inputs.keys()) == {"template", "template_variables", "var1", "var2", "var3"} + assert inputs["template"].type == Optional[str] + assert inputs["template_variables"].type == Optional[Dict[str, Any]] + assert inputs["var1"].type == Any + assert inputs["var2"].type == Any + assert inputs["var3"].type == Any + + # response is always prompt + outputs = builder.__haystack_output__._sockets_dict + assert set(outputs.keys()) == {"prompt"} + assert outputs["prompt"].type == str + + @patch("haystack.components.builders.prompt_builder.Jinja2TimeExtension") + def test_init_with_missing_extension_dependency(self, extension_mock): + extension_mock.side_effect = ImportError + builder = PromptBuilder(template="This is a {{ variable }}") + assert builder._env.extensions == {} + res = builder.run(variable="test") + assert res == {"prompt": "This is a test"} + + def test_to_dict(self): + builder = PromptBuilder( + template="This is a {{ variable }}", variables=["var1", "var2"], required_variables=["var1", "var3"] + ) + res = builder.to_dict() + assert res == { + "type": "haystack.components.builders.prompt_builder.PromptBuilder", + "init_parameters": { + "template": "This is a {{ variable }}", + "variables": ["var1", "var2"], + "required_variables": ["var1", "var3"], + }, + } + + def test_to_dict_without_optional_params(self): + builder = PromptBuilder(template="This is a {{ variable }}") + res = builder.to_dict() + assert res == { + "type": "haystack.components.builders.prompt_builder.PromptBuilder", + "init_parameters": {"template": "This is a {{ variable }}", "variables": None, "required_variables": None}, + } + + def test_run(self): + builder = PromptBuilder(template="This is a {{ variable }}") + res = builder.run(variable="test") + assert res == {"prompt": "This is a test"} + + def test_run_template_variable(self): + builder = PromptBuilder(template="This is a {{ variable }}") + res = builder.run(template_variables={"variable": "test"}) + assert res == {"prompt": "This is a test"} + + def test_run_template_variable_overrides_variable(self): + builder = PromptBuilder(template="This is a {{ variable }}") + res = builder.run(template_variables={"variable": "test_from_template_var"}, variable="test") + assert res == {"prompt": "This is a test_from_template_var"} + + def test_run_without_input(self): + builder = PromptBuilder(template="This is a template without input") + res = builder.run() + assert res == {"prompt": "This is a template without input"} + + def test_run_with_missing_input(self): + builder = PromptBuilder(template="This is a {{ variable }}") + res = builder.run() + assert res == {"prompt": "This is a "} + + def test_run_with_missing_required_input(self): + builder = PromptBuilder(template="This is a {{ foo }}, not a {{ bar }}", required_variables=["foo", "bar"]) + with pytest.raises(ValueError, match="foo"): + builder.run(bar="bar") + with pytest.raises(ValueError, match="bar"): + builder.run(foo="foo") + with pytest.raises(ValueError, match="foo, bar"): + builder.run() + + def test_run_with_variables(self): + variables = ["var1", "var2", "var3"] + template = "Hello, {{ name }}! {{ var1 }}" + + builder = PromptBuilder(template=template, variables=variables) + + template_variables = {"name": "John"} + expected_result = {"prompt": "Hello, John! How are you?"} + + assert builder.run(template_variables=template_variables, var1="How are you?") == expected_result + + def test_run_overwriting_default_template(self): + default_template = "Hello, {{ name }}!" + + builder = PromptBuilder(template=default_template) + + template = "Hello, {{ var1 }}{{ name }}!" + expected_result = {"prompt": "Hello, John!"} + + assert builder.run(template, name="John") == expected_result + + def test_run_overwriting_default_template_with_template_variables(self): + default_template = "Hello, {{ name }}!" + + builder = PromptBuilder(template=default_template) + + template = "Hello, {{ var1 }} {{ name }}!" + template_variables = {"var1": "Big"} + expected_result = {"prompt": "Hello, Big John!"} + + assert builder.run(template, template_variables, name="John") == expected_result + + def test_run_overwriting_default_template_with_variables(self): + variables = ["var1", "var2", "name"] + default_template = "Hello, {{ name }}!" + + builder = PromptBuilder(template=default_template, variables=variables) + + template = "Hello, {{ var1 }} {{ name }}!" + expected_result = {"prompt": "Hello, Big John!"} + + assert builder.run(template, name="John", var1="Big") == expected_result + + def test_run_with_invalid_template(self): + builder = PromptBuilder(template="Hello, {{ name }}!") + + template = "Hello, {{ name }!" + template_variables = {"name": "John"} + with pytest.raises(TemplateSyntaxError): + builder.run(template, template_variables) + + def test_init_with_invalid_template(self): + template = "Hello, {{ name }!" + with pytest.raises(TemplateSyntaxError): + PromptBuilder(template) + + def test_provided_template_variables(self): + prompt_builder = PromptBuilder(template="", variables=["documents"], required_variables=["city"]) + + # both variables are provided + prompt_builder._validate_variables({"name", "city"}) + + # provided variables are a superset of the required variables + prompt_builder._validate_variables({"name", "city", "age"}) + + with pytest.raises(ValueError): + prompt_builder._validate_variables({"name"}) + + def test_example_in_pipeline(self): + default_template = "Here is the document: {{documents[0].content}} \\n Answer: {{query}}" + prompt_builder = PromptBuilder(template=default_template, variables=["documents"]) + + @component + class DocumentProducer: + @component.output_types(documents=List[Document]) + def run(self, doc_input: str): + return {"documents": [Document(content=doc_input)]} + + pipe = Pipeline() + pipe.add_component("doc_producer", DocumentProducer()) + pipe.add_component("prompt_builder", prompt_builder) + pipe.connect("doc_producer.documents", "prompt_builder.documents") + + template = "Here is the document: {{documents[0].content}} \n Query: {{query}}" + result = pipe.run( + data={ + "doc_producer": {"doc_input": "Hello world, I live in Berlin"}, + "prompt_builder": { + "template": template, + "template_variables": {"query": "Where does the speaker live?"}, + }, + } + ) + + assert result == { + "prompt_builder": { + "prompt": "Here is the document: Hello world, I live in Berlin \n Query: Where does the speaker live?" + } + } + + def test_example_in_pipeline_simple(self): + default_template = "This is the default prompt:\n Query: {{query}}" + prompt_builder = PromptBuilder(template=default_template) + + pipe = Pipeline() + pipe.add_component("prompt_builder", prompt_builder) + + # using the default prompt + result = pipe.run(data={"query": "Where does the speaker live?"}) + expected_default = { + "prompt_builder": {"prompt": "This is the default prompt:\n Query: Where does the speaker live?"} + } + assert result == expected_default + + # using the dynamic prompt + result = pipe.run( + data={"query": "Where does the speaker live?", "template": "This is the dynamic prompt:\n Query: {{query}}"} + ) + expected_dynamic = { + "prompt_builder": {"prompt": "This is the dynamic prompt:\n Query: Where does the speaker live?"} + } + assert result == expected_dynamic + + def test_with_custom_dateformat(self) -> None: + template = "Formatted date: {% now 'UTC', '%Y-%m-%d' %}" + builder = PromptBuilder(template=template) + + result = builder.run()["prompt"] + + now_formatted = f"Formatted date: {arrow.now('UTC').strftime('%Y-%m-%d')}" + + assert now_formatted == result + + def test_with_different_timezone(self) -> None: + template = "Current time in New York is: {% now 'America/New_York' %}" + builder = PromptBuilder(template=template) + + result = builder.run()["prompt"] + + now_ny = f"Current time in New York is: {arrow.now('America/New_York').strftime('%Y-%m-%d %H:%M:%S')}" + + assert now_ny == result + + def test_date_with_addition_offset(self) -> None: + template = "Time after 2 hours is: {% now 'UTC' + 'hours=2' %}" + builder = PromptBuilder(template=template) + + result = builder.run()["prompt"] + + now_plus_2 = f"Time after 2 hours is: {(arrow.now('UTC').shift(hours=+2)).strftime('%Y-%m-%d %H:%M:%S')}" + + assert now_plus_2 == result + + def test_date_with_substraction_offset(self) -> None: + template = "Time after 12 days is: {% now 'UTC' - 'days=12' %}" + builder = PromptBuilder(template=template) + + result = builder.run()["prompt"] + + now_plus_2 = f"Time after 12 days is: {(arrow.now('UTC').shift(days=-12)).strftime('%Y-%m-%d %H:%M:%S')}" + + assert now_plus_2 == result + + def test_invalid_timezone(self) -> None: + template = "Current time is: {% now 'Invalid/Timezone' %}" + builder = PromptBuilder(template=template) + + # Expect ValueError for invalid timezone + with pytest.raises(ValueError, match="Invalid timezone"): + builder.run() + + def test_invalid_offset(self) -> None: + template = "Time after invalid offset is: {% now 'UTC' + 'invalid_offset' %}" + builder = PromptBuilder(template=template) + + # Expect ValueError for invalid offset + with pytest.raises(ValueError, match="Invalid offset or operator"): + builder.run() diff --git a/testbed/deepset-ai__haystack/test/components/caching/test_url_cache_checker.py b/testbed/deepset-ai__haystack/test/components/caching/test_url_cache_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..60b72ff8966b844025697f088ec4baff7dd534ce --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/caching/test_url_cache_checker.py @@ -0,0 +1,93 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document, DeserializationError +from haystack.testing.factory import document_store_class +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack.components.caching.cache_checker import CacheChecker +from unittest.mock import MagicMock + + +class TestCacheChecker: + def test_to_dict(self): + mocked_docstore_class = document_store_class("MockedDocumentStore") + component = CacheChecker(document_store=mocked_docstore_class(), cache_field="url") + data = component.to_dict() + assert data == { + "type": "haystack.components.caching.cache_checker.CacheChecker", + "init_parameters": { + "document_store": {"type": "haystack.testing.factory.MockedDocumentStore", "init_parameters": {}}, + "cache_field": "url", + }, + } + + def test_to_dict_with_custom_init_parameters(self): + mocked_docstore_class = document_store_class("MockedDocumentStore") + component = CacheChecker(document_store=mocked_docstore_class(), cache_field="my_url_field") + data = component.to_dict() + assert data == { + "type": "haystack.components.caching.cache_checker.CacheChecker", + "init_parameters": { + "document_store": {"type": "haystack.testing.factory.MockedDocumentStore", "init_parameters": {}}, + "cache_field": "my_url_field", + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.caching.cache_checker.CacheChecker", + "init_parameters": { + "document_store": { + "type": "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore", + "init_parameters": {}, + }, + "cache_field": "my_url_field", + }, + } + component = CacheChecker.from_dict(data) + assert isinstance(component.document_store, InMemoryDocumentStore) + assert component.cache_field == "my_url_field" + + def test_from_dict_without_docstore(self): + data = {"type": "haystack.components.caching.cache_checker.CacheChecker", "init_parameters": {}} + with pytest.raises(DeserializationError, match="Missing 'document_store' in serialization data"): + CacheChecker.from_dict(data) + + def test_from_dict_without_docstore_type(self): + data = { + "type": "haystack.components.caching.cache_checker.UrlCacheChecker", + "init_parameters": {"document_store": {"init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + CacheChecker.from_dict(data) + + def test_from_dict_nonexisting_docstore(self): + data = { + "type": "haystack.components.caching.cache_checker.UrlCacheChecker", + "init_parameters": {"document_store": {"type": "Nonexisting.DocumentStore", "init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + CacheChecker.from_dict(data) + + def test_run(self): + docstore = InMemoryDocumentStore() + documents = [ + Document(content="doc1", meta={"url": "https://example.com/1"}), + Document(content="doc2", meta={"url": "https://example.com/2"}), + Document(content="doc3", meta={"url": "https://example.com/1"}), + Document(content="doc4", meta={"url": "https://example.com/2"}), + ] + docstore.write_documents(documents) + checker = CacheChecker(docstore, cache_field="url") + results = checker.run(items=["https://example.com/1", "https://example.com/5"]) + assert results == {"hits": [documents[0], documents[2]], "misses": ["https://example.com/5"]} + + def test_filters_syntax(self): + mocked_docstore_class = document_store_class("MockedDocumentStore") + mocked_docstore_class.filter_documents = MagicMock() + checker = CacheChecker(document_store=mocked_docstore_class(), cache_field="url") + checker.run(items=["https://example.com/1"]) + valid_filters_syntax = {"field": "url", "operator": "==", "value": "https://example.com/1"} + mocked_docstore_class.filter_documents.assert_any_call(filters=valid_filters_syntax) diff --git a/testbed/deepset-ai__haystack/test/components/classifiers/test_document_language_classifier.py b/testbed/deepset-ai__haystack/test/components/classifiers/test_document_language_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..9204b308807d3c79f1cd780cdd47dc0a806b8242 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/classifiers/test_document_language_classifier.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import pytest + +from haystack import Document +from haystack.components.classifiers import DocumentLanguageClassifier + + +class TestDocumentLanguageClassifier: + def test_init(self): + component = DocumentLanguageClassifier() + assert component.languages == ["en"] + + def test_non_document_input(self): + with pytest.raises(TypeError, match="DocumentLanguageClassifier expects a list of Document as input."): + classifier = DocumentLanguageClassifier() + classifier.run(documents="This is an english sentence.") + + def test_single_document(self): + with pytest.raises(TypeError, match="DocumentLanguageClassifier expects a list of Document as input."): + classifier = DocumentLanguageClassifier() + classifier.run(documents=Document(content="This is an english sentence.")) + + def test_empty_list(self): + classifier = DocumentLanguageClassifier() + result = classifier.run(documents=[]) + assert result == {"documents": []} + + def test_detect_language(self): + classifier = DocumentLanguageClassifier() + detected_language = classifier._detect_language(Document(content="This is an english sentence.")) + assert detected_language == "en" + + def test_classify_as_en_and_unmatched(self): + classifier = DocumentLanguageClassifier() + english_document = Document(content="This is an english sentence.") + german_document = Document(content="Ein deutscher Satz ohne Verb.") + result = classifier.run(documents=[english_document, german_document]) + assert result["documents"][0].meta["language"] == "en" + assert result["documents"][1].meta["language"] == "unmatched" + + def test_warning_if_no_language_detected(self, caplog): + with caplog.at_level(logging.WARNING): + classifier = DocumentLanguageClassifier() + classifier.run(documents=[Document(content=".")]) + assert "Langdetect cannot detect the language of Document with id" in caplog.text diff --git a/testbed/deepset-ai__haystack/test/components/connectors/test_openapi_service.py b/testbed/deepset-ai__haystack/test/components/connectors/test_openapi_service.py new file mode 100644 index 0000000000000000000000000000000000000000..82340bdd766fe1000d289f765dd7fd1f86e39c64 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/connectors/test_openapi_service.py @@ -0,0 +1,333 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import json +from unittest.mock import MagicMock, Mock, patch, PropertyMock + +import pytest +from openapi3 import OpenAPI +from openapi3.schemas import Model + +from haystack.components.connectors import OpenAPIServiceConnector +from haystack.dataclasses import ChatMessage + + +@pytest.fixture +def openapi_service_mock(): + return MagicMock(spec=OpenAPI) + + +class TestOpenAPIServiceConnector: + @pytest.fixture + def connector(self): + return OpenAPIServiceConnector() + + def test_parse_message_invalid_json(self, connector): + # Test invalid JSON content + with pytest.raises(ValueError): + connector._parse_message(ChatMessage.from_assistant("invalid json")) + + def test_parse_valid_json_message(self): + connector = OpenAPIServiceConnector() + + # The content format here is OpenAI function calling descriptor + content = ( + '[{"function":{"name": "compare_branches","arguments": "{\\n \\"parameters\\": {\\n ' + ' \\"basehead\\": \\"main...openapi_container_v5\\",\\n ' + ' \\"owner\\": \\"deepset-ai\\",\\n \\"repo\\": \\"haystack\\"\\n }\\n}"}, "type": "function"}]' + ) + descriptors = connector._parse_message(ChatMessage.from_assistant(content)) + + # Assert that the descriptor contains the expected method name and arguments + assert descriptors[0]["name"] == "compare_branches" + assert descriptors[0]["arguments"]["parameters"] == { + "basehead": "main...openapi_container_v5", + "owner": "deepset-ai", + "repo": "haystack", + } + # but not the requestBody + assert "requestBody" not in descriptors[0]["arguments"] + + # The content format here is OpenAI function calling descriptor + content = '[{"function": {"name": "search","arguments": "{\\n \\"requestBody\\": {\\n \\"q\\": \\"haystack\\"\\n }\\n}"}, "type": "function"}]' + descriptors = connector._parse_message(ChatMessage.from_assistant(content)) + assert descriptors[0]["name"] == "search" + assert descriptors[0]["arguments"]["requestBody"] == {"q": "haystack"} + + # but not the parameters + assert "parameters" not in descriptors[0]["arguments"] + + def test_parse_message_missing_fields(self, connector): + # Test JSON content with missing fields + with pytest.raises(ValueError): + connector._parse_message(ChatMessage.from_assistant('[{"function": {"name": "test_method"}}]')) + + def test_authenticate_service_missing_authentication_token(self, connector, openapi_service_mock): + security_schemes_dict = { + "components": {"securitySchemes": {"apiKey": {"in": "header", "name": "x-api-key", "type": "apiKey"}}} + } + openapi_service_mock.raw_element = security_schemes_dict + + with pytest.raises(ValueError): + connector._authenticate_service(openapi_service_mock) + + def test_authenticate_service_having_authentication_token(self, connector, openapi_service_mock): + security_schemes_dict = { + "components": {"securitySchemes": {"apiKey": {"in": "header", "name": "x-api-key", "type": "apiKey"}}} + } + openapi_service_mock.raw_element = security_schemes_dict + openapi_service_mock.components.securitySchemes.raw_element = { + "apiKey": {"in": "header", "name": "x-api-key", "type": "apiKey"} + } + connector._authenticate_service(openapi_service_mock, "some_fake_token") + + def test_authenticate_service_having_authentication_dict(self, connector, openapi_service_mock): + security_schemes_dict = { + "components": {"securitySchemes": {"apiKey": {"in": "header", "name": "x-api-key", "type": "apiKey"}}} + } + openapi_service_mock.raw_element = security_schemes_dict + openapi_service_mock.components.securitySchemes.raw_element = { + "apiKey": {"in": "header", "name": "x-api-key", "type": "apiKey"} + } + connector._authenticate_service(openapi_service_mock, {"apiKey": "some_fake_token"}) + + def test_authenticate_service_having_authentication_dict_but_unsupported_auth( + self, connector, openapi_service_mock + ): + security_schemes_dict = {"components": {"securitySchemes": {"oauth2": {"type": "oauth2"}}}} + openapi_service_mock.raw_element = security_schemes_dict + openapi_service_mock.components.securitySchemes.raw_element = {"oauth2": {"type": "oauth2"}} + with pytest.raises(ValueError): + connector._authenticate_service(openapi_service_mock, {"apiKey": "some_fake_token"}) + + def test_for_internal_raw_data_field(self): + # see https://github.com/deepset-ai/haystack/pull/6772 for details + model = Model(data={}, schema={}) + assert hasattr(model, "_raw_data"), ( + "openapi3 changed. Model should have a _raw_data field, we rely on it in OpenAPIServiceConnector" + " to get the raw data from the service response" + ) + + @patch("haystack.components.connectors.openapi_service.OpenAPI") + def test_run(self, openapi_mock, test_files_path): + connector = OpenAPIServiceConnector() + spec_path = test_files_path / "json" / "github_compare_branch_openapi_spec.json" + spec = json.loads((spec_path).read_text()) + + mock_message = json.dumps( + [ + { + "id": "call_NJr1NBz2Th7iUWJpRIJZoJIA", + "function": { + "arguments": '{"basehead": "main...some_branch", "owner": "deepset-ai", "repo": "haystack"}', + "name": "compare_branches", + }, + "type": "function", + } + ] + ) + messages = [ChatMessage.from_assistant(mock_message)] + call_compare_branches = Mock(return_value=Mock(_raw_data="some_data")) + call_compare_branches.operation.__self__ = Mock() + call_compare_branches.operation.__self__.raw_element = { + "parameters": [{"name": "basehead"}, {"name": "owner"}, {"name": "repo"}] + } + mock_service = Mock( + call_compare_branches=call_compare_branches, + components=Mock(securitySchemes=Mock(raw_element={"apikey": {"type": "apiKey"}})), + ) + openapi_mock.return_value = mock_service + + connector.run(messages=messages, service_openapi_spec=spec, service_credentials="fake_key") + + openapi_mock.assert_called_once_with(spec) + mock_service.authenticate.assert_called_once_with("apikey", "fake_key") + + # verify call went through on the wire with the correct parameters + mock_service.call_compare_branches.assert_called_once_with( + parameters={"basehead": "main...some_branch", "owner": "deepset-ai", "repo": "haystack"} + ) + + @patch("haystack.components.connectors.openapi_service.OpenAPI") + def test_run_with_mix_params_request_body(self, openapi_mock, test_files_path): + connector = OpenAPIServiceConnector() + spec_path = test_files_path / "yaml" / "openapi_greeting_service.yml" + with open(spec_path, "r") as file: + spec = json.loads(file.read()) + mock_message = json.dumps( + [ + { + "id": "call_NJr1NBz2Th7iUWJpRIJZoJIA", + "function": {"arguments": '{"name": "John", "message": "Hello"}', "name": "greet"}, + "type": "function", + } + ] + ) + call_greet = Mock(return_value=Mock(_raw_data="Hello, John")) + call_greet.operation.__self__ = Mock() + call_greet.operation.__self__.raw_element = { + "parameters": [{"name": "name"}], + "requestBody": { + "content": {"application/json": {"schema": {"properties": {"message": {"type": "string"}}}}} + }, + } + + mock_service = Mock(call_greet=call_greet) + mock_service.raw_element = {} + openapi_mock.return_value = mock_service + + messages = [ChatMessage.from_assistant(mock_message)] + result = connector.run(messages=messages, service_openapi_spec=spec) + + # verify call went through on the wire + mock_service.call_greet.assert_called_once_with(parameters={"name": "John"}, data={"message": "Hello"}) + + response = json.loads(result["service_response"][0].content) + assert response == "Hello, John" + + @patch("haystack.components.connectors.openapi_service.OpenAPI") + def test_run_with_complex_types(self, openapi_mock, test_files_path): + connector = OpenAPIServiceConnector() + spec_path = test_files_path / "json" / "complex_types_openapi_service.json" + with open(spec_path, "r") as file: + spec = json.loads(file.read()) + mock_message = json.dumps( + [ + { + "id": "call_NJr1NBz2Th7iUWJpRIJZoJIA", + "function": { + "arguments": '{"transaction_amount": 150.75, "description": "Monthly subscription fee", "payment_method_id": "visa_ending_in_1234", "payer": {"name": "Alex Smith", "email": "alex.smith@example.com", "identification": {"type": "Driver\'s License", "number": "D12345678"}}}', + "name": "processPayment", + }, + "type": "function", + } + ] + ) + + call_processPayment = Mock(return_value=Mock(_raw_data={"result": "accepted"})) + call_processPayment.operation.__self__ = Mock() + call_processPayment.operation.__self__.raw_element = { + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "transaction_amount": {"type": "number", "example": 150.75}, + "description": {"type": "string", "example": "Monthly subscription fee"}, + "payment_method_id": {"type": "string", "example": "visa_ending_in_1234"}, + "payer": { + "type": "object", + "properties": { + "name": {"type": "string", "example": "Alex Smith"}, + "email": {"type": "string", "example": "alex.smith@example.com"}, + "identification": { + "type": "object", + "properties": { + "type": {"type": "string", "example": "Driver's License"}, + "number": {"type": "string", "example": "D12345678"}, + }, + "required": ["type", "number"], + }, + }, + "required": ["name", "email", "identification"], + }, + }, + "required": ["transaction_amount", "description", "payment_method_id", "payer"], + } + } + } + } + } + mock_service = Mock(call_processPayment=call_processPayment) + mock_service.raw_element = {} + openapi_mock.return_value = mock_service + + messages = [ChatMessage.from_assistant(mock_message)] + result = connector.run(messages=messages, service_openapi_spec=spec) + + # verify call went through on the wire + mock_service.call_processPayment.assert_called_once_with( + data={ + "transaction_amount": 150.75, + "description": "Monthly subscription fee", + "payment_method_id": "visa_ending_in_1234", + "payer": { + "name": "Alex Smith", + "email": "alex.smith@example.com", + "identification": {"type": "Driver's License", "number": "D12345678"}, + }, + } + ) + + response = json.loads(result["service_response"][0].content) + assert response == {"result": "accepted"} + + @patch("haystack.components.connectors.openapi_service.OpenAPI") + def test_run_with_request_params_missing_in_invocation_args(self, openapi_mock, test_files_path): + connector = OpenAPIServiceConnector() + spec_path = test_files_path / "yaml" / "openapi_greeting_service.yml" + with open(spec_path, "r") as file: + spec = json.loads(file.read()) + mock_message = json.dumps( + [ + { + "id": "call_NJr1NBz2Th7iUWJpRIJZoJIA", + "function": {"arguments": '{"message": "Hello"}', "name": "greet"}, + "type": "function", + } + ] + ) + call_greet = Mock(return_value=Mock(_raw_data="Hello, John")) + call_greet.operation.__self__ = Mock() + call_greet.operation.__self__.raw_element = { + "parameters": [{"name": "name", "required": True}], + "requestBody": { + "content": {"application/json": {"schema": {"properties": {"message": {"type": "string"}}}}} + }, + } + + mock_service = Mock(call_greet=call_greet) + mock_service.raw_element = {} + openapi_mock.return_value = mock_service + + messages = [ChatMessage.from_assistant(mock_message)] + with pytest.raises(ValueError, match="Missing parameter: 'name' required for the 'greet' operation."): + connector.run(messages=messages, service_openapi_spec=spec) + + @patch("haystack.components.connectors.openapi_service.OpenAPI") + def test_run_with_body_properties_missing_in_invocation_args(self, openapi_mock, test_files_path): + connector = OpenAPIServiceConnector() + spec_path = test_files_path / "yaml" / "openapi_greeting_service.yml" + with open(spec_path, "r") as file: + spec = json.loads(file.read()) + mock_message = json.dumps( + [ + { + "id": "call_NJr1NBz2Th7iUWJpRIJZoJIA", + "function": {"arguments": '{"name": "John"}', "name": "greet"}, + "type": "function", + } + ] + ) + call_greet = Mock(return_value=Mock(_raw_data="Hello, John")) + call_greet.operation.__self__ = Mock() + call_greet.operation.__self__.raw_element = { + "parameters": [{"name": "name"}], + "requestBody": { + "content": { + "application/json": { + "schema": {"properties": {"message": {"type": "string"}}, "required": ["message"]} + } + } + }, + } + + mock_service = Mock(call_greet=call_greet) + mock_service.raw_element = {} + openapi_mock.return_value = mock_service + + messages = [ChatMessage.from_assistant(mock_message)] + with pytest.raises( + ValueError, match="Missing requestBody parameter: 'message' required for the 'greet' operation." + ): + connector.run(messages=messages, service_openapi_spec=spec) diff --git a/testbed/deepset-ai__haystack/test/components/converters/__init__.py b/testbed/deepset-ai__haystack/test/components/converters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_azure_ocr_doc_converter.py b/testbed/deepset-ai__haystack/test/components/converters/test_azure_ocr_doc_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba7d33f5a60df96a9ed87cac314d50f0304db5c --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_azure_ocr_doc_converter.py @@ -0,0 +1,331 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +# ruff: noqa: E501 +import json +import os +import os.path +from typing import Literal +from unittest.mock import patch + +import pandas as pd +import pytest +from azure.ai.formrecognizer import AnalyzeResult + +from haystack.components.converters.azure import AzureOCRDocumentConverter +from haystack.dataclasses.byte_stream import ByteStream +from haystack.utils import Secret + + +def get_sample_pdf_1_text(page_layout: Literal["natural", "single_column"]) -> str: + if page_layout == "natural": + return ( + "A sample PDF file\nHistory and standardization\nFormat (PDF) Adobe Systems made the PDF specification " + "available free of charge in 1993. In the early years PDF was popular mainly in desktop publishing " + "workflows, and competed with a variety of formats such as DjVu, Envoy, Common Ground Digital Paper, " + "Farallon Replica and even Adobe's own PostScript format. PDF was a proprietary format controlled by " + "Adobe until it was released as an open standard on July 1, 2008, and published by the International " + "Organization for Standardization as ISO 32000-1:2008, at which time control of the specification " + "passed to an ISO Committee of volunteer industry experts. In 2008, Adobe published a Public Patent " + "License to ISO 32000-1 granting royalty-free rights for all patents owned by Adobe that are necessary " + "to make, use, sell, and distribute PDF-compliant implementations. PDF 1.7, the sixth edition of the PDF " + "specification that became ISO 32000-1, includes some proprietary technologies defined only by Adobe, " + "such as Adobe XML Forms Architecture (XFA) and JavaScript extension for Acrobat, which are referenced " + "by ISO 32000-1 as normative and indispensable for the full implementation of the ISO 32000-1 " + "specification. These proprietary technologies are not standardized and their specification is published " + "only on Adobe's website. Many of them are also not supported by popular third-party implementations of " + "PDF.\n\x0cPage 2 of Sample PDF\n\x0c\x0cPage 4 of Sample PDF\n... the page 3 is empty.\n" + ) + else: + return ( + "A sample PDF file\nHistory and standardization\nFormat (PDF) Adobe Systems made the PDF specification " + "available free of\ncharge in 1993. In the early years PDF was popular mainly in desktop\npublishing " + "workflows, and competed with a variety of formats such as DjVu,\nEnvoy, Common Ground Digital Paper, " + "Farallon Replica and even Adobe's\nown PostScript format. PDF was a proprietary format controlled by " + "Adobe\nuntil it was released as an open standard on July 1, 2008, and published by\nthe International " + "Organization for Standardization as ISO 32000-1:2008, at\nwhich time control of the specification passed " + "to an ISO Committee of\nvolunteer industry experts. In 2008, Adobe published a Public Patent License\nto " + "ISO 32000-1 granting royalty-free rights for all patents owned by Adobe\nthat are necessary to make, use, " + "sell, and distribute PDF-compliant\nimplementations. PDF 1.7, the sixth edition of the PDF specification " + "that\nbecame ISO 32000-1, includes some proprietary technologies defined only by\nAdobe, such as Adobe " + "XML Forms Architecture (XFA) and JavaScript\nextension for Acrobat, which are referenced by ISO 32000-1 " + "as normative\nand indispensable for the full implementation of the ISO 32000-1\nspecification. These " + "proprietary technologies are not standardized and their\nspecification is published only on Adobe's " + "website. Many of them are also not\nsupported by popular third-party implementations of PDF.\n\x0cPage 2 " + "of Sample PDF\n\x0c\x0cPage 4 of Sample PDF\n... the page 3 is empty.\n" + ) + + +def get_sample_pdf_2_text(page_layout: Literal["natural", "single_column"]) -> str: + if page_layout == "natural": + return ( + "A Simple PDF File\nThis is a small demonstration .pdf file -\njust for use in the Virtual Mechanics " + "tutorials. More text. And more text. And more text. And more text. And more text.\nAnd more text. And more " + "text. And more text. And more text. And more text. And more text. Boring, zzzzz. And more text. And more " + "text. And more text. And more text. And more text. And more text. And more text. And more text. And more " + "text.\nAnd more text. And more text. And more text. And more text. And more text. And more text. And more " + "text. Even more. Continued on page 2 ...\n\x0cSimple PDF File 2\n... continued from page 1. Yet more text. " + "And more text. And more text. And more text. And more text. And more text. And more text. And more text. " + "Oh, how boring typing this stuff. But not as boring as watching paint dry. And more text. And more text. " + "And more text. And more text. Boring. More, a little more text. The end, and just as well.\n" + ) + else: + return ( + "A Simple PDF File\nThis is a small demonstration .pdf file -\njust for use in the Virtual Mechanics " + "tutorials. More text. And more\ntext. And more text. And more text. And more text.\nAnd more text. And " + "more text. And more text. And more text. And more\ntext. And more text. Boring, zzzzz. And more text. " + "And more text. And\nmore text. And more text. And more text. And more text. And more text.\nAnd more text. " + "And more text.\nAnd more text. And more text. And more text. And more text. And more\ntext. And more text. " + "And more text. Even more. Continued on page 2 ...\n\x0cSimple PDF File 2\n... continued from page 1. " + "Yet more text. And more text. And more text.\nAnd more text. And more text. And more text. And more text. " + "And more\ntext. Oh, how boring typing this stuff. But not as boring as watching\npaint dry. And more text. " + "And more text. And more text. And more text.\nBoring. More, a little more text. The end, and just as well.\n" + ) + + +class TestAzureOCRDocumentConverter: + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("AZURE_AI_API_KEY", raising=False) + with pytest.raises(ValueError): + AzureOCRDocumentConverter(endpoint="test_endpoint") + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_to_dict(self, mock_resolve_value): + mock_resolve_value.return_value = "test_api_key" + component = AzureOCRDocumentConverter(endpoint="test_endpoint") + data = component.to_dict() + assert data == { + "type": "haystack.components.converters.azure.AzureOCRDocumentConverter", + "init_parameters": { + "api_key": {"env_vars": ["AZURE_AI_API_KEY"], "strict": True, "type": "env_var"}, + "endpoint": "test_endpoint", + "following_context_len": 3, + "merge_multiple_column_headers": True, + "model_id": "prebuilt-read", + "page_layout": "natural", + "preceding_context_len": 3, + "threshold_y": 0.05, + }, + } + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_azure_converter_with_pdf(self, mock_resolve_value, test_files_path) -> None: + mock_resolve_value.return_value = "test_api_key" + + class MockPoller: + def result(self) -> AnalyzeResult: + with open(test_files_path / "json" / "azure_sample_pdf_2.json", encoding="utf-8") as azure_file: + result = json.load(azure_file) + return AnalyzeResult.from_dict(result) + + with patch("azure.ai.formrecognizer.DocumentAnalysisClient.begin_analyze_document") as azure_mock: + azure_mock.return_value = MockPoller() + ocr_node = AzureOCRDocumentConverter(endpoint="") + out = ocr_node.run(sources=[test_files_path / "pdf" / "sample_pdf_2.pdf"]) + assert len(out["documents"]) == 1 + assert out["documents"][0].content == get_sample_pdf_2_text(page_layout="natural") + assert out["documents"][0].content.count("\f") == 1 + + @pytest.mark.parametrize("page_layout", ["natural", "single_column"]) + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_azure_converter_with_table( + self, mock_resolve_value, page_layout: Literal["natural", "single_column"], test_files_path + ) -> None: + mock_resolve_value.return_value = "test_api_key" + + class MockPoller: + def result(self) -> AnalyzeResult: + with open(test_files_path / "json" / "azure_sample_pdf_1.json", encoding="utf-8") as azure_file: + result = json.load(azure_file) + return AnalyzeResult.from_dict(result) + + with patch("azure.ai.formrecognizer.DocumentAnalysisClient.begin_analyze_document") as azure_mock: + azure_mock.return_value = MockPoller() + ocr_node = AzureOCRDocumentConverter(endpoint="", page_layout=page_layout) + out = ocr_node.run(sources=[test_files_path / "pdf" / "sample_pdf_1.pdf"]) + + docs = out["documents"] + assert len(docs) == 2 + # Checking the table doc extracted + assert docs[0].content_type == "table" + assert docs[0].dataframe.shape[0] == 4 # number of rows + assert docs[0].dataframe.shape[1] == 4 # number of columns + assert list(docs[0].dataframe.columns) == ["", "Column 1", "Column 2", "Column 3"] + assert list(docs[0].dataframe.iloc[3]) == ["D", "$54.35", "$6345.", ""] + assert ( + docs[0].meta["preceding_context"] == "specification. These proprietary technologies are not " + "standardized and their\nspecification is published only on " + "Adobe's website. Many of them are also not\nsupported by " + "popular third-party implementations of PDF." + ) + assert docs[0].meta["following_context"] == "" + assert docs[0].meta["page"] == 1 + + # Checking the text extracted + assert docs[1].content_type == "text" + assert docs[1].content.startswith("A sample PDF file") + assert docs[1].content.count("\f") == 3 # There should be three page separations + pages = docs[1].content.split("\f") + gold_pages = get_sample_pdf_1_text(page_layout=page_layout).split("\f") + assert pages[0] == gold_pages[0] + assert pages[1] == gold_pages[1] + assert pages[2] == gold_pages[2] + assert pages[3] == gold_pages[3] + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_azure_converter_with_table_no_bounding_region(self, mock_resolve_value, test_files_path) -> None: + mock_resolve_value.return_value = "test_api_key" + + class MockPoller: + def result(self) -> AnalyzeResult: + with open(test_files_path / "json" / "azure_sample_pdf_1.json", encoding="utf-8") as azure_file: + result = json.load(azure_file) + return AnalyzeResult.from_dict(result) + + with patch("azure.ai.formrecognizer.DocumentAnalysisClient.begin_analyze_document") as azure_mock: + azure_mock.return_value = MockPoller() + ocr_node = AzureOCRDocumentConverter(endpoint="") + out = ocr_node.run(sources=[test_files_path / "pdf" / "sample_pdf_1.pdf"]) + + docs = out["documents"] + assert len(docs) == 2 + # Checking the table doc extracted that is missing bounding info + assert docs[0].content_type == "table" + assert docs[0].dataframe.shape[0] == 4 # number of rows + assert docs[0].dataframe.shape[1] == 4 # number of columns + assert list(docs[0].dataframe.columns) == ["", "Column 1", "Column 2", "Column 3"] + assert list(docs[0].dataframe.iloc[3]) == ["D", "$54.35", "$6345.", ""] + # TODO below assert fails + # assert docs[0].meta["preceding_context"] == "" + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_azure_converter_with_multicolumn_header_table(self, mock_resolve_value, test_files_path) -> None: + mock_resolve_value.return_value = "test_api_key" + + class MockPoller: + def result(self) -> AnalyzeResult: + with open(test_files_path / "json" / "azure_sample_pdf_3.json", encoding="utf-8") as azure_file: + result = json.load(azure_file) + return AnalyzeResult.from_dict(result) + + with patch("azure.ai.formrecognizer.DocumentAnalysisClient.begin_analyze_document") as azure_mock: + azure_mock.return_value = MockPoller() + ocr_node = AzureOCRDocumentConverter(endpoint="") + + # TODO: fails because of non-unique column names, azure_sample_pdf_3.json has duplicate column names + out = ocr_node.run(sources=[test_files_path / "pdf" / "sample_pdf_3.pdf"]) + + docs = out["documents"] + assert len(docs) == 2 + assert docs[0].content_type == "table" + assert docs[0].dataframe.shape[0] == 1 # number of rows + assert docs[0].dataframe.shape[1] == 3 # number of columns + assert list(docs[0].dataframe.columns) == ["This is a subheader", "This is a subheader", "This is a subheader"] + assert list(docs[0].dataframe.iloc[0]) == ["Value 1", "Value 2", "Val 3"] + assert ( + docs[0].meta["preceding_context"] + == "Table 1. This is an example table with two multicolumn headers\nHeader 1" + ) + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_table_pdf_with_non_empty_meta(self, mock_resolve_value, test_files_path) -> None: + mock_resolve_value.return_value = "test_api_key" + + class MockPoller: + def result(self) -> AnalyzeResult: + with open(test_files_path / "json" / "azure_sample_pdf_1.json", encoding="utf-8") as azure_file: + result = json.load(azure_file) + return AnalyzeResult.from_dict(result) + + with patch("azure.ai.formrecognizer.DocumentAnalysisClient.begin_analyze_document") as azure_mock: + azure_mock.return_value = MockPoller() + ocr_node = AzureOCRDocumentConverter(endpoint="") + out = ocr_node.run(sources=[test_files_path / "pdf" / "sample_pdf_1.pdf"], meta=[{"test": "value_1"}]) + + docs = out["documents"] + # TODO assert below changed from the original test + assert docs[1].meta["test"] == "value_1" + + @pytest.mark.integration + @pytest.mark.skipif(not os.environ.get("CORE_AZURE_CS_ENDPOINT", None), reason="Azure endpoint not available") + @pytest.mark.skipif(not os.environ.get("CORE_AZURE_CS_API_KEY", None), reason="Azure credentials not available") + @pytest.mark.flaky(reruns=5, reruns_delay=5) + def test_run_with_pdf_file(self, test_files_path): + component = AzureOCRDocumentConverter( + endpoint=os.environ["CORE_AZURE_CS_ENDPOINT"], api_key=Secret.from_env_var("CORE_AZURE_CS_API_KEY") + ) + output = component.run(sources=[test_files_path / "pdf" / "sample_pdf_1.pdf"]) + documents = output["documents"] + assert len(documents) == 1 + assert "A sample PDF file" in documents[0].content + assert "Page 2 of Sample PDF" in documents[0].content + assert "Page 4 of Sample PDF" in documents[0].content + + @pytest.mark.integration + @pytest.mark.skipif(not os.environ.get("CORE_AZURE_CS_ENDPOINT", None), reason="Azure endpoint not available") + @pytest.mark.skipif(not os.environ.get("CORE_AZURE_CS_API_KEY", None), reason="Azure credentials not available") + def test_with_image_file(self, test_files_path): + component = AzureOCRDocumentConverter( + endpoint=os.environ["CORE_AZURE_CS_ENDPOINT"], api_key=Secret.from_env_var("CORE_AZURE_CS_API_KEY") + ) + output = component.run(sources=[test_files_path / "images" / "haystack-logo.png"]) + documents = output["documents"] + assert len(documents) == 1 + assert "haystack" in documents[0].content + assert "by deepset" in documents[0].content + + @pytest.mark.integration + @pytest.mark.skipif(not os.environ.get("CORE_AZURE_CS_ENDPOINT", None), reason="Azure endpoint not available") + @pytest.mark.skipif(not os.environ.get("CORE_AZURE_CS_API_KEY", None), reason="Azure credentials not available") + def test_run_with_docx_file(self, test_files_path): + component = AzureOCRDocumentConverter( + endpoint=os.environ["CORE_AZURE_CS_ENDPOINT"], api_key=Secret.from_env_var("CORE_AZURE_CS_API_KEY") + ) + output = component.run(sources=[test_files_path / "docx" / "sample_docx.docx"]) + documents = output["documents"] + assert len(documents) == 1 + assert "Sample Docx File" in documents[0].content + assert "Now we are in Page 2" in documents[0].content + assert "Page 3 was empty this is page 4" in documents[0].content + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_hashing_dataframe(self, mock_resolve_value): + mock_resolve_value.return_value = "test_api_key" + component = AzureOCRDocumentConverter(endpoint="") + hash_length = 32 + + df = pd.DataFrame({"A": [1, 2, 3]}) + hash_string_1 = component._hash_dataframe(df) + assert len(hash_string_1) == hash_length + + df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) + hash_string_2 = component._hash_dataframe(df) + assert len(hash_string_2) == hash_length + + df = pd.DataFrame({"B": [4, 5, 6], "A": [1, 2, 3], "D": [7, 8, 9]}) + hash_string_3 = component._hash_dataframe(df) + assert len(hash_string_3) == hash_length + + # doesn't mean much, more for sanity check + assert hash_string_1 != hash_string_2 != hash_string_3 + + @patch("haystack.utils.auth.EnvVarSecret.resolve_value") + def test_meta_from_byte_stream(self, mock_resolve_value, test_files_path) -> None: + mock_resolve_value.return_value = "test_api_key" + + class MockPoller: + def result(self) -> AnalyzeResult: + with open(test_files_path / "json" / "azure_sample_pdf_1.json", encoding="utf-8") as azure_file: + result = json.load(azure_file) + return AnalyzeResult.from_dict(result) + + with patch("azure.ai.formrecognizer.DocumentAnalysisClient.begin_analyze_document") as azure_mock: + azure_mock.return_value = MockPoller() + ocr_node = AzureOCRDocumentConverter(endpoint="") + bytes = (test_files_path / "pdf" / "sample_pdf_1.pdf").read_bytes() + byte_stream = ByteStream(data=bytes, meta={"test_from": "byte_stream"}) + out = ocr_node.run(sources=[byte_stream], meta=[{"test": "value_1"}]) + + docs = out["documents"] + assert docs[1].meta["test"] == "value_1" + assert docs[1].meta["test_from"] == "byte_stream" diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_docx_file_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_docx_file_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..64dfaa79f4a681a303b377e31b04242fc686b624 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_docx_file_to_document.py @@ -0,0 +1,367 @@ +import json +import logging +import pytest +import csv +from io import StringIO + +from haystack import Document, Pipeline +from haystack.components.converters.docx import DOCXMetadata, DOCXToDocument, DOCXTableFormat +from haystack.dataclasses import ByteStream + + +@pytest.fixture +def docx_converter(): + return DOCXToDocument() + + +class TestDOCXToDocument: + def test_init(self, docx_converter): + assert isinstance(docx_converter, DOCXToDocument) + + def test_init_with_string(self): + converter = DOCXToDocument(table_format="markdown") + assert isinstance(converter, DOCXToDocument) + assert converter.table_format == DOCXTableFormat.MARKDOWN + + def test_init_with_invalid_string(self): + with pytest.raises(ValueError, match="Unknown table format 'invalid_format'"): + DOCXToDocument(table_format="invalid_format") + + def test_to_dict(self): + converter = DOCXToDocument() + data = converter.to_dict() + assert data == { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "csv"}, + } + + def test_to_dict_custom_parameters(self): + converter = DOCXToDocument(table_format="markdown") + data = converter.to_dict() + assert data == { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "markdown"}, + } + + converter = DOCXToDocument(table_format="csv") + data = converter.to_dict() + assert data == { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "csv"}, + } + + converter = DOCXToDocument(table_format=DOCXTableFormat.MARKDOWN) + data = converter.to_dict() + assert data == { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "markdown"}, + } + + converter = DOCXToDocument(table_format=DOCXTableFormat.CSV) + data = converter.to_dict() + assert data == { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "csv"}, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "csv"}, + } + converter = DOCXToDocument.from_dict(data) + assert converter.table_format == DOCXTableFormat.CSV + + def test_from_dict_custom_parameters(self): + data = { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "markdown"}, + } + converter = DOCXToDocument.from_dict(data) + assert converter.table_format == DOCXTableFormat.MARKDOWN + + def test_from_dict_invalid_table_format(self): + data = { + "type": "haystack.components.converters.docx.DOCXToDocument", + "init_parameters": {"table_format": "invalid_format"}, + } + with pytest.raises(ValueError, match="Unknown table format 'invalid_format'"): + DOCXToDocument.from_dict(data) + + def test_from_dict_empty_init_parameters(self): + data = {"type": "haystack.components.converters.docx.DOCXToDocument", "init_parameters": {}} + converter = DOCXToDocument.from_dict(data) + assert converter.table_format == DOCXTableFormat.CSV + + def test_pipeline_serde(self): + pipeline = Pipeline() + converter = DOCXToDocument(table_format=DOCXTableFormat.MARKDOWN) + pipeline.add_component("converter", converter) + + pipeline_str = pipeline.dumps() + assert "haystack.components.converters.docx.DOCXToDocument" in pipeline_str + assert "table_format" in pipeline_str + assert "markdown" in pipeline_str + + new_pipeline = Pipeline.loads(pipeline_str) + new_converter = new_pipeline.get_component("converter") + assert isinstance(new_converter, DOCXToDocument) + assert new_converter.table_format == DOCXTableFormat.MARKDOWN + + def test_run(self, test_files_path, docx_converter): + """ + Test if the component runs correctly + """ + paths = [test_files_path / "docx" / "sample_docx_1.docx"] + output = docx_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 1 + assert "History" in docs[0].content + assert docs[0].meta.keys() == {"file_path", "docx"} + assert docs[0].meta == { + "file_path": str(paths[0]), + "docx": DOCXMetadata( + author="Microsoft Office User", + category="", + comments="", + content_status="", + created="2024-06-09T21:17:00+00:00", + identifier="", + keywords="", + language="", + last_modified_by="Carlos Fernández Lorán", + last_printed=None, + modified="2024-06-09T21:27:00+00:00", + revision=2, + subject="", + title="", + version="", + ), + } + + def test_run_with_table(self, test_files_path): + """ + Test if the component runs correctly + """ + docx_converter = DOCXToDocument(table_format=DOCXTableFormat.MARKDOWN) + paths = [test_files_path / "docx" / "sample_docx.docx"] + output = docx_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 1 + assert "Donald Trump" in docs[0].content ## :-) + assert docs[0].meta.keys() == {"file_path", "docx"} + assert docs[0].meta == { + "file_path": str(paths[0]), + "docx": DOCXMetadata( + author="Saha, Anirban", + category="", + comments="", + content_status="", + created="2020-07-14T08:14:00+00:00", + identifier="", + keywords="", + language="", + last_modified_by="Saha, Anirban", + last_printed=None, + modified="2020-07-14T08:16:00+00:00", + revision=1, + subject="", + title="", + version="", + ), + } + # let's now detect that the table markdown is correctly added and that order of elements is correct + content_parts = docs[0].content.split("\n\n") + table_index = next(i for i, part in enumerate(content_parts) if "| This | Is | Just a |" in part) + # check that natural order of the document is preserved + assert any("Donald Trump" in part for part in content_parts[:table_index]), "Text before table not found" + assert any( + "Now we are in Page 2" in part for part in content_parts[table_index + 1 :] + ), "Text after table not found" + + @pytest.mark.parametrize("table_format", ["markdown", "csv"]) + def test_table_between_two_paragraphs(self, test_files_path, table_format): + docx_converter = DOCXToDocument(table_format=table_format) + paths = [test_files_path / "docx" / "sample_docx_3.docx"] + output = docx_converter.run(sources=paths) + + content = output["documents"][0].content + + paragraphs_one = content.find("Table: AI Use Cases in Different Industries") + paragraphs_two = content.find("Paragraph 2:") + table = content[ + paragraphs_one + len("Table: AI Use Cases in Different Industries") + 1 : paragraphs_two + ].strip() + + if table_format == "markdown": + split = list(filter(None, table.split("\n"))) + expected_table_header = "| Industry | AI Use Case | Impact |" + expected_last_row = "| Finance | Fraud detection and prevention | Reduced financial losses |" + + assert split[0] == expected_table_header + assert split[-1] == expected_last_row + if table_format == "csv": # CSV format + csv_reader = csv.reader(StringIO(table)) + rows = list(csv_reader) + assert len(rows) == 3 # Header + 2 data rows + assert rows[0] == ["Industry", "AI Use Case", "Impact"] + assert rows[-1] == ["Finance", "Fraud detection and prevention", "Reduced financial losses"] + + @pytest.mark.parametrize("table_format", ["markdown", "csv"]) + def test_table_content_correct_parsing(self, test_files_path, table_format): + docx_converter = DOCXToDocument(table_format=table_format) + paths = [test_files_path / "docx" / "sample_docx_3.docx"] + output = docx_converter.run(sources=paths) + content = output["documents"][0].content + + paragraphs_one = content.find("Table: AI Use Cases in Different Industries") + paragraphs_two = content.find("Paragraph 2:") + table = content[ + paragraphs_one + len("Table: AI Use Cases in Different Industries") + 1 : paragraphs_two + ].strip() + + if table_format == "markdown": + split = list(filter(None, table.split("\n"))) + assert len(split) == 4 + + expected_table_header = "| Industry | AI Use Case | Impact |" + expected_table_top_border = "| ---------- | ------------------------------ | ------------------------- |" + expected_table_row_one = "| Healthcare | Predictive diagnostics | Improved patient outcomes |" + expected_table_row_two = "| Finance | Fraud detection and prevention | Reduced financial losses |" + + assert split[0] == expected_table_header + assert split[1] == expected_table_top_border + assert split[2] == expected_table_row_one + assert split[3] == expected_table_row_two + if table_format == "csv": # CSV format + csv_reader = csv.reader(StringIO(table)) + rows = list(csv_reader) + assert len(rows) == 3 # Header + 2 data rows + + expected_header = ["Industry", "AI Use Case", "Impact"] + expected_row_one = ["Healthcare", "Predictive diagnostics", "Improved patient outcomes"] + expected_row_two = ["Finance", "Fraud detection and prevention", "Reduced financial losses"] + + assert rows[0] == expected_header + assert rows[1] == expected_row_one + assert rows[2] == expected_row_two + + def test_run_with_additional_meta(self, test_files_path, docx_converter): + paths = [test_files_path / "docx" / "sample_docx_1.docx"] + output = docx_converter.run(sources=paths, meta={"language": "it", "author": "test_author"}) + doc = output["documents"][0] + assert doc.meta == { + "file_path": str(paths[0]), + "docx": DOCXMetadata( + author="Microsoft Office User", + category="", + comments="", + content_status="", + created="2024-06-09T21:17:00+00:00", + identifier="", + keywords="", + language="", + last_modified_by="Carlos Fernández Lorán", + last_printed=None, + modified="2024-06-09T21:27:00+00:00", + revision=2, + subject="", + title="", + version="", + ), + "language": "it", + "author": "test_author", + } + + def test_run_error_wrong_file_type(self, caplog, test_files_path, docx_converter): + sources = [str(test_files_path / "txt" / "doc_1.txt")] + with caplog.at_level(logging.WARNING): + results = docx_converter.run(sources=sources) + assert "doc_1.txt and convert it" in caplog.text + assert results["documents"] == [] + + def test_run_error_non_existent_file(self, docx_converter, caplog): + """ + Test if the component correctly handles errors. + """ + paths = ["non_existing_file.docx"] + with caplog.at_level(logging.WARNING): + docx_converter.run(sources=paths) + assert "Could not read non_existing_file.docx" in caplog.text + + def test_run_page_breaks(self, test_files_path, docx_converter): + """ + Test if the component correctly parses page breaks. + """ + paths = [test_files_path / "docx" / "sample_docx_2_page_breaks.docx"] + output = docx_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 1 + assert docs[0].content.count("\f") == 4 + + def test_mixed_sources_run(self, test_files_path, docx_converter): + """ + Test if the component runs correctly when mixed sources are provided. + """ + paths = [test_files_path / "docx" / "sample_docx_1.docx"] + with open(test_files_path / "docx" / "sample_docx_1.docx", "rb") as f: + paths.append(ByteStream(f.read())) + + output = docx_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 2 + assert "History and standardization" in docs[0].content + assert "History and standardization" in docs[1].content + + def test_document_with_docx_metadata_to_dict(self): + docx_metadata = DOCXMetadata( + author="Microsoft Office User", + category="category", + comments="comments", + content_status="", + created="2024-06-09T21:17:00+00:00", + identifier="", + keywords="", + language="", + last_modified_by="Carlos Fernández Lorán", + last_printed=None, + modified="2024-06-09T21:27:00+00:00", + revision=2, + subject="", + title="", + version="", + ) + doc = Document(content="content", meta={"test": 1, "docx": docx_metadata}, id="1") + assert doc.to_dict(flatten=False) == { + "blob": None, + "dataframe": None, + "content": "content", + "id": "1", + "score": None, + "embedding": None, + "sparse_embedding": None, + "meta": { + "test": 1, + "docx": { + "author": "Microsoft Office User", + "category": "category", + "comments": "comments", + "content_status": "", + "created": "2024-06-09T21:17:00+00:00", + "identifier": "", + "keywords": "", + "language": "", + "last_modified_by": "Carlos Fernández Lorán", + "last_printed": None, + "modified": "2024-06-09T21:27:00+00:00", + "revision": 2, + "subject": "", + "title": "", + "version": "", + }, + }, + } + + # check it is JSON serializable + json_str = json.dumps(doc.to_dict(flatten=False)) + assert json.loads(json_str) == doc.to_dict(flatten=False) diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_html_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_html_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..85c0ffd710ab576f04b382a3cd59ae7858afcac9 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_html_to_document.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from pathlib import Path + +import pytest +from unittest.mock import patch + +from haystack.components.converters import HTMLToDocument +from haystack.dataclasses import ByteStream + + +class TestHTMLToDocument: + def test_run(self, test_files_path): + """ + Test if the component runs correctly. + """ + sources = [test_files_path / "html" / "what_is_haystack.html"] + converter = HTMLToDocument() + results = converter.run(sources=sources, meta={"test": "TEST"}) + docs = results["documents"] + assert len(docs) == 1 + assert "Haystack" in docs[0].content + assert docs[0].meta["test"] == "TEST" + + def test_run_doc_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is supplied by the user. + """ + converter = HTMLToDocument() + sources = [test_files_path / "html" / "what_is_haystack.html"] + metadata = [{"file_name": "what_is_haystack.html"}] + results = converter.run(sources=sources, meta=metadata) + docs = results["documents"] + + assert len(docs) == 1 + assert "Haystack" in docs[0].content + assert docs[0].meta["file_name"] == "what_is_haystack.html" + + def test_incorrect_meta(self, test_files_path): + """ + Test if the component raises an error when incorrect metadata is supplied by the user. + """ + converter = HTMLToDocument() + sources = [test_files_path / "html" / "what_is_haystack.html"] + metadata = [{"file_name": "what_is_haystack.html"}, {"file_name": "haystack.html"}] + with pytest.raises(ValueError, match="The length of the metadata list must match the number of sources."): + converter.run(sources=sources, meta=metadata) + + def test_run_bytestream_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is read from the ByteStream object. + """ + converter = HTMLToDocument() + with open(test_files_path / "html" / "what_is_haystack.html", "rb") as file: + byte_stream = file.read() + stream = ByteStream(byte_stream, meta={"content_type": "text/html", "url": "test_url"}) + + results = converter.run(sources=[stream]) + docs = results["documents"] + + assert len(docs) == 1 + assert "Haystack" in docs[0].content + assert docs[0].meta == {"content_type": "text/html", "url": "test_url"} + + def test_run_bytestream_and_doc_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is read from the ByteStream object and supplied by the user. + + There is no overlap between the metadata received. + """ + converter = HTMLToDocument() + with open(test_files_path / "html" / "what_is_haystack.html", "rb") as file: + byte_stream = file.read() + stream = ByteStream(byte_stream, meta={"content_type": "text/html", "url": "test_url"}) + + metadata = [{"file_name": "what_is_haystack.html"}] + results = converter.run(sources=[stream], meta=metadata) + docs = results["documents"] + + assert len(docs) == 1 + assert "Haystack" in docs[0].content + assert docs[0].meta == {"file_name": "what_is_haystack.html", "content_type": "text/html", "url": "test_url"} + + def test_run_bytestream_doc_overlapping_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is read from the ByteStream object and supplied by the user. + + There is an overlap between the metadata received. + + The component should use the supplied metadata to overwrite the values if there is an overlap between the keys. + """ + converter = HTMLToDocument() + with open(test_files_path / "html" / "what_is_haystack.html", "rb") as file: + byte_stream = file.read() + # ByteStream has "url" present in metadata + stream = ByteStream(byte_stream, meta={"content_type": "text/html", "url": "test_url_correct"}) + + # "url" supplied by the user overwrites value present in metadata + metadata = [{"file_name": "what_is_haystack.html", "url": "test_url_new"}] + results = converter.run(sources=[stream], meta=metadata) + docs = results["documents"] + + assert len(docs) == 1 + assert "Haystack" in docs[0].content + assert docs[0].meta == { + "file_name": "what_is_haystack.html", + "content_type": "text/html", + "url": "test_url_new", + } + + def test_run_wrong_file_type(self, test_files_path, caplog): + """ + Test if the component runs correctly when an input file is not of the expected type. + """ + sources = [test_files_path / "audio" / "answer.wav"] + converter = HTMLToDocument() + with caplog.at_level(logging.WARNING): + results = converter.run(sources=sources) + assert "Failed to extract text from" in caplog.text + + assert results["documents"] == [] + + def test_run_error_handling(self, caplog): + """ + Test if the component correctly handles errors. + """ + sources = ["non_existing_file.html"] + converter = HTMLToDocument() + with caplog.at_level(logging.WARNING): + results = converter.run(sources=sources) + assert "Could not read non_existing_file.html" in caplog.text + assert results["documents"] == [] + + def test_mixed_sources_run(self, test_files_path): + """ + Test if the component runs correctly if the input is a mix of paths and ByteStreams. + """ + sources = [ + test_files_path / "html" / "what_is_haystack.html", + str((test_files_path / "html" / "what_is_haystack.html").absolute()), + ] + with open(test_files_path / "html" / "what_is_haystack.html", "rb") as f: + byte_stream = f.read() + sources.append(ByteStream(byte_stream)) + + converter = HTMLToDocument() + results = converter.run(sources=sources) + docs = results["documents"] + assert len(docs) == 3 + for doc in docs: + assert "Haystack" in doc.content + + def test_serde(self): + """ + Test if the component runs correctly gets serialized and deserialized. + """ + converter = HTMLToDocument() + serde_data = converter.to_dict() + new_converter = HTMLToDocument.from_dict(serde_data) + assert new_converter.extraction_kwargs == converter.extraction_kwargs + + def test_run_difficult_html(self, test_files_path): + converter = HTMLToDocument() + result = converter.run(sources=[Path(test_files_path / "html" / "paul_graham_superlinear.html")]) + + assert len(result["documents"]) == 1 + assert "Superlinear" in result["documents"][0].content + + @patch("haystack.components.converters.html.extract") + def test_run_with_extraction_kwargs(self, mock_extract, test_files_path): + sources = [test_files_path / "html" / "what_is_haystack.html"] + + converter = HTMLToDocument() + converter.run(sources=sources) + assert mock_extract.call_count == 1 + assert "favor_precision" not in mock_extract.call_args[1] + + precise_converter = HTMLToDocument(extraction_kwargs={"favor_precision": True}) + mock_extract.reset_mock() + precise_converter.run(sources=sources) + assert mock_extract.call_count == 1 + assert mock_extract.call_args[1]["favor_precision"] is True diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_json.py b/testbed/deepset-ai__haystack/test/components/converters/test_json.py new file mode 100644 index 0000000000000000000000000000000000000000..fe43044f749dc63943ccfdd418d9c75957e6658e --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_json.py @@ -0,0 +1,433 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +from unittest.mock import patch +from pathlib import Path +import logging + +import pytest + +from haystack.components.converters import JSONConverter +from haystack.dataclasses import ByteStream + + +test_data = [ + { + "year": "1997", + "category": "literature", + "laureates": [ + { + "id": "674", + "firstname": "Dario", + "surname": "Fo", + "motivation": "who emulates the jesters of the Middle Ages in scourging authority and upholding the dignity of the downtrodden", + "share": "1", + } + ], + }, + { + "year": "1986", + "category": "medicine", + "laureates": [ + { + "id": "434", + "firstname": "Stanley", + "surname": "Cohen", + "motivation": "for their discoveries of growth factors", + "share": "2", + }, + { + "id": "435", + "firstname": "Rita", + "surname": "Levi-Montalcini", + "motivation": "for their discoveries of growth factors", + "share": "2", + }, + ], + }, + { + "year": "1938", + "category": "physics", + "laureates": [ + { + "id": "46", + "firstname": "Enrico", + "surname": "Fermi", + "motivation": "for his demonstrations of the existence of new radioactive elements produced by neutron irradiation, and for his related discovery of nuclear reactions brought about by slow neutrons", + "share": "1", + } + ], + }, +] + + +def test_init_without_jq_schema_and_content_key(): + with pytest.raises( + ValueError, match="No `jq_schema` nor `content_key` specified. Set either or both to extract data." + ): + JSONConverter() + + +@patch("haystack.components.converters.json.jq_import") +def test_init_without_jq_schema_and_missing_dependency(jq_import): + converter = JSONConverter(content_key="foo") + jq_import.check.assert_not_called() + assert converter._jq_schema is None + assert converter._content_key == "foo" + assert converter._meta_fields is None + + +@patch("haystack.components.converters.json.jq_import") +def test_init_with_jq_schema_and_missing_dependency(jq_import): + jq_import.check.side_effect = ImportError + with pytest.raises(ImportError): + JSONConverter(jq_schema=".laureates[].motivation") + + +def test_init_with_jq_schema(): + converter = JSONConverter(jq_schema=".") + assert converter._jq_schema == "." + assert converter._content_key is None + assert converter._meta_fields is None + + +def test_to_dict(): + converter = JSONConverter( + jq_schema=".laureates[]", content_key="motivation", extra_meta_fields={"firstname", "surname"} + ) + + assert converter.to_dict() == { + "type": "haystack.components.converters.json.JSONConverter", + "init_parameters": { + "content_key": "motivation", + "jq_schema": ".laureates[]", + "extra_meta_fields": {"firstname", "surname"}, + }, + } + + +def test_from_dict(): + data = { + "type": "haystack.components.converters.json.JSONConverter", + "init_parameters": { + "content_key": "motivation", + "jq_schema": ".laureates[]", + "extra_meta_fields": ["firstname", "surname"], + }, + } + converter = JSONConverter.from_dict(data) + + assert converter._jq_schema == ".laureates[]" + assert converter._content_key == "motivation" + assert converter._meta_fields == ["firstname", "surname"] + + +def test_run(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + + converter = JSONConverter(jq_schema='.laureates[] | .firstname + " " + .surname + " " + .motivation') + result = converter.run(sources=sources) + assert len(result) == 1 + assert len(result["documents"]) == 4 + assert ( + result["documents"][0].content + == "Dario Fo who emulates the jesters of the Middle Ages in scourging authority and " + "upholding the dignity of the downtrodden" + ) + assert result["documents"][0].meta == {"file_path": str(first_test_file)} + assert result["documents"][1].content == "Stanley Cohen for their discoveries of growth factors" + assert result["documents"][1].meta == {"file_path": str(second_test_file)} + assert result["documents"][2].content == "Rita Levi-Montalcini for their discoveries of growth factors" + assert result["documents"][2].meta == {"file_path": str(second_test_file)} + assert ( + result["documents"][3].content == "Enrico Fermi for his demonstrations of the existence of new " + "radioactive elements produced by neutron irradiation, and for his related discovery of nuclear " + "reactions brought about by slow neutrons" + ) + assert result["documents"][3].meta == {} + + +def test_run_with_non_json_file(tmpdir, caplog): + test_file = Path(tmpdir / "test_file.md") + test_file.write_text("This is not a JSON file.", "utf-8") + + sources = [test_file] + converter = JSONConverter(".laureates | .motivation") + + caplog.clear() + with caplog.at_level(logging.WARNING): + result = converter.run(sources=sources) + + records = caplog.records + assert len(records) == 1 + assert ( + records[0].msg + == f"Failed to extract text from {test_file}. Skipping it. Error: parse error: Invalid numeric literal at line 1, column 5" + ) + assert result == {"documents": []} + + +def test_run_with_bad_filter(tmpdir, caplog): + test_file = Path(tmpdir / "test_file.json") + test_file.write_text(json.dumps(test_data[0]), "utf-8") + + sources = [test_file] + converter = JSONConverter(".laureates | .motivation") + + caplog.clear() + with caplog.at_level(logging.WARNING): + result = converter.run(sources=sources) + + records = caplog.records + assert len(records) == 1 + assert ( + records[0].msg + == f'Failed to extract text from {test_file}. Skipping it. Error: Cannot index array with string "motivation"' + ) + assert result == {"documents": []} + + +def test_run_with_single_meta(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + meta = {"creation_date": "1945-05-25T00:00:00"} + converter = JSONConverter(jq_schema='.laureates[] | .firstname + " " + .surname + " " + .motivation') + result = converter.run(sources=sources, meta=meta) + assert len(result) == 1 + assert len(result["documents"]) == 4 + assert ( + result["documents"][0].content + == "Dario Fo who emulates the jesters of the Middle Ages in scourging authority and " + "upholding the dignity of the downtrodden" + ) + assert result["documents"][0].meta == {"file_path": str(first_test_file), "creation_date": "1945-05-25T00:00:00"} + assert result["documents"][1].content == "Stanley Cohen for their discoveries of growth factors" + assert result["documents"][1].meta == {"file_path": str(second_test_file), "creation_date": "1945-05-25T00:00:00"} + assert result["documents"][2].content == "Rita Levi-Montalcini for their discoveries of growth factors" + assert result["documents"][2].meta == {"file_path": str(second_test_file), "creation_date": "1945-05-25T00:00:00"} + assert ( + result["documents"][3].content == "Enrico Fermi for his demonstrations of the existence of new " + "radioactive elements produced by neutron irradiation, and for his related discovery of nuclear " + "reactions brought about by slow neutrons" + ) + assert result["documents"][3].meta == {"creation_date": "1945-05-25T00:00:00"} + + +def test_run_with_meta_list(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + meta = [ + {"creation_date": "1945-05-25T00:00:00"}, + {"creation_date": "1943-09-03T00:00:00"}, + {"creation_date": "1989-11-09T00:00:00"}, + ] + converter = JSONConverter(jq_schema='.laureates[] | .firstname + " " + .surname + " " + .motivation') + result = converter.run(sources=sources, meta=meta) + assert len(result) == 1 + assert len(result["documents"]) == 4 + assert ( + result["documents"][0].content + == "Dario Fo who emulates the jesters of the Middle Ages in scourging authority and " + "upholding the dignity of the downtrodden" + ) + assert result["documents"][0].meta == {"file_path": str(first_test_file), "creation_date": "1945-05-25T00:00:00"} + assert result["documents"][1].content == "Stanley Cohen for their discoveries of growth factors" + assert result["documents"][1].meta == {"file_path": str(second_test_file), "creation_date": "1943-09-03T00:00:00"} + assert result["documents"][2].content == "Rita Levi-Montalcini for their discoveries of growth factors" + assert result["documents"][2].meta == {"file_path": str(second_test_file), "creation_date": "1943-09-03T00:00:00"} + assert ( + result["documents"][3].content == "Enrico Fermi for his demonstrations of the existence of new " + "radioactive elements produced by neutron irradiation, and for his related discovery of nuclear " + "reactions brought about by slow neutrons" + ) + assert result["documents"][3].meta == {"creation_date": "1989-11-09T00:00:00"} + + +def test_run_with_meta_list_of_differing_length(tmpdir): + sources = ["random_file.json"] + + meta = [{}, {}] + converter = JSONConverter(jq_schema=".") + with pytest.raises(ValueError, match="The length of the metadata list must match the number of sources."): + converter.run(sources=sources, meta=meta) + + +def test_run_with_jq_schema_and_content_key(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + converter = JSONConverter(jq_schema=".laureates[]", content_key="motivation") + result = converter.run(sources=sources) + assert len(result) == 1 + assert len(result["documents"]) == 4 + assert ( + result["documents"][0].content == "who emulates the jesters of the Middle Ages in scourging authority and " + "upholding the dignity of the downtrodden" + ) + assert result["documents"][0].meta == {"file_path": str(first_test_file)} + assert result["documents"][1].content == "for their discoveries of growth factors" + assert result["documents"][1].meta == {"file_path": str(second_test_file)} + assert result["documents"][2].content == "for their discoveries of growth factors" + assert result["documents"][2].meta == {"file_path": str(second_test_file)} + assert ( + result["documents"][3].content == "for his demonstrations of the existence of new " + "radioactive elements produced by neutron irradiation, and for his related discovery of nuclear " + "reactions brought about by slow neutrons" + ) + assert result["documents"][3].meta == {} + + +def test_run_with_jq_schema_content_key_and_extra_meta_fields(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + converter = JSONConverter( + jq_schema=".laureates[]", content_key="motivation", extra_meta_fields={"firstname", "surname"} + ) + result = converter.run(sources=sources) + assert len(result) == 1 + assert len(result["documents"]) == 4 + assert ( + result["documents"][0].content == "who emulates the jesters of the Middle Ages in scourging authority and " + "upholding the dignity of the downtrodden" + ) + assert result["documents"][0].meta == {"file_path": str(first_test_file), "firstname": "Dario", "surname": "Fo"} + assert result["documents"][1].content == "for their discoveries of growth factors" + assert result["documents"][1].meta == { + "file_path": str(second_test_file), + "firstname": "Stanley", + "surname": "Cohen", + } + assert result["documents"][2].content == "for their discoveries of growth factors" + assert result["documents"][2].meta == { + "file_path": str(second_test_file), + "firstname": "Rita", + "surname": "Levi-Montalcini", + } + assert ( + result["documents"][3].content == "for his demonstrations of the existence of new " + "radioactive elements produced by neutron irradiation, and for his related discovery of nuclear " + "reactions brought about by slow neutrons" + ) + assert result["documents"][3].meta == {"firstname": "Enrico", "surname": "Fermi"} + + +def test_run_with_content_key(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + converter = JSONConverter(content_key="category") + result = converter.run(sources=sources) + assert len(result) == 1 + assert len(result["documents"]) == 3 + assert result["documents"][0].content == "literature" + assert result["documents"][0].meta == {"file_path": str(first_test_file)} + assert result["documents"][1].content == "medicine" + assert result["documents"][1].meta == {"file_path": str(second_test_file)} + assert result["documents"][2].content == "physics" + assert result["documents"][2].meta == {} + + +def test_run_with_content_key_and_extra_meta_fields(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + converter = JSONConverter(content_key="category", extra_meta_fields={"year"}) + result = converter.run(sources=sources) + assert len(result) == 1 + assert len(result["documents"]) == 3 + assert result["documents"][0].content == "literature" + assert result["documents"][0].meta == {"file_path": str(first_test_file), "year": "1997"} + assert result["documents"][1].content == "medicine" + assert result["documents"][1].meta == {"file_path": str(second_test_file), "year": "1986"} + assert result["documents"][2].content == "physics" + assert result["documents"][2].meta == {"year": "1938"} + + +def test_run_with_jq_schema_content_key_and_extra_meta_fields_literal(tmpdir): + first_test_file = Path(tmpdir / "first_test_file.json") + second_test_file = Path(tmpdir / "second_test_file.json") + + first_test_file.write_text(json.dumps(test_data[0]), "utf-8") + second_test_file.write_text(json.dumps(test_data[1]), "utf-8") + byte_stream = ByteStream.from_string(json.dumps(test_data[2])) + + sources = [str(first_test_file), second_test_file, byte_stream] + converter = JSONConverter(jq_schema=".laureates[]", content_key="motivation", extra_meta_fields="*") + result = converter.run(sources=sources) + assert len(result) == 1 + assert len(result["documents"]) == 4 + assert ( + result["documents"][0].content + == "who emulates the jesters of the Middle Ages in scourging authority and upholding the dignity of the downtrodden" + ) + assert result["documents"][0].meta == { + "file_path": str(first_test_file), + "id": "674", + "firstname": "Dario", + "surname": "Fo", + "share": "1", + } + assert result["documents"][1].content == "for their discoveries of growth factors" + assert result["documents"][1].meta == { + "file_path": str(second_test_file), + "id": "434", + "firstname": "Stanley", + "surname": "Cohen", + "share": "2", + } + assert result["documents"][2].content == "for their discoveries of growth factors" + assert result["documents"][2].meta == { + "file_path": str(second_test_file), + "id": "435", + "firstname": "Rita", + "surname": "Levi-Montalcini", + "share": "2", + } + assert ( + result["documents"][3].content + == "for his demonstrations of the existence of new radioactive elements produced by neutron irradiation, " + "and for his related discovery of nuclear reactions brought about by slow neutrons" + ) + assert result["documents"][3].meta == {"id": "46", "firstname": "Enrico", "surname": "Fermi", "share": "1"} diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_markdown_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_markdown_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..302cc10434a0e4e7406ffdc6ec4aca36916d2ce4 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_markdown_to_document.py @@ -0,0 +1,109 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +from unittest.mock import patch +import pytest + +from haystack.components.converters.markdown import MarkdownToDocument +from haystack.dataclasses import ByteStream + + +@pytest.mark.integration +class TestMarkdownToDocument: + def test_init_params_default(self): + converter = MarkdownToDocument() + assert converter.table_to_single_line is False + assert converter.progress_bar is True + + def test_init_params_custom(self): + converter = MarkdownToDocument(table_to_single_line=True, progress_bar=False) + assert converter.table_to_single_line is True + assert converter.progress_bar is False + + @pytest.mark.integration + def test_run(self, test_files_path): + converter = MarkdownToDocument() + sources = [test_files_path / "markdown" / "sample.md"] + results = converter.run(sources=sources) + docs = results["documents"] + + assert len(docs) == 1 + for doc in docs: + assert "What to build with Haystack" in doc.content + assert "# git clone https://github.com/deepset-ai/haystack.git" in doc.content + + def test_run_calls_normalize_metadata(self, test_files_path): + bytestream = ByteStream(data=b"test", meta={"author": "test_author", "language": "en"}) + + converter = MarkdownToDocument() + + with patch("haystack.components.converters.markdown.normalize_metadata") as normalize_metadata, patch( + "haystack.components.converters.markdown.MarkdownIt" + ): + converter.run(sources=[bytestream, test_files_path / "markdown" / "sample.md"], meta={"language": "it"}) + + # check that the metadata normalizer is called properly + normalize_metadata.assert_called_with(meta={"language": "it"}, sources_count=2) + + def test_run_with_meta(self, test_files_path): + bytestream = ByteStream(data=b"test", meta={"author": "test_author", "language": "en"}) + + converter = MarkdownToDocument() + + with patch("haystack.components.converters.markdown.MarkdownIt"): + output = converter.run( + sources=[bytestream, test_files_path / "markdown" / "sample.md"], meta={"language": "it"} + ) + + # check that the metadata from the bytestream is merged with that from the meta parameter + assert output["documents"][0].meta["author"] == "test_author" + assert output["documents"][0].meta["language"] == "it" + assert output["documents"][1].meta["language"] == "it" + + @pytest.mark.integration + def test_run_wrong_file_type(self, test_files_path, caplog): + """ + Test if the component runs correctly when an input file is not of the expected type. + """ + sources = [test_files_path / "audio" / "answer.wav"] + converter = MarkdownToDocument() + with caplog.at_level(logging.WARNING): + output = converter.run(sources=sources) + assert "codec can't decode byte" in caplog.text + + docs = output["documents"] + assert not docs + + @pytest.mark.integration + def test_run_error_handling(self, caplog): + """ + Test if the component correctly handles errors. + """ + sources = ["non_existing_file.md"] + converter = MarkdownToDocument() + with caplog.at_level(logging.WARNING): + result = converter.run(sources=sources) + assert "Could not read non_existing_file.md" in caplog.text + assert not result["documents"] + + def test_mixed_sources_run(self, test_files_path): + """ + Test if the component runs correctly if the input is a mix of strings, paths and ByteStreams. + """ + sources = [ + test_files_path / "markdown" / "sample.md", + str((test_files_path / "markdown" / "sample.md").absolute()), + ] + with open(test_files_path / "markdown" / "sample.md", "rb") as f: + byte_stream = f.read() + sources.append(ByteStream(byte_stream)) + + converter = MarkdownToDocument() + output = converter.run(sources=sources) + docs = output["documents"] + assert len(docs) == 3 + for doc in docs: + assert "What to build with Haystack" in doc.content + assert "# git clone https://github.com/deepset-ai/haystack.git" in doc.content diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_openapi_functions.py b/testbed/deepset-ai__haystack/test/components/converters/test_openapi_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..e154059038ccbc3552bcfd84aeef15f4f8f33a1c --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_openapi_functions.py @@ -0,0 +1,259 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import json +import sys +import tempfile + +import pytest + +from haystack.components.converters import OpenAPIServiceToFunctions +from haystack.dataclasses import ByteStream + + +@pytest.fixture +def json_serperdev_openapi_spec(): + serper_spec = """ + { + "openapi": "3.0.0", + "info": { + "title": "SerperDev", + "version": "1.0.0", + "description": "API for performing search queries" + }, + "servers": [ + { + "url": "https://google.serper.dev" + } + ], + "paths": { + "/search": { + "post": { + "operationId": "search", + "description": "Search the web with Google", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "q": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "searchParameters": { + "type": "undefined" + }, + "knowledgeGraph": { + "type": "undefined" + }, + "answerBox": { + "type": "undefined" + }, + "organic": { + "type": "undefined" + }, + "topStories": { + "type": "undefined" + }, + "peopleAlsoAsk": { + "type": "undefined" + }, + "relatedSearches": { + "type": "undefined" + } + } + } + } + } + } + }, + "security": [ + { + "apikey": [] + } + ] + } + } + }, + "components": { + "securitySchemes": { + "apikey": { + "type": "apiKey", + "name": "x-api-key", + "in": "header" + } + } + } + } + """ + return serper_spec + + +@pytest.fixture +def yaml_serperdev_openapi_spec(): + serper_spec = """ + openapi: 3.0.0 + info: + title: SerperDev + version: 1.0.0 + description: API for performing search queries + servers: + - url: 'https://google.serper.dev' + paths: + /search: + post: + operationId: search + description: Search the web with Google + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + q: + type: string + responses: + '200': + description: Successful response + content: + application/json: + schema: + type: object + properties: + searchParameters: + type: undefined + knowledgeGraph: + type: undefined + answerBox: + type: undefined + organic: + type: undefined + topStories: + type: undefined + peopleAlsoAsk: + type: undefined + relatedSearches: + type: undefined + security: + - apikey: [] + components: + securitySchemes: + apikey: + type: apiKey + name: x-api-key + in: header + """ + return serper_spec + + +class TestOpenAPIServiceToFunctions: + # test we can parse openapi spec given in json + def test_openapi_spec_parsing_json(self, json_serperdev_openapi_spec): + service = OpenAPIServiceToFunctions() + + serper_spec_json = service._parse_openapi_spec(json_serperdev_openapi_spec) + assert serper_spec_json["openapi"] == "3.0.0" + assert serper_spec_json["info"]["title"] == "SerperDev" + + # test we can parse openapi spec given in yaml + def test_openapi_spec_parsing_yaml(self, yaml_serperdev_openapi_spec): + service = OpenAPIServiceToFunctions() + + serper_spec_yaml = service._parse_openapi_spec(yaml_serperdev_openapi_spec) + assert serper_spec_yaml["openapi"] == "3.0.0" + assert serper_spec_yaml["info"]["title"] == "SerperDev" + + # test we can extract functions from openapi spec given + def test_run_with_bytestream_source(self, json_serperdev_openapi_spec): + service = OpenAPIServiceToFunctions() + spec_stream = ByteStream.from_string(json_serperdev_openapi_spec) + result = service.run(sources=[spec_stream]) + assert len(result["functions"]) == 1 + fc = result["functions"][0] + + # check that fc definition is as expected + assert fc == { + "name": "search", + "description": "Search the web with Google", + "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}, + } + + @pytest.mark.skipif( + sys.platform in ["win32", "cygwin"], + reason="Can't run on Windows Github CI, need access temp file but windows does not allow it", + ) + def test_run_with_file_source(self, json_serperdev_openapi_spec): + # test we can extract functions from openapi spec given in file + service = OpenAPIServiceToFunctions() + # write the spec to NamedTemporaryFile and check that it is parsed correctly + with tempfile.NamedTemporaryFile() as tmp: + tmp.write(json_serperdev_openapi_spec.encode("utf-8")) + tmp.seek(0) + result = service.run(sources=[tmp.name]) + assert len(result["functions"]) == 1 + fc = result["functions"][0] + + # check that fc definition is as expected + assert fc == { + "name": "search", + "description": "Search the web with Google", + "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}, + } + + def test_run_with_invalid_file_source(self, caplog): + # test invalid source + service = OpenAPIServiceToFunctions() + result = service.run(sources=["invalid_source"]) + assert result["functions"] == [] + assert "not found" in caplog.text + + def test_run_with_invalid_bytestream_source(self, caplog): + # test invalid source + service = OpenAPIServiceToFunctions() + result = service.run(sources=[ByteStream.from_string("")]) + assert result["functions"] == [] + assert "Invalid OpenAPI specification" in caplog.text + + def test_complex_types_conversion(self, test_files_path): + # ensure that complex types from OpenAPI spec are converted to the expected format in OpenAI function calling + service = OpenAPIServiceToFunctions() + result = service.run(sources=[test_files_path / "json" / "complex_types_openapi_service.json"]) + assert len(result["functions"]) == 1 + + with open(test_files_path / "json" / "complex_types_openai_spec.json") as openai_spec_file: + desired_output = json.load(openai_spec_file) + assert result["functions"][0] == desired_output + + def test_simple_and_complex_at_once(self, test_files_path, json_serperdev_openapi_spec): + # ensure multiple functions are extracted from multiple paths in OpenAPI spec + service = OpenAPIServiceToFunctions() + sources = [ + ByteStream.from_string(json_serperdev_openapi_spec), + test_files_path / "json" / "complex_types_openapi_service.json", + ] + result = service.run(sources=sources) + assert len(result["functions"]) == 2 + + with open(test_files_path / "json" / "complex_types_openai_spec.json") as openai_spec_file: + desired_output = json.load(openai_spec_file) + assert result["functions"][0] == { + "name": "search", + "description": "Search the web with Google", + "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}, + } + assert result["functions"][1] == desired_output diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_output_adapter.py b/testbed/deepset-ai__haystack/test/components/converters/test_output_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..547ce433e68bd56dc3b8e274e5d4ca38db1d07ae --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_output_adapter.py @@ -0,0 +1,194 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from typing import List +import json + +import pytest + +from haystack import Pipeline, component +from haystack.dataclasses import Document +from haystack.components.converters import OutputAdapter +from haystack.components.converters.output_adapter import OutputAdaptationException + + +def custom_filter_to_sede(value): + return value.upper() + + +def another_custom_filter(value): + return value.upper() + + +class TestOutputAdapter: + # OutputAdapter can be initialized with a valid Jinja2 template string and output type. + def test_initialized_with_valid_template_and_output_type(self): + template = "{{ documents[0].content }}" + output_type = str + adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str) + + assert adapter.template == template + assert adapter.__haystack_output__.output.name == "output" + assert adapter.__haystack_output__.output.type == output_type + + # OutputAdapter can adapt the output of one component to be compatible with the input of another + # component using Jinja2 template expressions. + def test_output_adaptation(self): + adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str) + + input_data = {"documents": [{"content": "Test content"}]} + expected_output = {"output": "Test content"} + + assert adapter.run(**input_data) == expected_output + + # OutputAdapter can add filter 'json_loads' and use it + def test_predefined_filters(self): + adapter = OutputAdapter( + template="{{ documents[0].content|json_loads }}", + output_type=dict, + custom_filters={"json_loads": lambda s: json.loads(str(s))}, + ) + + input_data = {"documents": [{"content": '{"key": "value"}'}]} + expected_output = {"output": {"key": "value"}} + + assert adapter.run(**input_data) == expected_output + + # OutputAdapter can handle custom filters provided in the component configuration. + def test_custom_filters(self): + def custom_filter(value): + return value.upper() + + custom_filters = {"custom_filter": custom_filter} + adapter = OutputAdapter( + template="{{ documents[0].content|custom_filter }}", output_type=str, custom_filters=custom_filters + ) + + input_data = {"documents": [{"content": "test content"}]} + expected_output = {"output": "TEST CONTENT"} + + assert adapter.run(**input_data) == expected_output + + # OutputAdapter raises an exception on init if the Jinja2 template string is invalid. + def test_invalid_template_string(self): + with pytest.raises(ValueError): + OutputAdapter(template="{{ documents[0].content }", output_type=str) + + # OutputAdapter raises an exception if no input data is provided for output adaptation. + def test_no_input_data_provided(self): + adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str) + with pytest.raises(ValueError): + adapter.run() + + # OutputAdapter raises an exception if there's an error during the adaptation process. + def test_error_during_adaptation(self): + adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str) + input_data = {"documents": [{"title": "Test title"}]} + + with pytest.raises(OutputAdaptationException): + adapter.run(**input_data) + + # OutputAdapter can be serialized to a dictionary and deserialized back to an OutputAdapter instance. + def test_sede(self): + adapter = OutputAdapter(template="{{ documents[0].content }}", output_type=str) + adapter_dict = adapter.to_dict() + deserialized_adapter = OutputAdapter.from_dict(adapter_dict) + + assert adapter.template == deserialized_adapter.template + assert adapter.output_type == deserialized_adapter.output_type + + # OutputAdapter can be serialized to a dictionary and deserialized along with custom filters + def test_sede_with_custom_filters(self): + # NOTE: filters need to be declared in a namespace visible to the deserialization function + custom_filters = {"custom_filter": custom_filter_to_sede} + adapter = OutputAdapter( + template="{{ documents[0].content|custom_filter }}", output_type=str, custom_filters=custom_filters + ) + adapter_dict = adapter.to_dict() + deserialized_adapter = OutputAdapter.from_dict(adapter_dict) + + assert adapter.template == deserialized_adapter.template + assert adapter.output_type == deserialized_adapter.output_type + assert adapter.custom_filters == deserialized_adapter.custom_filters == custom_filters + + # invoke the custom filter to check if it is deserialized correctly + assert deserialized_adapter.custom_filters["custom_filter"]("test") == "TEST" + + # OutputAdapter can be serialized to a dictionary and deserialized along with multiple custom filters + def test_sede_with_multiple_custom_filters(self): + # NOTE: filters need to be declared in a namespace visible to the deserialization function + custom_filters = {"custom_filter": custom_filter_to_sede, "another_custom_filter": another_custom_filter} + adapter = OutputAdapter( + template="{{ documents[0].content|custom_filter }}", output_type=str, custom_filters=custom_filters + ) + adapter_dict = adapter.to_dict() + deserialized_adapter = OutputAdapter.from_dict(adapter_dict) + + assert adapter.template == deserialized_adapter.template + assert adapter.output_type == deserialized_adapter.output_type + assert adapter.custom_filters == deserialized_adapter.custom_filters == custom_filters + + # invoke the custom filter to check if it is deserialized correctly + assert deserialized_adapter.custom_filters["custom_filter"]("test") == "TEST" + + def test_sede_with_list_output_type_in_pipeline(self): + pipe = Pipeline() + pipe.add_component("adapter", OutputAdapter(template="{{ test }}", output_type=List[str])) + serialized_pipe = pipe.dumps() + + # we serialize the pipeline and check if the output type is serialized correctly (as typing.List[str]) + assert "typing.List[str]" in serialized_pipe + + deserialized_pipe = Pipeline.loads(serialized_pipe) + assert deserialized_pipe.get_component("adapter").output_type == List[str] + + def test_output_adapter_from_dict_custom_filters_none(self): + component = OutputAdapter.from_dict( + data={ + "type": "haystack.components.converters.output_adapter.OutputAdapter", + "init_parameters": { + "template": "{{ documents[0].content}}", + "output_type": "str", + "custom_filters": None, + "unsafe": False, + }, + } + ) + + assert component.template == "{{ documents[0].content}}" + assert component.output_type == str + assert component.custom_filters == {} + assert not component._unsafe + + def test_output_adapter_in_pipeline(self): + @component + class DocumentProducer: + @component.output_types(documents=dict) + def run(self): + return {"documents": [{"content": '{"framework": "Haystack"}'}]} + + pipe = Pipeline() + pipe.add_component( + name="output_adapter", + instance=OutputAdapter( + template="{{ documents[0].content | json_loads}}", + output_type=str, + custom_filters={"json_loads": lambda s: json.loads(str(s))}, + ), + ) + pipe.add_component(name="document_producer", instance=DocumentProducer()) + pipe.connect("document_producer", "output_adapter") + result = pipe.run(data={}) + assert result + assert result["output_adapter"]["output"] == {"framework": "Haystack"} + + def test_unsafe(self): + adapter = OutputAdapter(template="{{ documents[0] }}", output_type=Document, unsafe=True) + documents = [ + Document(content="Test document"), + Document(content="Another test document"), + Document(content="Yet another test document"), + ] + res = adapter.run(documents=documents) + assert res["output"] == documents[0] diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_pdfminer_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_pdfminer_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..53dececbee86ec4c1c6107e4dbdbc78e150040c7 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_pdfminer_to_document.py @@ -0,0 +1,136 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +import pytest + +from haystack.dataclasses import ByteStream +from haystack.components.converters.pdfminer import PDFMinerToDocument + + +class TestPDFMinerToDocument: + def test_run(self, test_files_path): + """ + Test if the component runs correctly. + """ + converter = PDFMinerToDocument() + sources = [test_files_path / "pdf" / "sample_pdf_1.pdf"] + results = converter.run(sources=sources) + docs = results["documents"] + + assert len(docs) == 1 + for doc in docs: + assert "the page 3 is empty" in doc.content + assert "Page 4 of Sample PDF" in doc.content + + def test_init_params_custom(self, test_files_path): + """ + Test if init arguments are passed successfully to PDFMinerToDocument layout parameters + """ + converter = PDFMinerToDocument(char_margin=0.5, all_texts=True) + assert converter.layout_params.char_margin == 0.5 + assert converter.layout_params.all_texts is True + + def test_run_wrong_file_type(self, test_files_path, caplog): + """ + Test if the component runs correctly when an input file is not of the expected type. + """ + sources = [test_files_path / "audio" / "answer.wav"] + converter = PDFMinerToDocument() + + with caplog.at_level(logging.WARNING): + output = converter.run(sources=sources) + assert "Is this really a PDF?" in caplog.text + + docs = output["documents"] + assert not docs + + def test_arg_is_none(self, test_files_path): + """ + Test if the component runs correctly when an argument is None. + """ + converter = PDFMinerToDocument(char_margin=None) + assert converter.layout_params.char_margin is None + + def test_run_doc_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is supplied by the user. + """ + converter = PDFMinerToDocument() + sources = [test_files_path / "pdf" / "sample_pdf_2.pdf"] + metadata = [{"file_name": "sample_pdf_2.pdf"}] + results = converter.run(sources=sources, meta=metadata) + docs = results["documents"] + + assert len(docs) == 1 + assert "Ward Cunningham" in docs[0].content + assert docs[0].meta["file_name"] == "sample_pdf_2.pdf" + + def test_incorrect_meta(self, test_files_path): + """ + Test if the component raises an error when incorrect metadata is supplied by the user. + """ + converter = PDFMinerToDocument() + sources = [test_files_path / "pdf" / "sample_pdf_3.pdf"] + metadata = [{"file_name": "sample_pdf_3.pdf"}, {"file_name": "sample_pdf_2.pdf"}] + with pytest.raises(ValueError, match="The length of the metadata list must match the number of sources."): + converter.run(sources=sources, meta=metadata) + + def test_run_bytestream_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is read from the ByteStream object. + """ + converter = PDFMinerToDocument() + with open(test_files_path / "pdf" / "sample_pdf_2.pdf", "rb") as file: + byte_stream = file.read() + stream = ByteStream(byte_stream, meta={"content_type": "text/pdf", "url": "test_url"}) + + results = converter.run(sources=[stream]) + docs = results["documents"] + + assert len(docs) == 1 + assert "Ward Cunningham" in docs[0].content + assert docs[0].meta == {"content_type": "text/pdf", "url": "test_url"} + + def test_run_bytestream_doc_overlapping_metadata(self, test_files_path): + """ + Test if the component runs correctly when metadata is read from the ByteStream object and supplied by the user. + + There is an overlap between the metadata received. + + The component should use the supplied metadata to overwrite the values if there is an overlap between the keys. + """ + converter = PDFMinerToDocument() + with open(test_files_path / "pdf" / "sample_pdf_2.pdf", "rb") as file: + byte_stream = file.read() + # ByteStream has "url" present in metadata + stream = ByteStream(byte_stream, meta={"content_type": "text/pdf", "url": "test_url_correct"}) + + # "url" supplied by the user overwrites value present in metadata + metadata = [{"file_name": "sample_pdf_2.pdf", "url": "test_url_new"}] + results = converter.run(sources=[stream], meta=metadata) + docs = results["documents"] + + assert len(docs) == 1 + assert "Ward Cunningham" in docs[0].content + assert docs[0].meta == {"file_name": "sample_pdf_2.pdf", "content_type": "text/pdf", "url": "test_url_new"} + + def test_run_error_handling(self, caplog): + """ + Test if the component correctly handles errors. + """ + sources = ["non_existing_file.pdf"] + converter = PDFMinerToDocument() + with caplog.at_level(logging.WARNING): + results = converter.run(sources=sources) + assert "Could not read non_existing_file.pdf" in caplog.text + assert results["documents"] == [] + + def test_run_empty_document(self, caplog, test_files_path): + sources = [test_files_path / "pdf" / "non_text_searchable.pdf"] + converter = PDFMinerToDocument() + with caplog.at_level(logging.WARNING): + results = converter.run(sources=sources) + assert "PDFMinerToDocument could not extract text from the file" in caplog.text + assert results["documents"][0].content == "" diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_pptx_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_pptx_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0c314e33743383f46807b7c0a51332411f4c26 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_pptx_to_document.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +from haystack.dataclasses import ByteStream +from haystack.components.converters.pptx import PPTXToDocument + + +class TestPPTXToDocument: + def test_run(self, test_files_path): + """ + Test if the component runs correctly. + """ + bytestream = ByteStream.from_file_path(test_files_path / "pptx" / "sample_pptx.pptx") + bytestream.meta["file_path"] = str(test_files_path / "pptx" / "sample_pptx.pptx") + bytestream.meta["key"] = "value" + files = [str(test_files_path / "pptx" / "sample_pptx.pptx"), bytestream] + converter = PPTXToDocument() + output = converter.run(sources=files) + docs = output["documents"] + + assert len(docs) == 2 + assert ( + "Sample Title Slide\nJane Doe\fTitle of First Slide\nThis is a bullet point\nThis is another bullet point" + in docs[0].content + ) + assert ( + "Sample Title Slide\nJane Doe\fTitle of First Slide\nThis is a bullet point\nThis is another bullet point" + in docs[0].content + ) + assert docs[0].meta["file_path"] == str(files[0]) + assert docs[1].meta == bytestream.meta + + def test_run_error_non_existent_file(self, caplog): + sources = ["non_existing_file.pptx"] + converter = PPTXToDocument() + with caplog.at_level(logging.WARNING): + results = converter.run(sources=sources) + assert "Could not read non_existing_file.pptx" in caplog.text + assert results["documents"] == [] + + def test_run_error_wrong_file_type(self, caplog, test_files_path): + sources = [str(test_files_path / "txt" / "doc_1.txt")] + converter = PPTXToDocument() + with caplog.at_level(logging.WARNING): + results = converter.run(sources=sources) + assert "doc_1.txt and convert it" in caplog.text + assert results["documents"] == [] + + def test_run_with_meta(self, test_files_path): + bytestream = ByteStream.from_file_path(test_files_path / "pptx" / "sample_pptx.pptx") + bytestream.meta["file_path"] = str(test_files_path / "pptx" / "sample_pptx.pptx") + bytestream.meta["key"] = "value" + + converter = PPTXToDocument() + output = converter.run(sources=[bytestream], meta=[{"language": "it"}]) + document = output["documents"][0] + + assert document.meta == { + "file_path": str(test_files_path / "pptx" / "sample_pptx.pptx"), + "key": "value", + "language": "it", + } diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_pypdf_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_pypdf_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..234b545eac47ae2481ec8307f3327dbc374c6996 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_pypdf_to_document.py @@ -0,0 +1,174 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from unittest.mock import patch + +import pytest + +from haystack import Document, default_from_dict, default_to_dict +from haystack.components.converters.pypdf import PyPDFToDocument +from haystack.dataclasses import ByteStream + + +@pytest.fixture +def pypdf_converter(): + return PyPDFToDocument() + + +class CustomConverter: + def convert(self, reader): + return Document(content="Custom converter") + + def to_dict(self): + return {"key": "value", "more": False} + + @classmethod + def from_dict(cls, data): + assert data == {"key": "value", "more": False} + return cls() + + +class TestPyPDFToDocument: + def test_init(self, pypdf_converter): + assert pypdf_converter.converter is None + + def test_init_params(self): + pypdf_converter = PyPDFToDocument(converter=CustomConverter()) + assert isinstance(pypdf_converter.converter, CustomConverter) + + def test_to_dict(self, pypdf_converter): + data = pypdf_converter.to_dict() + assert data == { + "type": "haystack.components.converters.pypdf.PyPDFToDocument", + "init_parameters": {"converter": None}, + } + + def test_to_dict_custom_converter(self): + pypdf_converter = PyPDFToDocument(converter=CustomConverter()) + data = pypdf_converter.to_dict() + assert data == { + "type": "haystack.components.converters.pypdf.PyPDFToDocument", + "init_parameters": { + "converter": { + "data": {"key": "value", "more": False}, + "type": "converters.test_pypdf_to_document.CustomConverter", + } + }, + } + + def test_from_dict(self): + data = {"type": "haystack.components.converters.pypdf.PyPDFToDocument", "init_parameters": {"converter": None}} + instance = PyPDFToDocument.from_dict(data) + assert isinstance(instance, PyPDFToDocument) + assert instance.converter is None + + def test_from_dict_defaults(self): + data = {"type": "haystack.components.converters.pypdf.PyPDFToDocument", "init_parameters": {}} + instance = PyPDFToDocument.from_dict(data) + assert isinstance(instance, PyPDFToDocument) + assert instance.converter is None + + def test_from_dict_custom_converter(self): + data = { + "type": "haystack.components.converters.pypdf.PyPDFToDocument", + "init_parameters": { + "converter": { + "data": {"key": "value", "more": False}, + "type": "converters.test_pypdf_to_document.CustomConverter", + } + }, + } + instance = PyPDFToDocument.from_dict(data) + assert isinstance(instance, PyPDFToDocument) + assert isinstance(instance.converter, CustomConverter) + + @pytest.mark.integration + def test_run(self, test_files_path, pypdf_converter): + """ + Test if the component runs correctly. + """ + paths = [test_files_path / "pdf" / "sample_pdf_1.pdf"] + output = pypdf_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 1 + assert "History" in docs[0].content + + @pytest.mark.integration + def test_page_breaks_added(self, test_files_path, pypdf_converter): + paths = [test_files_path / "pdf" / "sample_pdf_1.pdf"] + output = pypdf_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 1 + assert docs[0].content.count("\f") == 3 + + def test_run_with_meta(self, test_files_path, pypdf_converter): + bytestream = ByteStream(data=b"test", meta={"author": "test_author", "language": "en"}) + + with patch("haystack.components.converters.pypdf.PdfReader"): + output = pypdf_converter.run( + sources=[bytestream, test_files_path / "pdf" / "sample_pdf_1.pdf"], meta={"language": "it"} + ) + + # check that the metadata from the bytestream is merged with that from the meta parameter + assert output["documents"][0].meta["author"] == "test_author" + assert output["documents"][0].meta["language"] == "it" + assert output["documents"][1].meta["language"] == "it" + + def test_run_error_handling(self, test_files_path, pypdf_converter, caplog): + """ + Test if the component correctly handles errors. + """ + paths = ["non_existing_file.pdf"] + with caplog.at_level(logging.WARNING): + pypdf_converter.run(sources=paths) + assert "Could not read non_existing_file.pdf" in caplog.text + + @pytest.mark.integration + def test_mixed_sources_run(self, test_files_path, pypdf_converter): + """ + Test if the component runs correctly when mixed sources are provided. + """ + paths = [test_files_path / "pdf" / "sample_pdf_1.pdf"] + with open(test_files_path / "pdf" / "sample_pdf_1.pdf", "rb") as f: + paths.append(ByteStream(f.read())) + + output = pypdf_converter.run(sources=paths) + docs = output["documents"] + assert len(docs) == 2 + assert "History and standardization" in docs[0].content + assert "History and standardization" in docs[1].content + + @pytest.mark.integration + def test_custom_converter(self, test_files_path): + """ + Test if the component correctly handles custom converters. + """ + from pypdf import PdfReader + + paths = [test_files_path / "pdf" / "sample_pdf_1.pdf"] + + class MyCustomConverter: + def convert(self, reader: PdfReader) -> Document: + return Document(content="I don't care about converting given pdfs, I always return this") + + def to_dict(self): + return default_to_dict(self) + + @classmethod + def from_dict(cls, data): + return default_from_dict(cls, data) + + component = PyPDFToDocument(converter=MyCustomConverter()) + output = component.run(sources=paths) + docs = output["documents"] + assert len(docs) == 1 + assert "ReAct" not in docs[0].content + assert "I don't care about converting given pdfs, I always return this" in docs[0].content + + def test_run_empty_document(self, caplog, test_files_path): + paths = [test_files_path / "pdf" / "non_text_searchable.pdf"] + with caplog.at_level(logging.WARNING): + output = PyPDFToDocument().run(sources=paths) + assert "PyPDFToDocument could not extract text from the file" in caplog.text + assert output["documents"][0].content == "" diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_textfile_to_document.py b/testbed/deepset-ai__haystack/test/components/converters/test_textfile_to_document.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bdec101242eae8224194c455781615a6c2550 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_textfile_to_document.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from unittest.mock import patch +from pathlib import Path + +import pytest + +from haystack.dataclasses import ByteStream +from haystack.components.converters.txt import TextFileToDocument + + +class TestTextfileToDocument: + def test_run(self, test_files_path): + """ + Test if the component runs correctly. + """ + bytestream = ByteStream.from_file_path(test_files_path / "txt" / "doc_3.txt") + bytestream.meta["file_path"] = str(test_files_path / "txt" / "doc_3.txt") + bytestream.meta["key"] = "value" + files = [str(test_files_path / "txt" / "doc_1.txt"), test_files_path / "txt" / "doc_2.txt", bytestream] + converter = TextFileToDocument() + output = converter.run(sources=files) + docs = output["documents"] + assert len(docs) == 3 + assert "Some text for testing." in docs[0].content + assert "This is a test line." in docs[1].content + assert "That's yet another file!" in docs[2].content + assert docs[0].meta["file_path"] == str(files[0]) + assert docs[1].meta["file_path"] == str(files[1]) + assert docs[2].meta == bytestream.meta + + def test_run_error_handling(self, test_files_path, caplog): + """ + Test if the component correctly handles errors. + """ + paths = [test_files_path / "txt" / "doc_1.txt", "non_existing_file.txt", test_files_path / "txt" / "doc_3.txt"] + converter = TextFileToDocument() + with caplog.at_level(logging.WARNING): + output = converter.run(sources=paths) + assert "non_existing_file.txt" in caplog.text + docs = output["documents"] + assert len(docs) == 2 + assert docs[0].meta["file_path"] == str(paths[0]) + assert docs[1].meta["file_path"] == str(paths[2]) + + def test_encoding_override(self, test_files_path): + """ + Test if the encoding metadata field is used properly + """ + bytestream = ByteStream.from_file_path(test_files_path / "txt" / "doc_1.txt") + bytestream.meta["key"] = "value" + + converter = TextFileToDocument(encoding="utf-16") + output = converter.run(sources=[bytestream]) + assert "Some text for testing." not in output["documents"][0].content + + bytestream.meta["encoding"] = "utf-8" + output = converter.run(sources=[bytestream]) + assert "Some text for testing." in output["documents"][0].content + + def test_run_with_meta(self): + bytestream = ByteStream(data=b"test", meta={"author": "test_author", "language": "en"}) + + converter = TextFileToDocument() + + output = converter.run(sources=[bytestream], meta=[{"language": "it"}]) + document = output["documents"][0] + + # check that the metadata from the bytestream is merged with that from the meta parameter + assert document.meta == {"author": "test_author", "language": "it"} diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_tika_doc_converter.py b/testbed/deepset-ai__haystack/test/components/converters/test_tika_doc_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..42ba3ebe1d90f979067045f438b31cf5e1e827fd --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_tika_doc_converter.py @@ -0,0 +1,83 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import patch + +import pytest + +from haystack.dataclasses import ByteStream +from haystack.components.converters.tika import TikaDocumentConverter + + +class TestTikaDocumentConverter: + @patch("haystack.components.converters.tika.tika_parser.from_buffer") + def test_run(self, mock_tika_parser): + mock_tika_parser.return_value = {"content": "

    Content of mock source

    "} + + component = TikaDocumentConverter() + source = ByteStream(data=b"placeholder data") + documents = component.run(sources=[source])["documents"] + + assert len(documents) == 1 + assert documents[0].content == "Content of mock source" + + def test_run_with_meta(self, test_files_path): + bytestream = ByteStream(data=b"test", meta={"author": "test_author", "language": "en"}) + + converter = TikaDocumentConverter() + with patch("haystack.components.converters.tika.tika_parser.from_buffer"): + output = converter.run( + sources=[bytestream, test_files_path / "markdown" / "sample.md"], meta={"language": "it"} + ) + + # check that the metadata from the sources is merged with that from the meta parameter + assert output["documents"][0].meta["author"] == "test_author" + assert output["documents"][0].meta["language"] == "it" + assert output["documents"][1].meta["language"] == "it" + + def test_run_nonexistent_file(self, caplog): + component = TikaDocumentConverter() + with caplog.at_level("WARNING"): + component.run(sources=["nonexistent.pdf"]) + assert "Could not read nonexistent.pdf. Skipping it." in caplog.text + + @pytest.mark.integration + def test_run_with_txt_files(self, test_files_path): + component = TikaDocumentConverter() + output = component.run(sources=[test_files_path / "txt" / "doc_1.txt", test_files_path / "txt" / "doc_2.txt"]) + documents = output["documents"] + assert len(documents) == 2 + assert "Some text for testing.\nTwo lines in here." in documents[0].content + assert "This is a test line.\n123 456 789\n987 654 321" in documents[1].content + + @pytest.mark.integration + def test_run_with_pdf_file(self, test_files_path): + component = TikaDocumentConverter() + output = component.run( + sources=[test_files_path / "pdf" / "sample_pdf_1.pdf", test_files_path / "pdf" / "sample_pdf_2.pdf"] + ) + documents = output["documents"] + assert len(documents) == 2 + assert "A sample PDF file" in documents[0].content + assert "Page 2 of Sample PDF" in documents[0].content + assert "Page 4 of Sample PDF" in documents[0].content + assert documents[0].content.count("\f") == 3 # 4 pages + + assert "First Page" in documents[1].content + assert ( + "Wiki engines usually allow content to be written using a simplified markup language" + in documents[1].content + ) + assert "This section needs additional citations for verification." in documents[1].content + assert "This would make it easier for other users to find the article." in documents[1].content + assert documents[1].content.count("\f") == 3 # 4 pages + + @pytest.mark.integration + def test_run_with_docx_file(self, test_files_path): + component = TikaDocumentConverter() + output = component.run(sources=[test_files_path / "docx" / "sample_docx.docx"]) + documents = output["documents"] + assert len(documents) == 1 + assert "Sample Docx File" in documents[0].content + assert "Now we are in Page 2" in documents[0].content + assert "Page 3 was empty this is page 4" in documents[0].content diff --git a/testbed/deepset-ai__haystack/test/components/converters/test_utils.py b/testbed/deepset-ai__haystack/test/components/converters/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..296533491d5dc2b10a28d1d6c3f42047c7c10cff --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/converters/test_utils.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest +from haystack.components.converters.utils import normalize_metadata + + +def test_normalize_metadata_None(): + assert normalize_metadata(None, sources_count=1) == [{}] + assert normalize_metadata(None, sources_count=3) == [{}, {}, {}] + + +def test_normalize_metadata_single_dict(): + assert normalize_metadata({"a": 1}, sources_count=1) == [{"a": 1}] + assert normalize_metadata({"a": 1}, sources_count=3) == [{"a": 1}, {"a": 1}, {"a": 1}] + + +def test_normalize_metadata_list_of_right_size(): + assert normalize_metadata([{"a": 1}], sources_count=1) == [{"a": 1}] + assert normalize_metadata([{"a": 1}, {"b": 2}, {"c": 3}], sources_count=3) == [{"a": 1}, {"b": 2}, {"c": 3}] + + +def test_normalize_metadata_list_of_wrong_size(): + with pytest.raises(ValueError, match="The length of the metadata list must match the number of sources."): + normalize_metadata([{"a": 1}], sources_count=3) + with pytest.raises(ValueError, match="The length of the metadata list must match the number of sources."): + assert normalize_metadata([{"a": 1}, {"b": 2}, {"c": 3}], sources_count=1) + + +def test_normalize_metadata_other_type(): + with pytest.raises(ValueError, match="meta must be either None, a dictionary or a list of dictionaries."): + normalize_metadata(({"a": 1},), sources_count=1) diff --git a/testbed/deepset-ai__haystack/test/components/embedders/__init__.py b/testbed/deepset-ai__haystack/test/components/embedders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_azure_document_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_azure_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..354f35a0fc1150e784c1e2e6b15eb2cc91a6b7db --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_azure_document_embedder.py @@ -0,0 +1,84 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +import pytest + +from haystack import Document +from haystack.components.embedders import AzureOpenAIDocumentEmbedder + + +class TestAzureOpenAIDocumentEmbedder: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "fake-api-key") + embedder = AzureOpenAIDocumentEmbedder(azure_endpoint="https://example-resource.azure.openai.com/") + assert embedder.azure_deployment == "text-embedding-ada-002" + assert embedder.dimensions is None + assert embedder.organization is None + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.batch_size == 32 + assert embedder.progress_bar is True + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "fake-api-key") + component = AzureOpenAIDocumentEmbedder(azure_endpoint="https://example-resource.azure.openai.com/") + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["AZURE_OPENAI_API_KEY"], "strict": False, "type": "env_var"}, + "azure_ad_token": {"env_vars": ["AZURE_OPENAI_AD_TOKEN"], "strict": False, "type": "env_var"}, + "api_version": "2023-05-15", + "azure_deployment": "text-embedding-ada-002", + "dimensions": None, + "azure_endpoint": "https://example-resource.azure.openai.com/", + "organization": None, + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "meta_fields_to_embed": [], + "embedding_separator": "\n", + "max_retries": 5, + "timeout": 30.0, + }, + } + + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("AZURE_OPENAI_API_KEY", None) and not os.environ.get("AZURE_OPENAI_ENDPOINT", None), + reason=( + "Please export env variables called AZURE_OPENAI_API_KEY containing " + "the Azure OpenAI key, AZURE_OPENAI_ENDPOINT containing " + "the Azure OpenAI endpoint URL to run this test." + ), + ) + def test_run(self): + docs = [ + Document(content="I love cheese", meta={"topic": "Cuisine"}), + Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}), + ] + # the default model is text-embedding-ada-002 even if we don't specify it, but let's be explicit + embedder = AzureOpenAIDocumentEmbedder( + azure_deployment="text-embedding-ada-002", + meta_fields_to_embed=["topic"], + embedding_separator=" | ", + organization="HaystackCI", + ) + + result = embedder.run(documents=docs) + documents_with_embeddings = result["documents"] + metadata = result["meta"] + + assert isinstance(documents_with_embeddings, list) + assert len(documents_with_embeddings) == len(docs) + for doc in documents_with_embeddings: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert len(doc.embedding) == 1536 + assert all(isinstance(x, float) for x in doc.embedding) + assert metadata == {"model": "text-embedding-ada-002", "usage": {"prompt_tokens": 15, "total_tokens": 15}} diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_azure_text_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_azure_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1f82e3d8208eaf5cf99df3b6bc89bfe3b3d3c0 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_azure_text_embedder.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +import pytest + +from haystack.components.embedders import AzureOpenAITextEmbedder + + +class TestAzureOpenAITextEmbedder: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "fake-api-key") + embedder = AzureOpenAITextEmbedder(azure_endpoint="https://example-resource.azure.openai.com/") + + assert embedder._client.api_key == "fake-api-key" + assert embedder.azure_deployment == "text-embedding-ada-002" + assert embedder.dimensions is None + assert embedder.organization is None + assert embedder.prefix == "" + assert embedder.suffix == "" + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "fake-api-key") + component = AzureOpenAITextEmbedder(azure_endpoint="https://example-resource.azure.openai.com/") + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["AZURE_OPENAI_API_KEY"], "strict": False, "type": "env_var"}, + "azure_ad_token": {"env_vars": ["AZURE_OPENAI_AD_TOKEN"], "strict": False, "type": "env_var"}, + "azure_deployment": "text-embedding-ada-002", + "dimensions": None, + "organization": None, + "azure_endpoint": "https://example-resource.azure.openai.com/", + "api_version": "2023-05-15", + "max_retries": 5, + "timeout": 30.0, + "prefix": "", + "suffix": "", + }, + } + + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("AZURE_OPENAI_API_KEY", None) and not os.environ.get("AZURE_OPENAI_ENDPOINT", None), + reason=( + "Please export env variables called AZURE_OPENAI_API_KEY containing " + "the Azure OpenAI key, AZURE_OPENAI_ENDPOINT containing " + "the Azure OpenAI endpoint URL to run this test." + ), + ) + def test_run(self): + # the default model is text-embedding-ada-002 even if we don't specify it, but let's be explicit + embedder = AzureOpenAITextEmbedder( + azure_deployment="text-embedding-ada-002", prefix="prefix ", suffix=" suffix", organization="HaystackCI" + ) + result = embedder.run(text="The food was delicious") + + assert len(result["embedding"]) == 1536 + assert all(isinstance(x, float) for x in result["embedding"]) + assert result["meta"] == {"model": "text-embedding-ada-002", "usage": {"prompt_tokens": 6, "total_tokens": 6}} diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_hugging_face_api_document_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_hugging_face_api_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..b9332d5363276f8ccb05d5ba881bb1695f7eb34c --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_hugging_face_api_document_embedder.py @@ -0,0 +1,352 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from unittest.mock import MagicMock, patch + +import random +import pytest +from huggingface_hub.utils import RepositoryNotFoundError + +from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder +from haystack.dataclasses import Document +from haystack.utils.auth import Secret +from haystack.utils.hf import HFEmbeddingAPIType + + +@pytest.fixture +def mock_check_valid_model(): + with patch( + "haystack.components.embedders.hugging_face_api_document_embedder.check_valid_model", + MagicMock(return_value=None), + ) as mock: + yield mock + + +def mock_embedding_generation(json, **kwargs): + response = str([[random.random() for _ in range(384)] for _ in range(len(json["inputs"]))]).encode() + return response + + +class TestHuggingFaceAPIDocumentEmbedder: + def test_init_invalid_api_type(self): + with pytest.raises(ValueError): + HuggingFaceAPIDocumentEmbedder(api_type="invalid_api_type", api_params={}) + + def test_init_serverless(self, mock_check_valid_model): + model = "BAAI/bge-small-en-v1.5" + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"model": model} + ) + + assert embedder.api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API + assert embedder.api_params == {"model": model} + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.truncate + assert not embedder.normalize + assert embedder.batch_size == 32 + assert embedder.progress_bar + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + + def test_init_serverless_invalid_model(self, mock_check_valid_model): + mock_check_valid_model.side_effect = RepositoryNotFoundError("Invalid model id") + with pytest.raises(RepositoryNotFoundError): + HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "invalid_model_id"} + ) + + def test_init_serverless_no_model(self): + with pytest.raises(ValueError): + HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"param": "irrelevant"} + ) + + def test_init_tei(self): + url = "https://some_model.com" + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, api_params={"url": url} + ) + + assert embedder.api_type == HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE + assert embedder.api_params == {"url": url} + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.truncate + assert not embedder.normalize + assert embedder.batch_size == 32 + assert embedder.progress_bar + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + + def test_init_tei_invalid_url(self): + with pytest.raises(ValueError): + HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, api_params={"url": "invalid_url"} + ) + + def test_init_tei_no_url(self): + with pytest.raises(ValueError): + HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, api_params={"param": "irrelevant"} + ) + + def test_to_dict(self, mock_check_valid_model): + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + prefix="prefix", + suffix="suffix", + truncate=False, + normalize=True, + batch_size=128, + progress_bar=False, + meta_fields_to_embed=["meta_field"], + embedding_separator=" ", + ) + + data = embedder.to_dict() + + assert data == { + "type": "haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder", + "init_parameters": { + "api_type": "serverless_inference_api", + "api_params": {"model": "BAAI/bge-small-en-v1.5"}, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "truncate": False, + "normalize": True, + "batch_size": 128, + "progress_bar": False, + "meta_fields_to_embed": ["meta_field"], + "embedding_separator": " ", + }, + } + + def test_from_dict(self, mock_check_valid_model): + data = { + "type": "haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder", + "init_parameters": { + "api_type": HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + "api_params": {"model": "BAAI/bge-small-en-v1.5"}, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "truncate": False, + "normalize": True, + "batch_size": 128, + "progress_bar": False, + "meta_fields_to_embed": ["meta_field"], + "embedding_separator": " ", + }, + } + + embedder = HuggingFaceAPIDocumentEmbedder.from_dict(data) + + assert embedder.api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API + assert embedder.api_params == {"model": "BAAI/bge-small-en-v1.5"} + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert not embedder.truncate + assert embedder.normalize + assert embedder.batch_size == 128 + assert not embedder.progress_bar + assert embedder.meta_fields_to_embed == ["meta_field"] + assert embedder.embedding_separator == " " + + def test_prepare_texts_to_embed_w_metadata(self): + documents = [ + Document(content=f"document number {i}: content", meta={"meta_field": f"meta_value {i}"}) for i in range(5) + ] + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, + api_params={"url": "https://some_model.com"}, + token=Secret.from_token("fake-api-token"), + meta_fields_to_embed=["meta_field"], + embedding_separator=" | ", + ) + + prepared_texts = embedder._prepare_texts_to_embed(documents) + + assert prepared_texts == [ + "meta_value 0 | document number 0: content", + "meta_value 1 | document number 1: content", + "meta_value 2 | document number 2: content", + "meta_value 3 | document number 3: content", + "meta_value 4 | document number 4: content", + ] + + def test_prepare_texts_to_embed_w_suffix(self, mock_check_valid_model): + documents = [Document(content=f"document number {i}") for i in range(5)] + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, + api_params={"url": "https://some_model.com"}, + token=Secret.from_token("fake-api-token"), + prefix="my_prefix ", + suffix=" my_suffix", + ) + + prepared_texts = embedder._prepare_texts_to_embed(documents) + + assert prepared_texts == [ + "my_prefix document number 0 my_suffix", + "my_prefix document number 1 my_suffix", + "my_prefix document number 2 my_suffix", + "my_prefix document number 3 my_suffix", + "my_prefix document number 4 my_suffix", + ] + + def test_embed_batch(self, mock_check_valid_model): + texts = ["text 1", "text 2", "text 3", "text 4", "text 5"] + + with patch("huggingface_hub.InferenceClient.post") as mock_embedding_patch: + mock_embedding_patch.side_effect = mock_embedding_generation + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("fake-api-token"), + ) + embeddings = embedder._embed_batch(texts_to_embed=texts, batch_size=2) + + assert mock_embedding_patch.call_count == 3 + + assert isinstance(embeddings, list) + assert len(embeddings) == len(texts) + for embedding in embeddings: + assert isinstance(embedding, list) + assert len(embedding) == 384 + assert all(isinstance(x, float) for x in embedding) + + def test_run_wrong_input_format(self, mock_check_valid_model): + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "BAAI/bge-small-en-v1.5"} + ) + + list_integers_input = [1, 2, 3] + + with pytest.raises(TypeError): + embedder.run(text=list_integers_input) + + def test_run_on_empty_list(self, mock_check_valid_model): + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("fake-api-token"), + ) + + empty_list_input = [] + result = embedder.run(documents=empty_list_input) + + assert result["documents"] is not None + assert not result["documents"] # empty list + + def test_run(self, mock_check_valid_model): + docs = [ + Document(content="I love cheese", meta={"topic": "Cuisine"}), + Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}), + ] + + with patch("huggingface_hub.InferenceClient.post") as mock_embedding_patch: + mock_embedding_patch.side_effect = mock_embedding_generation + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("fake-api-token"), + prefix="prefix ", + suffix=" suffix", + meta_fields_to_embed=["topic"], + embedding_separator=" | ", + ) + + result = embedder.run(documents=docs) + + mock_embedding_patch.assert_called_once_with( + json={ + "inputs": [ + "prefix Cuisine | I love cheese suffix", + "prefix ML | A transformer is a deep learning architecture suffix", + ], + "truncate": True, + "normalize": False, + }, + task="feature-extraction", + ) + documents_with_embeddings = result["documents"] + + assert isinstance(documents_with_embeddings, list) + assert len(documents_with_embeddings) == len(docs) + for doc in documents_with_embeddings: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert len(doc.embedding) == 384 + assert all(isinstance(x, float) for x in doc.embedding) + + def test_run_custom_batch_size(self, mock_check_valid_model): + docs = [ + Document(content="I love cheese", meta={"topic": "Cuisine"}), + Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}), + ] + + with patch("huggingface_hub.InferenceClient.post") as mock_embedding_patch: + mock_embedding_patch.side_effect = mock_embedding_generation + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("fake-api-token"), + prefix="prefix ", + suffix=" suffix", + meta_fields_to_embed=["topic"], + embedding_separator=" | ", + batch_size=1, + ) + + result = embedder.run(documents=docs) + + assert mock_embedding_patch.call_count == 2 + + documents_with_embeddings = result["documents"] + + assert isinstance(documents_with_embeddings, list) + assert len(documents_with_embeddings) == len(docs) + for doc in documents_with_embeddings: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert len(doc.embedding) == 384 + assert all(isinstance(x, float) for x in doc.embedding) + + @pytest.mark.flaky(reruns=5, reruns_delay=5) + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("HF_API_TOKEN", None), + reason="Export an env var called HF_API_TOKEN containing the Hugging Face token to run this test.", + ) + def test_live_run_serverless(self): + docs = [ + Document(content="I love cheese", meta={"topic": "Cuisine"}), + Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}), + ] + + embedder = HuggingFaceAPIDocumentEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "sentence-transformers/all-MiniLM-L6-v2"}, + meta_fields_to_embed=["topic"], + embedding_separator=" | ", + ) + result = embedder.run(documents=docs) + documents_with_embeddings = result["documents"] + + assert isinstance(documents_with_embeddings, list) + assert len(documents_with_embeddings) == len(docs) + for doc in documents_with_embeddings: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert len(doc.embedding) == 384 + assert all(isinstance(x, float) for x in doc.embedding) diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_hugging_face_api_text_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_hugging_face_api_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..6e699fca2561766ebc425edd6b6f4d1f61be176e --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_hugging_face_api_text_embedder.py @@ -0,0 +1,180 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from unittest.mock import MagicMock, patch + +import random +import pytest +from huggingface_hub.utils import RepositoryNotFoundError + +from haystack.components.embedders import HuggingFaceAPITextEmbedder +from haystack.utils.auth import Secret +from haystack.utils.hf import HFEmbeddingAPIType + + +@pytest.fixture +def mock_check_valid_model(): + with patch( + "haystack.components.embedders.hugging_face_api_text_embedder.check_valid_model", MagicMock(return_value=None) + ) as mock: + yield mock + + +def mock_embedding_generation(json, **kwargs): + response = str([[random.random() for _ in range(384)] for _ in range(len(json["inputs"]))]).encode() + return response + + +class TestHuggingFaceAPITextEmbedder: + def test_init_invalid_api_type(self): + with pytest.raises(ValueError): + HuggingFaceAPITextEmbedder(api_type="invalid_api_type", api_params={}) + + def test_init_serverless(self, mock_check_valid_model): + model = "BAAI/bge-small-en-v1.5" + embedder = HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"model": model} + ) + + assert embedder.api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API + assert embedder.api_params == {"model": model} + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.truncate + assert not embedder.normalize + + def test_init_serverless_invalid_model(self, mock_check_valid_model): + mock_check_valid_model.side_effect = RepositoryNotFoundError("Invalid model id") + with pytest.raises(RepositoryNotFoundError): + HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "invalid_model_id"} + ) + + def test_init_serverless_no_model(self): + with pytest.raises(ValueError): + HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"param": "irrelevant"} + ) + + def test_init_tei(self): + url = "https://some_model.com" + + embedder = HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, api_params={"url": url} + ) + + assert embedder.api_type == HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE + assert embedder.api_params == {"url": url} + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.truncate + assert not embedder.normalize + + def test_init_tei_invalid_url(self): + with pytest.raises(ValueError): + HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, api_params={"url": "invalid_url"} + ) + + def test_init_tei_no_url(self): + with pytest.raises(ValueError): + HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE, api_params={"param": "irrelevant"} + ) + + def test_to_dict(self, mock_check_valid_model): + embedder = HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + prefix="prefix", + suffix="suffix", + truncate=False, + normalize=True, + ) + + data = embedder.to_dict() + + assert data == { + "type": "haystack.components.embedders.hugging_face_api_text_embedder.HuggingFaceAPITextEmbedder", + "init_parameters": { + "api_type": "serverless_inference_api", + "api_params": {"model": "BAAI/bge-small-en-v1.5"}, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "truncate": False, + "normalize": True, + }, + } + + def test_from_dict(self, mock_check_valid_model): + data = { + "type": "haystack.components.embedders.hugging_face_api_text_embedder.HuggingFaceAPITextEmbedder", + "init_parameters": { + "api_type": HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + "api_params": {"model": "BAAI/bge-small-en-v1.5"}, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "truncate": False, + "normalize": True, + }, + } + + embedder = HuggingFaceAPITextEmbedder.from_dict(data) + + assert embedder.api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API + assert embedder.api_params == {"model": "BAAI/bge-small-en-v1.5"} + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert not embedder.truncate + assert embedder.normalize + + def test_run_wrong_input_format(self, mock_check_valid_model): + embedder = HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "BAAI/bge-small-en-v1.5"} + ) + + list_integers_input = [1, 2, 3] + + with pytest.raises(TypeError): + embedder.run(text=list_integers_input) + + def test_run(self, mock_check_valid_model): + with patch("huggingface_hub.InferenceClient.post") as mock_embedding_patch: + mock_embedding_patch.side_effect = mock_embedding_generation + + embedder = HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "BAAI/bge-small-en-v1.5"}, + token=Secret.from_token("fake-api-token"), + prefix="prefix ", + suffix=" suffix", + ) + + result = embedder.run(text="The food was delicious") + + mock_embedding_patch.assert_called_once_with( + json={"inputs": ["prefix The food was delicious suffix"], "truncate": True, "normalize": False}, + task="feature-extraction", + ) + + assert len(result["embedding"]) == 384 + assert all(isinstance(x, float) for x in result["embedding"]) + + @pytest.mark.flaky(reruns=5, reruns_delay=5) + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("HF_API_TOKEN", None), + reason="Export an env var called HF_API_TOKEN containing the Hugging Face token to run this test.", + ) + def test_live_run_serverless(self): + embedder = HuggingFaceAPITextEmbedder( + api_type=HFEmbeddingAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "sentence-transformers/all-MiniLM-L6-v2"}, + ) + result = embedder.run(text="The food was delicious") + + assert len(result["embedding"]) == 384 + assert all(isinstance(x, float) for x in result["embedding"]) diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_openai_document_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_openai_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..89ce62a929383ad3793e9373c6d42dfd3861e6ea --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_openai_document_embedder.py @@ -0,0 +1,242 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from typing import List +from haystack.utils.auth import Secret + +import random +import pytest + +from haystack import Document +from haystack.components.embedders.openai_document_embedder import OpenAIDocumentEmbedder + + +def mock_openai_response(input: List[str], model: str = "text-embedding-ada-002", **kwargs) -> dict: + dict_response = { + "object": "list", + "data": [ + {"object": "embedding", "index": i, "embedding": [random.random() for _ in range(1536)]} + for i in range(len(input)) + ], + "model": model, + "usage": {"prompt_tokens": 4, "total_tokens": 4}, + } + + return dict_response + + +class TestOpenAIDocumentEmbedder: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key") + embedder = OpenAIDocumentEmbedder() + assert embedder.api_key.resolve_value() == "fake-api-key" + assert embedder.model == "text-embedding-ada-002" + assert embedder.organization is None + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.batch_size == 32 + assert embedder.progress_bar is True + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + assert embedder.client.max_retries == 5 + assert embedder.client.timeout == 30.0 + + def test_init_with_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + embedder = OpenAIDocumentEmbedder( + api_key=Secret.from_token("fake-api-key-2"), + model="model", + organization="my-org", + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator=" | ", + timeout=40.0, + max_retries=1, + ) + assert embedder.api_key.resolve_value() == "fake-api-key-2" + assert embedder.organization == "my-org" + assert embedder.model == "model" + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.meta_fields_to_embed == ["test_field"] + assert embedder.embedding_separator == " | " + assert embedder.client.max_retries == 1 + assert embedder.client.timeout == 40.0 + + def test_init_with_parameters_and_env_vars(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + embedder = OpenAIDocumentEmbedder( + api_key=Secret.from_token("fake-api-key-2"), + model="model", + organization="my-org", + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator=" | ", + ) + assert embedder.api_key.resolve_value() == "fake-api-key-2" + assert embedder.organization == "my-org" + assert embedder.model == "model" + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.meta_fields_to_embed == ["test_field"] + assert embedder.embedding_separator == " | " + assert embedder.client.max_retries == 10 + assert embedder.client.timeout == 100.0 + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + OpenAIDocumentEmbedder() + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key") + component = OpenAIDocumentEmbedder() + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "api_base_url": None, + "model": "text-embedding-ada-002", + "dimensions": None, + "organization": None, + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "meta_fields_to_embed": [], + "embedding_separator": "\n", + }, + } + + def test_to_dict_with_custom_init_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "fake-api-key") + component = OpenAIDocumentEmbedder( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + model="model", + organization="my-org", + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator=" | ", + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "api_base_url": None, + "model": "model", + "dimensions": None, + "organization": "my-org", + "prefix": "prefix", + "suffix": "suffix", + "batch_size": 64, + "progress_bar": False, + "meta_fields_to_embed": ["test_field"], + "embedding_separator": " | ", + }, + } + + def test_prepare_texts_to_embed_w_metadata(self): + documents = [ + Document(content=f"document number {i}:\ncontent", meta={"meta_field": f"meta_value {i}"}) for i in range(5) + ] + + embedder = OpenAIDocumentEmbedder( + api_key=Secret.from_token("fake-api-key"), meta_fields_to_embed=["meta_field"], embedding_separator=" | " + ) + + prepared_texts = embedder._prepare_texts_to_embed(documents) + + # note that newline is replaced by space + assert prepared_texts == [ + "meta_value 0 | document number 0: content", + "meta_value 1 | document number 1: content", + "meta_value 2 | document number 2: content", + "meta_value 3 | document number 3: content", + "meta_value 4 | document number 4: content", + ] + + def test_prepare_texts_to_embed_w_suffix(self): + documents = [Document(content=f"document number {i}") for i in range(5)] + + embedder = OpenAIDocumentEmbedder( + api_key=Secret.from_token("fake-api-key"), prefix="my_prefix ", suffix=" my_suffix" + ) + + prepared_texts = embedder._prepare_texts_to_embed(documents) + + assert prepared_texts == [ + "my_prefix document number 0 my_suffix", + "my_prefix document number 1 my_suffix", + "my_prefix document number 2 my_suffix", + "my_prefix document number 3 my_suffix", + "my_prefix document number 4 my_suffix", + ] + + def test_run_wrong_input_format(self): + embedder = OpenAIDocumentEmbedder(api_key=Secret.from_token("fake-api-key")) + + # wrong formats + string_input = "text" + list_integers_input = [1, 2, 3] + + with pytest.raises(TypeError, match="OpenAIDocumentEmbedder expects a list of Documents as input"): + embedder.run(documents=string_input) + + with pytest.raises(TypeError, match="OpenAIDocumentEmbedder expects a list of Documents as input"): + embedder.run(documents=list_integers_input) + + def test_run_on_empty_list(self): + embedder = OpenAIDocumentEmbedder(api_key=Secret.from_token("fake-api-key")) + + empty_list_input = [] + result = embedder.run(documents=empty_list_input) + + assert result["documents"] is not None + assert not result["documents"] # empty list + + @pytest.mark.skipif(os.environ.get("OPENAI_API_KEY", "") == "", reason="OPENAI_API_KEY is not set") + @pytest.mark.integration + def test_run(self): + docs = [ + Document(content="I love cheese", meta={"topic": "Cuisine"}), + Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}), + ] + + model = "text-embedding-ada-002" + + embedder = OpenAIDocumentEmbedder(model=model, meta_fields_to_embed=["topic"], embedding_separator=" | ") + + result = embedder.run(documents=docs) + documents_with_embeddings = result["documents"] + + assert isinstance(documents_with_embeddings, list) + assert len(documents_with_embeddings) == len(docs) + for doc in documents_with_embeddings: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert len(doc.embedding) == 1536 + assert all(isinstance(x, float) for x in doc.embedding) + + assert ( + "text" in result["meta"]["model"] and "ada" in result["meta"]["model"] + ), "The model name does not contain 'text' and 'ada'" + + assert result["meta"]["usage"] == {"prompt_tokens": 15, "total_tokens": 15}, "Usage information does not match" diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_openai_text_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_openai_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..31a0360555c7cfa2ddcbd0dd78008111c0a6735c --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_openai_text_embedder.py @@ -0,0 +1,137 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +import pytest + +from haystack.components.embedders.openai_text_embedder import OpenAITextEmbedder +from haystack.utils.auth import Secret + + +class TestOpenAITextEmbedder: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key") + embedder = OpenAITextEmbedder() + + assert embedder.client.api_key == "fake-api-key" + assert embedder.model == "text-embedding-ada-002" + assert embedder.api_base_url == None + assert embedder.organization is None + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.client.timeout == 30 + assert embedder.client.max_retries == 5 + + def test_init_with_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + embedder = OpenAITextEmbedder( + api_key=Secret.from_token("fake-api-key"), + model="model", + api_base_url="https://my-custom-base-url.com", + organization="fake-organization", + prefix="prefix", + suffix="suffix", + timeout=40.0, + max_retries=1, + ) + assert embedder.client.api_key == "fake-api-key" + assert embedder.model == "model" + assert embedder.api_base_url == "https://my-custom-base-url.com" + assert embedder.organization == "fake-organization" + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert embedder.client.timeout == 40.0 + assert embedder.client.max_retries == 1 + + def test_init_with_parameters_and_env_vars(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + embedder = OpenAITextEmbedder( + api_key=Secret.from_token("fake-api-key"), + model="model", + api_base_url="https://my-custom-base-url.com", + organization="fake-organization", + prefix="prefix", + suffix="suffix", + ) + assert embedder.client.api_key == "fake-api-key" + assert embedder.model == "model" + assert embedder.api_base_url == "https://my-custom-base-url.com" + assert embedder.organization == "fake-organization" + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert embedder.client.timeout == 100.0 + assert embedder.client.max_retries == 10 + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + OpenAITextEmbedder() + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key") + component = OpenAITextEmbedder() + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "api_base_url": None, + "dimensions": None, + "model": "text-embedding-ada-002", + "organization": None, + "prefix": "", + "suffix": "", + }, + } + + def test_to_dict_with_custom_init_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "fake-api-key") + component = OpenAITextEmbedder( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + model="model", + api_base_url="https://my-custom-base-url.com", + organization="fake-organization", + prefix="prefix", + suffix="suffix", + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.openai_text_embedder.OpenAITextEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "api_base_url": "https://my-custom-base-url.com", + "model": "model", + "dimensions": None, + "organization": "fake-organization", + "prefix": "prefix", + "suffix": "suffix", + }, + } + + def test_run_wrong_input_format(self): + embedder = OpenAITextEmbedder(api_key=Secret.from_token("fake-api-key")) + + list_integers_input = [1, 2, 3] + + with pytest.raises(TypeError, match="OpenAITextEmbedder expects a string as an input"): + embedder.run(text=list_integers_input) + + @pytest.mark.skipif(os.environ.get("OPENAI_API_KEY", "") == "", reason="OPENAI_API_KEY is not set") + @pytest.mark.integration + def test_run(self): + model = "text-embedding-ada-002" + + embedder = OpenAITextEmbedder(model=model, prefix="prefix ", suffix=" suffix") + result = embedder.run(text="The food was delicious") + + assert len(result["embedding"]) == 1536 + assert all(isinstance(x, float) for x in result["embedding"]) + + assert ( + "text" in result["meta"]["model"] and "ada" in result["meta"]["model"] + ), "The model name does not contain 'text' and 'ada'" + + assert result["meta"]["usage"] == {"prompt_tokens": 6, "total_tokens": 6}, "Usage information does not match" diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_document_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_document_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..d8813f36f4902cfb0d00383474686dd3f1ed4d7f --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_document_embedder.py @@ -0,0 +1,342 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import MagicMock, patch + +import random +import pytest +import torch + +from haystack import Document +from haystack.components.embedders.sentence_transformers_document_embedder import SentenceTransformersDocumentEmbedder +from haystack.utils import ComponentDevice, Secret + + +class TestSentenceTransformersDocumentEmbedder: + def test_init_default(self): + embedder = SentenceTransformersDocumentEmbedder(model="model") + assert embedder.model == "model" + assert embedder.device == ComponentDevice.resolve_device(None) + assert embedder.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.batch_size == 32 + assert embedder.progress_bar is True + assert embedder.normalize_embeddings is False + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + assert embedder.trust_remote_code is False + assert embedder.truncate_dim is None + assert embedder.precision == "float32" + + def test_init_with_parameters(self): + embedder = SentenceTransformersDocumentEmbedder( + model="model", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_token("fake-api-token"), + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + normalize_embeddings=True, + meta_fields_to_embed=["test_field"], + embedding_separator=" | ", + trust_remote_code=True, + truncate_dim=256, + precision="int8", + ) + assert embedder.model == "model" + assert embedder.device == ComponentDevice.from_str("cuda:0") + assert embedder.token == Secret.from_token("fake-api-token") + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.normalize_embeddings is True + assert embedder.meta_fields_to_embed == ["test_field"] + assert embedder.embedding_separator == " | " + assert embedder.trust_remote_code + assert embedder.truncate_dim == 256 + assert embedder.precision == "int8" + + def test_to_dict(self): + component = SentenceTransformersDocumentEmbedder(model="model", device=ComponentDevice.from_str("cpu")) + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder", + "init_parameters": { + "model": "model", + "device": ComponentDevice.from_str("cpu").to_dict(), + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "normalize_embeddings": False, + "embedding_separator": "\n", + "meta_fields_to_embed": [], + "trust_remote_code": False, + "truncate_dim": None, + "model_kwargs": None, + "tokenizer_kwargs": None, + "config_kwargs": None, + "precision": "float32", + }, + } + + def test_to_dict_with_custom_init_parameters(self): + component = SentenceTransformersDocumentEmbedder( + model="model", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_env_var("ENV_VAR", strict=False), + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + normalize_embeddings=True, + meta_fields_to_embed=["meta_field"], + embedding_separator=" - ", + trust_remote_code=True, + truncate_dim=256, + model_kwargs={"torch_dtype": torch.float32}, + tokenizer_kwargs={"model_max_length": 512}, + config_kwargs={"use_memory_efficient_attention": True}, + precision="int8", + ) + data = component.to_dict() + + assert data == { + "type": "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder", + "init_parameters": { + "model": "model", + "device": ComponentDevice.from_str("cuda:0").to_dict(), + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "batch_size": 64, + "progress_bar": False, + "normalize_embeddings": True, + "embedding_separator": " - ", + "trust_remote_code": True, + "meta_fields_to_embed": ["meta_field"], + "truncate_dim": 256, + "model_kwargs": {"torch_dtype": "torch.float32"}, + "tokenizer_kwargs": {"model_max_length": 512}, + "config_kwargs": {"use_memory_efficient_attention": True}, + "precision": "int8", + }, + } + + def test_from_dict(self): + init_parameters = { + "model": "model", + "device": ComponentDevice.from_str("cuda:0").to_dict(), + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "batch_size": 64, + "progress_bar": False, + "normalize_embeddings": True, + "embedding_separator": " - ", + "meta_fields_to_embed": ["meta_field"], + "trust_remote_code": True, + "truncate_dim": 256, + "model_kwargs": {"torch_dtype": "torch.float32"}, + "tokenizer_kwargs": {"model_max_length": 512}, + "config_kwargs": {"use_memory_efficient_attention": True}, + "precision": "int8", + } + component = SentenceTransformersDocumentEmbedder.from_dict( + { + "type": "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder", + "init_parameters": init_parameters, + } + ) + assert component.model == "model" + assert component.device == ComponentDevice.from_str("cuda:0") + assert component.token == Secret.from_env_var("ENV_VAR", strict=False) + assert component.prefix == "prefix" + assert component.suffix == "suffix" + assert component.batch_size == 64 + assert component.progress_bar is False + assert component.normalize_embeddings is True + assert component.embedding_separator == " - " + assert component.trust_remote_code + assert component.meta_fields_to_embed == ["meta_field"] + assert component.truncate_dim == 256 + assert component.model_kwargs == {"torch_dtype": torch.float32} + assert component.tokenizer_kwargs == {"model_max_length": 512} + assert component.config_kwargs == {"use_memory_efficient_attention": True} + assert component.precision == "int8" + + def test_from_dict_no_default_parameters(self): + component = SentenceTransformersDocumentEmbedder.from_dict( + { + "type": "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder", + "init_parameters": {}, + } + ) + assert component.model == "sentence-transformers/all-mpnet-base-v2" + assert component.device == ComponentDevice.resolve_device(None) + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.prefix == "" + assert component.suffix == "" + assert component.batch_size == 32 + assert component.progress_bar is True + assert component.normalize_embeddings is False + assert component.embedding_separator == "\n" + assert component.trust_remote_code is False + assert component.meta_fields_to_embed == [] + assert component.truncate_dim is None + assert component.precision == "float32" + + def test_from_dict_none_device(self): + init_parameters = { + "model": "model", + "device": None, + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "prefix": "prefix", + "suffix": "suffix", + "batch_size": 64, + "progress_bar": False, + "normalize_embeddings": True, + "embedding_separator": " - ", + "meta_fields_to_embed": ["meta_field"], + "trust_remote_code": True, + "truncate_dim": None, + "precision": "float32", + } + component = SentenceTransformersDocumentEmbedder.from_dict( + { + "type": "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder", + "init_parameters": init_parameters, + } + ) + assert component.model == "model" + assert component.device == ComponentDevice.resolve_device(None) + assert component.token == Secret.from_env_var("ENV_VAR", strict=False) + assert component.prefix == "prefix" + assert component.suffix == "suffix" + assert component.batch_size == 64 + assert component.progress_bar is False + assert component.normalize_embeddings is True + assert component.embedding_separator == " - " + assert component.trust_remote_code + assert component.meta_fields_to_embed == ["meta_field"] + assert component.truncate_dim is None + assert component.precision == "float32" + + @patch( + "haystack.components.embedders.sentence_transformers_document_embedder._SentenceTransformersEmbeddingBackendFactory" + ) + def test_warmup(self, mocked_factory): + embedder = SentenceTransformersDocumentEmbedder( + model="model", + token=None, + device=ComponentDevice.from_str("cpu"), + tokenizer_kwargs={"model_max_length": 512}, + config_kwargs={"use_memory_efficient_attention": True}, + ) + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + embedder.embedding_backend.model.max_seq_length = 512 + mocked_factory.get_embedding_backend.assert_called_once_with( + model="model", + device="cpu", + auth_token=None, + trust_remote_code=False, + truncate_dim=None, + model_kwargs=None, + tokenizer_kwargs={"model_max_length": 512}, + config_kwargs={"use_memory_efficient_attention": True}, + ) + + @patch( + "haystack.components.embedders.sentence_transformers_document_embedder._SentenceTransformersEmbeddingBackendFactory" + ) + def test_warmup_doesnt_reload(self, mocked_factory): + embedder = SentenceTransformersDocumentEmbedder(model="model") + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + embedder.warm_up() + mocked_factory.get_embedding_backend.assert_called_once() + + def test_run(self): + embedder = SentenceTransformersDocumentEmbedder(model="model") + embedder.embedding_backend = MagicMock() + embedder.embedding_backend.embed = lambda x, **kwargs: [ + [random.random() for _ in range(16)] for _ in range(len(x)) + ] + + documents = [Document(content=f"document number {i}") for i in range(5)] + + result = embedder.run(documents=documents) + + assert isinstance(result["documents"], list) + assert len(result["documents"]) == len(documents) + for doc in result["documents"]: + assert isinstance(doc, Document) + assert isinstance(doc.embedding, list) + assert isinstance(doc.embedding[0], float) + + def test_run_wrong_input_format(self): + embedder = SentenceTransformersDocumentEmbedder(model="model") + + string_input = "text" + list_integers_input = [1, 2, 3] + + with pytest.raises( + TypeError, match="SentenceTransformersDocumentEmbedder expects a list of Documents as input" + ): + embedder.run(documents=string_input) + + with pytest.raises( + TypeError, match="SentenceTransformersDocumentEmbedder expects a list of Documents as input" + ): + embedder.run(documents=list_integers_input) + + def test_embed_metadata(self): + embedder = SentenceTransformersDocumentEmbedder( + model="model", meta_fields_to_embed=["meta_field"], embedding_separator="\n" + ) + embedder.embedding_backend = MagicMock() + documents = [Document(content=f"document number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + embedder.run(documents=documents) + embedder.embedding_backend.embed.assert_called_once_with( + [ + "meta_value 0\ndocument number 0", + "meta_value 1\ndocument number 1", + "meta_value 2\ndocument number 2", + "meta_value 3\ndocument number 3", + "meta_value 4\ndocument number 4", + ], + batch_size=32, + show_progress_bar=True, + normalize_embeddings=False, + precision="float32", + ) + + def test_prefix_suffix(self): + embedder = SentenceTransformersDocumentEmbedder( + model="model", + prefix="my_prefix ", + suffix=" my_suffix", + meta_fields_to_embed=["meta_field"], + embedding_separator="\n", + ) + embedder.embedding_backend = MagicMock() + documents = [Document(content=f"document number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + embedder.run(documents=documents) + embedder.embedding_backend.embed.assert_called_once_with( + [ + "my_prefix meta_value 0\ndocument number 0 my_suffix", + "my_prefix meta_value 1\ndocument number 1 my_suffix", + "my_prefix meta_value 2\ndocument number 2 my_suffix", + "my_prefix meta_value 3\ndocument number 3 my_suffix", + "my_prefix meta_value 4\ndocument number 4 my_suffix", + ], + batch_size=32, + show_progress_bar=True, + normalize_embeddings=False, + precision="float32", + ) diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_embedding_backend.py b/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_embedding_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..55014183b2371d625277079aa503b44080c18ffc --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_embedding_backend.py @@ -0,0 +1,56 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import patch + +import pytest + +from haystack.components.embedders.backends.sentence_transformers_backend import ( + _SentenceTransformersEmbeddingBackendFactory, +) +from haystack.utils.auth import Secret + + +@patch("haystack.components.embedders.backends.sentence_transformers_backend.SentenceTransformer") +def test_factory_behavior(mock_sentence_transformer): + embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend( + model="my_model", device="cpu" + ) + same_embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend("my_model", "cpu") + another_embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend( + model="another_model", device="cpu" + ) + + assert same_embedding_backend is embedding_backend + assert another_embedding_backend is not embedding_backend + + +@patch("haystack.components.embedders.backends.sentence_transformers_backend.SentenceTransformer") +def test_model_initialization(mock_sentence_transformer): + _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend( + model="model", + device="cpu", + auth_token=Secret.from_token("fake-api-token"), + trust_remote_code=True, + truncate_dim=256, + ) + mock_sentence_transformer.assert_called_once_with( + model_name_or_path="model", + device="cpu", + use_auth_token="fake-api-token", + trust_remote_code=True, + truncate_dim=256, + model_kwargs=None, + tokenizer_kwargs=None, + config_kwargs=None, + ) + + +@patch("haystack.components.embedders.backends.sentence_transformers_backend.SentenceTransformer") +def test_embedding_function_with_kwargs(mock_sentence_transformer): + embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend(model="model") + + data = ["sentence1", "sentence2"] + embedding_backend.embed(data=data, normalize_embeddings=True) + + embedding_backend.model.encode.assert_called_once_with(data, normalize_embeddings=True) diff --git a/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_text_embedder.py b/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_text_embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..195ee8efd1b58aaca4a42bbf27470250e6fe6892 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/embedders/test_sentence_transformers_text_embedder.py @@ -0,0 +1,298 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import MagicMock, patch + +import torch +import random +import pytest + +from haystack.components.embedders.sentence_transformers_text_embedder import SentenceTransformersTextEmbedder +from haystack.utils import ComponentDevice, Secret + + +class TestSentenceTransformersTextEmbedder: + def test_init_default(self): + embedder = SentenceTransformersTextEmbedder(model="model") + assert embedder.model == "model" + assert embedder.device == ComponentDevice.resolve_device(None) + assert embedder.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.batch_size == 32 + assert embedder.progress_bar is True + assert embedder.normalize_embeddings is False + assert embedder.trust_remote_code is False + assert embedder.truncate_dim is None + assert embedder.precision == "float32" + + def test_init_with_parameters(self): + embedder = SentenceTransformersTextEmbedder( + model="model", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_token("fake-api-token"), + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + normalize_embeddings=True, + trust_remote_code=True, + truncate_dim=256, + precision="int8", + ) + assert embedder.model == "model" + assert embedder.device == ComponentDevice.from_str("cuda:0") + assert embedder.token == Secret.from_token("fake-api-token") + assert embedder.prefix == "prefix" + assert embedder.suffix == "suffix" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.normalize_embeddings is True + assert embedder.trust_remote_code is True + assert embedder.truncate_dim == 256 + assert embedder.precision == "int8" + + def test_to_dict(self): + component = SentenceTransformersTextEmbedder(model="model", device=ComponentDevice.from_str("cpu")) + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder", + "init_parameters": { + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "model": "model", + "device": ComponentDevice.from_str("cpu").to_dict(), + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "normalize_embeddings": False, + "trust_remote_code": False, + "truncate_dim": None, + "model_kwargs": None, + "tokenizer_kwargs": None, + "config_kwargs": None, + "precision": "float32", + }, + } + + def test_to_dict_with_custom_init_parameters(self): + component = SentenceTransformersTextEmbedder( + model="model", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_env_var("ENV_VAR", strict=False), + prefix="prefix", + suffix="suffix", + batch_size=64, + progress_bar=False, + normalize_embeddings=True, + trust_remote_code=True, + truncate_dim=256, + model_kwargs={"torch_dtype": torch.float32}, + tokenizer_kwargs={"model_max_length": 512}, + config_kwargs={"use_memory_efficient_attention": False}, + precision="int8", + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder", + "init_parameters": { + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "model": "model", + "device": ComponentDevice.from_str("cuda:0").to_dict(), + "prefix": "prefix", + "suffix": "suffix", + "batch_size": 64, + "progress_bar": False, + "normalize_embeddings": True, + "trust_remote_code": True, + "truncate_dim": 256, + "model_kwargs": {"torch_dtype": "torch.float32"}, + "tokenizer_kwargs": {"model_max_length": 512}, + "config_kwargs": {"use_memory_efficient_attention": False}, + "precision": "int8", + }, + } + + def test_to_dict_not_serialize_token(self): + component = SentenceTransformersTextEmbedder(model="model", token=Secret.from_token("fake-api-token")) + with pytest.raises(ValueError, match="Cannot serialize token-based secret"): + component.to_dict() + + def test_from_dict(self): + data = { + "type": "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder", + "init_parameters": { + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "model": "model", + "device": ComponentDevice.from_str("cpu").to_dict(), + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "normalize_embeddings": False, + "trust_remote_code": False, + "truncate_dim": None, + "model_kwargs": {"torch_dtype": "torch.float32"}, + "tokenizer_kwargs": {"model_max_length": 512}, + "config_kwargs": {"use_memory_efficient_attention": False}, + "precision": "float32", + }, + } + component = SentenceTransformersTextEmbedder.from_dict(data) + assert component.model == "model" + assert component.device == ComponentDevice.from_str("cpu") + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.prefix == "" + assert component.suffix == "" + assert component.batch_size == 32 + assert component.progress_bar is True + assert component.normalize_embeddings is False + assert component.trust_remote_code is False + assert component.truncate_dim is None + assert component.model_kwargs == {"torch_dtype": torch.float32} + assert component.tokenizer_kwargs == {"model_max_length": 512} + assert component.config_kwargs == {"use_memory_efficient_attention": False} + assert component.precision == "float32" + + def test_from_dict_no_default_parameters(self): + data = { + "type": "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder", + "init_parameters": {}, + } + component = SentenceTransformersTextEmbedder.from_dict(data) + assert component.model == "sentence-transformers/all-mpnet-base-v2" + assert component.device == ComponentDevice.resolve_device(None) + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.prefix == "" + assert component.suffix == "" + assert component.batch_size == 32 + assert component.progress_bar is True + assert component.normalize_embeddings is False + assert component.trust_remote_code is False + assert component.truncate_dim is None + assert component.precision == "float32" + + def test_from_dict_none_device(self): + data = { + "type": "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder", + "init_parameters": { + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "model": "model", + "device": None, + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "normalize_embeddings": False, + "trust_remote_code": False, + "truncate_dim": 256, + "precision": "int8", + }, + } + component = SentenceTransformersTextEmbedder.from_dict(data) + assert component.model == "model" + assert component.device == ComponentDevice.resolve_device(None) + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.prefix == "" + assert component.suffix == "" + assert component.batch_size == 32 + assert component.progress_bar is True + assert component.normalize_embeddings is False + assert component.trust_remote_code is False + assert component.truncate_dim == 256 + assert component.precision == "int8" + + @patch( + "haystack.components.embedders.sentence_transformers_text_embedder._SentenceTransformersEmbeddingBackendFactory" + ) + def test_warmup(self, mocked_factory): + embedder = SentenceTransformersTextEmbedder( + model="model", + token=None, + device=ComponentDevice.from_str("cpu"), + tokenizer_kwargs={"model_max_length": 512}, + ) + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + embedder.embedding_backend.model.max_seq_length = 512 + mocked_factory.get_embedding_backend.assert_called_once_with( + model="model", + device="cpu", + auth_token=None, + trust_remote_code=False, + truncate_dim=None, + model_kwargs=None, + tokenizer_kwargs={"model_max_length": 512}, + config_kwargs=None, + ) + + @patch( + "haystack.components.embedders.sentence_transformers_text_embedder._SentenceTransformersEmbeddingBackendFactory" + ) + def test_warmup_doesnt_reload(self, mocked_factory): + embedder = SentenceTransformersTextEmbedder(model="model") + mocked_factory.get_embedding_backend.assert_not_called() + embedder.warm_up() + embedder.warm_up() + mocked_factory.get_embedding_backend.assert_called_once() + + def test_run(self): + embedder = SentenceTransformersTextEmbedder(model="model") + embedder.embedding_backend = MagicMock() + embedder.embedding_backend.embed = lambda x, **kwargs: [ + [random.random() for _ in range(16)] for _ in range(len(x)) + ] + + text = "a nice text to embed" + + result = embedder.run(text=text) + embedding = result["embedding"] + + assert isinstance(embedding, list) + assert all(isinstance(el, float) for el in embedding) + + def test_run_wrong_input_format(self): + embedder = SentenceTransformersTextEmbedder(model="model") + embedder.embedding_backend = MagicMock() + + list_integers_input = [1, 2, 3] + + with pytest.raises(TypeError, match="SentenceTransformersTextEmbedder expects a string as input"): + embedder.run(text=list_integers_input) + + @pytest.mark.integration + def test_run_trunc(self): + """ + sentence-transformers/paraphrase-albert-small-v2 maps sentences & paragraphs to a 768 dimensional dense vector space + """ + checkpoint = "sentence-transformers/paraphrase-albert-small-v2" + text = "a nice text to embed" + + embedder_def = SentenceTransformersTextEmbedder(model=checkpoint) + embedder_def.warm_up() + result_def = embedder_def.run(text=text) + embedding_def = result_def["embedding"] + + embedder_trunc = SentenceTransformersTextEmbedder(model=checkpoint, truncate_dim=128) + embedder_trunc.warm_up() + result_trunc = embedder_trunc.run(text=text) + embedding_trunc = result_trunc["embedding"] + + assert len(embedding_def) == 768 + assert len(embedding_trunc) == 128 + + @pytest.mark.integration + def test_run_quantization(self): + """ + sentence-transformers/paraphrase-albert-small-v2 maps sentences & paragraphs to a 768 dimensional dense vector space + """ + checkpoint = "sentence-transformers/paraphrase-albert-small-v2" + text = "a nice text to embed" + + embedder_def = SentenceTransformersTextEmbedder(model=checkpoint, precision="int8") + embedder_def.warm_up() + result_def = embedder_def.run(text=text) + embedding_def = result_def["embedding"] + + assert len(embedding_def) == 768 + assert all(isinstance(el, int) for el in embedding_def) diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/__init__.py b/testbed/deepset-ai__haystack/test/components/evaluators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_answer_exact_match.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_answer_exact_match.py new file mode 100644 index 0000000000000000000000000000000000000000..0c123f0d3a6d0e0ca96273136cf769f28cbacfd3 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_answer_exact_match.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.components.evaluators import AnswerExactMatchEvaluator + + +def test_run_with_all_matching(): + evaluator = AnswerExactMatchEvaluator() + result = evaluator.run(ground_truth_answers=["Berlin", "Paris"], predicted_answers=["Berlin", "Paris"]) + + assert result == {"individual_scores": [1, 1], "score": 1.0} + + +def test_run_with_no_matching(): + evaluator = AnswerExactMatchEvaluator() + result = evaluator.run(ground_truth_answers=["Berlin", "Paris"], predicted_answers=["Paris", "London"]) + + assert result == {"individual_scores": [0, 0], "score": 0.0} + + +def test_run_with_partial_matching(): + evaluator = AnswerExactMatchEvaluator() + result = evaluator.run(ground_truth_answers=["Berlin", "Paris"], predicted_answers=["Berlin", "London"]) + + assert result == {"individual_scores": [1, 0], "score": 0.5} + + +def test_run_with_complex_data(): + evaluator = AnswerExactMatchEvaluator() + result = evaluator.run( + ground_truth_answers=[ + "France", + "9th century", + "9th", + "classical music", + "classical", + "11th century", + "the 11th", + "Denmark", + "Iceland", + "Norway", + "10th century", + "10th", + ], + predicted_answers=[ + "France", + "9th century", + "10th century", + "9th", + "classic music", + "rock music", + "dubstep", + "the 11th", + "11th century", + "Denmark, Iceland and Norway", + "10th century", + "10th", + ], + ) + assert result == {"individual_scores": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], "score": 0.3333333333333333} + + +def test_run_with_different_lengths(): + evaluator = AnswerExactMatchEvaluator() + + with pytest.raises(ValueError): + evaluator.run(ground_truth_answers=["Berlin"], predicted_answers=["Berlin", "London"]) + + with pytest.raises(ValueError): + evaluator.run(ground_truth_answers=["Berlin", "Paris"], predicted_answers=["Berlin"]) diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_document_map.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_document_map.py new file mode 100644 index 0000000000000000000000000000000000000000..7c7b26c0892215368b22719d5a64556a8b20c986 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_document_map.py @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document +from haystack.components.evaluators.document_map import DocumentMAPEvaluator + + +def test_run_with_all_matching(): + evaluator = DocumentMAPEvaluator() + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + ) + + assert result == {"individual_scores": [1.0, 1.0], "score": 1.0} + + +def test_run_with_no_matching(): + evaluator = DocumentMAPEvaluator() + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Paris")], [Document(content="London")]], + ) + + assert result == {"individual_scores": [0.0, 0.0], "score": 0.0} + + +def test_run_with_partial_matching(): + evaluator = DocumentMAPEvaluator() + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + + assert result == {"individual_scores": [1.0, 0.0], "score": 0.5} + + +def test_run_with_complex_data(): + evaluator = DocumentMAPEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + [Document(content="classical music"), Document(content="classical")], + [Document(content="11th century"), Document(content="the 11th")], + [Document(content="Denmark, Iceland and Norway")], + [Document(content="10th century"), Document(content="10th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + [Document(content="classical"), Document(content="rock music"), Document(content="dubstep")], + [Document(content="11th"), Document(content="the 11th"), Document(content="11th century")], + [Document(content="Denmark"), Document(content="Norway"), Document(content="Iceland")], + [ + Document(content="10th century"), + Document(content="the first half of the 10th century"), + Document(content="10th"), + Document(content="10th"), + ], + ], + ) + assert result == { + "individual_scores": [ + 1.0, + pytest.approx(0.8333333333333333), + 1.0, + pytest.approx(0.5833333333333333), + 0.0, + pytest.approx(0.8055555555555555), + ], + "score": pytest.approx(0.7037037037037037), + } + + +def test_run_with_different_lengths(): + with pytest.raises(ValueError): + evaluator = DocumentMAPEvaluator() + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + + with pytest.raises(ValueError): + evaluator = DocumentMAPEvaluator() + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")]], + ) diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_document_ndcg.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_document_ndcg.py new file mode 100644 index 0000000000000000000000000000000000000000..3924855f720a215dcccd77f58e1e535df668fe58 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_document_ndcg.py @@ -0,0 +1,202 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document +from haystack.components.evaluators.document_ndcg import DocumentNDCGEvaluator + + +def test_run_with_scores(): + evaluator = DocumentNDCGEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [ + Document(content="doc1", score=3), + Document(content="doc2", score=2), + Document(content="doc3", score=3), + Document(content="doc6", score=2), + Document(content="doc7", score=3), + Document(content="doc8", score=2), + ] + ], + retrieved_documents=[ + [ + Document(content="doc1"), + Document(content="doc2"), + Document(content="doc3"), + Document(content="doc4"), + Document(content="doc5"), + ] + ], + ) + assert result["individual_scores"][0] == pytest.approx(0.6592, abs=1e-4) + assert result["score"] == pytest.approx(0.6592, abs=1e-4) + + +def test_run_without_scores(): + evaluator = DocumentNDCGEvaluator() + result = evaluator.run( + ground_truth_documents=[[Document(content="France"), Document(content="Paris")]], + retrieved_documents=[[Document(content="France"), Document(content="Germany"), Document(content="Paris")]], + ) + assert result["individual_scores"][0] == pytest.approx(0.9197, abs=1e-4) + assert result["score"] == pytest.approx(0.9197, abs=1e-4) + + +def test_run_with_multiple_lists_of_docs(): + evaluator = DocumentNDCGEvaluator() + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France"), Document(content="Paris")], + [ + Document(content="doc1", score=3), + Document(content="doc2", score=2), + Document(content="doc3", score=3), + Document(content="doc6", score=2), + Document(content="doc7", score=3), + Document(content="doc8", score=2), + ], + ], + retrieved_documents=[ + [Document(content="France"), Document(content="Germany"), Document(content="Paris")], + [ + Document(content="doc1"), + Document(content="doc2"), + Document(content="doc3"), + Document(content="doc4"), + Document(content="doc5"), + ], + ], + ) + assert result["individual_scores"][0] == pytest.approx(0.9197, abs=1e-4) + assert result["individual_scores"][1] == pytest.approx(0.6592, abs=1e-4) + assert result["score"] == pytest.approx(0.7895, abs=1e-4) + + +def test_run_with_different_lengths(): + evaluator = DocumentNDCGEvaluator() + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")]], + ) + + +def test_run_with_mixed_documents_with_and_without_scores(): + evaluator = DocumentNDCGEvaluator() + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="France", score=3), Document(content="Paris")]], + retrieved_documents=[[Document(content="France"), Document(content="Germany"), Document(content="Paris")]], + ) + + +def test_run_empty_retrieved(): + evaluator = DocumentNDCGEvaluator() + result = evaluator.run(ground_truth_documents=[[Document(content="France")]], retrieved_documents=[[]]) + assert result["individual_scores"] == [0.0] + assert result["score"] == 0.0 + + +def test_run_empty_ground_truth(): + evaluator = DocumentNDCGEvaluator() + result = evaluator.run(ground_truth_documents=[[]], retrieved_documents=[[Document(content="France")]]) + assert result["individual_scores"] == [0.0] + assert result["score"] == 0.0 + + +def test_run_empty_retrieved_and_empty_ground_truth(): + evaluator = DocumentNDCGEvaluator() + result = evaluator.run(ground_truth_documents=[[]], retrieved_documents=[[]]) + assert result["individual_scores"] == [0.0] + assert result["score"] == 0.0 + + +def test_run_no_retrieved(): + evaluator = DocumentNDCGEvaluator() + with pytest.raises(ValueError): + result = evaluator.run(ground_truth_documents=[[Document(content="France")]], retrieved_documents=[]) + + +def test_run_no_ground_truth(): + evaluator = DocumentNDCGEvaluator() + with pytest.raises(ValueError): + evaluator.run(ground_truth_documents=[], retrieved_documents=[[Document(content="France")]]) + + +def test_run_no_retrieved_and_no_ground_truth(): + evaluator = DocumentNDCGEvaluator() + with pytest.raises(ValueError): + evaluator.run(ground_truth_documents=[], retrieved_documents=[]) + + +def test_calculate_dcg_with_scores(): + evaluator = DocumentNDCGEvaluator() + gt_docs = [ + Document(content="doc1", score=3), + Document(content="doc2", score=2), + Document(content="doc3", score=3), + Document(content="doc4", score=0), + Document(content="doc5", score=1), + Document(content="doc6", score=2), + ] + ret_docs = [ + Document(content="doc1"), + Document(content="doc2"), + Document(content="doc3"), + Document(content="doc4"), + Document(content="doc5"), + Document(content="doc6"), + ] + dcg = evaluator.calculate_dcg(gt_docs, ret_docs) + assert dcg == pytest.approx(6.8611, abs=1e-4) + + +def test_calculate_dcg_without_scores(): + evaluator = DocumentNDCGEvaluator() + gt_docs = [Document(content="doc1"), Document(content="doc2")] + ret_docs = [Document(content="doc2"), Document(content="doc3"), Document(content="doc1")] + dcg = evaluator.calculate_dcg(gt_docs, ret_docs) + assert dcg == pytest.approx(1.5, abs=1e-4) + + +def test_calculate_dcg_empty(): + evaluator = DocumentNDCGEvaluator() + gt_docs = [Document(content="doc1")] + ret_docs = [] + dcg = evaluator.calculate_dcg(gt_docs, ret_docs) + assert dcg == 0 + + +def test_calculate_idcg_with_scores(): + evaluator = DocumentNDCGEvaluator() + gt_docs = [ + Document(content="doc1", score=3), + Document(content="doc2", score=3), + Document(content="doc3", score=2), + Document(content="doc4", score=3), + Document(content="doc5", score=2), + Document(content="doc6", score=2), + ] + idcg = evaluator.calculate_idcg(gt_docs) + assert idcg == pytest.approx(8.7403, abs=1e-4) + + +def test_calculate_idcg_without_scores(): + evaluator = DocumentNDCGEvaluator() + gt_docs = [Document(content="doc1"), Document(content="doc2"), Document(content="doc3")] + idcg = evaluator.calculate_idcg(gt_docs) + assert idcg == pytest.approx(2.1309, abs=1e-4) + + +def test_calculate_idcg_empty(): + evaluator = DocumentNDCGEvaluator() + gt_docs = [] + idcg = evaluator.calculate_idcg(gt_docs) + assert idcg == 0 diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_document_recall.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_document_recall.py new file mode 100644 index 0000000000000000000000000000000000000000..2c438441ccd082091f7d333080129024ecbddd04 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_document_recall.py @@ -0,0 +1,188 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.components.evaluators.document_recall import DocumentRecallEvaluator, RecallMode +from haystack.dataclasses import Document +from haystack import default_from_dict + + +def test_init_with_unknown_mode_string(): + with pytest.raises(ValueError): + DocumentRecallEvaluator(mode="unknown_mode") + + +class TestDocumentRecallEvaluatorSingleHit: + @pytest.fixture + def evaluator(self): + return DocumentRecallEvaluator(mode=RecallMode.SINGLE_HIT) + + def test_run_with_all_matching(self, evaluator): + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [1.0, 1.0], "score": 1.0} + + def test_run_with_no_matching(self, evaluator): + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Paris")], [Document(content="London")]], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [0.0, 0.0], "score": 0.0} + + def test_run_with_partial_matching(self, evaluator): + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [1.0, 0.0], "score": 0.5} + + def test_run_with_complex_data(self, evaluator): + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + [Document(content="classical music"), Document(content="classical")], + [Document(content="11th century"), Document(content="the 11th")], + [Document(content="Denmark, Iceland and Norway")], + [Document(content="10th century"), Document(content="10th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + [Document(content="classical"), Document(content="rock music"), Document(content="dubstep")], + [Document(content="11th"), Document(content="the 11th"), Document(content="11th century")], + [Document(content="Denmark"), Document(content="Norway"), Document(content="Iceland")], + [ + Document(content="10th century"), + Document(content="the first half of the 10th century"), + Document(content="10th"), + Document(content="10th"), + ], + ], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [1, 1, 1, 1, 0, 1], "score": 0.8333333333333334} + + def test_run_with_different_lengths(self, evaluator): + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")]], + ) + + def test_to_dict(self, evaluator): + data = evaluator.to_dict() + assert data == { + "type": "haystack.components.evaluators.document_recall.DocumentRecallEvaluator", + "init_parameters": {"mode": "single_hit"}, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.evaluators.document_recall.DocumentRecallEvaluator", + "init_parameters": {"mode": "single_hit"}, + } + new_evaluator = default_from_dict(DocumentRecallEvaluator, data) + assert new_evaluator.mode == RecallMode.SINGLE_HIT + + +class TestDocumentRecallEvaluatorMultiHit: + @pytest.fixture + def evaluator(self): + return DocumentRecallEvaluator(mode=RecallMode.MULTI_HIT) + + def test_run_with_all_matching(self, evaluator): + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [1.0, 1.0], "score": 1.0} + + def test_run_with_no_matching(self, evaluator): + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Paris")], [Document(content="London")]], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [0.0, 0.0], "score": 0.0} + + def test_run_with_partial_matching(self, evaluator): + result = evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [1.0, 0.0], "score": 0.5} + + def test_run_with_complex_data(self, evaluator): + result = evaluator.run( + ground_truth_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="9th")], + [Document(content="classical music"), Document(content="classical")], + [Document(content="11th century"), Document(content="the 11th")], + [ + Document(content="Denmark"), + Document(content="Iceland"), + Document(content="Norway"), + Document(content="Denmark, Iceland and Norway"), + ], + [Document(content="10th century"), Document(content="10th")], + ], + retrieved_documents=[ + [Document(content="France")], + [Document(content="9th century"), Document(content="10th century"), Document(content="9th")], + [Document(content="classical"), Document(content="rock music"), Document(content="dubstep")], + [Document(content="11th"), Document(content="the 11th"), Document(content="11th century")], + [Document(content="Denmark"), Document(content="Norway"), Document(content="Iceland")], + [ + Document(content="10th century"), + Document(content="the first half of the 10th century"), + Document(content="10th"), + Document(content="10th"), + ], + ], + ) + assert all(isinstance(individual_score, float) for individual_score in result["individual_scores"]) + assert result == {"individual_scores": [1.0, 1.0, 0.5, 1.0, 0.75, 1.0], "score": 0.875} + + def test_run_with_different_lengths(self, evaluator): + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")]], + retrieved_documents=[[Document(content="Berlin")], [Document(content="London")]], + ) + + with pytest.raises(ValueError): + evaluator.run( + ground_truth_documents=[[Document(content="Berlin")], [Document(content="Paris")]], + retrieved_documents=[[Document(content="Berlin")]], + ) + + def test_to_dict(self, evaluator): + data = evaluator.to_dict() + assert data == { + "type": "haystack.components.evaluators.document_recall.DocumentRecallEvaluator", + "init_parameters": {"mode": "multi_hit"}, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.evaluators.document_recall.DocumentRecallEvaluator", + "init_parameters": {"mode": "multi_hit"}, + } + new_evaluator = default_from_dict(DocumentRecallEvaluator, data) + assert new_evaluator.mode == RecallMode.MULTI_HIT diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_faithfulness_evaluator.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_faithfulness_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..de92388ece08266f3482206a6d4b8b6314194763 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_faithfulness_evaluator.py @@ -0,0 +1,292 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +import math +from typing import List + +import pytest + +from haystack import Pipeline +from haystack.components.evaluators import FaithfulnessEvaluator +from haystack.utils.auth import Secret + + +class TestFaithfulnessEvaluator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = FaithfulnessEvaluator() + assert component.api == "openai" + assert component.generator.client.api_key == "test-api-key" + assert component.instructions == ( + "Your task is to judge the faithfulness or groundedness of statements based " + "on context information. First, please extract statements from a provided predicted " + "answer to a question. Second, calculate a faithfulness score for each " + "statement made in the predicted answer. The score is 1 if the statement can be " + "inferred from the provided context or 0 if it cannot be inferred." + ) + assert component.inputs == [ + ("questions", List[str]), + ("contexts", List[List[str]]), + ("predicted_answers", List[str]), + ] + assert component.outputs == ["statements", "statement_scores"] + assert component.examples == [ + { + "inputs": { + "questions": "What is the capital of Germany and when was it founded?", + "contexts": ["Berlin is the capital of Germany and was founded in 1244."], + "predicted_answers": "The capital of Germany, Berlin, was founded in the 13th century.", + }, + "outputs": { + "statements": ["Berlin is the capital of Germany.", "Berlin was founded in 1244."], + "statement_scores": [1, 1], + }, + }, + { + "inputs": { + "questions": "What is the capital of France?", + "contexts": ["Berlin is the capital of Germany."], + "predicted_answers": "Paris", + }, + "outputs": {"statements": ["Paris is the capital of France."], "statement_scores": [0]}, + }, + { + "inputs": { + "questions": "What is the capital of Italy?", + "contexts": ["Rome is the capital of Italy."], + "predicted_answers": "Rome is the capital of Italy with more than 4 million inhabitants.", + }, + "outputs": { + "statements": ["Rome is the capital of Italy.", "Rome has more than 4 million inhabitants."], + "statement_scores": [1, 0], + }, + }, + ] + + def test_init_fail_wo_openai_api_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + FaithfulnessEvaluator() + + def test_init_with_parameters(self): + component = FaithfulnessEvaluator( + api_key=Secret.from_token("test-api-key"), + api="openai", + examples=[ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + { + "inputs": {"predicted_answers": "Football is the most popular sport."}, + "outputs": {"custom_score": 0}, + }, + ], + ) + assert component.generator.client.api_key == "test-api-key" + assert component.api == "openai" + assert component.examples == [ + {"inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, "outputs": {"custom_score": 1}}, + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"custom_score": 0}}, + ] + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = FaithfulnessEvaluator( + api="openai", + api_key=Secret.from_env_var("ENV_VAR"), + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + raise_on_failure=False, + progress_bar=False, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.evaluators.faithfulness.FaithfulnessEvaluator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "api": "openai", + "api_params": {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}}, + "examples": [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + "progress_bar": False, + "raise_on_failure": False, + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + + data = { + "type": "haystack.components.evaluators.faithfulness.FaithfulnessEvaluator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "api": "openai", + "examples": [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + }, + } + component = FaithfulnessEvaluator.from_dict(data) + assert component.api == "openai" + assert component.generator.client.api_key == "test-api-key" + assert component.examples == [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ] + + pipeline = Pipeline() + pipeline.add_component("evaluator", component) + assert pipeline.loads(pipeline.dumps()) + + def test_run_calculates_mean_score(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = FaithfulnessEvaluator() + + def generator_run(self, *args, **kwargs): + if "Football" in kwargs["prompt"]: + return {"replies": ['{"statements": ["a", "b"], "statement_scores": [1, 0]}']} + else: + return {"replies": ['{"statements": ["c", "d"], "statement_scores": [1, 1]}']} + + monkeypatch.setattr("haystack.components.generators.openai.OpenAIGenerator.run", generator_run) + + questions = ["Which is the most popular global sport?", "Who created the Python language?"] + contexts = [ + [ + "The popularity of sports can be measured in various ways, including TV viewership, social media " + "presence, number of participants, and economic impact. Football is undoubtedly the world's most " + "popular sport with major events like the FIFA World Cup and sports personalities like Ronaldo and " + "Messi, drawing a followership of more than 4 billion people." + ], + [ + "Python, created by Guido van Rossum in the late 1980s, is a high-level general-purpose programming " + "language. Its design philosophy emphasizes code readability, and its language constructs aim to help " + "programmers write clear, logical code for both small and large-scale software projects." + ], + ] + predicted_answers = [ + "Football is the most popular sport with around 4 billion followers worldwide.", + "Python is a high-level general-purpose programming language that was created by George Lucas.", + ] + results = component.run(questions=questions, contexts=contexts, predicted_answers=predicted_answers) + assert results == { + "individual_scores": [0.5, 1], + "results": [ + {"score": 0.5, "statement_scores": [1, 0], "statements": ["a", "b"]}, + {"score": 1, "statement_scores": [1, 1], "statements": ["c", "d"]}, + ], + "score": 0.75, + "meta": None, + } + + def test_run_no_statements_extracted(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = FaithfulnessEvaluator() + + def generator_run(self, *args, **kwargs): + if "Football" in kwargs["prompt"]: + return {"replies": ['{"statements": ["a", "b"], "statement_scores": [1, 0]}']} + else: + return {"replies": ['{"statements": [], "statement_scores": []}']} + + monkeypatch.setattr("haystack.components.generators.openai.OpenAIGenerator.run", generator_run) + + questions = ["Which is the most popular global sport?", "Who created the Python language?"] + contexts = [ + [ + "The popularity of sports can be measured in various ways, including TV viewership, social media " + "presence, number of participants, and economic impact. Football is undoubtedly the world's most " + "popular sport with major events like the FIFA World Cup and sports personalities like Ronaldo and " + "Messi, drawing a followership of more than 4 billion people." + ], + [], + ] + predicted_answers = [ + "Football is the most popular sport with around 4 billion followers worldwide.", + "I don't know.", + ] + results = component.run(questions=questions, contexts=contexts, predicted_answers=predicted_answers) + assert results == { + "individual_scores": [0.5, 0], + "results": [ + {"score": 0.5, "statement_scores": [1, 0], "statements": ["a", "b"]}, + {"score": 0, "statement_scores": [], "statements": []}, + ], + "score": 0.25, + "meta": None, + } + + def test_run_missing_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = FaithfulnessEvaluator() + with pytest.raises(ValueError, match="LLM evaluator expected input parameter"): + component.run() + + def test_run_returns_nan_raise_on_failure_false(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = FaithfulnessEvaluator(raise_on_failure=False) + + def generator_run(self, *args, **kwargs): + if "Python" in kwargs["prompt"]: + raise Exception("OpenAI API request failed.") + else: + return {"replies": ['{"statements": ["c", "d"], "statement_scores": [1, 1]}']} + + monkeypatch.setattr("haystack.components.generators.openai.OpenAIGenerator.run", generator_run) + + questions = ["Which is the most popular global sport?", "Who created the Python language?"] + contexts = [ + [ + "The popularity of sports can be measured in various ways, including TV viewership, social media " + "presence, number of participants, and economic impact. Football is undoubtedly the world's most " + "popular sport with major events like the FIFA World Cup and sports personalities like Ronaldo and " + "Messi, drawing a followership of more than 4 billion people." + ], + [ + "Python, created by Guido van Rossum in the late 1980s, is a high-level general-purpose programming " + "language. Its design philosophy emphasizes code readability, and its language constructs aim to help " + "programmers write clear, logical code for both small and large-scale software projects." + ], + ] + predicted_answers = [ + "Football is the most popular sport with around 4 billion followers worldwide.", + "Guido van Rossum.", + ] + results = component.run(questions=questions, contexts=contexts, predicted_answers=predicted_answers) + + assert math.isnan(results["score"]) + + assert results["individual_scores"][0] == 1.0 + assert math.isnan(results["individual_scores"][1]) + + assert results["results"][0] == {"statements": ["c", "d"], "statement_scores": [1, 1], "score": 1.0} + + assert results["results"][1]["statements"] == [] + assert results["results"][1]["statement_scores"] == [] + assert math.isnan(results["results"][1]["score"]) + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run(self): + questions = ["What is Python and who created it?"] + contexts = [["Python is a programming language created by Guido van Rossum."]] + predicted_answers = ["Python is a programming language created by George Lucas."] + evaluator = FaithfulnessEvaluator() + result = evaluator.run(questions=questions, contexts=contexts, predicted_answers=predicted_answers) + + required_fields = {"individual_scores", "results", "score"} + assert all(field in result for field in required_fields) + nested_required_fields = {"score", "statement_scores", "statements"} + assert all(field in result["results"][0] for field in nested_required_fields) + + # assert that metadata is present in the result + assert "meta" in result + assert "prompt_tokens" in result["meta"][0]["usage"] + assert "completion_tokens" in result["meta"][0]["usage"] + assert "total_tokens" in result["meta"][0]["usage"] diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_llm_evaluator.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_llm_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..e0feb6c0f43e58d08360ca9ceaea39b92e78b558 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_llm_evaluator.py @@ -0,0 +1,513 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from typing import List + +import pytest + +from haystack import Pipeline +from haystack.components.evaluators import LLMEvaluator +from haystack.utils.auth import Secret + + +class TestLLMEvaluator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + assert component.api == "openai" + assert component.generator.client.api_key == "test-api-key" + assert component.api_params == {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}} + assert component.instructions == "test-instruction" + assert component.inputs == [("predicted_answers", List[str])] + assert component.outputs == ["score"] + assert component.examples == [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ] + + def test_init_fail_wo_openai_api_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + LLMEvaluator( + api="openai", + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + + def test_init_with_parameters(self): + component = LLMEvaluator( + instructions="test-instruction", + api_key=Secret.from_token("test-api-key"), + api_params={"generation_kwargs": {"seed": 43}}, + inputs=[("predicted_answers", List[str])], + outputs=["custom_score"], + api="openai", + examples=[ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + { + "inputs": {"predicted_answers": "Football is the most popular sport."}, + "outputs": {"custom_score": 0}, + }, + ], + ) + assert component.generator.client.api_key == "test-api-key" + assert component.api_params == {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 43}} + assert component.api == "openai" + assert component.examples == [ + {"inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, "outputs": {"custom_score": 1}}, + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"custom_score": 0}}, + ] + assert component.instructions == "test-instruction" + assert component.inputs == [("predicted_answers", List[str])] + assert component.outputs == ["custom_score"] + + def test_init_with_invalid_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + # Invalid inputs + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs={("predicted_answers", List[str])}, + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[(List[str], "predicted_answers")], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[List[str]], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs={("predicted_answers", str)}, + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + + # Invalid outputs + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs="score", + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=[["score"]], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + + # Invalid examples + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples={ + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + [ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + } + ] + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + { + "wrong_key": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + } + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + { + "inputs": [{"predicted_answers": "Damn, this is straight outta hell!!!"}], + "outputs": [{"custom_score": 1}], + } + ], + ) + with pytest.raises(ValueError): + LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[{"inputs": {1: "Damn, this is straight outta hell!!!"}, "outputs": {2: 1}}], + ) + + def test_to_dict_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + api_key=Secret.from_env_var("OPENAI_API_KEY"), + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.evaluators.llm_evaluator.LLMEvaluator", + "init_parameters": { + "api_params": {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}}, + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "api": "openai", + "instructions": "test-instruction", + "inputs": [["predicted_answers", "typing.List[str]"]], + "outputs": ["score"], + "progress_bar": True, + "examples": [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + + data = { + "type": "haystack.components.evaluators.llm_evaluator.LLMEvaluator", + "init_parameters": { + "api_params": {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}}, + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "api": "openai", + "instructions": "test-instruction", + "inputs": [["predicted_answers", "typing.List[str]"]], + "outputs": ["score"], + "examples": [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + }, + } + component = LLMEvaluator.from_dict(data) + assert component.api == "openai" + assert component.generator.client.api_key == "test-api-key" + assert component.api_params == {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}} + assert component.instructions == "test-instruction" + assert component.inputs == [("predicted_answers", List[str])] + assert component.outputs == ["score"] + assert component.examples == [ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ] + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + api_key=Secret.from_env_var("ENV_VAR"), + inputs=[("predicted_answers", List[str])], + outputs=["custom_score"], + api="openai", + examples=[ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + { + "inputs": {"predicted_answers": "Football is the most popular sport."}, + "outputs": {"custom_score": 0}, + }, + ], + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.evaluators.llm_evaluator.LLMEvaluator", + "init_parameters": { + "api_params": {"generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}}, + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "api": "openai", + "instructions": "test-instruction", + "inputs": [["predicted_answers", "typing.List[str]"]], + "outputs": ["custom_score"], + "progress_bar": True, + "examples": [ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + { + "inputs": {"predicted_answers": "Football is the most popular sport."}, + "outputs": {"custom_score": 0}, + }, + ], + }, + } + + def test_serde(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + pipeline = Pipeline() + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("questions", List[str]), ("predicted_answers", List[List[str]])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + pipeline.add_component("evaluator", component) + serialized_pipeline = pipeline.dumps() + deserialized_pipeline = Pipeline.loads(serialized_pipeline) + + def test_run_with_different_lengths(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("questions", List[str]), ("predicted_answers", List[List[str]])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + + def generator_run(self, *args, **kwargs): + return {"replies": ['{"score": 0.5}']} + + monkeypatch.setattr("haystack.components.generators.openai.OpenAIGenerator.run", generator_run) + + with pytest.raises(ValueError): + component.run(questions=["What is the capital of Germany?"], predicted_answers=[["Berlin"], ["Paris"]]) + + with pytest.raises(ValueError): + component.run( + questions=["What is the capital of Germany?", "What is the capital of France?"], + predicted_answers=[["Berlin"]], + ) + + def test_run_returns_parsed_result(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("questions", List[str]), ("predicted_answers", List[List[str]])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + + def generator_run(self, *args, **kwargs): + return {"replies": ['{"score": 0.5}']} + + monkeypatch.setattr("haystack.components.generators.openai.OpenAIGenerator.run", generator_run) + + results = component.run(questions=["What is the capital of Germany?"], predicted_answers=["Berlin"]) + assert results == {"results": [{"score": 0.5}], "meta": None} + + def test_prepare_template(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, "outputs": {"score": 1}}, + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}}, + ], + ) + template = component.prepare_template() + assert ( + template + == 'Instructions:\ntest-instruction\n\nGenerate the response in JSON format with the following keys:\n["score"]\nConsider the instructions and the examples below to determine those values.\n\nExamples:\nInputs:\n{"predicted_answers": "Damn, this is straight outta hell!!!"}\nOutputs:\n{"score": 1}\nInputs:\n{"predicted_answers": "Football is the most popular sport."}\nOutputs:\n{"score": 0}\n\nInputs:\n{"predicted_answers": {{ predicted_answers }}}\nOutputs:\n' + ) + + def test_invalid_input_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + # None of the expected parameters are received + with pytest.raises(ValueError): + component.validate_input_parameters( + expected={"predicted_answers": List[str]}, received={"questions": List[str]} + ) + + # Only one but not all the expected parameters are received + with pytest.raises(ValueError): + component.validate_input_parameters( + expected={"predicted_answers": List[str], "questions": List[str]}, received={"questions": List[str]} + ) + + # Received inputs are not lists + with pytest.raises(ValueError): + component.validate_input_parameters(expected={"questions": List[str]}, received={"questions": str}) + + def test_invalid_outputs(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + with pytest.raises(ValueError): + component.is_valid_json_and_has_expected_keys( + expected=["score", "another_expected_output"], received='{"score": 1.0}' + ) + + with pytest.raises(ValueError): + component.is_valid_json_and_has_expected_keys(expected=["score"], received='{"wrong_name": 1.0}') + + def test_output_invalid_json_raise_on_failure_false(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + raise_on_failure=False, + ) + assert ( + component.is_valid_json_and_has_expected_keys(expected=["score"], received="some_invalid_json_output") + is False + ) + + def test_output_invalid_json_raise_on_failure_true(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = LLMEvaluator( + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + with pytest.raises(ValueError): + component.is_valid_json_and_has_expected_keys(expected=["score"], received="some_invalid_json_output") + + def test_unsupported_api(self): + with pytest.raises(ValueError): + LLMEvaluator( + api="unsupported_api", + instructions="test-instruction", + inputs=[("predicted_answers", List[str])], + outputs=["score"], + examples=[ + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"score": 0}} + ], + ) + + def test_init_with_base_url(self): + component = LLMEvaluator( + instructions="test-instruction", + api_key=Secret.from_token("test-api-key"), + api_params={"api_base_url": "http://127.0.0.1:11434/v1"}, + inputs=[("predicted_answers", List[str])], + outputs=["custom_score"], + api="openai", + examples=[ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + { + "inputs": {"predicted_answers": "Football is the most popular sport."}, + "outputs": {"custom_score": 0}, + }, + ], + ) + assert component.generator.client.api_key == "test-api-key" + assert component.api_params == { + "generation_kwargs": {"response_format": {"type": "json_object"}, "seed": 42}, + "api_base_url": "http://127.0.0.1:11434/v1", + } + assert component.api == "openai" + assert component.examples == [ + {"inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, "outputs": {"custom_score": 1}}, + {"inputs": {"predicted_answers": "Football is the most popular sport."}, "outputs": {"custom_score": 0}}, + ] + assert component.instructions == "test-instruction" + assert component.inputs == [("predicted_answers", List[str])] + assert component.outputs == ["custom_score"] + + @pytest.mark.skipif( + not (os.environ.get("API_BASE_URL") and os.environ.get("MODEL_NAME")), + reason="Export env vars API_BASE_URL and MODEL_NAME containing the OpenAI API compatible server URL and the model name to run this test.", + ) + @pytest.mark.integration + def test_run_with_base_url(self): + component = LLMEvaluator( + instructions="test-instruction", + api_key=Secret.from_token("test-api-key"), + api_params={"api_base_url": os.environ["API_BASE_URL"], "model": os.environ["MODEL_NAME"]}, + inputs=[("predicted_answers", List[str])], + outputs=["custom_score"], + api="openai", + examples=[ + { + "inputs": {"predicted_answers": "Damn, this is straight outta hell!!!"}, + "outputs": {"custom_score": 1}, + }, + { + "inputs": {"predicted_answers": "Football is the most popular sport."}, + "outputs": {"custom_score": 0}, + }, + ], + ) + component.run(predicted_answers=["Damn, this is straight outta hell!!!", "Football is the most popular sport."]) + assert component.outputs == ["custom_score"] diff --git a/testbed/deepset-ai__haystack/test/components/evaluators/test_sas_evaluator.py b/testbed/deepset-ai__haystack/test/components/evaluators/test_sas_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dad15151537f954df31befb90461db0858b994 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/evaluators/test_sas_evaluator.py @@ -0,0 +1,196 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.components.evaluators.sas_evaluator import SASEvaluator +from haystack.utils.device import ComponentDevice + + +class TestSASEvaluator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("HF_API_TOKEN", "fake-token") + evaluator = SASEvaluator() + + assert evaluator._model == "sentence-transformers/paraphrase-multilingual-mpnet-base-v2" + assert evaluator._batch_size == 32 + assert evaluator._device is None + assert evaluator._token.resolve_value() == "fake-token" + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("HF_API_TOKEN", "fake-token") + + evaluator = SASEvaluator(device=ComponentDevice.from_str("cuda:0")) + + expected_dict = { + "type": "haystack.components.evaluators.sas_evaluator.SASEvaluator", + "init_parameters": { + "model": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", + "batch_size": 32, + "device": {"type": "single", "device": "cuda:0"}, + "token": {"type": "env_var", "env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False}, + }, + } + assert evaluator.to_dict() == expected_dict + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("HF_API_TOKEN", "fake-token") + evaluator = SASEvaluator.from_dict( + { + "type": "haystack.components.evaluators.sas_evaluator.SASEvaluator", + "init_parameters": { + "model": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2", + "batch_size": 32, + "device": {"type": "single", "device": "cuda:0"}, + "token": {"type": "env_var", "env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False}, + }, + } + ) + + assert evaluator._model == "sentence-transformers/paraphrase-multilingual-mpnet-base-v2" + assert evaluator._batch_size == 32 + assert evaluator._device.to_torch_str() == "cuda:0" + assert evaluator._token.resolve_value() == "fake-token" + + def test_run_with_empty_inputs(self): + evaluator = SASEvaluator() + result = evaluator.run(ground_truth_answers=[], predicted_answers=[]) + assert len(result) == 2 + assert result["score"] == 0.0 + assert result["individual_scores"] == [0.0] + + def test_run_with_different_lengths(self): + evaluator = SASEvaluator() + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + with pytest.raises(ValueError): + evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + + def test_run_with_none_in_predictions(self): + evaluator = SASEvaluator() + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + None, + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + with pytest.raises(ValueError): + evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + + def test_run_not_warmed_up(self): + evaluator = SASEvaluator() + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + with pytest.raises(RuntimeError): + evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + + @pytest.mark.integration + def test_run_with_matching_predictions(self): + evaluator = SASEvaluator() + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + evaluator.warm_up() + result = evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + + assert len(result) == 2 + assert result["score"] == pytest.approx(1.0) + assert result["individual_scores"] == pytest.approx([1.0, 1.0, 1.0]) + + @pytest.mark.integration + def test_run_with_single_prediction(self): + evaluator = SASEvaluator() + + ground_truths = ["US $2.3 billion"] + evaluator.warm_up() + result = evaluator.run( + ground_truth_answers=ground_truths, predicted_answers=["A construction budget of US $2.3 billion"] + ) + assert len(result) == 2 + assert result["score"] == pytest.approx(0.689089, abs=1e-5) + assert result["individual_scores"] == pytest.approx([0.689089], abs=1e-5) + + @pytest.mark.integration + def test_run_with_mismatched_predictions(self): + evaluator = SASEvaluator() + ground_truths = [ + "US $2.3 billion", + "Paris's cultural magnificence is symbolized by the Eiffel Tower", + "Japan was transformed into a modernized world power after the Meiji Restoration.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + evaluator.warm_up() + result = evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + assert len(result) == 2 + assert result["score"] == pytest.approx(0.8227189) + assert result["individual_scores"] == pytest.approx([0.689089, 0.870389, 0.908679], abs=1e-5) + + @pytest.mark.integration + def test_run_with_bi_encoder_model(self): + evaluator = SASEvaluator(model="sentence-transformers/all-mpnet-base-v2") + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + evaluator.warm_up() + result = evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + assert len(result) == 2 + assert result["score"] == pytest.approx(1.0) + assert result["individual_scores"] == pytest.approx([1.0, 1.0, 1.0]) + + @pytest.mark.integration + def test_run_with_cross_encoder_model(self): + evaluator = SASEvaluator(model="cross-encoder/ms-marco-MiniLM-L-6-v2") + ground_truths = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + predictions = [ + "A construction budget of US $2.3 billion", + "The Eiffel Tower, completed in 1889, symbolizes Paris's cultural magnificence.", + "The Meiji Restoration in 1868 transformed Japan into a modernized world power.", + ] + evaluator.warm_up() + result = evaluator.run(ground_truth_answers=ground_truths, predicted_answers=predictions) + assert len(result) == 2 + assert result["score"] == pytest.approx(0.999967, abs=1e-5) + assert result["individual_scores"] == pytest.approx( + [0.9999765157699585, 0.999968409538269, 0.9999572038650513], abs=1e-5 + ) diff --git a/testbed/deepset-ai__haystack/test/components/extractors/__init__.py b/testbed/deepset-ai__haystack/test/components/extractors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/extractors/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/extractors/test_named_entity_extractor.py b/testbed/deepset-ai__haystack/test/components/extractors/test_named_entity_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..a4826c1e9517486534fe7a3be10594b659052ec1 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/extractors/test_named_entity_extractor.py @@ -0,0 +1,78 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import ComponentError, DeserializationError, Pipeline +from haystack.components.extractors import NamedEntityExtractor, NamedEntityExtractorBackend +from haystack.utils.device import ComponentDevice + + +def test_named_entity_extractor_backend(): + _ = NamedEntityExtractor(backend=NamedEntityExtractorBackend.HUGGING_FACE, model="dslim/bert-base-NER") + + _ = NamedEntityExtractor(backend="hugging_face", model="dslim/bert-base-NER") + + _ = NamedEntityExtractor(backend=NamedEntityExtractorBackend.SPACY, model="en_core_web_sm") + + _ = NamedEntityExtractor(backend="spacy", model="en_core_web_sm") + + with pytest.raises(ComponentError, match=r"Invalid backend"): + NamedEntityExtractor(backend="random_backend", model="dslim/bert-base-NER") + + +def test_named_entity_extractor_serde(): + extractor = NamedEntityExtractor( + backend=NamedEntityExtractorBackend.HUGGING_FACE, + model="dslim/bert-base-NER", + device=ComponentDevice.from_str("cuda:1"), + ) + + serde_data = extractor.to_dict() + new_extractor = NamedEntityExtractor.from_dict(serde_data) + + assert type(new_extractor._backend) == type(extractor._backend) + assert new_extractor._backend.model_name == extractor._backend.model_name + assert new_extractor._backend.device == extractor._backend.device + + with pytest.raises(DeserializationError, match=r"Couldn't deserialize"): + serde_data["init_parameters"].pop("backend") + _ = NamedEntityExtractor.from_dict(serde_data) + + +def test_named_entity_extractor_from_dict_no_default_parameters_hf(): + data = { + "type": "haystack.components.extractors.named_entity_extractor.NamedEntityExtractor", + "init_parameters": {"backend": "HUGGING_FACE", "model": "dslim/bert-base-NER"}, + } + extractor = NamedEntityExtractor.from_dict(data) + + assert extractor._backend.model_name == "dslim/bert-base-NER" + assert extractor._backend.device == ComponentDevice.resolve_device(None) + + +# tests for NamedEntityExtractor serialization/deserialization in a pipeline +def test_named_entity_extractor_pipeline_serde(tmp_path): + extractor = NamedEntityExtractor(backend=NamedEntityExtractorBackend.HUGGING_FACE, model="dslim/bert-base-NER") + p = Pipeline() + p.add_component(instance=extractor, name="extractor") + + with open(tmp_path / "test_pipeline.yaml", "w") as f: + p.dump(f) + with open(tmp_path / "test_pipeline.yaml", "r") as f: + q = Pipeline.load(f) + + assert p.to_dict() == q.to_dict(), "Pipeline serialization/deserialization with NamedEntityExtractor failed." + + +def test_named_entity_extractor_serde_none_device(): + extractor = NamedEntityExtractor( + backend=NamedEntityExtractorBackend.HUGGING_FACE, model="dslim/bert-base-NER", device=None + ) + + serde_data = extractor.to_dict() + new_extractor = NamedEntityExtractor.from_dict(serde_data) + + assert type(new_extractor._backend) == type(extractor._backend) + assert new_extractor._backend.model_name == extractor._backend.model_name + assert new_extractor._backend.device == extractor._backend.device diff --git a/testbed/deepset-ai__haystack/test/components/fetchers/__init__.py b/testbed/deepset-ai__haystack/test/components/fetchers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/fetchers/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/fetchers/test_link_content_fetcher.py b/testbed/deepset-ai__haystack/test/components/fetchers/test_link_content_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..35cbd5e40cc8cdf94a568c614290c9f2ee8abc43 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/fetchers/test_link_content_fetcher.py @@ -0,0 +1,204 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import patch, Mock + +import pytest +import requests + +from haystack.components.fetchers.link_content import ( + LinkContentFetcher, + _text_content_handler, + _binary_content_handler, + DEFAULT_USER_AGENT, +) + +HTML_URL = "https://docs.haystack.deepset.ai/docs" +TEXT_URL = "https://raw.githubusercontent.com/deepset-ai/haystack/main/README.md" +PDF_URL = "https://raw.githubusercontent.com/deepset-ai/haystack/b5987a6d8d0714eb2f3011183ab40093d2e4a41a/e2e/samples/pipelines/sample_pdf_1.pdf" + + +@pytest.fixture +def mock_get_link_text_content(): + with patch("haystack.components.fetchers.link_content.requests") as mock_run: + mock_run.get.return_value = Mock( + status_code=200, text="Example test response", headers={"Content-Type": "text/plain"} + ) + yield mock_run + + +@pytest.fixture +def mock_get_link_content(test_files_path): + with patch("haystack.components.fetchers.link_content.requests") as mock_run: + mock_run.get.return_value = Mock( + status_code=200, + content=open(test_files_path / "pdf" / "sample_pdf_1.pdf", "rb").read(), + headers={"Content-Type": "application/pdf"}, + ) + yield mock_run + + +class TestLinkContentFetcher: + def test_init(self): + fetcher = LinkContentFetcher() + assert fetcher.raise_on_failure is True + assert fetcher.user_agents == [DEFAULT_USER_AGENT] + assert fetcher.retry_attempts == 2 + assert fetcher.timeout == 3 + assert fetcher.handlers == { + "text/*": _text_content_handler, + "text/html": _binary_content_handler, + "application/json": _text_content_handler, + "application/*": _binary_content_handler, + "image/*": _binary_content_handler, + "audio/*": _binary_content_handler, + "video/*": _binary_content_handler, + } + assert hasattr(fetcher, "_get_response") + + def test_init_with_params(self): + fetcher = LinkContentFetcher(raise_on_failure=False, user_agents=["test"], retry_attempts=1, timeout=2) + assert fetcher.raise_on_failure is False + assert fetcher.user_agents == ["test"] + assert fetcher.retry_attempts == 1 + assert fetcher.timeout == 2 + + def test_run_text(self): + correct_response = b"Example test response" + with patch("haystack.components.fetchers.link_content.requests") as mock_run: + mock_run.get.return_value = Mock( + status_code=200, text="Example test response", headers={"Content-Type": "text/plain"} + ) + fetcher = LinkContentFetcher() + streams = fetcher.run(urls=["https://www.example.com"])["streams"] + first_stream = streams[0] + assert first_stream.data == correct_response + assert first_stream.meta["content_type"] == "text/plain" + + def test_run_html(self): + correct_response = b"

    Example test response

    " + with patch("haystack.components.fetchers.link_content.requests") as mock_run: + mock_run.get.return_value = Mock( + status_code=200, content=b"

    Example test response

    ", headers={"Content-Type": "text/html"} + ) + fetcher = LinkContentFetcher() + streams = fetcher.run(urls=["https://www.example.com"])["streams"] + first_stream = streams[0] + assert first_stream.data == correct_response + assert first_stream.meta["content_type"] == "text/html" + + def test_run_binary(self, test_files_path): + file_bytes = open(test_files_path / "pdf" / "sample_pdf_1.pdf", "rb").read() + with patch("haystack.components.fetchers.link_content.requests") as mock_run: + mock_run.get.return_value = Mock( + status_code=200, content=file_bytes, headers={"Content-Type": "application/pdf"} + ) + fetcher = LinkContentFetcher() + streams = fetcher.run(urls=["https://www.example.com"])["streams"] + first_stream = streams[0] + assert first_stream.data == file_bytes + assert first_stream.meta["content_type"] == "application/pdf" + + def test_run_bad_status_code(self): + empty_byte_stream = b"" + fetcher = LinkContentFetcher(raise_on_failure=False) + mock_response = Mock(status_code=403) + with patch("haystack.components.fetchers.link_content.requests") as mock_run: + mock_run.get.return_value = mock_response + streams = fetcher.run(urls=["https://www.example.com"])["streams"] + + # empty byte stream is returned because raise_on_failure is False + assert len(streams) == 1 + first_stream = streams[0] + assert first_stream.data == empty_byte_stream + assert first_stream.meta["content_type"] == "text/html" + + @pytest.mark.integration + def test_link_content_fetcher_html(self): + fetcher = LinkContentFetcher() + streams = fetcher.run([HTML_URL])["streams"] + first_stream = streams[0] + assert "Haystack" in first_stream.data.decode("utf-8") + assert first_stream.meta["content_type"] == "text/html" + assert "url" in first_stream.meta and first_stream.meta["url"] == HTML_URL + + @pytest.mark.integration + def test_link_content_fetcher_text(self): + fetcher = LinkContentFetcher() + streams = fetcher.run([TEXT_URL])["streams"] + first_stream = streams[0] + assert "Haystack" in first_stream.data.decode("utf-8") + assert first_stream.meta["content_type"] == "text/plain" + assert "url" in first_stream.meta and first_stream.meta["url"] == TEXT_URL + + @pytest.mark.integration + def test_link_content_fetcher_pdf(self): + fetcher = LinkContentFetcher() + streams = fetcher.run([PDF_URL])["streams"] + assert len(streams) == 1 + first_stream = streams[0] + assert first_stream.meta["content_type"] in ("application/octet-stream", "application/pdf") + assert "url" in first_stream.meta and first_stream.meta["url"] == PDF_URL + + @pytest.mark.integration + def test_link_content_fetcher_multiple_different_content_types(self): + """ + This test is to ensure that the fetcher can handle a list of URLs that contain different content types. + """ + fetcher = LinkContentFetcher() + streams = fetcher.run([PDF_URL, HTML_URL])["streams"] + assert len(streams) == 2 + for stream in streams: + assert stream.meta["content_type"] in ("text/html", "application/pdf", "application/octet-stream") + if stream.meta["content_type"] == "text/html": + assert "Haystack" in stream.data.decode("utf-8") + elif stream.meta["content_type"] == "application/pdf": + assert len(stream.data) > 0 + + @pytest.mark.integration + def test_link_content_fetcher_multiple_html_streams(self): + """ + This test is to ensure that the fetcher can handle a list of URLs that contain different content types, + and that we have two html streams. + """ + + fetcher = LinkContentFetcher() + streams = fetcher.run([PDF_URL, HTML_URL, "https://google.com"])["streams"] + assert len(streams) == 3 + for stream in streams: + assert stream.meta["content_type"] in ("text/html", "application/pdf", "application/octet-stream") + if stream.meta["content_type"] == "text/html": + assert "Haystack" in stream.data.decode("utf-8") or "Google" in stream.data.decode("utf-8") + elif stream.meta["content_type"] == "application/pdf": + assert len(stream.data) > 0 + + @pytest.mark.integration + def test_mix_of_good_and_failed_requests(self): + """ + This test is to ensure that the fetcher can handle a list of URLs that contain URLs that fail to be fetched. + In such a case, the fetcher should return the content of the URLs that were successfully fetched and not raise + an exception. + """ + fetcher = LinkContentFetcher() + result = fetcher.run(["https://non_existent_website_dot.com/", "https://www.google.com/"]) + assert len(result["streams"]) == 1 + first_stream = result["streams"][0] + assert first_stream.meta["content_type"] == "text/html" + + @pytest.mark.integration + def test_bad_request_exception_raised(self): + """ + This test is to ensure that the fetcher raises an exception when a single bad request is made and it is configured to + do so. + """ + fetcher = LinkContentFetcher() + with pytest.raises(requests.exceptions.ConnectionError): + fetcher.run(["https://non_existent_website_dot.com/"]) + + @pytest.mark.integration + def test_link_content_fetcher_audio(self): + fetcher = LinkContentFetcher() + streams = fetcher.run(["https://download.samplelib.com/mp3/sample-3s.mp3"])["streams"] + first_stream = streams[0] + assert first_stream.meta["content_type"] == "audio/mpeg" + assert len(first_stream.data) > 0 diff --git a/testbed/deepset-ai__haystack/test/components/generators/chat/__init__.py b/testbed/deepset-ai__haystack/test/components/generators/chat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/chat/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/generators/chat/conftest.py b/testbed/deepset-ai__haystack/test/components/generators/chat/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..842e447b562781304b0172cca3b6f939f10bc056 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/chat/conftest.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.dataclasses import ChatMessage + + +@pytest.fixture +def chat_messages(): + return [ + ChatMessage.from_system("You are a helpful assistant speaking A2 level of English"), + ChatMessage.from_user("Tell me about Berlin"), + ] diff --git a/testbed/deepset-ai__haystack/test/components/generators/chat/test_azure.py b/testbed/deepset-ai__haystack/test/components/generators/chat/test_azure.py new file mode 100644 index 0000000000000000000000000000000000000000..fdafec682d4ebcc4cc14af6f76f01fc5012a66cc --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/chat/test_azure.py @@ -0,0 +1,120 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +import pytest +from openai import OpenAIError + +from haystack import Pipeline +from haystack.components.generators.chat import AzureOpenAIChatGenerator +from haystack.components.generators.utils import print_streaming_chunk +from haystack.dataclasses import ChatMessage +from haystack.utils.auth import Secret + + +class TestOpenAIChatGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-api-key") + component = AzureOpenAIChatGenerator(azure_endpoint="some-non-existing-endpoint") + assert component.client.api_key == "test-api-key" + assert component.azure_deployment == "gpt-4o-mini" + assert component.streaming_callback is None + assert not component.generation_kwargs + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("AZURE_OPENAI_API_KEY", raising=False) + monkeypatch.delenv("AZURE_OPENAI_AD_TOKEN", raising=False) + with pytest.raises(OpenAIError): + AzureOpenAIChatGenerator(azure_endpoint="some-non-existing-endpoint") + + def test_init_with_parameters(self): + component = AzureOpenAIChatGenerator( + api_key=Secret.from_token("test-api-key"), + azure_endpoint="some-non-existing-endpoint", + streaming_callback=print_streaming_chunk, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + assert component.client.api_key == "test-api-key" + assert component.azure_deployment == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + + def test_to_dict_default(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-api-key") + component = AzureOpenAIChatGenerator(azure_endpoint="some-non-existing-endpoint") + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.chat.azure.AzureOpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["AZURE_OPENAI_API_KEY"], "strict": False, "type": "env_var"}, + "azure_ad_token": {"env_vars": ["AZURE_OPENAI_AD_TOKEN"], "strict": False, "type": "env_var"}, + "api_version": "2023-05-15", + "azure_endpoint": "some-non-existing-endpoint", + "azure_deployment": "gpt-4o-mini", + "organization": None, + "streaming_callback": None, + "generation_kwargs": {}, + "timeout": 30.0, + "max_retries": 5, + "default_headers": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = AzureOpenAIChatGenerator( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + azure_ad_token=Secret.from_env_var("ENV_VAR1", strict=False), + azure_endpoint="some-non-existing-endpoint", + timeout=2.5, + max_retries=10, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.chat.azure.AzureOpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "azure_ad_token": {"env_vars": ["ENV_VAR1"], "strict": False, "type": "env_var"}, + "api_version": "2023-05-15", + "azure_endpoint": "some-non-existing-endpoint", + "azure_deployment": "gpt-4o-mini", + "organization": None, + "streaming_callback": None, + "timeout": 2.5, + "max_retries": 10, + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + "default_headers": {}, + }, + } + + def test_pipeline_serialization_deserialization(self, tmp_path, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-api-key") + generator = AzureOpenAIChatGenerator(azure_endpoint="some-non-existing-endpoint") + p = Pipeline() + p.add_component(instance=generator, name="generator") + p_str = p.dumps() + q = Pipeline.loads(p_str) + assert p.to_dict() == q.to_dict(), "Pipeline serialization/deserialization w/ AzureOpenAIChatGenerator failed." + + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("AZURE_OPENAI_API_KEY", None) or not os.environ.get("AZURE_OPENAI_ENDPOINT", None), + reason=( + "Please export env variables called AZURE_OPENAI_API_KEY containing " + "the Azure OpenAI key, AZURE_OPENAI_ENDPOINT containing " + "the Azure OpenAI endpoint URL to run this test." + ), + ) + def test_live_run(self): + chat_messages = [ChatMessage.from_user("What's the capital of France")] + component = AzureOpenAIChatGenerator(organization="HaystackCI") + results = component.run(chat_messages) + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.content + assert "gpt-4o-mini" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + # additional tests intentionally omitted as they are covered by test_openai.py diff --git a/testbed/deepset-ai__haystack/test/components/generators/chat/test_hugging_face_api.py b/testbed/deepset-ai__haystack/test/components/generators/chat/test_hugging_face_api.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7fd617c09101dbc736f696a8b7e281a9a39d60 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/chat/test_hugging_face_api.py @@ -0,0 +1,317 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from unittest.mock import MagicMock, Mock, patch + +import pytest +from huggingface_hub import ( + ChatCompletionOutput, + ChatCompletionStreamOutput, + ChatCompletionOutputComplete, + ChatCompletionStreamOutputChoice, + ChatCompletionOutputMessage, + ChatCompletionStreamOutputDelta, +) +from huggingface_hub.utils import RepositoryNotFoundError + +from haystack.components.generators.chat.hugging_face_api import ( + HuggingFaceAPIChatGenerator, + _convert_message_to_hfapi_format, +) +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.utils.auth import Secret +from haystack.utils.hf import HFGenerationAPIType + + +@pytest.fixture +def mock_check_valid_model(): + with patch( + "haystack.components.generators.chat.hugging_face_api.check_valid_model", MagicMock(return_value=None) + ) as mock: + yield mock + + +@pytest.fixture +def mock_chat_completion(): + # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion.example + + with patch("huggingface_hub.InferenceClient.chat_completion", autospec=True) as mock_chat_completion: + completion = ChatCompletionOutput( + choices=[ + ChatCompletionOutputComplete( + finish_reason="eos_token", + index=0, + message=ChatCompletionOutputMessage(content="The capital of France is Paris.", role="assistant"), + ) + ], + id="some_id", + model="some_model", + system_fingerprint="some_fingerprint", + usage={"completion_tokens": 10, "prompt_tokens": 5, "total_tokens": 15}, + created=1710498360, + ) + + mock_chat_completion.return_value = completion + yield mock_chat_completion + + +# used to test serialization of streaming_callback +def streaming_callback_handler(x): + return x + + +def test_convert_message_to_hfapi_format(): + message = ChatMessage.from_system("You are good assistant") + assert _convert_message_to_hfapi_format(message) == {"role": "system", "content": "You are good assistant"} + + message = ChatMessage.from_user("I have a question") + assert _convert_message_to_hfapi_format(message) == {"role": "user", "content": "I have a question"} + + message = ChatMessage.from_function("Function call", "function_name") + assert _convert_message_to_hfapi_format(message) == { + "role": "function", + "content": "Function call", + "name": "function_name", + } + + +class TestHuggingFaceAPIGenerator: + def test_init_invalid_api_type(self): + with pytest.raises(ValueError): + HuggingFaceAPIChatGenerator(api_type="invalid_api_type", api_params={}) + + def test_init_serverless(self, mock_check_valid_model): + model = "HuggingFaceH4/zephyr-7b-alpha" + generation_kwargs = {"temperature": 0.6} + stop_words = ["stop"] + streaming_callback = None + + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": model}, + token=None, + generation_kwargs=generation_kwargs, + stop_words=stop_words, + streaming_callback=streaming_callback, + ) + + assert generator.api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API + assert generator.api_params == {"model": model} + assert generator.generation_kwargs == {**generation_kwargs, **{"stop": ["stop"]}, **{"max_tokens": 512}} + assert generator.streaming_callback == streaming_callback + + def test_init_serverless_invalid_model(self, mock_check_valid_model): + mock_check_valid_model.side_effect = RepositoryNotFoundError("Invalid model id") + with pytest.raises(RepositoryNotFoundError): + HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "invalid_model_id"} + ) + + def test_init_serverless_no_model(self): + with pytest.raises(ValueError): + HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, api_params={"param": "irrelevant"} + ) + + def test_init_tgi(self): + url = "https://some_model.com" + generation_kwargs = {"temperature": 0.6} + stop_words = ["stop"] + streaming_callback = None + + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.TEXT_GENERATION_INFERENCE, + api_params={"url": url}, + token=None, + generation_kwargs=generation_kwargs, + stop_words=stop_words, + streaming_callback=streaming_callback, + ) + + assert generator.api_type == HFGenerationAPIType.TEXT_GENERATION_INFERENCE + assert generator.api_params == {"url": url} + assert generator.generation_kwargs == {**generation_kwargs, **{"stop": ["stop"]}, **{"max_tokens": 512}} + assert generator.streaming_callback == streaming_callback + + def test_init_tgi_invalid_url(self): + with pytest.raises(ValueError): + HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.TEXT_GENERATION_INFERENCE, api_params={"url": "invalid_url"} + ) + + def test_init_tgi_no_url(self): + with pytest.raises(ValueError): + HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.TEXT_GENERATION_INFERENCE, api_params={"param": "irrelevant"} + ) + + def test_to_dict(self, mock_check_valid_model): + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + generation_kwargs={"temperature": 0.6}, + stop_words=["stop", "words"], + ) + + result = generator.to_dict() + init_params = result["init_parameters"] + + assert init_params["api_type"] == "serverless_inference_api" + assert init_params["api_params"] == {"model": "HuggingFaceH4/zephyr-7b-beta"} + assert init_params["token"] == {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + assert init_params["generation_kwargs"] == {"temperature": 0.6, "stop": ["stop", "words"], "max_tokens": 512} + + def test_from_dict(self, mock_check_valid_model): + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + token=Secret.from_env_var("ENV_VAR", strict=False), + generation_kwargs={"temperature": 0.6}, + stop_words=["stop", "words"], + streaming_callback=streaming_callback_handler, + ) + result = generator.to_dict() + + # now deserialize, call from_dict + generator_2 = HuggingFaceAPIChatGenerator.from_dict(result) + assert generator_2.api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API + assert generator_2.api_params == {"model": "HuggingFaceH4/zephyr-7b-beta"} + assert generator_2.token == Secret.from_env_var("ENV_VAR", strict=False) + assert generator_2.generation_kwargs == {"temperature": 0.6, "stop": ["stop", "words"], "max_tokens": 512} + assert generator_2.streaming_callback is streaming_callback_handler + + def test_generate_text_response_with_valid_prompt_and_generation_parameters( + self, mock_check_valid_model, mock_chat_completion, chat_messages + ): + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "meta-llama/Llama-2-13b-chat-hf"}, + generation_kwargs={"temperature": 0.6}, + stop_words=["stop", "words"], + streaming_callback=None, + ) + + response = generator.run(messages=chat_messages) + + # check kwargs passed to text_generation + _, kwargs = mock_chat_completion.call_args + assert kwargs == {"temperature": 0.6, "stop": ["stop", "words"], "max_tokens": 512} + + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + + def test_generate_text_with_streaming_callback(self, mock_check_valid_model, mock_chat_completion, chat_messages): + streaming_call_count = 0 + + # Define the streaming callback function + def streaming_callback_fn(chunk: StreamingChunk): + nonlocal streaming_call_count + streaming_call_count += 1 + assert isinstance(chunk, StreamingChunk) + + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "meta-llama/Llama-2-13b-chat-hf"}, + streaming_callback=streaming_callback_fn, + ) + + # Create a fake streamed response + # self needed here, don't remove + def mock_iter(self): + yield ChatCompletionStreamOutput( + choices=[ + ChatCompletionStreamOutputChoice( + delta=ChatCompletionStreamOutputDelta(content="The", role="assistant"), + index=0, + finish_reason=None, + ) + ], + id="some_id", + model="some_model", + system_fingerprint="some_fingerprint", + created=1710498504, + ) + + yield ChatCompletionStreamOutput( + choices=[ + ChatCompletionStreamOutputChoice( + delta=ChatCompletionStreamOutputDelta(content=None, role=None), index=0, finish_reason="length" + ) + ], + id="some_id", + model="some_model", + system_fingerprint="some_fingerprint", + created=1710498504, + ) + + mock_response = Mock(**{"__iter__": mock_iter}) + mock_chat_completion.return_value = mock_response + + # Generate text response with streaming callback + response = generator.run(chat_messages) + + # check kwargs passed to text_generation + _, kwargs = mock_chat_completion.call_args + assert kwargs == {"stop": [], "stream": True, "max_tokens": 512} + + # Assert that the streaming callback was called twice + assert streaming_call_count == 2 + + # Assert that the response contains the generated replies + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) > 0 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + + @pytest.mark.flaky(reruns=5, reruns_delay=5) + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("HF_API_TOKEN", None), + reason="Export an env var called HF_API_TOKEN containing the Hugging Face token to run this test.", + ) + def test_run_serverless(self): + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + generation_kwargs={"max_tokens": 20}, + ) + + messages = [ChatMessage.from_user("What is the capital of France?")] + response = generator.run(messages=messages) + + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) > 0 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + assert "usage" in response["replies"][0].meta + assert "prompt_tokens" in response["replies"][0].meta["usage"] + assert "completion_tokens" in response["replies"][0].meta["usage"] + + @pytest.mark.flaky(reruns=5, reruns_delay=5) + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("HF_API_TOKEN", None), + reason="Export an env var called HF_API_TOKEN containing the Hugging Face token to run this test.", + ) + def test_run_serverless_streaming(self): + generator = HuggingFaceAPIChatGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + generation_kwargs={"max_tokens": 20}, + streaming_callback=streaming_callback_handler, + ) + + messages = [ChatMessage.from_user("What is the capital of France?")] + response = generator.run(messages=messages) + + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) > 0 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + assert "usage" in response["replies"][0].meta + assert "prompt_tokens" in response["replies"][0].meta["usage"] + assert "completion_tokens" in response["replies"][0].meta["usage"] diff --git a/testbed/deepset-ai__haystack/test/components/generators/chat/test_hugging_face_local.py b/testbed/deepset-ai__haystack/test/components/generators/chat/test_hugging_face_local.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4dbdd06a115529d0b9657c1c057cbf85f1f21f --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/chat/test_hugging_face_local.py @@ -0,0 +1,219 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import Mock, patch + +import pytest +from transformers import PreTrainedTokenizer + +from haystack.components.generators.chat import HuggingFaceLocalChatGenerator +from haystack.dataclasses import ChatMessage, ChatRole +from haystack.utils import ComponentDevice +from haystack.utils.auth import Secret + + +# used to test serialization of streaming_callback +def streaming_callback_handler(x): + return x + + +@pytest.fixture +def model_info_mock(): + with patch( + "haystack.components.generators.chat.hugging_face_local.model_info", + new=Mock(return_value=Mock(pipeline_tag="text2text-generation")), + ) as mock: + yield mock + + +@pytest.fixture +def mock_pipeline_tokenizer(): + # Mocking the pipeline + mock_pipeline = Mock(return_value=[{"generated_text": "Berlin is cool"}]) + + # Mocking the tokenizer + mock_tokenizer = Mock(spec=PreTrainedTokenizer) + mock_tokenizer.encode.return_value = ["Berlin", "is", "cool"] + mock_pipeline.tokenizer = mock_tokenizer + + return mock_pipeline + + +class TestHuggingFaceLocalChatGenerator: + def test_initialize_with_valid_model_and_generation_parameters(self, model_info_mock): + model = "HuggingFaceH4/zephyr-7b-alpha" + generation_kwargs = {"n": 1} + stop_words = ["stop"] + streaming_callback = None + + generator = HuggingFaceLocalChatGenerator( + model=model, + generation_kwargs=generation_kwargs, + stop_words=stop_words, + streaming_callback=streaming_callback, + ) + + assert generator.generation_kwargs == {**generation_kwargs, **{"stop_sequences": ["stop"]}} + assert generator.streaming_callback == streaming_callback + + def test_init_custom_token(self): + generator = HuggingFaceLocalChatGenerator( + model="mistralai/Mistral-7B-Instruct-v0.2", + task="text2text-generation", + token=Secret.from_token("test-token"), + device=ComponentDevice.from_str("cpu"), + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "mistralai/Mistral-7B-Instruct-v0.2", + "task": "text2text-generation", + "token": "test-token", + "device": "cpu", + } + + def test_init_custom_device(self): + generator = HuggingFaceLocalChatGenerator( + model="mistralai/Mistral-7B-Instruct-v0.2", + task="text2text-generation", + device=ComponentDevice.from_str("cpu"), + token=None, + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "mistralai/Mistral-7B-Instruct-v0.2", + "task": "text2text-generation", + "token": None, + "device": "cpu", + } + + def test_init_task_parameter(self): + generator = HuggingFaceLocalChatGenerator( + task="text2text-generation", device=ComponentDevice.from_str("cpu"), token=None + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "HuggingFaceH4/zephyr-7b-beta", + "task": "text2text-generation", + "token": None, + "device": "cpu", + } + + def test_init_task_in_huggingface_pipeline_kwargs(self): + generator = HuggingFaceLocalChatGenerator( + huggingface_pipeline_kwargs={"task": "text2text-generation"}, + device=ComponentDevice.from_str("cpu"), + token=None, + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "HuggingFaceH4/zephyr-7b-beta", + "task": "text2text-generation", + "token": None, + "device": "cpu", + } + + def test_init_task_inferred_from_model_name(self, model_info_mock): + generator = HuggingFaceLocalChatGenerator( + model="mistralai/Mistral-7B-Instruct-v0.2", device=ComponentDevice.from_str("cpu"), token=None + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "mistralai/Mistral-7B-Instruct-v0.2", + "task": "text2text-generation", + "token": None, + "device": "cpu", + } + + def test_init_invalid_task(self): + with pytest.raises(ValueError, match="is not supported."): + HuggingFaceLocalChatGenerator(task="text-classification") + + def test_to_dict(self, model_info_mock): + generator = HuggingFaceLocalChatGenerator( + model="NousResearch/Llama-2-7b-chat-hf", + token=Secret.from_env_var("ENV_VAR", strict=False), + generation_kwargs={"n": 5}, + stop_words=["stop", "words"], + streaming_callback=lambda x: x, + ) + + # Call the to_dict method + result = generator.to_dict() + init_params = result["init_parameters"] + + # Assert that the init_params dictionary contains the expected keys and values + assert init_params["token"] == {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"} + assert init_params["huggingface_pipeline_kwargs"]["model"] == "NousResearch/Llama-2-7b-chat-hf" + assert "token" not in init_params["huggingface_pipeline_kwargs"] + assert init_params["generation_kwargs"] == {"max_new_tokens": 512, "n": 5, "stop_sequences": ["stop", "words"]} + + def test_from_dict(self, model_info_mock): + generator = HuggingFaceLocalChatGenerator( + model="NousResearch/Llama-2-7b-chat-hf", + generation_kwargs={"n": 5}, + stop_words=["stop", "words"], + streaming_callback=streaming_callback_handler, + ) + # Call the to_dict method + result = generator.to_dict() + + generator_2 = HuggingFaceLocalChatGenerator.from_dict(result) + + assert generator_2.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert generator_2.generation_kwargs == {"max_new_tokens": 512, "n": 5, "stop_sequences": ["stop", "words"]} + assert generator_2.streaming_callback is streaming_callback_handler + + @patch("haystack.components.generators.chat.hugging_face_local.pipeline") + def test_warm_up(self, pipeline_mock, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + generator = HuggingFaceLocalChatGenerator( + model="mistralai/Mistral-7B-Instruct-v0.2", + task="text2text-generation", + device=ComponentDevice.from_str("cpu"), + ) + + pipeline_mock.assert_not_called() + + generator.warm_up() + + pipeline_mock.assert_called_once_with( + model="mistralai/Mistral-7B-Instruct-v0.2", task="text2text-generation", token=None, device="cpu" + ) + + def test_run(self, model_info_mock, mock_pipeline_tokenizer, chat_messages): + generator = HuggingFaceLocalChatGenerator(model="meta-llama/Llama-2-13b-chat-hf") + + # Use the mocked pipeline from the fixture and simulate warm_up + generator.pipeline = mock_pipeline_tokenizer + + results = generator.run(messages=chat_messages) + + assert "replies" in results + assert isinstance(results["replies"][0], ChatMessage) + chat_message = results["replies"][0] + assert chat_message.is_from(ChatRole.ASSISTANT) + assert chat_message.content == "Berlin is cool" + + def test_run_with_custom_generation_parameters(self, model_info_mock, mock_pipeline_tokenizer, chat_messages): + generator = HuggingFaceLocalChatGenerator(model="meta-llama/Llama-2-13b-chat-hf") + + # Use the mocked pipeline from the fixture and simulate warm_up + generator.pipeline = mock_pipeline_tokenizer + + generation_kwargs = {"temperature": 0.8, "max_new_tokens": 100} + + # Use the mocked pipeline from the fixture and simulate warm_up + generator.pipeline = mock_pipeline_tokenizer + results = generator.run(messages=chat_messages, generation_kwargs=generation_kwargs) + + # check kwargs passed pipeline + _, kwargs = generator.pipeline.call_args + assert kwargs["max_new_tokens"] == 100 + assert kwargs["temperature"] == 0.8 + + # replies are properly parsed and returned + assert "replies" in results + assert isinstance(results["replies"][0], ChatMessage) + chat_message = results["replies"][0] + assert chat_message.is_from(ChatRole.ASSISTANT) + assert chat_message.content == "Berlin is cool" diff --git a/testbed/deepset-ai__haystack/test/components/generators/chat/test_openai.py b/testbed/deepset-ai__haystack/test/components/generators/chat/test_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5122d069d0f1a5f264df20deedcea4312cb8a4 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/chat/test_openai.py @@ -0,0 +1,331 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import os +from unittest.mock import patch + +import pytest +from openai import OpenAIError + +from haystack.components.generators.chat import OpenAIChatGenerator +from haystack.components.generators.utils import print_streaming_chunk +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.utils.auth import Secret + + +@pytest.fixture +def chat_messages(): + return [ + ChatMessage.from_system("You are a helpful assistant"), + ChatMessage.from_user("What's the capital of France"), + ] + + +class TestOpenAIChatGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = OpenAIChatGenerator() + assert component.client.api_key == "test-api-key" + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is None + assert not component.generation_kwargs + assert component.client.timeout == 30 + assert component.client.max_retries == 5 + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + OpenAIChatGenerator() + + def test_init_with_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + component = OpenAIChatGenerator( + api_key=Secret.from_token("test-api-key"), + model="gpt-4o-mini", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + timeout=40.0, + max_retries=1, + ) + assert component.client.api_key == "test-api-key" + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.client.timeout == 40.0 + assert component.client.max_retries == 1 + + def test_init_with_parameters_and_env_vars(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + component = OpenAIChatGenerator( + api_key=Secret.from_token("test-api-key"), + model="gpt-4o-mini", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + assert component.client.api_key == "test-api-key" + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.client.timeout == 100.0 + assert component.client.max_retries == 10 + + def test_to_dict_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = OpenAIChatGenerator() + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.chat.openai.OpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "organization": None, + "streaming_callback": None, + "api_base_url": None, + "generation_kwargs": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = OpenAIChatGenerator( + api_key=Secret.from_env_var("ENV_VAR"), + model="gpt-4o-mini", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.chat.openai.OpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "organization": None, + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_to_dict_with_lambda_streaming_callback(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = OpenAIChatGenerator( + model="gpt-4o-mini", + streaming_callback=lambda x: x, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.chat.openai.OpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "organization": None, + "api_base_url": "test-base-url", + "streaming_callback": "chat.test_openai.", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key") + data = { + "type": "haystack.components.generators.chat.openai.OpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + component = OpenAIChatGenerator.from_dict(data) + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.api_base_url == "test-base-url" + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.api_key == Secret.from_env_var("OPENAI_API_KEY") + + def test_from_dict_fail_wo_env_var(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + data = { + "type": "haystack.components.generators.chat.openai.OpenAIChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "organization": None, + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + OpenAIChatGenerator.from_dict(data) + + def test_run(self, chat_messages, mock_chat_completion): + component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key")) + response = component.run(chat_messages) + + # check that the component returns the correct ChatMessage response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + + def test_run_with_params(self, chat_messages, mock_chat_completion): + component = OpenAIChatGenerator( + api_key=Secret.from_token("test-api-key"), generation_kwargs={"max_tokens": 10, "temperature": 0.5} + ) + response = component.run(chat_messages) + + # check that the component calls the OpenAI API with the correct parameters + _, kwargs = mock_chat_completion.call_args + assert kwargs["max_tokens"] == 10 + assert kwargs["temperature"] == 0.5 + + # check that the component returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + + def test_run_with_params_streaming(self, chat_messages, mock_chat_completion_chunk): + streaming_callback_called = False + + def streaming_callback(chunk: StreamingChunk) -> None: + nonlocal streaming_callback_called + streaming_callback_called = True + + component = OpenAIChatGenerator( + api_key=Secret.from_token("test-api-key"), streaming_callback=streaming_callback + ) + response = component.run(chat_messages) + + # check we called the streaming callback + assert streaming_callback_called + + # check that the component still returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + assert "Hello" in response["replies"][0].content # see mock_chat_completion_chunk + + @patch("haystack.components.generators.chat.openai.datetime") + def test_run_with_streaming_callback_in_run_method(self, mock_datetime, chat_messages, mock_chat_completion_chunk): + streaming_callback_called = False + + def streaming_callback(chunk: StreamingChunk) -> None: + nonlocal streaming_callback_called + streaming_callback_called = True + + component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key")) + response = component.run(chat_messages, streaming_callback=streaming_callback) + + # check we called the streaming callback + assert streaming_callback_called + + # check that the component still returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + assert "Hello" in response["replies"][0].content # see mock_chat_completion_chunk + + assert hasattr(response["replies"][0], "meta") + assert isinstance(response["replies"][0].meta, dict) + assert ( + response["replies"][0].meta["completion_start_time"] + == mock_datetime.now.return_value.isoformat.return_value + ) + + def test_check_abnormal_completions(self, caplog): + caplog.set_level(logging.INFO) + component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key")) + messages = [ + ChatMessage.from_assistant( + "", meta={"finish_reason": "content_filter" if i % 2 == 0 else "length", "index": i} + ) + for i, _ in enumerate(range(4)) + ] + + for m in messages: + component._check_finish_reason(m) + + # check truncation warning + message_template = ( + "The completion for index {index} has been truncated before reaching a natural stopping point. " + "Increase the max_tokens parameter to allow for longer completions." + ) + + for index in [1, 3]: + assert caplog.records[index].message == message_template.format(index=index) + + # check content filter warning + message_template = "The completion for index {index} has been truncated due to the content filter." + for index in [0, 2]: + assert caplog.records[index].message == message_template.format(index=index) + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run(self): + chat_messages = [ChatMessage.from_user("What's the capital of France")] + component = OpenAIChatGenerator(generation_kwargs={"n": 1}) + results = component.run(chat_messages) + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.content + assert "gpt-4o-mini" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_wrong_model(self, chat_messages): + component = OpenAIChatGenerator(model="something-obviously-wrong") + with pytest.raises(OpenAIError): + component.run(chat_messages) + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_streaming(self): + class Callback: + def __init__(self): + self.responses = "" + self.counter = 0 + + def __call__(self, chunk: StreamingChunk) -> None: + self.counter += 1 + self.responses += chunk.content if chunk.content else "" + + callback = Callback() + component = OpenAIChatGenerator(streaming_callback=callback) + results = component.run([ChatMessage.from_user("What's the capital of France?")]) + + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.content + + assert "gpt-4o-mini" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + assert callback.counter > 1 + assert "Paris" in callback.responses diff --git a/testbed/deepset-ai__haystack/test/components/generators/conftest.py b/testbed/deepset-ai__haystack/test/components/generators/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..92ed8feb3a89cec8463266f2a0c49ba483d72ee3 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/conftest.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from datetime import datetime +from typing import Iterator +from unittest.mock import MagicMock, patch + +import pytest +from openai import Stream +from openai.types.chat import ChatCompletionChunk +from openai.types.chat.chat_completion_chunk import Choice, ChoiceDelta + + +@pytest.fixture +def mock_auto_tokenizer(): + """ + In the original mock_auto_tokenizer fixture, we were mocking the transformers.AutoTokenizer.from_pretrained + method directly, but we were not providing a return value for this method. Therefore, when from_pretrained + was called within HuggingFaceTGIChatGenerator, it returned None because that's the default behavior of a + MagicMock object when a return value isn't specified. + + We will update the mock_auto_tokenizer fixture to return a MagicMock object when from_pretrained is called + in another PR. For now, we will use this fixture to mock the AutoTokenizer.from_pretrained method. + """ + + with patch("transformers.AutoTokenizer.from_pretrained", autospec=True) as mock_from_pretrained: + mock_tokenizer = MagicMock() + mock_from_pretrained.return_value = mock_tokenizer + yield mock_tokenizer + + +@pytest.fixture +def mock_chat_completion_chunk(): + """ + Mock the OpenAI API completion chunk response and reuse it for tests + """ + + class MockStream(Stream[ChatCompletionChunk]): + def __init__(self, mock_chunk: ChatCompletionChunk, client=None, *args, **kwargs): + client = client or MagicMock() + super().__init__(client=client, *args, **kwargs) + self.mock_chunk = mock_chunk + + def __stream__(self) -> Iterator[ChatCompletionChunk]: + # Yielding only one ChatCompletionChunk object + yield self.mock_chunk + + with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create: + completion = ChatCompletionChunk( + id="foo", + model="gpt-4", + object="chat.completion.chunk", + choices=[ + Choice( + finish_reason="stop", logprobs=None, index=0, delta=ChoiceDelta(content="Hello", role="assistant") + ) + ], + created=int(datetime.now().timestamp()), + usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97}, + ) + mock_chat_completion_create.return_value = MockStream(completion, cast_to=None, response=None, client=None) + yield mock_chat_completion_create diff --git a/testbed/deepset-ai__haystack/test/components/generators/test_azure.py b/testbed/deepset-ai__haystack/test/components/generators/test_azure.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e524f602f01fc06698b876f17d5bad70660a09 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/test_azure.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +from haystack import Pipeline +from haystack.utils.auth import Secret + +import pytest +from openai import OpenAIError + +from haystack.components.generators import AzureOpenAIGenerator +from haystack.components.generators.utils import print_streaming_chunk + + +class TestAzureOpenAIGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-api-key") + component = AzureOpenAIGenerator(azure_endpoint="some-non-existing-endpoint") + assert component.client.api_key == "test-api-key" + assert component.azure_deployment == "gpt-4o-mini" + assert component.streaming_callback is None + assert not component.generation_kwargs + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("AZURE_OPENAI_API_KEY", raising=False) + monkeypatch.delenv("AZURE_OPENAI_AD_TOKEN", raising=False) + with pytest.raises(OpenAIError): + AzureOpenAIGenerator(azure_endpoint="some-non-existing-endpoint") + + def test_init_with_parameters(self): + component = AzureOpenAIGenerator( + api_key=Secret.from_token("fake-api-key"), + azure_endpoint="some-non-existing-endpoint", + azure_deployment="gpt-4o-mini", + streaming_callback=print_streaming_chunk, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + assert component.client.api_key == "fake-api-key" + assert component.azure_deployment == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.timeout == 30.0 + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + + def test_to_dict_default(self, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-api-key") + component = AzureOpenAIGenerator(azure_endpoint="some-non-existing-endpoint") + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.azure.AzureOpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["AZURE_OPENAI_API_KEY"], "strict": False, "type": "env_var"}, + "azure_ad_token": {"env_vars": ["AZURE_OPENAI_AD_TOKEN"], "strict": False, "type": "env_var"}, + "azure_deployment": "gpt-4o-mini", + "api_version": "2023-05-15", + "streaming_callback": None, + "azure_endpoint": "some-non-existing-endpoint", + "organization": None, + "system_prompt": None, + "timeout": 30.0, + "max_retries": 5, + "generation_kwargs": {}, + "default_headers": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = AzureOpenAIGenerator( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + azure_ad_token=Secret.from_env_var("ENV_VAR1", strict=False), + azure_endpoint="some-non-existing-endpoint", + timeout=3.5, + max_retries=10, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.azure.AzureOpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "azure_ad_token": {"env_vars": ["ENV_VAR1"], "strict": False, "type": "env_var"}, + "azure_deployment": "gpt-4o-mini", + "api_version": "2023-05-15", + "streaming_callback": None, + "azure_endpoint": "some-non-existing-endpoint", + "organization": None, + "system_prompt": None, + "timeout": 3.5, + "max_retries": 10, + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + "default_headers": {}, + }, + } + + def test_pipeline_serialization_deserialization(self, tmp_path, monkeypatch): + monkeypatch.setenv("AZURE_OPENAI_API_KEY", "test-api-key") + generator = AzureOpenAIGenerator(azure_endpoint="some-non-existing-endpoint") + p = Pipeline() + p.add_component(instance=generator, name="generator") + p_str = p.dumps() + q = Pipeline.loads(p_str) + assert p.to_dict() == q.to_dict(), "Pipeline serialization/deserialization with AzureOpenAIGenerator failed." + + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("AZURE_OPENAI_API_KEY", None) or not os.environ.get("AZURE_OPENAI_ENDPOINT", None), + reason=( + "Please export env variables called AZURE_OPENAI_API_KEY containing " + "the Azure OpenAI key, AZURE_OPENAI_ENDPOINT containing " + "the Azure OpenAI endpoint URL to run this test." + ), + ) + def test_live_run(self): + component = AzureOpenAIGenerator(organization="HaystackCI") + results = component.run("What's the capital of France?") + assert len(results["replies"]) == 1 + assert len(results["meta"]) == 1 + response: str = results["replies"][0] + assert "Paris" in response + + metadata = results["meta"][0] + assert "gpt-4o-mini" in metadata["model"] + assert metadata["finish_reason"] == "stop" + + assert "usage" in metadata + assert "prompt_tokens" in metadata["usage"] and metadata["usage"]["prompt_tokens"] > 0 + assert "completion_tokens" in metadata["usage"] and metadata["usage"]["completion_tokens"] > 0 + assert "total_tokens" in metadata["usage"] and metadata["usage"]["total_tokens"] > 0 + + # additional tests intentionally omitted as they are covered by test_openai.py diff --git a/testbed/deepset-ai__haystack/test/components/generators/test_hf_utils.py b/testbed/deepset-ai__haystack/test/components/generators/test_hf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..22e2e1cac076a729e35f324264a56ca20e57c940 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/test_hf_utils.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.utils.hf import check_generation_params + + +def test_empty_dictionary(): + # no exception raised + check_generation_params({}) + + +def test_valid_generation_parameters(): + # these are valid parameters + kwargs = {"max_new_tokens": 100, "temperature": 0.8} + additional_accepted_params = None + check_generation_params(kwargs, additional_accepted_params) + + +def test_invalid_generation_parameters(): + # these are invalid parameters + kwargs = {"invalid_param": "value"} + additional_accepted_params = None + with pytest.raises(ValueError): + check_generation_params(kwargs, additional_accepted_params) + + +def test_additional_accepted_params_empty_list(): + kwargs = {"temperature": 0.8} + additional_accepted_params = [] + check_generation_params(kwargs, additional_accepted_params) + + +def test_additional_accepted_params_known_parameter(): + # both are valid parameters + kwargs = {"temperature": 0.8} + additional_accepted_params = ["max_new_tokens"] + check_generation_params(kwargs, additional_accepted_params) + + +def test_additional_accepted_params_unknown_parameter(): + kwargs = {"strange_param": "value"} + additional_accepted_params = ["strange_param"] + # Although strange_param is not generation param the check_generation_params + # does not raise exception because strange_param is passed as additional_accepted_params + check_generation_params(kwargs, additional_accepted_params) diff --git a/testbed/deepset-ai__haystack/test/components/generators/test_hugging_face_api.py b/testbed/deepset-ai__haystack/test/components/generators/test_hugging_face_api.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4be2f9cb46a833617feaca51402aa359519a53 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/test_hugging_face_api.py @@ -0,0 +1,314 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from unittest.mock import MagicMock, Mock, patch + +import pytest +from huggingface_hub import ( + TextGenerationOutputToken, + TextGenerationStreamOutput, + TextGenerationStreamOutputStreamDetails, +) +from huggingface_hub.utils import RepositoryNotFoundError + +from haystack.components.generators import HuggingFaceAPIGenerator +from haystack.dataclasses import StreamingChunk +from haystack.utils.auth import Secret +from haystack.utils.hf import HFGenerationAPIType + + +@pytest.fixture +def mock_check_valid_model(): + with patch( + "haystack.components.generators.hugging_face_api.check_valid_model", MagicMock(return_value=None) + ) as mock: + yield mock + + +@pytest.fixture +def mock_text_generation(): + with patch("huggingface_hub.InferenceClient.text_generation", autospec=True) as mock_text_generation: + mock_response = Mock() + mock_response.generated_text = "I'm fine, thanks." + details = Mock() + details.finish_reason = MagicMock(field1="value") + details.tokens = [1, 2, 3] + mock_response.details = details + mock_text_generation.return_value = mock_response + yield mock_text_generation + + +# used to test serialization of streaming_callback +def streaming_callback_handler(x): + return x + + +class TestHuggingFaceAPIGenerator: + def test_init_invalid_api_type(self): + with pytest.raises(ValueError): + HuggingFaceAPIGenerator(api_type="invalid_api_type", api_params={}) + + def test_init_serverless(self, mock_check_valid_model): + model = "HuggingFaceH4/zephyr-7b-alpha" + generation_kwargs = {"temperature": 0.6} + stop_words = ["stop"] + streaming_callback = None + + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": model}, + token=None, + generation_kwargs=generation_kwargs, + stop_words=stop_words, + streaming_callback=streaming_callback, + ) + + assert generator.api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API + assert generator.api_params == {"model": model} + assert generator.generation_kwargs == { + **generation_kwargs, + **{"stop_sequences": ["stop"]}, + **{"max_new_tokens": 512}, + } + assert generator.streaming_callback == streaming_callback + + def test_init_serverless_invalid_model(self, mock_check_valid_model): + mock_check_valid_model.side_effect = RepositoryNotFoundError("Invalid model id") + with pytest.raises(RepositoryNotFoundError): + HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "invalid_model_id"} + ) + + def test_init_serverless_no_model(self): + with pytest.raises(ValueError): + HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, api_params={"param": "irrelevant"} + ) + + def test_init_tgi(self): + url = "https://some_model.com" + generation_kwargs = {"temperature": 0.6} + stop_words = ["stop"] + streaming_callback = None + + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.TEXT_GENERATION_INFERENCE, + api_params={"url": url}, + token=None, + generation_kwargs=generation_kwargs, + stop_words=stop_words, + streaming_callback=streaming_callback, + ) + + assert generator.api_type == HFGenerationAPIType.TEXT_GENERATION_INFERENCE + assert generator.api_params == {"url": url} + assert generator.generation_kwargs == { + **generation_kwargs, + **{"stop_sequences": ["stop"]}, + **{"max_new_tokens": 512}, + } + assert generator.streaming_callback == streaming_callback + + def test_init_tgi_invalid_url(self): + with pytest.raises(ValueError): + HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.TEXT_GENERATION_INFERENCE, api_params={"url": "invalid_url"} + ) + + def test_init_tgi_no_url(self): + with pytest.raises(ValueError): + HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.TEXT_GENERATION_INFERENCE, api_params={"param": "irrelevant"} + ) + + def test_to_dict(self, mock_check_valid_model): + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + generation_kwargs={"temperature": 0.6}, + stop_words=["stop", "words"], + ) + + result = generator.to_dict() + init_params = result["init_parameters"] + + assert init_params["api_type"] == "serverless_inference_api" + assert init_params["api_params"] == {"model": "HuggingFaceH4/zephyr-7b-beta"} + assert init_params["token"] == {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + assert init_params["generation_kwargs"] == { + "temperature": 0.6, + "stop_sequences": ["stop", "words"], + "max_new_tokens": 512, + } + + def test_from_dict(self, mock_check_valid_model): + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + token=Secret.from_env_var("ENV_VAR", strict=False), + generation_kwargs={"temperature": 0.6}, + stop_words=["stop", "words"], + streaming_callback=streaming_callback_handler, + ) + result = generator.to_dict() + + # now deserialize, call from_dict + generator_2 = HuggingFaceAPIGenerator.from_dict(result) + assert generator_2.api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API + assert generator_2.api_params == {"model": "HuggingFaceH4/zephyr-7b-beta"} + assert generator_2.token == Secret.from_env_var("ENV_VAR", strict=False) + assert generator_2.generation_kwargs == { + "temperature": 0.6, + "stop_sequences": ["stop", "words"], + "max_new_tokens": 512, + } + assert generator_2.streaming_callback is streaming_callback_handler + + def test_generate_text_response_with_valid_prompt_and_generation_parameters( + self, mock_check_valid_model, mock_text_generation + ): + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + token=Secret.from_env_var("ENV_VAR", strict=False), + generation_kwargs={"temperature": 0.6}, + stop_words=["stop", "words"], + streaming_callback=None, + ) + + prompt = "Hello, how are you?" + response = generator.run(prompt) + + # check kwargs passed to text_generation + _, kwargs = mock_text_generation.call_args + assert kwargs == { + "details": True, + "temperature": 0.6, + "stop_sequences": ["stop", "words"], + "stream": False, + "max_new_tokens": 512, + } + + assert isinstance(response, dict) + assert "replies" in response + assert "meta" in response + assert isinstance(response["replies"], list) + assert isinstance(response["meta"], list) + assert len(response["replies"]) == 1 + assert len(response["meta"]) == 1 + assert [isinstance(reply, str) for reply in response["replies"]] + + def test_generate_text_with_custom_generation_parameters(self, mock_check_valid_model, mock_text_generation): + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, api_params={"model": "HuggingFaceH4/zephyr-7b-beta"} + ) + + generation_kwargs = {"temperature": 0.8, "max_new_tokens": 100} + response = generator.run("How are you?", generation_kwargs=generation_kwargs) + + # check kwargs passed to text_generation + _, kwargs = mock_text_generation.call_args + assert kwargs == { + "details": True, + "max_new_tokens": 100, + "stop_sequences": [], + "stream": False, + "temperature": 0.8, + } + + # Assert that the response contains the generated replies and the right response + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) > 0 + assert [isinstance(reply, str) for reply in response["replies"]] + assert response["replies"][0] == "I'm fine, thanks." + + # Assert that the response contains the metadata + assert "meta" in response + assert isinstance(response["meta"], list) + assert len(response["meta"]) > 0 + assert [isinstance(reply, str) for reply in response["replies"]] + + def test_generate_text_with_streaming_callback(self, mock_check_valid_model, mock_text_generation): + streaming_call_count = 0 + + # Define the streaming callback function + def streaming_callback_fn(chunk: StreamingChunk): + nonlocal streaming_call_count + streaming_call_count += 1 + assert isinstance(chunk, StreamingChunk) + + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + streaming_callback=streaming_callback_fn, + ) + + # Create a fake streamed response + # Don't remove self + def mock_iter(self): + yield TextGenerationStreamOutput( + index=0, + generated_text=None, + token=TextGenerationOutputToken(id=1, text="I'm fine, thanks.", logprob=0.0, special=False), + ) + yield TextGenerationStreamOutput( + index=1, + generated_text=None, + token=TextGenerationOutputToken(id=1, text="Ok bye", logprob=0.0, special=False), + details=TextGenerationStreamOutputStreamDetails( + finish_reason="length", generated_tokens=5, seed=None, input_length=10 + ), + ) + + mock_response = Mock(**{"__iter__": mock_iter}) + mock_text_generation.return_value = mock_response + + # Generate text response with streaming callback + response = generator.run("prompt") + + # check kwargs passed to text_generation + _, kwargs = mock_text_generation.call_args + assert kwargs == {"details": True, "stop_sequences": [], "stream": True, "max_new_tokens": 512} + + # Assert that the streaming callback was called twice + assert streaming_call_count == 2 + + # Assert that the response contains the generated replies + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) > 0 + assert [isinstance(reply, str) for reply in response["replies"]] + + # Assert that the response contains the metadata + assert "meta" in response + assert isinstance(response["meta"], list) + assert len(response["meta"]) > 0 + assert [isinstance(meta, dict) for meta in response["meta"]] + + @pytest.mark.flaky(reruns=5, reruns_delay=5) + @pytest.mark.integration + @pytest.mark.skipif( + not os.environ.get("HF_API_TOKEN", None), + reason="Export an env var called HF_API_TOKEN containing the Hugging Face token to run this test.", + ) + def test_run_serverless(self): + generator = HuggingFaceAPIGenerator( + api_type=HFGenerationAPIType.SERVERLESS_INFERENCE_API, + api_params={"model": "HuggingFaceH4/zephyr-7b-beta"}, + generation_kwargs={"max_new_tokens": 20}, + ) + + response = generator.run("How are you?") + # Assert that the response contains the generated replies + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) > 0 + assert [isinstance(reply, str) for reply in response["replies"]] + + # Assert that the response contains the metadata + assert "meta" in response + assert isinstance(response["meta"], list) + assert len(response["meta"]) > 0 + assert [isinstance(meta, dict) for meta in response["meta"]] diff --git a/testbed/deepset-ai__haystack/test/components/generators/test_hugging_face_local_generator.py b/testbed/deepset-ai__haystack/test/components/generators/test_hugging_face_local_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3b162a314549956dbb19649dbb58ffcf172dd2 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/test_hugging_face_local_generator.py @@ -0,0 +1,460 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +# pylint: disable=too-many-public-methods +from unittest.mock import Mock, patch + +import pytest +import torch +from transformers import PreTrainedTokenizerFast + +from haystack.components.generators.hugging_face_local import HuggingFaceLocalGenerator, StopWordsCriteria +from haystack.utils import ComponentDevice +from haystack.utils.auth import Secret +from haystack.utils.hf import HFTokenStreamingHandler + + +class TestHuggingFaceLocalGenerator: + @patch("haystack.utils.hf.model_info") + def test_init_default(self, model_info_mock, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + model_info_mock.return_value.pipeline_tag = "text2text-generation" + generator = HuggingFaceLocalGenerator() + + assert generator.huggingface_pipeline_kwargs == { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "token": None, + "device": ComponentDevice.resolve_device(None).to_hf(), + } + assert generator.generation_kwargs == {"max_new_tokens": 512} + assert generator.pipeline is None + + def test_init_custom_token(self): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", token=Secret.from_token("fake-api-token") + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "token": "fake-api-token", + "device": ComponentDevice.resolve_device(None).to_hf(), + } + + def test_init_custom_device(self): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", + task="text2text-generation", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_token("fake-api-token"), + ) + + assert generator.huggingface_pipeline_kwargs == { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "token": "fake-api-token", + "device": "cuda:0", + } + + def test_init_task_parameter(self): + generator = HuggingFaceLocalGenerator(task="text2text-generation", token=None) + + assert generator.huggingface_pipeline_kwargs == { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "token": None, + "device": ComponentDevice.resolve_device(None).to_hf(), + } + + def test_init_task_in_huggingface_pipeline_kwargs(self): + generator = HuggingFaceLocalGenerator(huggingface_pipeline_kwargs={"task": "text2text-generation"}, token=None) + + assert generator.huggingface_pipeline_kwargs == { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "token": None, + "device": ComponentDevice.resolve_device(None).to_hf(), + } + + @patch("haystack.utils.hf.model_info") + def test_init_task_inferred_from_model_name(self, model_info_mock): + model_info_mock.return_value.pipeline_tag = "text2text-generation" + generator = HuggingFaceLocalGenerator(model="google/flan-t5-base", token=None) + + assert generator.huggingface_pipeline_kwargs == { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "token": None, + "device": ComponentDevice.resolve_device(None).to_hf(), + } + + def test_init_invalid_task(self): + with pytest.raises(ValueError, match="is not supported."): + HuggingFaceLocalGenerator(task="text-classification") + + def test_init_huggingface_pipeline_kwargs_override_other_parameters(self): + """ + huggingface_pipeline_kwargs represent the main configuration of this component. + If they are provided, they should override other init parameters. + """ + + huggingface_pipeline_kwargs = { + "model": "gpt2", + "task": "text-generation", + "device": "cuda:0", + "token": "another-test-token", + } + + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", + task="text2text-generation", + device=ComponentDevice.from_str("cpu"), + token=None, + huggingface_pipeline_kwargs=huggingface_pipeline_kwargs, + ) + + assert generator.huggingface_pipeline_kwargs == huggingface_pipeline_kwargs + + def test_init_generation_kwargs(self): + generator = HuggingFaceLocalGenerator(task="text2text-generation", generation_kwargs={"max_new_tokens": 100}) + + assert generator.generation_kwargs == {"max_new_tokens": 100} + + def test_init_set_return_full_text(self): + """ + if not specified, return_full_text is set to False for text-generation task + (only generated text is returned, excluding prompt) + """ + generator = HuggingFaceLocalGenerator(task="text-generation") + + assert generator.generation_kwargs == {"max_new_tokens": 512, "return_full_text": False} + + def test_init_fails_with_both_stopwords_and_stoppingcriteria(self): + with pytest.raises( + ValueError, + match="Found both the `stop_words` init parameter and the `stopping_criteria` key in `generation_kwargs`", + ): + HuggingFaceLocalGenerator( + task="text2text-generation", + stop_words=["coca", "cola"], + generation_kwargs={"stopping_criteria": "fake-stopping-criteria"}, + ) + + @patch("haystack.utils.hf.model_info") + def test_to_dict_default(self, model_info_mock): + model_info_mock.return_value.pipeline_tag = "text2text-generation" + + component = HuggingFaceLocalGenerator() + data = component.to_dict() + + assert data == { + "type": "haystack.components.generators.hugging_face_local.HuggingFaceLocalGenerator", + "init_parameters": { + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "google/flan-t5-base", + "task": "text2text-generation", + "device": ComponentDevice.resolve_device(None).to_hf(), + }, + "generation_kwargs": {"max_new_tokens": 512}, + "streaming_callback": None, + "stop_words": None, + }, + } + + def test_to_dict_with_parameters(self): + component = HuggingFaceLocalGenerator( + model="gpt2", + task="text-generation", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_env_var("ENV_VAR", strict=False), + generation_kwargs={"max_new_tokens": 100}, + stop_words=["coca", "cola"], + huggingface_pipeline_kwargs={ + "model_kwargs": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + "bnb_4bit_compute_dtype": torch.bfloat16, + } + }, + ) + data = component.to_dict() + + assert data == { + "type": "haystack.components.generators.hugging_face_local.HuggingFaceLocalGenerator", + "init_parameters": { + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "gpt2", + "task": "text-generation", + "device": "cuda:0", + "model_kwargs": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + # dtype is correctly serialized + "bnb_4bit_compute_dtype": "torch.bfloat16", + }, + }, + "generation_kwargs": {"max_new_tokens": 100, "return_full_text": False}, + "streaming_callback": None, + "stop_words": ["coca", "cola"], + }, + } + + def test_to_dict_with_quantization_config(self): + component = HuggingFaceLocalGenerator( + model="gpt2", + task="text-generation", + device=ComponentDevice.from_str("cuda:0"), + token=None, + generation_kwargs={"max_new_tokens": 100}, + stop_words=["coca", "cola"], + huggingface_pipeline_kwargs={ + "model_kwargs": { + "quantization_config": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + "bnb_4bit_compute_dtype": torch.bfloat16, + } + } + }, + ) + data = component.to_dict() + + assert data == { + "type": "haystack.components.generators.hugging_face_local.HuggingFaceLocalGenerator", + "init_parameters": { + "token": None, + "huggingface_pipeline_kwargs": { + "model": "gpt2", + "task": "text-generation", + "device": "cuda:0", + "model_kwargs": { + "quantization_config": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + # dtype is correctly serialized + "bnb_4bit_compute_dtype": "torch.bfloat16", + } + }, + }, + "generation_kwargs": {"max_new_tokens": 100, "return_full_text": False}, + "streaming_callback": None, + "stop_words": ["coca", "cola"], + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.generators.hugging_face_local.HuggingFaceLocalGenerator", + "init_parameters": { + "token": None, + "huggingface_pipeline_kwargs": { + "model": "gpt2", + "task": "text-generation", + "device": "cuda:0", + "model_kwargs": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + # dtype is correctly serialized + "bnb_4bit_compute_dtype": "torch.bfloat16", + }, + }, + "generation_kwargs": {"max_new_tokens": 100, "return_full_text": False}, + "stop_words": ["coca", "cola"], + }, + } + + component = HuggingFaceLocalGenerator.from_dict(data) + + assert component.huggingface_pipeline_kwargs == { + "model": "gpt2", + "task": "text-generation", + "device": "cuda:0", + "token": None, + "model_kwargs": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + # dtype is correctly deserialized + "bnb_4bit_compute_dtype": torch.bfloat16, + }, + } + assert component.generation_kwargs == {"max_new_tokens": 100, "return_full_text": False} + assert component.stop_words == ["coca", "cola"] + + @patch("haystack.components.generators.hugging_face_local.pipeline") + def test_warm_up(self, pipeline_mock): + generator = HuggingFaceLocalGenerator(model="google/flan-t5-base", task="text2text-generation", token=None) + pipeline_mock.assert_not_called() + + generator.warm_up() + + pipeline_mock.assert_called_once_with( + model="google/flan-t5-base", + task="text2text-generation", + token=None, + device=ComponentDevice.resolve_device(None).to_hf(), + ) + + @patch("haystack.components.generators.hugging_face_local.pipeline") + def test_warm_up_doesnt_reload(self, pipeline_mock): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", token=Secret.from_token("fake-api-token") + ) + + pipeline_mock.assert_not_called() + + generator.warm_up() + generator.warm_up() + + pipeline_mock.assert_called_once() + + def test_run(self): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", generation_kwargs={"max_new_tokens": 100} + ) + + # create the pipeline object (simulating the warm_up) + generator.pipeline = Mock(return_value=[{"generated_text": "Rome"}]) + + results = generator.run(prompt="What's the capital of Italy?") + + generator.pipeline.assert_called_once_with( + "What's the capital of Italy?", max_new_tokens=100, stopping_criteria=None + ) + assert results == {"replies": ["Rome"]} + + @patch("haystack.components.generators.hugging_face_local.pipeline") + def test_run_empty_prompt(self, pipeline_mock): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", generation_kwargs={"max_new_tokens": 100} + ) + + generator.warm_up() + + results = generator.run(prompt="") + + assert results == {"replies": []} + + def test_run_with_generation_kwargs(self): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", generation_kwargs={"max_new_tokens": 100} + ) + + # create the pipeline object (simulating the warm_up) + generator.pipeline = Mock(return_value=[{"generated_text": "Rome"}]) + + generator.run(prompt="irrelevant", generation_kwargs={"max_new_tokens": 200, "temperature": 0.5}) + + generator.pipeline.assert_called_once_with( + "irrelevant", max_new_tokens=200, temperature=0.5, stopping_criteria=None + ) + + def test_run_with_streaming(self): + def streaming_callback_handler(x): + return x + + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", streaming_callback=streaming_callback_handler + ) + + # create the pipeline object (simulating the warm_up) + generator.pipeline = Mock(return_value=[{"generated_text": "Rome"}]) + + generator.run(prompt="irrelevant") + + # when we use streaming, the pipeline should be called with the `streamer` argument being an instance of + # ouf our adapter class HFTokenStreamingHandler + assert isinstance(generator.pipeline.call_args.kwargs["streamer"], HFTokenStreamingHandler) + streamer = generator.pipeline.call_args.kwargs["streamer"] + + # check that the streaming callback is set + assert streamer.token_handler == streaming_callback_handler + # the tokenizer should be set, here it is a mock + assert streamer.tokenizer + + def test_run_fails_without_warm_up(self): + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-base", task="text2text-generation", generation_kwargs={"max_new_tokens": 100} + ) + + with pytest.raises(RuntimeError, match="The component HuggingFaceLocalGenerator was not warmed up"): + generator.run(prompt="irrelevant") + + def test_stop_words_criteria_with_a_mocked_tokenizer(self): + """ + Test that StopWordsCriteria will caught stop word tokens in a continuous and sequential order in the input_ids + """ + stop_words_id = torch.LongTensor([[73, 24621, 11937]]) # "unambiguously" + # "This is ambiguously, but is unrelated." + input_ids_one = torch.LongTensor([[100, 19, 24621, 11937, 6, 68, 19, 73, 3897, 5]]) + input_ids_two = torch.LongTensor([[100, 19, 73, 24621, 11937]]) # "This is unambiguously" + stop_words_criteria = StopWordsCriteria(tokenizer=Mock(spec=PreTrainedTokenizerFast), stop_words=["mock data"]) + stop_words_criteria.stop_ids = stop_words_id + assert not stop_words_criteria(input_ids_one, scores=None) + assert stop_words_criteria(input_ids_two, scores=None) + + @patch("haystack.components.generators.hugging_face_local.pipeline") + @patch("haystack.components.generators.hugging_face_local.StopWordsCriteria") + @patch("haystack.components.generators.hugging_face_local.StoppingCriteriaList") + def test_warm_up_set_stopping_criteria_list( + self, pipeline_mock, stop_words_criteria_mock, stopping_criteria_list_mock + ): + """ + Test that warm_up method sets the `stopping_criteria_list` attribute if `stop_words` is provided + """ + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-small", task="text2text-generation", stop_words=["coca", "cola"] + ) + generator.warm_up() + stop_words_criteria_mock.assert_called_once() + stopping_criteria_list_mock.assert_called_once() + assert hasattr(generator, "stopping_criteria_list") + + def test_run_stop_words_removal(self): + """Test that stop words are removed from the generated text (does not test stopping text generation)""" + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-small", task="text2text-generation", stop_words=["world"] + ) + generator.pipeline = Mock(return_value=[{"generated_text": "Hello world"}]) + generator.stopping_criteria_list = Mock() + results = generator.run(prompt="irrelevant") + assert results == {"replies": ["Hello"]} + + @pytest.mark.integration + def test_stop_words_criteria_using_hf_tokenizer(self): + """ + Test that StopWordsCriteria catches stop word tokens in a continuous and sequential order in the input_ids + using a real Huggingface tokenizer. + """ + from transformers import AutoTokenizer + + model_name = "google/flan-t5-small" + tokenizer = AutoTokenizer.from_pretrained(model_name) + criteria = StopWordsCriteria(tokenizer=tokenizer, stop_words=["unambiguously"]) + + text_one = "This is ambiguously, but is unrelated." + generated_text_ids = tokenizer.encode(text_one, add_special_tokens=False, return_tensors="pt") + assert criteria(generated_text_ids, scores=None) is False + + text_two = "This is unambiguously" + generated_text_ids = tokenizer.encode(text_two, add_special_tokens=False, return_tensors="pt") + assert criteria(generated_text_ids, scores=None) is True + + @pytest.mark.integration + def test_hf_pipeline_runs_with_our_criteria(self): + """Test that creating our own StopWordsCriteria and passing it to a Huggingface pipeline works.""" + generator = HuggingFaceLocalGenerator( + model="google/flan-t5-small", task="text2text-generation", stop_words=["unambiguously"] + ) + generator.warm_up() + results = generator.run(prompt="something that triggers something") + assert results["replies"] != [] + assert generator.stopping_criteria_list is not None diff --git a/testbed/deepset-ai__haystack/test/components/generators/test_openai.py b/testbed/deepset-ai__haystack/test/components/generators/test_openai.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5e73d85c239bb5e31bfa1958165462c6bd705a --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/test_openai.py @@ -0,0 +1,335 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import os +from typing import List + +import pytest +from openai import OpenAIError + +from haystack.components.generators import OpenAIGenerator +from haystack.components.generators.utils import print_streaming_chunk +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.utils.auth import Secret + + +class TestOpenAIGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = OpenAIGenerator() + assert component.client.api_key == "test-api-key" + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is None + assert not component.generation_kwargs + assert component.client.timeout == 30 + assert component.client.max_retries == 5 + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + OpenAIGenerator() + + def test_init_with_parameters(self, monkeypatch): + monkeypatch.setenv("OPENAI_TIMEOUT", "100") + monkeypatch.setenv("OPENAI_MAX_RETRIES", "10") + component = OpenAIGenerator( + api_key=Secret.from_token("test-api-key"), + model="gpt-4o-mini", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + timeout=40.0, + max_retries=1, + ) + assert component.client.api_key == "test-api-key" + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.client.timeout == 40.0 + assert component.client.max_retries == 1 + + def test_to_dict_default(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = OpenAIGenerator() + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.openai.OpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "streaming_callback": None, + "system_prompt": None, + "api_base_url": None, + "organization": None, + "generation_kwargs": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = OpenAIGenerator( + api_key=Secret.from_env_var("ENV_VAR"), + model="gpt-4o-mini", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + organization="org-1234567", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.openai.OpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "system_prompt": None, + "api_base_url": "test-base-url", + "organization": "org-1234567", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_to_dict_with_lambda_streaming_callback(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "test-api-key") + component = OpenAIGenerator( + model="gpt-4o-mini", + streaming_callback=lambda x: x, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.generators.openai.OpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "system_prompt": None, + "organization": None, + "api_base_url": "test-base-url", + "streaming_callback": "test_openai.", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key") + data = { + "type": "haystack.components.generators.openai.OpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "system_prompt": None, + "organization": None, + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + component = OpenAIGenerator.from_dict(data) + assert component.model == "gpt-4o-mini" + assert component.streaming_callback is print_streaming_chunk + assert component.api_base_url == "test-base-url" + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.api_key == Secret.from_env_var("OPENAI_API_KEY") + + def test_from_dict_fail_wo_env_var(self, monkeypatch): + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + data = { + "type": "haystack.components.generators.openai.OpenAIGenerator", + "init_parameters": { + "api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"}, + "model": "gpt-4o-mini", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + OpenAIGenerator.from_dict(data) + + def test_run(self, mock_chat_completion): + component = OpenAIGenerator(api_key=Secret.from_token("test-api-key")) + response = component.run("What's Natural Language Processing?") + + # check that the component returns the correct ChatMessage response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, str) for reply in response["replies"]] + + def test_run_with_params_streaming(self, mock_chat_completion_chunk): + streaming_callback_called = False + + def streaming_callback(chunk: StreamingChunk) -> None: + nonlocal streaming_callback_called + streaming_callback_called = True + + component = OpenAIGenerator(api_key=Secret.from_token("test-api-key"), streaming_callback=streaming_callback) + response = component.run("Come on, stream!") + + # check we called the streaming callback + assert streaming_callback_called + + # check that the component still returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert "Hello" in response["replies"][0] # see mock_chat_completion_chunk + + def test_run_with_streaming_callback_in_run_method(self, mock_chat_completion_chunk): + streaming_callback_called = False + + def streaming_callback(chunk: StreamingChunk) -> None: + nonlocal streaming_callback_called + streaming_callback_called = True + + # pass streaming_callback to run() + component = OpenAIGenerator(api_key=Secret.from_token("test-api-key")) + response = component.run("Come on, stream!", streaming_callback=streaming_callback) + + # check we called the streaming callback + assert streaming_callback_called + + # check that the component still returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert "Hello" in response["replies"][0] # see mock_chat_completion_chunk + + def test_run_with_params(self, mock_chat_completion): + component = OpenAIGenerator( + api_key=Secret.from_token("test-api-key"), generation_kwargs={"max_tokens": 10, "temperature": 0.5} + ) + response = component.run("What's Natural Language Processing?") + + # check that the component calls the OpenAI API with the correct parameters + _, kwargs = mock_chat_completion.call_args + assert kwargs["max_tokens"] == 10 + assert kwargs["temperature"] == 0.5 + + # check that the component returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, str) for reply in response["replies"]] + + def test_check_abnormal_completions(self, caplog): + caplog.set_level(logging.INFO) + component = OpenAIGenerator(api_key=Secret.from_token("test-api-key")) + + # underlying implementation uses ChatMessage objects so we have to use them here + messages: List[ChatMessage] = [] + for i, _ in enumerate(range(4)): + message = ChatMessage.from_assistant("Hello") + metadata = {"finish_reason": "content_filter" if i % 2 == 0 else "length", "index": i} + message.meta.update(metadata) + messages.append(message) + + for m in messages: + component._check_finish_reason(m) + + # check truncation warning + message_template = ( + "The completion for index {index} has been truncated before reaching a natural stopping point. " + "Increase the max_tokens parameter to allow for longer completions." + ) + + for index in [1, 3]: + assert caplog.records[index].message == message_template.format(index=index) + + # check content filter warning + message_template = "The completion for index {index} has been truncated due to the content filter." + for index in [0, 2]: + assert caplog.records[index].message == message_template.format(index=index) + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run(self): + component = OpenAIGenerator() + results = component.run("What's the capital of France?") + assert len(results["replies"]) == 1 + assert len(results["meta"]) == 1 + response: str = results["replies"][0] + assert "Paris" in response + + metadata = results["meta"][0] + assert "gpt-4o-mini" in metadata["model"] + assert metadata["finish_reason"] == "stop" + + assert "usage" in metadata + assert "prompt_tokens" in metadata["usage"] and metadata["usage"]["prompt_tokens"] > 0 + assert "completion_tokens" in metadata["usage"] and metadata["usage"]["completion_tokens"] > 0 + assert "total_tokens" in metadata["usage"] and metadata["usage"]["total_tokens"] > 0 + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_wrong_model(self): + component = OpenAIGenerator(model="something-obviously-wrong") + with pytest.raises(OpenAIError): + component.run("Whatever") + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_streaming(self): + class Callback: + def __init__(self): + self.responses = "" + self.counter = 0 + + def __call__(self, chunk: StreamingChunk) -> None: + self.counter += 1 + self.responses += chunk.content if chunk.content else "" + + callback = Callback() + component = OpenAIGenerator(streaming_callback=callback) + results = component.run("What's the capital of France?") + + assert len(results["replies"]) == 1 + assert len(results["meta"]) == 1 + response: str = results["replies"][0] + assert "Paris" in response + + metadata = results["meta"][0] + + assert "gpt-4o-mini" in metadata["model"] + assert metadata["finish_reason"] == "stop" + + # unfortunately, the usage is not available for streaming calls + # we keep the key in the metadata for compatibility + assert "usage" in metadata and len(metadata["usage"]) == 0 + + assert callback.counter > 1 + assert "Paris" in callback.responses + + @pytest.mark.skipif( + not os.environ.get("OPENAI_API_KEY", None), + reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_run_with_system_prompt(self): + generator = OpenAIGenerator( + model="gpt-4o-mini", + system_prompt="You answer in Portuguese, regardless of the language on which a question is asked", + ) + result = generator.run("Can you explain the Pitagoras therom?") + assert "teorema" in result["replies"][0].lower() + + result = generator.run( + "Can you explain the Pitagoras therom?", + system_prompt="You answer in German, regardless of the language on which a question is asked.", + ) + assert "pythagoras".lower() in result["replies"][0].lower() diff --git a/testbed/deepset-ai__haystack/test/components/generators/test_openai_utils.py b/testbed/deepset-ai__haystack/test/components/generators/test_openai_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..226b32f811b4294456dfba2a4d43c5f274133802 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/generators/test_openai_utils.py @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from haystack.dataclasses import ChatMessage +from haystack.components.generators.openai_utils import _convert_message_to_openai_format + + +def test_convert_message_to_openai_format(): + message = ChatMessage.from_system("You are good assistant") + assert _convert_message_to_openai_format(message) == {"role": "system", "content": "You are good assistant"} + + message = ChatMessage.from_user("I have a question") + assert _convert_message_to_openai_format(message) == {"role": "user", "content": "I have a question"} + + message = ChatMessage.from_function("Function call", "function_name") + assert _convert_message_to_openai_format(message) == { + "role": "function", + "content": "Function call", + "name": "function_name", + } diff --git a/testbed/deepset-ai__haystack/test/components/joiners/__init__.py b/testbed/deepset-ai__haystack/test/components/joiners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/joiners/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/joiners/test_answer_joiner.py b/testbed/deepset-ai__haystack/test/components/joiners/test_answer_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0a1be2befe522035ec51365ab8bee50b040b6e --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/joiners/test_answer_joiner.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document +from haystack.dataclasses.answer import ExtractedAnswer, GeneratedAnswer, ExtractedTableAnswer +from haystack.components.joiners.answer_joiner import AnswerJoiner, JoinMode + + +class TestAnswerJoiner: + def test_init(self): + joiner = AnswerJoiner() + assert joiner.join_mode == JoinMode.CONCATENATE + assert joiner.top_k is None + assert joiner.sort_by_score is False + + def test_init_with_custom_parameters(self): + joiner = AnswerJoiner(join_mode="concatenate", top_k=5, sort_by_score=True) + assert joiner.join_mode == JoinMode.CONCATENATE + assert joiner.top_k == 5 + assert joiner.sort_by_score is True + + def test_to_dict(self): + joiner = AnswerJoiner() + data = joiner.to_dict() + assert data == { + "type": "haystack.components.joiners.answer_joiner.AnswerJoiner", + "init_parameters": {"join_mode": "concatenate", "top_k": None, "sort_by_score": False}, + } + + def test_to_from_dict_custom_parameters(self): + joiner = AnswerJoiner("concatenate", top_k=5, sort_by_score=True) + data = joiner.to_dict() + assert data == { + "type": "haystack.components.joiners.answer_joiner.AnswerJoiner", + "init_parameters": {"join_mode": "concatenate", "top_k": 5, "sort_by_score": True}, + } + + deserialized_joiner = AnswerJoiner.from_dict(data) + assert deserialized_joiner.join_mode == JoinMode.CONCATENATE + assert deserialized_joiner.top_k == 5 + assert deserialized_joiner.sort_by_score is True + + def test_from_dict(self): + data = {"type": "haystack.components.joiners.answer_joiner.AnswerJoiner", "init_parameters": {}} + answer_joiner = AnswerJoiner.from_dict(data) + assert answer_joiner.join_mode == JoinMode.CONCATENATE + assert answer_joiner.top_k is None + assert answer_joiner.sort_by_score is False + + def test_from_dict_customs_parameters(self): + data = { + "type": "haystack.components.joiners.answer_joiner.AnswerJoiner", + "init_parameters": {"join_mode": "concatenate", "top_k": 5, "sort_by_score": True}, + } + answer_joiner = AnswerJoiner.from_dict(data) + assert answer_joiner.join_mode == JoinMode.CONCATENATE + assert answer_joiner.top_k == 5 + assert answer_joiner.sort_by_score is True + + def test_empty_list(self): + joiner = AnswerJoiner() + result = joiner.run([]) + assert result == {"answers": []} + + def test_list_of_empty_lists(self): + joiner = AnswerJoiner() + result = joiner.run([[], []]) + assert result == {"answers": []} + + def test_list_of_single_answer(self): + joiner = AnswerJoiner() + answers = [ + GeneratedAnswer(query="a", data="a", meta={}, documents=[Document(content="a")]), + GeneratedAnswer(query="b", data="b", meta={}, documents=[Document(content="b")]), + GeneratedAnswer(query="c", data="c", meta={}, documents=[Document(content="c")]), + ] + result = joiner.run([answers]) + assert result == {"answers": answers} + + def test_two_lists_of_generated_answers(self): + joiner = AnswerJoiner() + answers1 = [GeneratedAnswer(query="a", data="a", meta={}, documents=[Document(content="a")])] + answers2 = [GeneratedAnswer(query="d", data="d", meta={}, documents=[Document(content="d")])] + result = joiner.run([answers1, answers2]) + assert result == {"answers": answers1 + answers2} + + def test_multiple_lists_of_mixed_answers(self): + joiner = AnswerJoiner() + answers1 = [GeneratedAnswer(query="a", data="a", meta={}, documents=[Document(content="a")])] + answers2 = [ExtractedAnswer(query="d", score=0.9, meta={}, document=Document(content="d"))] + answers3 = [ExtractedTableAnswer(query="e", score=0.7, meta={}, document=Document(content="e"))] + answers4 = [GeneratedAnswer(query="f", data="f", meta={}, documents=[Document(content="f")])] + all_answers = answers1 + answers2 + answers3 + answers4 # type: ignore + result = joiner.run([answers1, answers2, answers3, answers4]) + assert result == {"answers": all_answers} + + def test_unsupported_join_mode(self): + unsupported_mode = "unsupported_mode" + with pytest.raises(ValueError): + AnswerJoiner(join_mode=unsupported_mode) diff --git a/testbed/deepset-ai__haystack/test/components/joiners/test_branch_joiner.py b/testbed/deepset-ai__haystack/test/components/joiners/test_branch_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..05d30ad6d380928d38f7cad96058e062480335c5 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/joiners/test_branch_joiner.py @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.components.joiners import BranchJoiner + + +class TestBranchJoiner: + def test_one_value(self): + joiner = BranchJoiner(int) + output = joiner.run(value=[2]) + assert output == {"value": 2} + + def test_one_value_of_wrong_type(self): + # BranchJoiner does not type check the input + joiner = BranchJoiner(int) + output = joiner.run(value=["hello"]) + assert output == {"value": "hello"} + + def test_one_value_of_none_type(self): + # BranchJoiner does not type check the input + joiner = BranchJoiner(int) + output = joiner.run(value=[None]) + assert output == {"value": None} + + def test_more_values_of_expected_type(self): + joiner = BranchJoiner(int) + with pytest.raises(ValueError, match="BranchJoiner expects only one input, but 3 were received."): + joiner.run(value=[2, 3, 4]) + + def test_no_values(self): + joiner = BranchJoiner(int) + with pytest.raises(ValueError, match="BranchJoiner expects only one input, but 0 were received."): + joiner.run(value=[]) diff --git a/testbed/deepset-ai__haystack/test/components/joiners/test_document_joiner.py b/testbed/deepset-ai__haystack/test/components/joiners/test_document_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..56bdfb64438aab0e1a377b163f6775f2ce974146 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/joiners/test_document_joiner.py @@ -0,0 +1,280 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import re + +import pytest + +from haystack import Document +from haystack.components.joiners.document_joiner import DocumentJoiner, JoinMode + + +class TestDocumentJoiner: + def test_init(self): + joiner = DocumentJoiner() + assert joiner.join_mode == JoinMode.CONCATENATE + assert joiner.weights is None + assert joiner.top_k is None + assert joiner.sort_by_score + + def test_init_with_custom_parameters(self): + joiner = DocumentJoiner(join_mode="merge", weights=[0.4, 0.6], top_k=5, sort_by_score=False) + assert joiner.join_mode == JoinMode.MERGE + assert joiner.weights == [0.4, 0.6] + assert joiner.top_k == 5 + assert not joiner.sort_by_score + + def test_to_dict(self): + joiner = DocumentJoiner() + data = joiner.to_dict() + assert data == { + "type": "haystack.components.joiners.document_joiner.DocumentJoiner", + "init_parameters": {"join_mode": "concatenate", "sort_by_score": True, "top_k": None, "weights": None}, + } + + def test_to_dict_custom_parameters(self): + joiner = DocumentJoiner("merge", weights=[0.4, 0.6], top_k=4, sort_by_score=False) + data = joiner.to_dict() + assert data == { + "type": "haystack.components.joiners.document_joiner.DocumentJoiner", + "init_parameters": {"join_mode": "merge", "weights": [0.4, 0.6], "top_k": 4, "sort_by_score": False}, + } + + def test_from_dict(self): + data = {"type": "haystack.components.joiners.document_joiner.DocumentJoiner", "init_parameters": {}} + document_joiner = DocumentJoiner.from_dict(data) + assert document_joiner.join_mode == JoinMode.CONCATENATE + assert document_joiner.weights == None + assert document_joiner.top_k == None + assert document_joiner.sort_by_score + + def test_from_dict_customs_parameters(self): + data = { + "type": "haystack.components.joiners.document_joiner.DocumentJoiner", + "init_parameters": {"join_mode": "merge", "weights": [0.5, 0.6], "top_k": 6, "sort_by_score": False}, + } + document_joiner = DocumentJoiner.from_dict(data) + assert document_joiner.join_mode == JoinMode.MERGE + assert document_joiner.weights == pytest.approx([0.5, 0.6], rel=0.1) + assert document_joiner.top_k == 6 + assert not document_joiner.sort_by_score + + def test_empty_list(self): + joiner = DocumentJoiner() + result = joiner.run([]) + assert result == {"documents": []} + + def test_list_of_empty_lists(self): + joiner = DocumentJoiner() + result = joiner.run([[], []]) + assert result == {"documents": []} + + def test_list_with_one_empty_list(self): + joiner = DocumentJoiner() + documents = [Document(content="a"), Document(content="b"), Document(content="c")] + result = joiner.run([[], documents]) + assert result == {"documents": documents} + + def test_unsupported_join_mode(self): + unsupported_mode = "unsupported_mode" + expected_error_pattern = ( + re.escape(f"Unknown join mode '{unsupported_mode}'") + r".*Supported modes in DocumentJoiner are: \[.*\]" + ) + + with pytest.raises(ValueError, match=expected_error_pattern): + DocumentJoiner(join_mode=unsupported_mode) + + def test_run_with_concatenate_join_mode_and_top_k(self): + joiner = DocumentJoiner(top_k=6) + documents_1 = [Document(content="a"), Document(content="b"), Document(content="c")] + documents_2 = [ + Document(content="d"), + Document(content="e"), + Document(content="f", meta={"key": "value"}), + Document(content="g"), + ] + output = joiner.run([documents_1, documents_2]) + assert len(output["documents"]) == 6 + assert sorted(documents_1 + documents_2[:-1], key=lambda d: d.id) == sorted( + output["documents"], key=lambda d: d.id + ) + + def test_run_with_concatenate_join_mode_and_duplicate_documents(self): + joiner = DocumentJoiner() + documents_1 = [Document(content="a", score=0.3), Document(content="b"), Document(content="c")] + documents_2 = [ + Document(content="a", score=0.2), + Document(content="a"), + Document(content="f", meta={"key": "value"}), + ] + output = joiner.run([documents_1, documents_2]) + assert len(output["documents"]) == 4 + assert sorted(documents_1 + [documents_2[-1]], key=lambda d: d.id) == sorted( + output["documents"], key=lambda d: d.id + ) + + def test_run_with_merge_join_mode(self): + joiner = DocumentJoiner(join_mode="merge", weights=[1.5, 0.5]) + documents_1 = [Document(content="a", score=1.0), Document(content="b", score=2.0)] + documents_2 = [ + Document(content="a", score=0.5), + Document(content="b", score=3.0), + Document(content="f", score=4.0, meta={"key": "value"}), + ] + output = joiner.run([documents_1, documents_2]) + assert len(output["documents"]) == 3 + expected_document_ids = [ + doc.id + for doc in [ + Document(content="a", score=1.25), + Document(content="b", score=2.25), + Document(content="f", score=4.0, meta={"key": "value"}), + ] + ] + assert all(doc.id in expected_document_ids for doc in output["documents"]) + + def test_run_with_reciprocal_rank_fusion_join_mode(self): + joiner = DocumentJoiner(join_mode="reciprocal_rank_fusion") + documents_1 = [Document(content="a"), Document(content="b"), Document(content="c")] + documents_2 = [ + Document(content="b", score=1000.0), + Document(content="c"), + Document(content="a"), + Document(content="f", meta={"key": "value"}), + ] + output = joiner.run([documents_1, documents_2]) + assert len(output["documents"]) == 4 + expected_document_ids = [ + doc.id + for doc in [ + Document(content="b"), + Document(content="a"), + Document(content="c"), + Document(content="f", meta={"key": "value"}), + ] + ] + assert all(doc.id in expected_document_ids for doc in output["documents"]) + + def test_run_with_distribution_based_rank_fusion_join_mode(self): + joiner = DocumentJoiner(join_mode="distribution_based_rank_fusion") + documents_1 = [ + Document(content="a", score=0.6), + Document(content="b", score=0.2), + Document(content="c", score=0.5), + ] + documents_2 = [ + Document(content="d", score=0.5), + Document(content="e", score=0.8), + Document(content="f", score=1.1, meta={"key": "value"}), + Document(content="g", score=0.3), + Document(content="a", score=0.3), + ] + output = joiner.run([documents_1, documents_2]) + assert len(output["documents"]) == 7 + expected_document_ids = [ + doc.id + for doc in [ + Document(content="a", score=0.66), + Document(content="b", score=0.27), + Document(content="c", score=0.56), + Document(content="d", score=0.44), + Document(content="e", score=0.60), + Document(content="f", score=0.76, meta={"key": "value"}), + Document(content="g", score=0.33), + ] + ] + assert all(doc.id in expected_document_ids for doc in output["documents"]) + + def test_run_with_distribution_based_rank_fusion_join_mode_same_scores(self): + joiner = DocumentJoiner(join_mode="distribution_based_rank_fusion") + documents_1 = [ + Document(content="a", score=0.2), + Document(content="b", score=0.2), + Document(content="c", score=0.2), + ] + documents_2 = [ + Document(content="d", score=0.5), + Document(content="e", score=0.8), + Document(content="f", score=1.1, meta={"key": "value"}), + Document(content="g", score=0.3), + Document(content="a", score=0.3), + ] + output = joiner.run([documents_1, documents_2]) + assert len(output["documents"]) == 7 + expected_document_ids = [ + doc.id + for doc in [ + Document(content="a", score=0), + Document(content="b", score=0), + Document(content="c", score=0), + Document(content="d", score=0.44), + Document(content="e", score=0.60), + Document(content="f", score=0.76, meta={"key": "value"}), + Document(content="g", score=0.33), + ] + ] + assert all(doc.id in expected_document_ids for doc in output["documents"]) + + def test_run_with_top_k_in_run_method(self): + joiner = DocumentJoiner() + documents_1 = [Document(content="a"), Document(content="b"), Document(content="c")] + documents_2 = [Document(content="d"), Document(content="e"), Document(content="f")] + top_k = 4 + output = joiner.run([documents_1, documents_2], top_k=top_k) + assert len(output["documents"]) == top_k + + def test_sort_by_score_without_scores(self, caplog): + joiner = DocumentJoiner() + with caplog.at_level(logging.INFO): + documents = [Document(content="a"), Document(content="b", score=0.5)] + output = joiner.run([documents]) + assert "those with score=None were sorted as if they had a score of -infinity" in caplog.text + assert output["documents"] == documents[::-1] + + def test_output_documents_not_sorted_by_score(self): + joiner = DocumentJoiner(sort_by_score=False) + documents_1 = [Document(content="a", score=0.1)] + documents_2 = [Document(content="d", score=0.2)] + output = joiner.run([documents_1, documents_2]) + assert output["documents"] == documents_1 + documents_2 + + def test_test_score_norm_with_rrf(self): + """ + Verifies reciprocal rank fusion (RRF) of the DocumentJoiner component with various weight configurations. + It creates a set of documents, forms them into two lists, and then applies multiple DocumentJoiner + instances with distinct weights to these lists. The test checks if the resulting + joined documents are correctly sorted in descending order by score, ensuring the RRF ranking works as + expected under different weighting scenarios. + """ + num_docs = 6 + docs = [] + + for i in range(num_docs): + docs.append(Document(content=f"doc{i}")) + + docs_2 = [docs[0], docs[4], docs[2], docs[5], docs[1]] + document_lists = [docs, docs_2] + + joiner_1 = DocumentJoiner(join_mode="reciprocal_rank_fusion", weights=[0.5, 0.5]) + + joiner_2 = DocumentJoiner(join_mode="reciprocal_rank_fusion", weights=[7, 7]) + + joiner_3 = DocumentJoiner(join_mode="reciprocal_rank_fusion", weights=[0.7, 0.3]) + + joiner_4 = DocumentJoiner(join_mode="reciprocal_rank_fusion", weights=[0.6, 0.4]) + + joiner_5 = DocumentJoiner(join_mode="reciprocal_rank_fusion", weights=[1, 0]) + + joiners = [joiner_1, joiner_2, joiner_3, joiner_4, joiner_5] + + for index, joiner in enumerate(joiners): + join_results = joiner.run(documents=document_lists) + is_sorted = all( + join_results["documents"][i].score >= join_results["documents"][i + 1].score + for i in range(len(join_results["documents"]) - 1) + ) + + assert ( + is_sorted + ), "Documents are not sorted in descending order by score, there is an issue with rff ranking" diff --git a/testbed/deepset-ai__haystack/test/components/joiners/test_string_joiner.py b/testbed/deepset-ai__haystack/test/components/joiners/test_string_joiner.py new file mode 100644 index 0000000000000000000000000000000000000000..9939ae96a760949242a827fa013c2e128878ae51 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/joiners/test_string_joiner.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from haystack.core.serialization import component_from_dict, component_to_dict +from haystack.components.joiners.string_joiner import StringJoiner + + +class TestStringJoiner: + def test_init(self): + joiner = StringJoiner() + assert isinstance(joiner, StringJoiner) + + def test_to_dict(self): + joiner = StringJoiner() + data = component_to_dict(joiner, name="string_joiner") + assert data == {"type": "haystack.components.joiners.string_joiner.StringJoiner", "init_parameters": {}} + + def test_from_dict(self): + data = {"type": "haystack.components.joiners.string_joiner.StringJoiner", "init_parameters": {}} + string_joiner = component_from_dict(StringJoiner, data=data, name="string_joiner") + assert isinstance(string_joiner, StringJoiner) + + def test_empty_list(self): + joiner = StringJoiner() + result = joiner.run([]) + assert result == {"strings": []} + + def test_single_string(self): + joiner = StringJoiner() + result = joiner.run("a") + assert result == {"strings": ["a"]} + + def test_two_strings(self): + joiner = StringJoiner() + result = joiner.run(["a", "b"]) + assert result == {"strings": ["a", "b"]} diff --git a/testbed/deepset-ai__haystack/test/components/preprocessors/__init__.py b/testbed/deepset-ai__haystack/test/components/preprocessors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/preprocessors/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/preprocessors/test_document_cleaner.py b/testbed/deepset-ai__haystack/test/components/preprocessors/test_document_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..2c84d5b12dc8187050448d91054a5ff74fd49308 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/preprocessors/test_document_cleaner.py @@ -0,0 +1,206 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +import pytest + +from haystack import Document +from haystack.components.preprocessors import DocumentCleaner + + +class TestDocumentCleaner: + def test_init(self): + cleaner = DocumentCleaner() + assert cleaner.remove_empty_lines is True + assert cleaner.remove_extra_whitespaces is True + assert cleaner.remove_repeated_substrings is False + assert cleaner.remove_substrings is None + assert cleaner.remove_regex is None + assert cleaner.keep_id is False + + def test_non_text_document(self, caplog): + with caplog.at_level(logging.WARNING): + cleaner = DocumentCleaner() + cleaner.run(documents=[Document()]) + assert "DocumentCleaner only cleans text documents but document.content for document ID" in caplog.text + + def test_single_document(self): + with pytest.raises(TypeError, match="DocumentCleaner expects a List of Documents as input."): + cleaner = DocumentCleaner() + cleaner.run(documents=Document()) + + def test_empty_list(self): + cleaner = DocumentCleaner() + result = cleaner.run(documents=[]) + assert result == {"documents": []} + + def test_remove_empty_lines(self): + cleaner = DocumentCleaner(remove_extra_whitespaces=False) + result = cleaner.run( + documents=[ + Document( + content="This is a text with some words. \f" + "" + "There is a second sentence. " + "" + "And there is a third sentence." + ) + ] + ) + assert len(result["documents"]) == 1 + assert ( + result["documents"][0].content + == "This is a text with some words. \fThere is a second sentence. And there is a third sentence." + ) + + def test_remove_whitespaces(self): + cleaner = DocumentCleaner(remove_empty_lines=False) + result = cleaner.run( + documents=[ + Document( + content=" This is a text with some words. " + "" + "There is a second sentence. " + "" + "And there is a third sentence.\f " + ) + ] + ) + assert len(result["documents"]) == 1 + assert result["documents"][0].content == ( + "This is a text with some words. " "" "There is a second sentence. " "" "And there is a third sentence.\f" + ) + + def test_remove_substrings(self): + cleaner = DocumentCleaner(remove_substrings=["This", "A", "words", "🪲"]) + result = cleaner.run(documents=[Document(content="This is a text with some words.\f🪲")]) + assert len(result["documents"]) == 1 + assert result["documents"][0].content == " is a text with some .\f" + + def test_remove_regex(self): + cleaner = DocumentCleaner(remove_regex=r"\s\s+") + result = cleaner.run(documents=[Document(content="This is a text \f with some words.")]) + assert len(result["documents"]) == 1 + assert result["documents"][0].content == "This is a text\fwith some words." + + def test_remove_repeated_substrings(self): + cleaner = DocumentCleaner( + remove_empty_lines=False, remove_extra_whitespaces=False, remove_repeated_substrings=True + ) + + text = """First Page\f This is a header. + Page of + 2 + 4 + Lorem ipsum dolor sit amet + This is a footer number 1 + This is footer number 2 This is a header. + Page of + 3 + 4 + Sid ut perspiciatis unde + This is a footer number 1 + This is footer number 2 This is a header. + Page of + 4 + 4 + Sed do eiusmod tempor. + This is a footer number 1 + This is footer number 2""" + + expected_text = """First Page\f 2 + 4 + Lorem ipsum dolor sit amet 3 + 4 + Sid ut perspiciatis unde 4 + 4 + Sed do eiusmod tempor.""" + result = cleaner.run(documents=[Document(content=text)]) + assert result["documents"][0].content == expected_text + + def test_copy_metadata(self): + cleaner = DocumentCleaner() + documents = [ + Document(content="Text. ", meta={"name": "doc 0"}), + Document(content="Text. ", meta={"name": "doc 1"}), + ] + result = cleaner.run(documents=documents) + assert len(result["documents"]) == 2 + assert result["documents"][0].id != result["documents"][1].id + for doc, cleaned_doc in zip(documents, result["documents"]): + assert doc.meta == cleaned_doc.meta + assert cleaned_doc.content == "Text." + + def test_keep_id_does_not_alter_document_ids(self): + cleaner = DocumentCleaner(keep_id=True) + documents = [Document(content="Text. ", id="1"), Document(content="Text. ", id="2")] + result = cleaner.run(documents=documents) + assert len(result["documents"]) == 2 + assert result["documents"][0].id == "1" + assert result["documents"][1].id == "2" + + def test_unicode_normalization(self): + text = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFC = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFD = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFKC = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFKD = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + nfc_cleaner = DocumentCleaner(unicode_normalization="NFC", remove_extra_whitespaces=False) + nfd_cleaner = DocumentCleaner(unicode_normalization="NFD", remove_extra_whitespaces=False) + nfkc_cleaner = DocumentCleaner(unicode_normalization="NFKC", remove_extra_whitespaces=False) + nfkd_cleaner = DocumentCleaner(unicode_normalization="NFKD", remove_extra_whitespaces=False) + + nfc_result = nfc_cleaner.run(documents=[Document(content=text)]) + nfd_result = nfd_cleaner.run(documents=[Document(content=text)]) + nfkc_result = nfkc_cleaner.run(documents=[Document(content=text)]) + nfkd_result = nfkd_cleaner.run(documents=[Document(content=text)]) + + assert nfc_result["documents"][0].content == expected_text_NFC + assert nfd_result["documents"][0].content == expected_text_NFD + assert nfkc_result["documents"][0].content == expected_text_NFKC + assert nfkd_result["documents"][0].content == expected_text_NFKD + + def test_ascii_only(self): + text = """\ + アイウエオ + Comment ça va + Á + مرحبا بالعالم + em Space""" + + expected_text = """\ + \n\ + Comment ca va + A + \n\ + em Space""" + + cleaner = DocumentCleaner(ascii_only=True, remove_extra_whitespaces=False, remove_empty_lines=False) + result = cleaner.run(documents=[Document(content=text)]) + assert result["documents"][0].content == expected_text diff --git a/testbed/deepset-ai__haystack/test/components/preprocessors/test_document_splitter.py b/testbed/deepset-ai__haystack/test/components/preprocessors/test_document_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..aecb8531755d26e8b48cb3ac3db13cdd50e5892e --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/preprocessors/test_document_splitter.py @@ -0,0 +1,466 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import re + +import pytest + +from haystack import Document +from haystack.components.preprocessors import DocumentSplitter +from haystack.utils import deserialize_callable, serialize_callable + + +# custom split function for testing +def custom_split(text): + return text.split(".") + + +def merge_documents(documents): + """Merge a list of doc chunks into a single doc by concatenating their content, eliminating overlapping content.""" + sorted_docs = sorted(documents, key=lambda doc: doc.meta["split_idx_start"]) + merged_text = "" + last_idx_end = 0 + for doc in sorted_docs: + start = doc.meta["split_idx_start"] # start of the current content + + # if the start of the current content is before the end of the last appended content, adjust it + if start < last_idx_end: + start = last_idx_end + + # append the non-overlapping part to the merged text + merged_text += doc.content[start - doc.meta["split_idx_start"] :] + + # update the last end index + last_idx_end = doc.meta["split_idx_start"] + len(doc.content) + + return merged_text + + +class TestDocumentSplitter: + def test_non_text_document(self): + with pytest.raises( + ValueError, match="DocumentSplitter only works with text documents but content for document ID" + ): + splitter = DocumentSplitter() + splitter.run(documents=[Document()]) + assert "DocumentSplitter only works with text documents but content for document ID" in caplog.text + + def test_single_doc(self): + with pytest.raises(TypeError, match="DocumentSplitter expects a List of Documents as input."): + splitter = DocumentSplitter() + splitter.run(documents=Document()) + + def test_empty_list(self): + splitter = DocumentSplitter() + res = splitter.run(documents=[]) + assert res == {"documents": []} + + def test_unsupported_split_by(self): + with pytest.raises(ValueError, match="split_by must be one of 'word', 'sentence', 'page' or 'passage'."): + DocumentSplitter(split_by="unsupported") + + def test_unsupported_split_length(self): + with pytest.raises(ValueError, match="split_length must be greater than 0."): + DocumentSplitter(split_length=0) + + def test_unsupported_split_overlap(self): + with pytest.raises(ValueError, match="split_overlap must be greater than or equal to 0."): + DocumentSplitter(split_overlap=-1) + + def test_split_by_word(self): + splitter = DocumentSplitter(split_by="word", split_length=10) + text = "This is a text with some words. There is a second sentence. And there is a third sentence." + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 2 + assert docs[0].content == "This is a text with some words. There is a " + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text.index(docs[0].content) + assert docs[1].content == "second sentence. And there is a third sentence." + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text.index(docs[1].content) + + def test_split_by_word_with_threshold(self): + splitter = DocumentSplitter(split_by="word", split_length=15, split_threshold=10) + result = splitter.run( + documents=[ + Document( + content="This is a text with some words. There is a second sentence. And there is a third sentence." + ) + ] + ) + assert len(result["documents"]) == 1 + assert ( + result["documents"][0].content + == "This is a text with some words. There is a second sentence. And there is a third sentence." + ) + + def test_split_by_word_multiple_input_docs(self): + splitter = DocumentSplitter(split_by="word", split_length=10) + text1 = "This is a text with some words. There is a second sentence. And there is a third sentence." + text2 = "This is a different text with some words. There is a second sentence. And there is a third sentence. And there is a fourth sentence." + result = splitter.run(documents=[Document(content=text1), Document(content=text2)]) + docs = result["documents"] + assert len(docs) == 5 + # doc 0 + assert docs[0].content == "This is a text with some words. There is a " + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text1.index(docs[0].content) + # doc 1 + assert docs[1].content == "second sentence. And there is a third sentence." + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text1.index(docs[1].content) + # doc 2 + assert docs[2].content == "This is a different text with some words. There is " + assert docs[2].meta["split_id"] == 0 + assert docs[2].meta["split_idx_start"] == text2.index(docs[2].content) + # doc 3 + assert docs[3].content == "a second sentence. And there is a third sentence. And " + assert docs[3].meta["split_id"] == 1 + assert docs[3].meta["split_idx_start"] == text2.index(docs[3].content) + # doc 4 + assert docs[4].content == "there is a fourth sentence." + assert docs[4].meta["split_id"] == 2 + assert docs[4].meta["split_idx_start"] == text2.index(docs[4].content) + + def test_split_by_sentence(self): + splitter = DocumentSplitter(split_by="sentence", split_length=1) + text = "This is a text with some words. There is a second sentence. And there is a third sentence." + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 3 + assert docs[0].content == "This is a text with some words." + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text.index(docs[0].content) + assert docs[1].content == " There is a second sentence." + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text.index(docs[1].content) + assert docs[2].content == " And there is a third sentence." + assert docs[2].meta["split_id"] == 2 + assert docs[2].meta["split_idx_start"] == text.index(docs[2].content) + + def test_split_by_passage(self): + splitter = DocumentSplitter(split_by="passage", split_length=1) + text = "This is a text with some words. There is a second sentence.\n\nAnd there is a third sentence.\n\n And another passage." + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 3 + assert docs[0].content == "This is a text with some words. There is a second sentence.\n\n" + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text.index(docs[0].content) + assert docs[1].content == "And there is a third sentence.\n\n" + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text.index(docs[1].content) + assert docs[2].content == " And another passage." + assert docs[2].meta["split_id"] == 2 + assert docs[2].meta["split_idx_start"] == text.index(docs[2].content) + + def test_split_by_page(self): + splitter = DocumentSplitter(split_by="page", split_length=1) + text = "This is a text with some words. There is a second sentence.\f And there is a third sentence.\f And another passage." + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 3 + assert docs[0].content == "This is a text with some words. There is a second sentence.\f" + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text.index(docs[0].content) + assert docs[0].meta["page_number"] == 1 + assert docs[1].content == " And there is a third sentence.\f" + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text.index(docs[1].content) + assert docs[1].meta["page_number"] == 2 + assert docs[2].content == " And another passage." + assert docs[2].meta["split_id"] == 2 + assert docs[2].meta["split_idx_start"] == text.index(docs[2].content) + assert docs[2].meta["page_number"] == 3 + + def test_split_by_function(self): + splitting_function = lambda input_str: input_str.split(".") + splitter = DocumentSplitter(split_by="function", splitting_function=splitting_function, split_length=1) + text = "This.Is.A.Test" + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + + word_list = ["This", "Is", "A", "Test"] + assert len(docs) == 4 + for w_target, w_split in zip(word_list, docs): + assert w_split.content == w_target + + splitting_function = lambda input_str: re.split("[\s]{2,}", input_str) + splitter = DocumentSplitter(split_by="function", splitting_function=splitting_function, split_length=1) + text = "This Is\n A Test" + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 4 + for w_target, w_split in zip(word_list, docs): + assert w_split.content == w_target + + def test_split_by_word_with_overlap(self): + splitter = DocumentSplitter(split_by="word", split_length=10, split_overlap=2) + text = "This is a text with some words. There is a second sentence. And there is a third sentence." + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 2 + # doc 0 + assert docs[0].content == "This is a text with some words. There is a " + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text.index(docs[0].content) + assert docs[0].meta["_split_overlap"][0]["range"] == (0, 5) + assert docs[1].content[0:5] == "is a " + # doc 1 + assert docs[1].content == "is a second sentence. And there is a third sentence." + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text.index(docs[1].content) + assert docs[1].meta["_split_overlap"][0]["range"] == (38, 43) + assert docs[0].content[38:43] == "is a " + + def test_source_id_stored_in_metadata(self): + splitter = DocumentSplitter(split_by="word", split_length=10) + doc1 = Document(content="This is a text with some words.") + doc2 = Document(content="This is a different text with some words.") + result = splitter.run(documents=[doc1, doc2]) + assert result["documents"][0].meta["source_id"] == doc1.id + assert result["documents"][1].meta["source_id"] == doc2.id + + def test_copy_metadata(self): + splitter = DocumentSplitter(split_by="word", split_length=10) + documents = [ + Document(content="Text.", meta={"name": "doc 0"}), + Document(content="Text.", meta={"name": "doc 1"}), + ] + result = splitter.run(documents=documents) + assert len(result["documents"]) == 2 + assert result["documents"][0].id != result["documents"][1].id + for doc, split_doc in zip(documents, result["documents"]): + assert doc.meta.items() <= split_doc.meta.items() + assert split_doc.content == "Text." + + def test_add_page_number_to_metadata_with_no_overlap_word_split(self): + splitter = DocumentSplitter(split_by="word", split_length=2) + doc1 = Document(content="This is some text.\f This text is on another page.") + doc2 = Document(content="This content has two.\f\f page brakes.") + result = splitter.run(documents=[doc1, doc2]) + + expected_pages = [1, 1, 2, 2, 2, 1, 1, 3] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_no_overlap_sentence_split(self): + splitter = DocumentSplitter(split_by="sentence", split_length=1) + doc1 = Document(content="This is some text.\f This text is on another page.") + doc2 = Document(content="This content has two.\f\f page brakes.") + result = splitter.run(documents=[doc1, doc2]) + + expected_pages = [1, 1, 1, 1] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_no_overlap_passage_split(self): + splitter = DocumentSplitter(split_by="passage", split_length=1) + doc1 = Document( + content="This is a text with some words.\f There is a second sentence.\n\nAnd there is a third sentence.\n\nAnd more passages.\n\n\f And another passage." + ) + result = splitter.run(documents=[doc1]) + + expected_pages = [1, 2, 2, 2] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_no_overlap_page_split(self): + splitter = DocumentSplitter(split_by="page", split_length=1) + doc1 = Document( + content="This is a text with some words. There is a second sentence.\f And there is a third sentence.\f And another passage." + ) + result = splitter.run(documents=[doc1]) + expected_pages = [1, 2, 3] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + splitter = DocumentSplitter(split_by="page", split_length=2) + doc1 = Document( + content="This is a text with some words. There is a second sentence.\f And there is a third sentence.\f And another passage." + ) + result = splitter.run(documents=[doc1]) + expected_pages = [1, 3] + + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_overlap_word_split(self): + splitter = DocumentSplitter(split_by="word", split_length=3, split_overlap=1) + doc1 = Document(content="This is some text. And\f this text is on another page.") + doc2 = Document(content="This content has two.\f\f page brakes.") + result = splitter.run(documents=[doc1, doc2]) + + expected_pages = [1, 1, 1, 2, 2, 1, 1, 3] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_overlap_sentence_split(self): + splitter = DocumentSplitter(split_by="sentence", split_length=2, split_overlap=1) + doc1 = Document(content="This is some text. And this is more text.\f This text is on another page. End.") + doc2 = Document(content="This content has two.\f\f page brakes. More text.") + result = splitter.run(documents=[doc1, doc2]) + + expected_pages = [1, 1, 1, 2, 1, 1] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_overlap_passage_split(self): + splitter = DocumentSplitter(split_by="passage", split_length=2, split_overlap=1) + doc1 = Document( + content="This is a text with some words.\f There is a second sentence.\n\nAnd there is a third sentence.\n\nAnd more passages.\n\n\f And another passage." + ) + result = splitter.run(documents=[doc1]) + + expected_pages = [1, 2, 2] + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_page_number_to_metadata_with_overlap_page_split(self): + splitter = DocumentSplitter(split_by="page", split_length=2, split_overlap=1) + doc1 = Document( + content="This is a text with some words. There is a second sentence.\f And there is a third sentence.\f And another passage." + ) + result = splitter.run(documents=[doc1]) + expected_pages = [1, 2, 3] + + for doc, p in zip(result["documents"], expected_pages): + assert doc.meta["page_number"] == p + + def test_add_split_overlap_information(self): + splitter = DocumentSplitter(split_length=10, split_overlap=5, split_by="word") + text = "This is a text with some words. There is a second sentence. And a third sentence." + doc = Document(content="This is a text with some words. There is a second sentence. And a third sentence.") + docs = splitter.run(documents=[doc])["documents"] + + # check split_overlap is added to all the documents + assert len(docs) == 3 + # doc 0 + assert docs[0].content == "This is a text with some words. There is a " + assert docs[0].meta["split_id"] == 0 + assert docs[0].meta["split_idx_start"] == text.index(docs[0].content) # 0 + assert docs[0].meta["_split_overlap"][0]["range"] == (0, 23) + assert docs[1].content[0:23] == "some words. There is a " + # doc 1 + assert docs[1].content == "some words. There is a second sentence. And a third " + assert docs[1].meta["split_id"] == 1 + assert docs[1].meta["split_idx_start"] == text.index(docs[1].content) # 20 + assert docs[1].meta["_split_overlap"][0]["range"] == (20, 43) + assert docs[1].meta["_split_overlap"][1]["range"] == (0, 29) + assert docs[0].content[20:43] == "some words. There is a " + assert docs[2].content[0:29] == "second sentence. And a third " + # doc 2 + assert docs[2].content == "second sentence. And a third sentence." + assert docs[2].meta["split_id"] == 2 + assert docs[2].meta["split_idx_start"] == text.index(docs[2].content) # 43 + assert docs[2].meta["_split_overlap"][0]["range"] == (23, 52) + assert docs[1].content[23:52] == "second sentence. And a third " + + # reconstruct the original document content from the split documents + assert doc.content == merge_documents(docs) + + def test_to_dict(self): + """ + Test the to_dict method of the DocumentSplitter class. + """ + splitter = DocumentSplitter(split_by="word", split_length=10, split_overlap=2, split_threshold=5) + serialized = splitter.to_dict() + + assert serialized["type"] == "haystack.components.preprocessors.document_splitter.DocumentSplitter" + assert serialized["init_parameters"]["split_by"] == "word" + assert serialized["init_parameters"]["split_length"] == 10 + assert serialized["init_parameters"]["split_overlap"] == 2 + assert serialized["init_parameters"]["split_threshold"] == 5 + assert "splitting_function" not in serialized["init_parameters"] + + def test_to_dict_with_splitting_function(self): + """ + Test the to_dict method of the DocumentSplitter class when a custom splitting function is provided. + """ + + splitter = DocumentSplitter(split_by="function", splitting_function=custom_split) + serialized = splitter.to_dict() + + assert serialized["type"] == "haystack.components.preprocessors.document_splitter.DocumentSplitter" + assert serialized["init_parameters"]["split_by"] == "function" + assert "splitting_function" in serialized["init_parameters"] + assert callable(deserialize_callable(serialized["init_parameters"]["splitting_function"])) + + def test_from_dict(self): + """ + Test the from_dict class method of the DocumentSplitter class. + """ + data = { + "type": "haystack.components.preprocessors.document_splitter.DocumentSplitter", + "init_parameters": {"split_by": "word", "split_length": 10, "split_overlap": 2, "split_threshold": 5}, + } + splitter = DocumentSplitter.from_dict(data) + + assert splitter.split_by == "word" + assert splitter.split_length == 10 + assert splitter.split_overlap == 2 + assert splitter.split_threshold == 5 + assert splitter.splitting_function is None + + def test_from_dict_with_splitting_function(self): + """ + Test the from_dict class method of the DocumentSplitter class when a custom splitting function is provided. + """ + + def custom_split(text): + return text.split(".") + + data = { + "type": "haystack.components.preprocessors.document_splitter.DocumentSplitter", + "init_parameters": {"split_by": "function", "splitting_function": serialize_callable(custom_split)}, + } + splitter = DocumentSplitter.from_dict(data) + + assert splitter.split_by == "function" + assert callable(splitter.splitting_function) + assert splitter.splitting_function("a.b.c") == ["a", "b", "c"] + + def test_roundtrip_serialization(self): + """ + Test the round-trip serialization of the DocumentSplitter class. + """ + original_splitter = DocumentSplitter(split_by="word", split_length=10, split_overlap=2, split_threshold=5) + serialized = original_splitter.to_dict() + deserialized_splitter = DocumentSplitter.from_dict(serialized) + + assert original_splitter.split_by == deserialized_splitter.split_by + assert original_splitter.split_length == deserialized_splitter.split_length + assert original_splitter.split_overlap == deserialized_splitter.split_overlap + assert original_splitter.split_threshold == deserialized_splitter.split_threshold + + def test_roundtrip_serialization_with_splitting_function(self): + """ + Test the round-trip serialization of the DocumentSplitter class when a custom splitting function is provided. + """ + + original_splitter = DocumentSplitter(split_by="function", splitting_function=custom_split) + serialized = original_splitter.to_dict() + deserialized_splitter = DocumentSplitter.from_dict(serialized) + + assert original_splitter.split_by == deserialized_splitter.split_by + assert callable(deserialized_splitter.splitting_function) + assert deserialized_splitter.splitting_function("a.b.c") == ["a", "b", "c"] + + def test_run_empty_document(self): + """ + Test if the component runs correctly with an empty document. + """ + splitter = DocumentSplitter() + doc = Document(content="") + results = splitter.run([doc]) + assert results["documents"] == [] + + def test_run_document_only_whitespaces(self): + """ + Test if the component runs correctly with a document containing only whitespaces. + """ + splitter = DocumentSplitter() + doc = Document(content=" ") + results = splitter.run([doc]) + assert results["documents"][0].content == " " diff --git a/testbed/deepset-ai__haystack/test/components/preprocessors/test_nltk_document_splitter.py b/testbed/deepset-ai__haystack/test/components/preprocessors/test_nltk_document_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..4819dc602d50ccdecb8d363939c068f916842fea --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/preprocessors/test_nltk_document_splitter.py @@ -0,0 +1,362 @@ +from typing import List + +import pytest +from haystack import Document +from pytest import LogCaptureFixture + +from haystack.components.preprocessors.nltk_document_splitter import NLTKDocumentSplitter, SentenceSplitter + + +def test_init_warning_message(caplog: LogCaptureFixture) -> None: + _ = NLTKDocumentSplitter(split_by="page", respect_sentence_boundary=True) + assert "The 'respect_sentence_boundary' option is only supported for" in caplog.text + + +class TestNLTKDocumentSplitterSplitIntoUnits: + def test_document_splitter_split_into_units_word(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="word", split_length=3, split_overlap=0, split_threshold=0, language="en" + ) + + text = "Moonlight shimmered softly, wolves howled nearby, night enveloped everything." + units = document_splitter._split_into_units(text=text, split_by="word") + + assert units == [ + "Moonlight ", + "shimmered ", + "softly, ", + "wolves ", + "howled ", + "nearby, ", + "night ", + "enveloped ", + "everything.", + ] + + def test_document_splitter_split_into_units_sentence(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="sentence", split_length=2, split_overlap=0, split_threshold=0, language="en" + ) + + text = "Moonlight shimmered softly, wolves howled nearby, night enveloped everything. It was a dark night." + units = document_splitter._split_into_units(text=text, split_by="sentence") + + assert units == [ + "Moonlight shimmered softly, wolves howled nearby, night enveloped everything. ", + "It was a dark night.", + ] + + def test_document_splitter_split_into_units_passage(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="passage", split_length=2, split_overlap=0, split_threshold=0, language="en" + ) + + text = "Moonlight shimmered softly, wolves howled nearby, night enveloped everything.\n\nIt was a dark night." + units = document_splitter._split_into_units(text=text, split_by="passage") + + assert units == [ + "Moonlight shimmered softly, wolves howled nearby, night enveloped everything.\n\n", + "It was a dark night.", + ] + + def test_document_splitter_split_into_units_page(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="page", split_length=2, split_overlap=0, split_threshold=0, language="en" + ) + + text = "Moonlight shimmered softly, wolves howled nearby, night enveloped everything.\fIt was a dark night." + units = document_splitter._split_into_units(text=text, split_by="page") + + assert units == [ + "Moonlight shimmered softly, wolves howled nearby, night enveloped everything.\f", + "It was a dark night.", + ] + + def test_document_splitter_split_into_units_raise_error(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="word", split_length=3, split_overlap=0, split_threshold=0, language="en" + ) + + text = "Moonlight shimmered softly, wolves howled nearby, night enveloped everything." + + with pytest.raises(NotImplementedError): + document_splitter._split_into_units(text=text, split_by="invalid") # type: ignore + + +class TestNLTKDocumentSplitterNumberOfSentencesToKeep: + @pytest.mark.parametrize( + "sentences, expected_num_sentences", + [ + (["Moonlight shimmered softly, wolves howled nearby, night enveloped everything."], 0), + ([" It was a dark night ..."], 0), + ([" The moon was full."], 1), + ], + ) + def test_number_of_sentences_to_keep(self, sentences: List[str], expected_num_sentences: int) -> None: + num_sentences = NLTKDocumentSplitter._number_of_sentences_to_keep( + sentences=sentences, split_length=5, split_overlap=2 + ) + assert num_sentences == expected_num_sentences + + def test_number_of_sentences_to_keep_split_overlap_zero(self) -> None: + sentences = [ + "Moonlight shimmered softly, wolves howled nearby, night enveloped everything.", + " It was a dark night ...", + " The moon was full.", + ] + num_sentences = NLTKDocumentSplitter._number_of_sentences_to_keep( + sentences=sentences, split_length=5, split_overlap=0 + ) + assert num_sentences == 0 + + +class TestNLTKDocumentSplitterRun: + def test_run_type_error(self) -> None: + document_splitter = NLTKDocumentSplitter() + with pytest.raises(TypeError): + document_splitter.run(documents=Document(content="Moonlight shimmered softly.")) # type: ignore + + def test_run_value_error(self) -> None: + document_splitter = NLTKDocumentSplitter() + with pytest.raises(ValueError): + document_splitter.run(documents=[Document(content=None)]) + + def test_run_split_by_sentence_1(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="sentence", + split_length=2, + split_overlap=0, + split_threshold=0, + language="en", + use_split_rules=True, + extend_abbreviations=True, + ) + + text = ( + "Moonlight shimmered softly, wolves howled nearby, night enveloped everything. It was a dark night ... " + "The moon was full." + ) + documents = document_splitter.run(documents=[Document(content=text)])["documents"] + + assert len(documents) == 2 + assert ( + documents[0].content == "Moonlight shimmered softly, wolves howled nearby, night enveloped " + "everything. It was a dark night ... " + ) + assert documents[1].content == "The moon was full." + + def test_run_split_by_sentence_2(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="sentence", + split_length=1, + split_overlap=0, + split_threshold=0, + language="en", + use_split_rules=False, + extend_abbreviations=True, + ) + + text = ( + "This is a test sentence with many many words that exceeds the split length and should not be repeated. " + "This is another test sentence. (This is a third test sentence.) " + "This is the last test sentence." + ) + documents = document_splitter.run(documents=[Document(content=text)])["documents"] + + assert len(documents) == 4 + assert ( + documents[0].content + == "This is a test sentence with many many words that exceeds the split length and should not be repeated. " + ) + assert documents[0].meta["page_number"] == 1 + assert documents[0].meta["split_id"] == 0 + assert documents[0].meta["split_idx_start"] == text.index(documents[0].content) + assert documents[1].content == "This is another test sentence. " + assert documents[1].meta["page_number"] == 1 + assert documents[1].meta["split_id"] == 1 + assert documents[1].meta["split_idx_start"] == text.index(documents[1].content) + assert documents[2].content == "(This is a third test sentence.) " + assert documents[2].meta["page_number"] == 1 + assert documents[2].meta["split_id"] == 2 + assert documents[2].meta["split_idx_start"] == text.index(documents[2].content) + assert documents[3].content == "This is the last test sentence." + assert documents[3].meta["page_number"] == 1 + assert documents[3].meta["split_id"] == 3 + assert documents[3].meta["split_idx_start"] == text.index(documents[3].content) + + def test_run_split_by_sentence_3(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="sentence", + split_length=1, + split_overlap=0, + split_threshold=0, + language="en", + use_split_rules=True, + extend_abbreviations=True, + ) + + text = "Sentence on page 1.\fSentence on page 2. \fSentence on page 3. \f\f Sentence on page 5." + documents = document_splitter.run(documents=[Document(content=text)])["documents"] + + assert len(documents) == 4 + assert documents[0].content == "Sentence on page 1.\f" + assert documents[0].meta["page_number"] == 1 + assert documents[0].meta["split_id"] == 0 + assert documents[0].meta["split_idx_start"] == text.index(documents[0].content) + assert documents[1].content == "Sentence on page 2. \f" + assert documents[1].meta["page_number"] == 2 + assert documents[1].meta["split_id"] == 1 + assert documents[1].meta["split_idx_start"] == text.index(documents[1].content) + assert documents[2].content == "Sentence on page 3. \f\f " + assert documents[2].meta["page_number"] == 3 + assert documents[2].meta["split_id"] == 2 + assert documents[2].meta["split_idx_start"] == text.index(documents[2].content) + assert documents[3].content == "Sentence on page 5." + assert documents[3].meta["page_number"] == 5 + assert documents[3].meta["split_id"] == 3 + assert documents[3].meta["split_idx_start"] == text.index(documents[3].content) + + def test_run_split_by_sentence_4(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="sentence", + split_length=2, + split_overlap=1, + split_threshold=0, + language="en", + use_split_rules=True, + extend_abbreviations=True, + ) + + text = "Sentence on page 1.\fSentence on page 2. \fSentence on page 3. \f\f Sentence on page 5." + documents = document_splitter.run(documents=[Document(content=text)])["documents"] + + assert len(documents) == 3 + assert documents[0].content == "Sentence on page 1.\fSentence on page 2. \f" + assert documents[0].meta["page_number"] == 1 + assert documents[0].meta["split_id"] == 0 + assert documents[0].meta["split_idx_start"] == text.index(documents[0].content) + assert documents[1].content == "Sentence on page 2. \fSentence on page 3. \f\f " + assert documents[1].meta["page_number"] == 2 + assert documents[1].meta["split_id"] == 1 + assert documents[1].meta["split_idx_start"] == text.index(documents[1].content) + assert documents[2].content == "Sentence on page 3. \f\f Sentence on page 5." + assert documents[2].meta["page_number"] == 3 + assert documents[2].meta["split_id"] == 2 + assert documents[2].meta["split_idx_start"] == text.index(documents[2].content) + + +class TestNLTKDocumentSplitterRespectSentenceBoundary: + def test_run_split_by_word_respect_sentence_boundary(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="word", + split_length=3, + split_overlap=0, + split_threshold=0, + language="en", + respect_sentence_boundary=True, + ) + + text = ( + "Moonlight shimmered softly, wolves howled nearby, night enveloped everything. It was a dark night.\f" + "The moon was full." + ) + documents = document_splitter.run(documents=[Document(content=text)])["documents"] + + assert len(documents) == 3 + assert documents[0].content == "Moonlight shimmered softly, wolves howled nearby, night enveloped everything. " + assert documents[0].meta["page_number"] == 1 + assert documents[0].meta["split_id"] == 0 + assert documents[0].meta["split_idx_start"] == text.index(documents[0].content) + assert documents[1].content == "It was a dark night.\f" + assert documents[1].meta["page_number"] == 1 + assert documents[1].meta["split_id"] == 1 + assert documents[1].meta["split_idx_start"] == text.index(documents[1].content) + assert documents[2].content == "The moon was full." + assert documents[2].meta["page_number"] == 2 + assert documents[2].meta["split_id"] == 2 + assert documents[2].meta["split_idx_start"] == text.index(documents[2].content) + + def test_run_split_by_word_respect_sentence_boundary_no_repeats(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="word", + split_length=13, + split_overlap=3, + split_threshold=0, + language="en", + respect_sentence_boundary=True, + use_split_rules=False, + extend_abbreviations=False, + ) + text = ( + "This is a test sentence with many many words that exceeds the split length and should not be repeated. " + "This is another test sentence. (This is a third test sentence.) " + "This is the last test sentence." + ) + documents = document_splitter.run([Document(content=text)])["documents"] + assert len(documents) == 3 + assert ( + documents[0].content + == "This is a test sentence with many many words that exceeds the split length and should not be repeated. " + ) + assert "This is a test sentence with many many words" not in documents[1].content + assert "This is a test sentence with many many words" not in documents[2].content + + def test_run_split_by_word_respect_sentence_boundary_with_split_overlap_and_page_breaks(self) -> None: + document_splitter = NLTKDocumentSplitter( + split_by="word", + split_length=5, + split_overlap=1, + split_threshold=0, + language="en", + use_split_rules=True, + extend_abbreviations=True, + respect_sentence_boundary=True, + ) + + text = "Sentence on page 1.\fSentence on page 2. \fSentence on page 3. \f\f Sentence on page 5." + documents = document_splitter.run(documents=[Document(content=text)])["documents"] + + assert len(documents) == 4 + assert documents[0].content == "Sentence on page 1.\f" + assert documents[0].meta["page_number"] == 1 + assert documents[0].meta["split_id"] == 0 + assert documents[0].meta["split_idx_start"] == text.index(documents[0].content) + assert documents[1].content == "Sentence on page 1.\fSentence on page 2. \f" + assert documents[1].meta["page_number"] == 1 + assert documents[1].meta["split_id"] == 1 + assert documents[1].meta["split_idx_start"] == text.index(documents[1].content) + assert documents[2].content == "Sentence on page 2. \fSentence on page 3. \f\f " + assert documents[2].meta["page_number"] == 2 + assert documents[2].meta["split_id"] == 2 + assert documents[2].meta["split_idx_start"] == text.index(documents[2].content) + assert documents[3].content == "Sentence on page 3. \f\f Sentence on page 5." + assert documents[3].meta["page_number"] == 3 + assert documents[3].meta["split_id"] == 3 + assert documents[3].meta["split_idx_start"] == text.index(documents[3].content) + + +class TestSentenceSplitter: + def test_apply_split_rules_second_while_loop(self) -> None: + text = "This is a test. (With a parenthetical statement.) And another sentence." + spans = [(0, 15), (16, 50), (51, 74)] + result = SentenceSplitter._apply_split_rules(text, spans) + assert len(result) == 2 + assert result == [(0, 50), (51, 74)] + + def test_apply_split_rules_no_join(self) -> None: + text = "This is a test. This is another test. And a third test." + spans = [(0, 15), (16, 36), (37, 54)] + result = SentenceSplitter._apply_split_rules(text, spans) + assert len(result) == 3 + assert result == [(0, 15), (16, 36), (37, 54)] + + @pytest.mark.parametrize( + "text,span,next_span,quote_spans,expected", + [ + # triggers sentence boundary is inside a quote + ('He said, "Hello World." Then left.', (0, 15), (16, 23), [(9, 23)], True) + ], + ) + def test_needs_join_cases(self, text, span, next_span, quote_spans, expected): + result = SentenceSplitter._needs_join(text, span, next_span, quote_spans) + assert result == expected, f"Expected {expected} for input: {text}, {span}, {next_span}, {quote_spans}" diff --git a/testbed/deepset-ai__haystack/test/components/preprocessors/test_text_cleaner.py b/testbed/deepset-ai__haystack/test/components/preprocessors/test_text_cleaner.py new file mode 100644 index 0000000000000000000000000000000000000000..38cd8ade57a42291f47fc198e7867022daaf99ac --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/preprocessors/test_text_cleaner.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.components.preprocessors import TextCleaner + + +def test_init_default(): + cleaner = TextCleaner() + assert cleaner._remove_regexps is None + assert not cleaner._convert_to_lowercase + assert not cleaner._remove_punctuation + assert not cleaner._remove_numbers + assert cleaner._regex is None + assert cleaner._translator is None + + +def test_run(): + cleaner = TextCleaner() + texts = ["Some text", "Some other text", "Yet another text"] + result = cleaner.run(texts=texts) + assert len(result) == 1 + assert result["texts"] == texts + + +def test_run_with_empty_inputs(): + cleaner = TextCleaner() + result = cleaner.run(texts=[]) + assert len(result) == 1 + assert result["texts"] == [] + + +def test_run_with_regex(): + cleaner = TextCleaner(remove_regexps=[r"\d+"]) + result = cleaner.run(texts=["Open123 Source", "HaystackAI"]) + assert len(result) == 1 + assert result["texts"] == ["Open Source", "HaystackAI"] + + +def test_run_with_multiple_regexps(): + cleaner = TextCleaner(remove_regexps=[r"\d+", r"[^\w\s]"]) + result = cleaner.run(texts=["Open123! Source", "Haystack.AI"]) + assert len(result) == 1 + assert result["texts"] == ["Open Source", "HaystackAI"] + + +def test_run_with_convert_to_lowercase(): + cleaner = TextCleaner(convert_to_lowercase=True) + result = cleaner.run(texts=["Open123! Source", "Haystack.AI"]) + assert len(result) == 1 + assert result["texts"] == ["open123! source", "haystack.ai"] + + +def test_run_with_remove_punctuation(): + cleaner = TextCleaner(remove_punctuation=True) + result = cleaner.run(texts=["Open123! Source", "Haystack.AI"]) + assert len(result) == 1 + assert result["texts"] == ["Open123 Source", "HaystackAI"] + + +def test_run_with_remove_numbers(): + cleaner = TextCleaner(remove_numbers=True) + result = cleaner.run(texts=["Open123! Source", "Haystack.AI"]) + assert len(result) == 1 + assert result["texts"] == ["Open! Source", "Haystack.AI"] + + +def test_run_with_multiple_parameters(): + cleaner = TextCleaner( + remove_regexps=[r"\d+", r"[^\w\s]"], convert_to_lowercase=True, remove_punctuation=True, remove_numbers=True + ) + result = cleaner.run(texts=["Open%123. !$Source", "Haystack.AI##"]) + assert len(result) == 1 + assert result["texts"] == ["open source", "haystackai"] diff --git a/testbed/deepset-ai__haystack/test/components/rankers/__init__.py b/testbed/deepset-ai__haystack/test/components/rankers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/rankers/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/rankers/test_lost_in_the_middle.py b/testbed/deepset-ai__haystack/test/components/rankers/test_lost_in_the_middle.py new file mode 100644 index 0000000000000000000000000000000000000000..edbe13a897c272e0bb2aa914106c406542529e2d --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/rankers/test_lost_in_the_middle.py @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest +from haystack import Document +from haystack.components.rankers.lost_in_the_middle import LostInTheMiddleRanker + + +class TestLostInTheMiddleRanker: + def test_lost_in_the_middle_order_odd(self): + # tests that lost_in_the_middle order works with an odd number of documents + docs = [Document(content=str(i)) for i in range(1, 10)] + ranker = LostInTheMiddleRanker() + result = ranker.run(documents=docs) + assert result["documents"] + expected_order = "1 3 5 7 9 8 6 4 2".split() + assert all(doc.content == expected_order[idx] for idx, doc in enumerate(result["documents"])) + + def test_lost_in_the_middle_order_even(self): + # tests that lost_in_the_middle order works with an even number of documents + docs = [Document(content=str(i)) for i in range(1, 11)] + ranker = LostInTheMiddleRanker() + result = ranker.run(documents=docs) + expected_order = "1 3 5 7 9 10 8 6 4 2".split() + assert all(doc.content == expected_order[idx] for idx, doc in enumerate(result["documents"])) + + def test_lost_in_the_middle_order_two_docs(self): + # tests that lost_in_the_middle order works with two documents + ranker = LostInTheMiddleRanker() + # two docs + docs = [Document(content="1"), Document(content="2")] + result = ranker.run(documents=docs) + assert result["documents"][0].content == "1" + assert result["documents"][1].content == "2" + + def test_lost_in_the_middle_init(self): + # tests that LostInTheMiddleRanker initializes with default values + ranker = LostInTheMiddleRanker() + assert ranker.word_count_threshold is None + + ranker = LostInTheMiddleRanker(word_count_threshold=10) + assert ranker.word_count_threshold == 10 + + def test_lost_in_the_middle_init_invalid_word_count_threshold(self): + # tests that LostInTheMiddleRanker raises an error when word_count_threshold is <= 0 + with pytest.raises(ValueError, match="Invalid value for word_count_threshold"): + LostInTheMiddleRanker(word_count_threshold=0) + + with pytest.raises(ValueError, match="Invalid value for word_count_threshold"): + LostInTheMiddleRanker(word_count_threshold=-5) + + def test_lost_in_the_middle_with_word_count_threshold(self): + # tests that lost_in_the_middle with word_count_threshold works as expected + ranker = LostInTheMiddleRanker(word_count_threshold=6) + docs = [Document(content="word" + str(i)) for i in range(1, 10)] + # result, _ = ranker.run(query="", documents=docs) + result = ranker.run(documents=docs) + expected_order = "word1 word3 word5 word6 word4 word2".split() + assert all(doc.content == expected_order[idx] for idx, doc in enumerate(result["documents"])) + + ranker = LostInTheMiddleRanker(word_count_threshold=9) + # result, _ = ranker.run(query="", documents=docs) + result = ranker.run(documents=docs) + expected_order = "word1 word3 word5 word7 word9 word8 word6 word4 word2".split() + assert all(doc.content == expected_order[idx] for idx, doc in enumerate(result["documents"])) + + def test_word_count_threshold_greater_than_total_number_of_words_returns_all_documents(self): + ranker = LostInTheMiddleRanker(word_count_threshold=100) + docs = [Document(content="word" + str(i)) for i in range(1, 10)] + ordered_docs = ranker.run(documents=docs) + # assert len(ordered_docs) == len(docs) + expected_order = "word1 word3 word5 word7 word9 word8 word6 word4 word2".split() + assert all(doc.content == expected_order[idx] for idx, doc in enumerate(ordered_docs["documents"])) + + def test_empty_documents_returns_empty_list(self): + ranker = LostInTheMiddleRanker() + result = ranker.run(documents=[]) + assert result == {"documents": []} + + def test_list_of_one_document_returns_same_document(self): + ranker = LostInTheMiddleRanker() + doc = Document(content="test") + assert ranker.run(documents=[doc]) == {"documents": [doc]} + + @pytest.mark.parametrize("top_k", [1, 2, 3, 4, 5, 6, 7, 8, 12, 20]) + def test_lost_in_the_middle_order_with_top_k(self, top_k: int): + # tests that lost_in_the_middle order works with an odd number of documents and a top_k parameter + docs = [Document(content=str(i)) for i in range(1, 10)] + ranker = LostInTheMiddleRanker() + result = ranker.run(documents=docs, top_k=top_k) + if top_k < len(docs): + # top_k is less than the number of documents, so only the top_k documents should be returned in LITM order + assert len(result["documents"]) == top_k + expected_order = ranker.run(documents=[Document(content=str(i)) for i in range(1, top_k + 1)]) + assert result == expected_order + else: + # top_k is greater than the number of documents, so all documents should be returned in LITM order + assert len(result["documents"]) == len(docs) + assert result == ranker.run(documents=docs) diff --git a/testbed/deepset-ai__haystack/test/components/rankers/test_metafield.py b/testbed/deepset-ai__haystack/test/components/rankers/test_metafield.py new file mode 100644 index 0000000000000000000000000000000000000000..87366e27c5b060b8eec80d5efbc0d06dfc45196d --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/rankers/test_metafield.py @@ -0,0 +1,281 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging + +import pytest + +from haystack import Document +from haystack.components.rankers.meta_field import MetaFieldRanker + + +class TestMetaFieldRanker: + @pytest.mark.parametrize("meta_field_values, expected_first_value", [([1.3, 0.7, 2.1], 2.1), ([1, 5, 8], 8)]) + def test_run(self, meta_field_values, expected_first_value): + """ + Test if the component ranks documents correctly. + """ + ranker = MetaFieldRanker(meta_field="rating") + docs_before = [Document(content="abc", meta={"rating": value}) for value in meta_field_values] + + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 3 + assert docs_after[0].meta["rating"] == expected_first_value + + sorted_scores = sorted([doc.meta["rating"] for doc in docs_after], reverse=True) + assert [doc.meta["rating"] for doc in docs_after] == sorted_scores + + def test_run_with_weight_equal_to_0(self): + ranker = MetaFieldRanker(meta_field="rating", weight=0.0) + docs_before = [Document(content="abc", meta={"rating": value}) for value in [1.1, 0.5, 2.3]] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 3 + assert [doc.meta["rating"] for doc in docs_after] == [1.1, 0.5, 2.3] + + def test_run_with_weight_equal_to_1(self): + ranker = MetaFieldRanker(meta_field="rating", weight=1.0) + docs_before = [Document(content="abc", meta={"rating": value}) for value in [1.1, 0.5, 2.3]] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 3 + sorted_scores = sorted([doc.meta["rating"] for doc in docs_after], reverse=True) + assert [doc.meta["rating"] for doc in docs_after] == sorted_scores + + def test_run_with_weight_equal_to_1_passed_in_run_method(self): + ranker = MetaFieldRanker(meta_field="rating", weight=0.0) + docs_before = [Document(content="abc", meta={"rating": value}) for value in [1.1, 0.5, 2.3]] + output = ranker.run(documents=docs_before, weight=1.0) + docs_after = output["documents"] + + assert len(docs_after) == 3 + sorted_scores = sorted([doc.meta["rating"] for doc in docs_after], reverse=True) + assert [doc.meta["rating"] for doc in docs_after] == sorted_scores + + def test_sort_order_ascending(self): + ranker = MetaFieldRanker(meta_field="rating", weight=1.0, sort_order="ascending") + docs_before = [Document(content="abc", meta={"rating": value}) for value in [1.1, 0.5, 2.3]] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 3 + sorted_scores = sorted([doc.meta["rating"] for doc in docs_after]) + assert [doc.meta["rating"] for doc in docs_after] == sorted_scores + + def test_meta_value_type_float(self): + ranker = MetaFieldRanker(meta_field="rating", weight=1.0, meta_value_type="float") + docs_before = [Document(content="abc", meta={"rating": value}) for value in ["1.1", "10.5", "2.3"]] + docs_after = ranker.run(documents=docs_before)["documents"] + assert len(docs_after) == 3 + assert [doc.meta["rating"] for doc in docs_after] == ["10.5", "2.3", "1.1"] + + def test_meta_value_type_int(self): + ranker = MetaFieldRanker(meta_field="rating", weight=1.0, meta_value_type="int") + docs_before = [Document(content="abc", meta={"rating": value}) for value in ["1", "10", "2"]] + docs_after = ranker.run(documents=docs_before)["documents"] + assert len(docs_after) == 3 + assert [doc.meta["rating"] for doc in docs_after] == ["10", "2", "1"] + + def test_meta_value_type_date(self): + ranker = MetaFieldRanker(meta_field="rating", weight=1.0, meta_value_type="date") + docs_before = [Document(content="abc", meta={"rating": value}) for value in ["2022-10", "2023-01", "2022-11"]] + docs_after = ranker.run(documents=docs_before)["documents"] + assert len(docs_after) == 3 + assert [doc.meta["rating"] for doc in docs_after] == ["2023-01", "2022-11", "2022-10"] + + def test_returns_empty_list_if_no_documents_are_provided(self): + ranker = MetaFieldRanker(meta_field="rating") + output = ranker.run(documents=[]) + docs_after = output["documents"] + assert docs_after == [] + + def test_warning_if_meta_not_found(self, caplog): + ranker = MetaFieldRanker(meta_field="rating") + docs_before = [Document(id="1", content="abc", meta={"wrong_field": 1.3})] + with caplog.at_level(logging.WARNING): + ranker.run(documents=docs_before) + assert ( + "The parameter is currently set to 'rating', but none of the provided Documents with IDs 1 have this meta key." + in caplog.text + ) + + def test_warning_if_some_meta_not_found(self, caplog): + ranker = MetaFieldRanker(meta_field="rating") + docs_before = [ + Document(id="1", content="abc", meta={"wrong_field": 1.3}), + Document(id="2", content="def", meta={"rating": 1.3}), + ] + with caplog.at_level(logging.WARNING): + ranker.run(documents=docs_before) + assert ( + "The parameter is currently set to 'rating' but the Documents with IDs 1 don't have this meta key." + in caplog.text + ) + + def test_warning_if_unsortable_values(self, caplog): + ranker = MetaFieldRanker(meta_field="rating") + docs_before = [ + Document(id="1", content="abc", meta={"rating": 1.3}), + Document(id="2", content="abc", meta={"rating": "1.2"}), + Document(id="3", content="abc", meta={"rating": 2.1}), + ] + with caplog.at_level(logging.WARNING): + output = ranker.run(documents=docs_before) + assert len(output["documents"]) == 3 + assert "Tried to sort Documents with IDs 1,2,3, but got TypeError with the message:" in caplog.text + + def test_warning_if_meta_value_parsing_error(self, caplog): + ranker = MetaFieldRanker(meta_field="rating", meta_value_type="float") + docs_before = [ + Document(id="1", content="abc", meta={"rating": "1.3"}), + Document(id="2", content="abc", meta={"rating": "1.2"}), + Document(id="3", content="abc", meta={"rating": "not a float"}), + ] + with caplog.at_level(logging.WARNING): + output = ranker.run(documents=docs_before) + assert len(output["documents"]) == 3 + assert ( + "Tried to parse the meta values of Documents with IDs 1,2,3, but got ValueError with the message:" + in caplog.text + ) + + def test_warning_meta_value_type_not_all_strings(self, caplog): + ranker = MetaFieldRanker(meta_field="rating", meta_value_type="float") + docs_before = [ + Document(id="1", content="abc", meta={"rating": "1.3"}), + Document(id="2", content="abc", meta={"rating": "1.2"}), + Document(id="3", content="abc", meta={"rating": 2.1}), + ] + with caplog.at_level(logging.WARNING): + output = ranker.run(documents=docs_before) + assert len(output["documents"]) == 3 + assert ( + "The parameter is currently set to 'float', but not all of meta values in the provided Documents with IDs 1,2,3 are strings." + in caplog.text + ) + + def test_raises_value_error_if_wrong_ranking_mode(self): + with pytest.raises(ValueError): + MetaFieldRanker(meta_field="rating", ranking_mode="wrong_mode") + + def test_raises_value_error_if_wrong_top_k(self): + with pytest.raises(ValueError): + MetaFieldRanker(meta_field="rating", top_k=-1) + + @pytest.mark.parametrize("score", [-1, 2, 1.3, 2.1]) + def test_raises_component_error_if_wrong_weight(self, score): + with pytest.raises(ValueError): + MetaFieldRanker(meta_field="rating", weight=score) + + def test_raises_value_error_if_wrong_sort_order(self): + with pytest.raises(ValueError): + MetaFieldRanker(meta_field="rating", sort_order="wrong_order") + + def test_raises_value_error_if_wrong_missing_meta(self): + with pytest.raises(ValueError): + MetaFieldRanker(meta_field="rating", missing_meta="wrong_missing_meta") + + def test_raises_value_error_if_wrong_meta_value_type(self): + with pytest.raises(ValueError): + MetaFieldRanker(meta_field="rating", meta_value_type="wrong_type") + + def test_linear_score(self): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5) + docs_before = [ + Document(content="abc", meta={"rating": 1.3}, score=0.3), + Document(content="abc", meta={"rating": 0.7}, score=0.4), + Document(content="abc", meta={"rating": 2.1}, score=0.6), + ] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + assert docs_after[0].score == 0.8 + + def test_reciprocal_rank_fusion(self): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="reciprocal_rank_fusion", weight=0.5) + docs_before = [ + Document(content="abc", meta={"rating": 1.3}, score=0.3), + Document(content="abc", meta={"rating": 0.7}, score=0.4), + Document(content="abc", meta={"rating": 2.1}, score=0.6), + ] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + assert docs_after[0].score == pytest.approx(0.016261, abs=1e-5) + + @pytest.mark.parametrize("score", [-1, 2, 1.3, 2.1]) + def test_linear_score_raises_warning_if_doc_wrong_score(self, score, caplog): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5) + docs_before = [ + Document(id="1", content="abc", meta={"rating": 1.3}, score=score), + Document(id="2", content="abc", meta={"rating": 0.7}, score=0.4), + Document(id="3", content="abc", meta={"rating": 2.1}, score=0.6), + ] + with caplog.at_level(logging.WARNING): + ranker.run(documents=docs_before) + assert f"The score {score} for Document 1 is outside the [0,1] range; defaulting to 0" in caplog.text + + def test_linear_score_raises_raises_warning_if_doc_without_score(self, caplog): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5) + docs_before = [ + Document(content="abc", meta={"rating": 1.3}), + Document(content="abc", meta={"rating": 0.7}), + Document(content="abc", meta={"rating": 2.1}), + ] + + with caplog.at_level(logging.WARNING): + ranker.run(documents=docs_before) + assert "The score wasn't provided; defaulting to 0." in caplog.text + + def test_different_ranking_mode_for_init_vs_run(self): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5) + docs_before = [ + Document(content="abc", meta={"rating": 1.3}, score=0.3), + Document(content="abc", meta={"rating": 0.7}, score=0.4), + Document(content="abc", meta={"rating": 2.1}, score=0.6), + ] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + assert docs_after[0].score == 0.8 + + output = ranker.run(documents=docs_before, ranking_mode="reciprocal_rank_fusion") + docs_after = output["documents"] + assert docs_after[0].score == pytest.approx(0.016261, abs=1e-5) + + def test_missing_meta_bottom(self): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5, missing_meta="bottom") + docs_before = [ + Document(id="1", content="abc", meta={"rating": 1.3}, score=0.6), + Document(id="2", content="abc", meta={}, score=0.4), + Document(id="3", content="abc", meta={"rating": 2.1}, score=0.39), + ] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + assert len(docs_after) == 3 + assert docs_after[2].id == "2" + + def test_missing_meta_top(self): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5, missing_meta="top") + docs_before = [ + Document(id="1", content="abc", meta={"rating": 1.3}, score=0.6), + Document(id="2", content="abc", meta={}, score=0.59), + Document(id="3", content="abc", meta={"rating": 2.1}, score=0.4), + ] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + assert len(docs_after) == 3 + assert docs_after[0].id == "2" + + def test_missing_meta_drop(self): + ranker = MetaFieldRanker(meta_field="rating", ranking_mode="linear_score", weight=0.5, missing_meta="drop") + docs_before = [ + Document(id="1", content="abc", meta={"rating": 1.3}, score=0.6), + Document(id="2", content="abc", meta={}, score=0.59), + Document(id="3", content="abc", meta={"rating": 2.1}, score=0.4), + ] + output = ranker.run(documents=docs_before) + docs_after = output["documents"] + assert len(docs_after) == 2 + assert "2" not in [doc.id for doc in docs_after] diff --git a/testbed/deepset-ai__haystack/test/components/rankers/test_sentence_transformers_diversity.py b/testbed/deepset-ai__haystack/test/components/rankers/test_sentence_transformers_diversity.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3b10ae5c2bc9b38e73c3f4cea8416183a9ce31 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/rankers/test_sentence_transformers_diversity.py @@ -0,0 +1,609 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import MagicMock, call, patch + +import pytest +import torch + +from haystack import Document +from haystack.components.rankers import SentenceTransformersDiversityRanker +from haystack.utils import ComponentDevice +from haystack.utils.auth import Secret + + +def mock_encode_response(texts, **kwargs): + if texts == ["city"]: + return torch.tensor([[1.0, 1.0]]) + elif texts == ["Eiffel Tower", "Berlin", "Bananas"]: + return torch.tensor([[1.0, 0.0], [0.8, 0.8], [0.0, 1.0]]) + else: + return torch.tensor([[0.0, 1.0]] * len(texts)) + + +class TestSentenceTransformersDiversityRanker: + def test_init(self): + component = SentenceTransformersDiversityRanker() + assert component.model_name_or_path == "sentence-transformers/all-MiniLM-L6-v2" + assert component.top_k == 10 + assert component.device == ComponentDevice.resolve_device(None) + assert component.similarity == "cosine" + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.query_prefix == "" + assert component.document_prefix == "" + assert component.query_suffix == "" + assert component.document_suffix == "" + assert component.meta_fields_to_embed == [] + assert component.embedding_separator == "\n" + + def test_init_with_custom_init_parameters(self): + component = SentenceTransformersDiversityRanker( + model="sentence-transformers/msmarco-distilbert-base-v4", + top_k=5, + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_token("fake-api-token"), + similarity="dot_product", + query_prefix="query:", + document_prefix="document:", + query_suffix="query suffix", + document_suffix="document suffix", + meta_fields_to_embed=["meta_field"], + embedding_separator="--", + ) + assert component.model_name_or_path == "sentence-transformers/msmarco-distilbert-base-v4" + assert component.top_k == 5 + assert component.device == ComponentDevice.from_str("cuda:0") + assert component.similarity == "dot_product" + assert component.token == Secret.from_token("fake-api-token") + assert component.query_prefix == "query:" + assert component.document_prefix == "document:" + assert component.query_suffix == "query suffix" + assert component.document_suffix == "document suffix" + assert component.meta_fields_to_embed == ["meta_field"] + assert component.embedding_separator == "--" + + def test_to_dict(self): + component = SentenceTransformersDiversityRanker() + data = component.to_dict() + assert data == { + "type": "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker", + "init_parameters": { + "model": "sentence-transformers/all-MiniLM-L6-v2", + "top_k": 10, + "device": ComponentDevice.resolve_device(None).to_dict(), + "similarity": "cosine", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "query_prefix": "", + "document_prefix": "", + "query_suffix": "", + "document_suffix": "", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker", + "init_parameters": { + "model": "sentence-transformers/all-MiniLM-L6-v2", + "top_k": 10, + "device": ComponentDevice.resolve_device(None).to_dict(), + "similarity": "cosine", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "query_prefix": "", + "document_prefix": "", + "query_suffix": "", + "document_suffix": "", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + }, + } + ranker = SentenceTransformersDiversityRanker.from_dict(data) + + assert ranker.model_name_or_path == "sentence-transformers/all-MiniLM-L6-v2" + assert ranker.top_k == 10 + assert ranker.device == ComponentDevice.resolve_device(None) + assert ranker.similarity == "cosine" + assert ranker.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert ranker.query_prefix == "" + assert ranker.document_prefix == "" + assert ranker.query_suffix == "" + assert ranker.document_suffix == "" + assert ranker.meta_fields_to_embed == [] + assert ranker.embedding_separator == "\n" + + def test_from_dict_none_device(self): + data = { + "type": "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker", + "init_parameters": { + "model": "sentence-transformers/all-MiniLM-L6-v2", + "top_k": 10, + "device": None, + "similarity": "cosine", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "query_prefix": "", + "document_prefix": "", + "query_suffix": "", + "document_suffix": "", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + }, + } + ranker = SentenceTransformersDiversityRanker.from_dict(data) + + assert ranker.model_name_or_path == "sentence-transformers/all-MiniLM-L6-v2" + assert ranker.top_k == 10 + assert ranker.device == ComponentDevice.resolve_device(None) + assert ranker.similarity == "cosine" + assert ranker.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert ranker.query_prefix == "" + assert ranker.document_prefix == "" + assert ranker.query_suffix == "" + assert ranker.document_suffix == "" + assert ranker.meta_fields_to_embed == [] + assert ranker.embedding_separator == "\n" + + def test_from_dict_no_default_parameters(self): + data = { + "type": "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker", + "init_parameters": {}, + } + ranker = SentenceTransformersDiversityRanker.from_dict(data) + + assert ranker.model_name_or_path == "sentence-transformers/all-MiniLM-L6-v2" + assert ranker.top_k == 10 + assert ranker.device == ComponentDevice.resolve_device(None) + assert ranker.similarity == "cosine" + assert ranker.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert ranker.query_prefix == "" + assert ranker.document_prefix == "" + assert ranker.query_suffix == "" + assert ranker.document_suffix == "" + assert ranker.meta_fields_to_embed == [] + assert ranker.embedding_separator == "\n" + + def test_to_dict_with_custom_init_parameters(self): + component = SentenceTransformersDiversityRanker( + model="sentence-transformers/msmarco-distilbert-base-v4", + top_k=5, + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_env_var("ENV_VAR", strict=False), + similarity="dot_product", + query_prefix="query:", + document_prefix="document:", + query_suffix="query suffix", + document_suffix="document suffix", + meta_fields_to_embed=["meta_field"], + embedding_separator="--", + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker", + "init_parameters": { + "model": "sentence-transformers/msmarco-distilbert-base-v4", + "top_k": 5, + "device": ComponentDevice.from_str("cuda:0").to_dict(), + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "similarity": "dot_product", + "query_prefix": "query:", + "document_prefix": "document:", + "query_suffix": "query suffix", + "document_suffix": "document suffix", + "meta_fields_to_embed": ["meta_field"], + "embedding_separator": "--", + }, + } + + def test_from_dict_with_custom_init_parameters(self): + data = { + "type": "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker", + "init_parameters": { + "model": "sentence-transformers/msmarco-distilbert-base-v4", + "top_k": 5, + "device": ComponentDevice.from_str("cuda:0").to_dict(), + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "similarity": "dot_product", + "query_prefix": "query:", + "document_prefix": "document:", + "query_suffix": "query suffix", + "document_suffix": "document suffix", + "meta_fields_to_embed": ["meta_field"], + "embedding_separator": "--", + }, + } + ranker = SentenceTransformersDiversityRanker.from_dict(data) + + assert ranker.model_name_or_path == "sentence-transformers/msmarco-distilbert-base-v4" + assert ranker.top_k == 5 + assert ranker.device == ComponentDevice.from_str("cuda:0") + assert ranker.similarity == "dot_product" + assert ranker.token == Secret.from_env_var("ENV_VAR", strict=False) + assert ranker.query_prefix == "query:" + assert ranker.document_prefix == "document:" + assert ranker.query_suffix == "query suffix" + assert ranker.document_suffix == "document suffix" + assert ranker.meta_fields_to_embed == ["meta_field"] + assert ranker.embedding_separator == "--" + + def test_run_incorrect_similarity(self): + """ + Tests that run method raises ValueError if similarity is incorrect + """ + similarity = "incorrect" + with pytest.raises( + ValueError, match=f"Similarity must be one of 'dot_product' or 'cosine', but got {similarity}." + ): + SentenceTransformersDiversityRanker(model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_without_warm_up(self, similarity): + """ + Tests that run method raises ComponentError if model is not warmed up + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", top_k=1, similarity=similarity + ) + documents = [Document(content="doc1"), Document(content="doc2")] + + error_msg = "The component SentenceTransformersDiversityRanker wasn't warmed up." + with pytest.raises(RuntimeError, match=error_msg): + ranker.run(query="test query", documents=documents) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_warm_up(self, similarity, monkeypatch): + """ + Test that ranker loads the SentenceTransformer model correctly during warm up. + """ + monkeypatch.delenv("HF_API_TOKEN", raising=False) + + mock_model_class = MagicMock() + mock_model_instance = MagicMock() + mock_model_class.return_value = mock_model_instance + + with patch( + "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformer", new=mock_model_class + ): + ranker = SentenceTransformersDiversityRanker(model="mock_model_name", similarity=similarity) + + assert ranker.model is None + + ranker.warm_up() + + mock_model_class.assert_called_once_with( + model_name_or_path="mock_model_name", + device=ComponentDevice.resolve_device(None).to_torch_str(), + use_auth_token=None, + ) + assert ranker.model == mock_model_instance + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_empty_query(self, similarity): + """ + Test that ranker can be run with an empty query. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", top_k=3, similarity=similarity + ) + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + documents = [Document(content="doc1"), Document(content="doc2")] + + result = ranker.run(query="", documents=documents) + ranked_docs = result["documents"] + + assert isinstance(ranked_docs, list) + assert len(ranked_docs) == 2 + assert all(isinstance(doc, Document) for doc in ranked_docs) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_top_k(self, similarity): + """ + Test that run method returns the correct number of documents for different top_k values passed at + initialization and runtime. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity, top_k=3 + ) + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + query = "test query" + documents = [ + Document(content="doc1"), + Document(content="doc2"), + Document(content="doc3"), + Document(content="doc4"), + ] + + result = ranker.run(query=query, documents=documents) + ranked_docs = result["documents"] + + assert isinstance(ranked_docs, list) + assert len(ranked_docs) == 3 + assert all(isinstance(doc, Document) for doc in ranked_docs) + + # Passing a different top_k at runtime + result = ranker.run(query=query, documents=documents, top_k=2) + ranked_docs = result["documents"] + + assert isinstance(ranked_docs, list) + assert len(ranked_docs) == 2 + assert all(isinstance(doc, Document) for doc in ranked_docs) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_negative_top_k_at_init(self, similarity): + """ + Tests that run method raises an error for negative top-k set at init. + """ + with pytest.raises(ValueError, match="top_k must be > 0, but got"): + SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity, top_k=-5 + ) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_top_k_is_none_at_init(self, similarity): + """ + Tests that run method raises an error for top-k set to None at init. + """ + with pytest.raises(ValueError, match="top_k must be > 0, but got"): + SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity, top_k=None + ) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_negative_top_k(self, similarity): + """ + Tests that run method raises an error for negative top-k set at runtime. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity, top_k=10 + ) + ranker.model = MagicMock() + query = "test" + documents = [Document(content="doc1"), Document(content="doc2"), Document(content="doc3")] + + with pytest.raises(ValueError, match="top_k must be > 0, but got"): + ranker.run(query=query, documents=documents, top_k=-5) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_top_k_is_none(self, similarity): + """ + Tests that run method returns the correct order of documents for top-k set to None. + """ + # Setting top_k to None is ignored during runtime, it should use top_k set at init. + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity, top_k=2 + ) + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + query = "test" + documents = [Document(content="doc1"), Document(content="doc2"), Document(content="doc3")] + result = ranker.run(query=query, documents=documents, top_k=None) + + assert len(result["documents"]) == 2 + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_no_documents_provided(self, similarity): + """ + Test that run method returns an empty list if no documents are supplied. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity + ) + ranker.model = MagicMock() + query = "test query" + documents = [] + results = ranker.run(query=query, documents=documents) + + assert len(results["documents"]) == 0 + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_with_less_documents_than_top_k(self, similarity): + """ + Tests that run method returns the correct number of documents for top_k values greater than number of documents. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity, top_k=5 + ) + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + query = "test" + documents = [Document(content="doc1"), Document(content="doc2"), Document(content="doc3")] + result = ranker.run(query=query, documents=documents) + + assert len(result["documents"]) == 3 + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_single_document_corner_case(self, similarity): + """ + Tests that run method returns the correct number of documents for a single document + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity + ) + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + query = "test" + documents = [Document(content="doc1")] + result = ranker.run(query=query, documents=documents) + + assert len(result["documents"]) == 1 + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_prepare_texts_to_embed(self, similarity): + """ + Test creation of texts to embed from documents with meta fields, document prefix and suffix. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", + similarity=similarity, + document_prefix="test doc: ", + document_suffix=" end doc.", + meta_fields_to_embed=["meta_field"], + embedding_separator="\n", + ) + documents = [Document(content=f"document number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + texts = ranker._prepare_texts_to_embed(documents=documents) + + assert texts == [ + "test doc: meta_value 0\ndocument number 0 end doc.", + "test doc: meta_value 1\ndocument number 1 end doc.", + "test doc: meta_value 2\ndocument number 2 end doc.", + "test doc: meta_value 3\ndocument number 3 end doc.", + "test doc: meta_value 4\ndocument number 4 end doc.", + ] + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_encode_text(self, similarity): + """ + Test addition of suffix and prefix to the query and documents when creating embeddings. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", + similarity=similarity, + query_prefix="test query: ", + query_suffix=" end query.", + document_prefix="test doc: ", + document_suffix=" end doc.", + meta_fields_to_embed=["meta_field"], + embedding_separator="\n", + ) + query = "query" + documents = [Document(content=f"document number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + ranker.run(query=query, documents=documents) + + assert ranker.model.encode.call_count == 2 + ranker.model.assert_has_calls( + [ + call.encode( + [ + "test doc: meta_value 0\ndocument number 0 end doc.", + "test doc: meta_value 1\ndocument number 1 end doc.", + "test doc: meta_value 2\ndocument number 2 end doc.", + "test doc: meta_value 3\ndocument number 3 end doc.", + "test doc: meta_value 4\ndocument number 4 end doc.", + ], + convert_to_tensor=True, + ), + call.encode(["test query: query end query."], convert_to_tensor=True), + ] + ) + + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_greedy_diversity_order(self, similarity): + """ + Tests that the given list of documents is ordered to maximize diversity. + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity + ) + query = "city" + documents = [Document(content="Eiffel Tower"), Document(content="Berlin"), Document(content="Bananas")] + ranker.model = MagicMock() + ranker.model.encode = MagicMock(side_effect=mock_encode_response) + + ranked_docs = ranker._greedy_diversity_order(query=query, documents=documents) + ranked_text = " ".join([doc.content for doc in ranked_docs]) + + assert ranked_text == "Berlin Eiffel Tower Bananas" + + @pytest.mark.integration + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run(self, similarity): + """ + Tests that run method returns documents in the correct order + """ + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity + ) + ranker.warm_up() + query = "city" + documents = [ + Document(content="France"), + Document(content="Germany"), + Document(content="Eiffel Tower"), + Document(content="Berlin"), + Document(content="Bananas"), + Document(content="Silicon Valley"), + Document(content="Brandenburg Gate"), + ] + result = ranker.run(query=query, documents=documents) + ranked_docs = result["documents"] + ranked_order = ", ".join([doc.content for doc in ranked_docs]) + expected_order = "Berlin, Bananas, Eiffel Tower, Silicon Valley, France, Brandenburg Gate, Germany" + + assert ranked_order == expected_order + + @pytest.mark.integration + @pytest.mark.parametrize("similarity", ["dot_product", "cosine"]) + def test_run_real_world_use_case(self, similarity): + ranker = SentenceTransformersDiversityRanker( + model="sentence-transformers/all-MiniLM-L6-v2", similarity=similarity + ) + ranker.warm_up() + query = "What are the reasons for long-standing animosities between Russia and Poland?" + + doc1 = Document( + "One of the earliest known events in Russian-Polish history dates back to 981, when the Grand Prince of Kiev , " + "Vladimir Svyatoslavich , seized the Cherven Cities from the Duchy of Poland . The relationship between two by " + "that time was mostly close and cordial, as there had been no serious wars between both. In 966, Poland " + "accepted Christianity from Rome while Kievan Rus' —the ancestor of Russia, Ukraine and Belarus—was " + "Christianized by Constantinople. In 1054, the internal Christian divide formally split the Church into " + "the Catholic and Orthodox branches separating the Poles from the Eastern Slavs." + ) + doc2 = Document( + "Since the fall of the Soviet Union , with Lithuania , Ukraine and Belarus regaining independence, the " + "Polish Russian border has mostly been replaced by borders with the respective countries, but there still " + "is a 210 km long border between Poland and the Kaliningrad Oblast" + ) + doc3 = Document( + "As part of Poland's plans to become fully energy independent from Russia within the next years, Piotr " + "Wozniak, president of state-controlled oil and gas company PGNiG , stated in February 2019: 'The strategy of " + "the company is just to forget about Eastern suppliers and especially about Gazprom .'[53] In 2020, the " + "Stockholm Arbitrary Tribunal ruled that PGNiG's long-term contract gas price with Gazprom linked to oil prices " + "should be changed to approximate the Western European gas market price, backdated to 1 November 2014 when " + "PGNiG requested a price review under the contract. Gazprom had to refund about $1.5 billion to PGNiG." + ) + doc4 = Document( + "Both Poland and Russia had accused each other for their historical revisionism . Russia has repeatedly " + "accused Poland for not honoring Soviet Red Army soldiers fallen in World War II for Poland, notably in " + "2017, in which Poland was thought on 'attempting to impose its own version of history' after Moscow was " + "not allowed to join an international effort to renovate a World War II museum at Sobibór , site of a " + "notorious Sobibor extermination camp." + ) + doc5 = Document( + "President of Russia Vladimir Putin and Prime Minister of Poland Leszek Miller in 2002 Modern Polish Russian " + "relations begin with the fall of communism in1989 in Poland ( Solidarity and the Polish Round Table " + "Agreement ) and 1991 in Russia ( dissolution of the Soviet Union ). With a new democratic government after " + "the 1989 elections , Poland regained full sovereignty, [2] and what was the Soviet Union, became 15 newly " + "independent states , including the Russian Federation . Relations between modern Poland and Russia suffer " + "from constant ups and downs." + ) + doc6 = Document( + "Soviet influence in Poland finally ended with the Round Table Agreement of 1989 guaranteeing free elections " + "in Poland, the Revolutions of 1989 against Soviet-sponsored Communist governments in the Eastern Block , and " + "finally the formal dissolution of the Warsaw Pact." + ) + doc7 = Document( + "Dmitry Medvedev and then Polish Prime Minister Donald Tusk , 6 December 2010 BBC News reported that one of " + "the main effects of the 2010 Polish Air Force Tu-154 crash would be the impact it has on Russian-Polish " + "relations. [38] It was thought if the inquiry into the crash were not transparent, it would increase " + "suspicions toward Russia in Poland." + ) + doc8 = Document( + "Soviet control over the Polish People's Republic lessened after Stalin's death and Gomulka's Thaw , and " + "ceased completely after the fall of the communist government in Poland in late 1989, although the " + "Soviet-Russian Northern Group of Forces did not leave Polish soil until 1993. The continuing Soviet military " + "presence allowed the Soviet Union to heavily influence Polish politics." + ) + + documents = [doc1, doc2, doc3, doc4, doc5, doc6, doc7, doc8] + result = ranker.run(query=query, documents=documents) + expected_order = [doc5, doc7, doc3, doc1, doc4, doc2, doc6, doc8] + expected_content = " ".join([doc.content or "" for doc in expected_order]) + result_content = " ".join([doc.content or "" for doc in result["documents"]]) + + # Check the order of ranked documents by comparing the content of the ranked documents + assert result_content == expected_content diff --git a/testbed/deepset-ai__haystack/test/components/rankers/test_transformers_similarity.py b/testbed/deepset-ai__haystack/test/components/rankers/test_transformers_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..6031d85e15195ea0d846f7ec92cae5170edd89f3 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/rankers/test_transformers_similarity.py @@ -0,0 +1,463 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from unittest.mock import MagicMock, patch + +import pytest +import torch +from transformers.modeling_outputs import SequenceClassifierOutput + +from haystack import Document +from haystack.components.rankers.transformers_similarity import TransformersSimilarityRanker +from haystack.utils.auth import Secret +from haystack.utils.device import ComponentDevice, DeviceMap + + +class TestSimilarityRanker: + def test_to_dict(self): + component = TransformersSimilarityRanker() + data = component.to_dict() + assert data == { + "type": "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker", + "init_parameters": { + "device": None, + "top_k": 10, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "query_prefix": "", + "document_prefix": "", + "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + "scale_score": True, + "calibration_factor": 1.0, + "score_threshold": None, + "model_kwargs": {"device_map": ComponentDevice.resolve_device(None).to_hf()}, + "tokenizer_kwargs": {}, + }, + } + + def test_to_dict_with_custom_init_parameters(self): + component = TransformersSimilarityRanker( + model="my_model", + device=ComponentDevice.from_str("cuda:0"), + token=Secret.from_env_var("ENV_VAR", strict=False), + top_k=5, + query_prefix="query_instruction: ", + document_prefix="document_instruction: ", + scale_score=False, + calibration_factor=None, + score_threshold=0.01, + model_kwargs={"torch_dtype": torch.float16}, + tokenizer_kwargs={"model_max_length": 512}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker", + "init_parameters": { + "device": None, + "model": "my_model", + "token": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "top_k": 5, + "query_prefix": "query_instruction: ", + "document_prefix": "document_instruction: ", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + "scale_score": False, + "calibration_factor": None, + "score_threshold": 0.01, + "model_kwargs": { + "torch_dtype": "torch.float16", + "device_map": ComponentDevice.from_str("cuda:0").to_hf(), + }, # torch_dtype is correctly serialized + "tokenizer_kwargs": {"model_max_length": 512}, + }, + } + + def test_to_dict_with_quantization_options(self): + component = TransformersSimilarityRanker( + model_kwargs={ + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + "bnb_4bit_compute_dtype": torch.bfloat16, + } + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker", + "init_parameters": { + "device": None, + "top_k": 10, + "query_prefix": "", + "document_prefix": "", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + "scale_score": True, + "calibration_factor": 1.0, + "score_threshold": None, + "model_kwargs": { + "load_in_4bit": True, + "bnb_4bit_use_double_quant": True, + "bnb_4bit_quant_type": "nf4", + "bnb_4bit_compute_dtype": "torch.bfloat16", + "device_map": ComponentDevice.resolve_device(None).to_hf(), + }, + "tokenizer_kwargs": {}, + }, + } + + @pytest.mark.parametrize( + "device_map,expected", + [ + ("auto", "auto"), + ("cpu:0", ComponentDevice.from_str("cpu:0").to_hf()), + ({"": "cpu:0"}, ComponentDevice.from_multiple(DeviceMap.from_hf({"": "cpu:0"})).to_hf()), + ], + ) + def test_to_dict_device_map(self, device_map, expected): + component = TransformersSimilarityRanker(model_kwargs={"device_map": device_map}, token=None) + data = component.to_dict() + + assert data == { + "type": "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker", + "init_parameters": { + "device": None, + "top_k": 10, + "token": None, + "query_prefix": "", + "document_prefix": "", + "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + "scale_score": True, + "calibration_factor": 1.0, + "score_threshold": None, + "model_kwargs": {"device_map": expected}, + "tokenizer_kwargs": {}, + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker", + "init_parameters": { + "device": None, + "model": "my_model", + "token": None, + "top_k": 5, + "query_prefix": "", + "document_prefix": "", + "meta_fields_to_embed": [], + "embedding_separator": "\n", + "scale_score": False, + "calibration_factor": None, + "score_threshold": 0.01, + "model_kwargs": {"torch_dtype": "torch.float16"}, + "tokenizer_kwargs": {"model_max_length": 512}, + }, + } + + component = TransformersSimilarityRanker.from_dict(data) + assert component.device is None + assert component.model_name_or_path == "my_model" + assert component.token is None + assert component.top_k == 5 + assert component.query_prefix == "" + assert component.document_prefix == "" + assert component.meta_fields_to_embed == [] + assert component.embedding_separator == "\n" + assert not component.scale_score + assert component.calibration_factor is None + assert component.score_threshold == 0.01 + # torch_dtype is correctly deserialized + assert component.model_kwargs == { + "torch_dtype": torch.float16, + "device_map": ComponentDevice.resolve_device(None).to_hf(), + } + assert component.tokenizer_kwargs == {"model_max_length": 512} + + def test_from_dict_no_default_parameters(self): + data = { + "type": "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker", + "init_parameters": {}, + } + + component = TransformersSimilarityRanker.from_dict(data) + assert component.device is None + assert component.model_name_or_path == "cross-encoder/ms-marco-MiniLM-L-6-v2" + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.top_k == 10 + assert component.query_prefix == "" + assert component.document_prefix == "" + assert component.meta_fields_to_embed == [] + assert component.embedding_separator == "\n" + assert component.scale_score + assert component.calibration_factor == 1.0 + assert component.score_threshold is None + # torch_dtype is correctly deserialized + assert component.model_kwargs == {"device_map": ComponentDevice.resolve_device(None).to_hf()} + + @patch("torch.sigmoid") + @patch("torch.sort") + @patch("torch.stack") + def test_embed_meta(self, mocked_stack, mocked_sort, mocked_sigmoid): + mocked_stack.return_value = torch.tensor([0]) + mocked_sort.return_value = (None, torch.tensor([0])) + mocked_sigmoid.return_value = torch.tensor([0]) + embedder = TransformersSimilarityRanker( + model="model", meta_fields_to_embed=["meta_field"], embedding_separator="\n" + ) + embedder.model = MagicMock() + embedder.tokenizer = MagicMock() + embedder.device = MagicMock() + embedder.warm_up() + + documents = [Document(content=f"document number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + + embedder.run(query="test", documents=documents) + + embedder.tokenizer.assert_called_once_with( + [ + ["test", "meta_value 0\ndocument number 0"], + ["test", "meta_value 1\ndocument number 1"], + ["test", "meta_value 2\ndocument number 2"], + ["test", "meta_value 3\ndocument number 3"], + ["test", "meta_value 4\ndocument number 4"], + ], + padding=True, + truncation=True, + return_tensors="pt", + ) + + @patch("torch.sigmoid") + @patch("torch.sort") + @patch("torch.stack") + def test_prefix(self, mocked_stack, mocked_sort, mocked_sigmoid): + mocked_stack.return_value = torch.tensor([0]) + mocked_sort.return_value = (None, torch.tensor([0])) + mocked_sigmoid.return_value = torch.tensor([0]) + embedder = TransformersSimilarityRanker( + model="model", query_prefix="query_instruction: ", document_prefix="document_instruction: " + ) + embedder.model = MagicMock() + embedder.tokenizer = MagicMock() + embedder.device = MagicMock() + embedder.warm_up() + + documents = [Document(content=f"document number {i}", meta={"meta_field": f"meta_value {i}"}) for i in range(5)] + + embedder.run(query="test", documents=documents) + + embedder.tokenizer.assert_called_once_with( + [ + ["query_instruction: test", "document_instruction: document number 0"], + ["query_instruction: test", "document_instruction: document number 1"], + ["query_instruction: test", "document_instruction: document number 2"], + ["query_instruction: test", "document_instruction: document number 3"], + ["query_instruction: test", "document_instruction: document number 4"], + ], + padding=True, + truncation=True, + return_tensors="pt", + ) + + @patch("torch.sort") + @patch("torch.stack") + def test_scale_score_false(self, mocked_stack, mocked_sort): + mocked_stack.return_value = torch.FloatTensor([-10.6859, -8.9874]) + mocked_sort.return_value = (None, torch.tensor([0, 1])) + embedder = TransformersSimilarityRanker(model="model", scale_score=False) + embedder.model = MagicMock() + embedder.model.return_value = SequenceClassifierOutput( + loss=None, logits=torch.FloatTensor([[-10.6859], [-8.9874]]), hidden_states=None, attentions=None + ) + embedder.tokenizer = MagicMock() + embedder.device = MagicMock() + + documents = [Document(content="document number 0"), Document(content="document number 1")] + out = embedder.run(query="test", documents=documents) + assert out["documents"][0].score == pytest.approx(-10.6859, abs=1e-4) + assert out["documents"][1].score == pytest.approx(-8.9874, abs=1e-4) + + @patch("torch.sort") + @patch("torch.stack") + def test_score_threshold(self, mocked_stack, mocked_sort): + mocked_stack.return_value = torch.FloatTensor([0.955, 0.001]) + mocked_sort.return_value = (None, torch.tensor([0, 1])) + embedder = TransformersSimilarityRanker(model="model", scale_score=False, score_threshold=0.1) + embedder.model = MagicMock() + embedder.model.return_value = SequenceClassifierOutput( + loss=None, logits=torch.FloatTensor([[0.955], [0.001]]), hidden_states=None, attentions=None + ) + embedder.tokenizer = MagicMock() + embedder.device = MagicMock() + + documents = [Document(content="document number 0"), Document(content="document number 1")] + out = embedder.run(query="test", documents=documents) + assert len(out["documents"]) == 1 + + def test_device_map_and_device_raises(self, caplog): + with caplog.at_level(logging.WARNING): + _ = TransformersSimilarityRanker( + "model", model_kwargs={"device_map": "cpu"}, device=ComponentDevice.from_str("cuda") + ) + assert ( + "The parameters `device` and `device_map` from `model_kwargs` are both provided. Ignoring `device` and using `device_map`." + in caplog.text + ) + + @patch("haystack.components.rankers.transformers_similarity.AutoTokenizer.from_pretrained") + @patch("haystack.components.rankers.transformers_similarity.AutoModelForSequenceClassification.from_pretrained") + def test_device_map_dict(self, mocked_automodel, _mocked_autotokenizer, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + ranker = TransformersSimilarityRanker("model", model_kwargs={"device_map": {"layer_1": 1, "classifier": "cpu"}}) + + class MockedModel: + def __init__(self): + self.hf_device_map = {"layer_1": 1, "classifier": "cpu"} + + mocked_automodel.return_value = MockedModel() + ranker.warm_up() + + mocked_automodel.assert_called_once_with("model", token=None, device_map={"layer_1": 1, "classifier": "cpu"}) + assert ranker.device == ComponentDevice.from_multiple(DeviceMap.from_hf({"layer_1": 1, "classifier": "cpu"})) + + @pytest.mark.integration + @pytest.mark.parametrize( + "query,docs_before_texts,expected_first_text,scores", + [ + ( + "City in Bosnia and Herzegovina", + ["Berlin", "Belgrade", "Sarajevo"], + "Sarajevo", + [2.2864143829792738e-05, 0.00012495707778725773, 0.009869757108390331], + ), + ( + "Machine learning", + ["Python", "Bakery in Paris", "Tesla Giga Berlin"], + "Python", + [1.9063229046878405e-05, 1.434577916370472e-05, 1.3049247172602918e-05], + ), + ( + "Cubist movement", + ["Nirvana", "Pablo Picasso", "Coffee"], + "Pablo Picasso", + [1.3313065210240893e-05, 9.90335684036836e-05, 1.3518535524781328e-05], + ), + ], + ) + def test_run(self, query, docs_before_texts, expected_first_text, scores): + """ + Test if the component ranks documents correctly. + """ + ranker = TransformersSimilarityRanker(model="cross-encoder/ms-marco-MiniLM-L-6-v2") + ranker.warm_up() + docs_before = [Document(content=text) for text in docs_before_texts] + output = ranker.run(query=query, documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 3 + assert docs_after[0].content == expected_first_text + + sorted_scores = sorted(scores, reverse=True) + assert docs_after[0].score == pytest.approx(sorted_scores[0], abs=1e-6) + assert docs_after[1].score == pytest.approx(sorted_scores[1], abs=1e-6) + assert docs_after[2].score == pytest.approx(sorted_scores[2], abs=1e-6) + + @pytest.mark.integration + @pytest.mark.parametrize( + "query,docs_before_texts,expected_first_text,scores", + [ + ( + "City in Bosnia and Herzegovina", + ["Berlin", "Belgrade", "Sarajevo"], + "Sarajevo", + [2.2864143829792738e-05, 0.00012495707778725773, 0.009869757108390331], + ), + ( + "Machine learning", + ["Python", "Bakery in Paris", "Tesla Giga Berlin"], + "Python", + [1.9063229046878405e-05, 1.434577916370472e-05, 1.3049247172602918e-05], + ), + ( + "Cubist movement", + ["Nirvana", "Pablo Picasso", "Coffee"], + "Pablo Picasso", + [1.3313065210240893e-05, 9.90335684036836e-05, 1.3518535524781328e-05], + ), + ], + ) + def test_run_small_batch_size(self, query, docs_before_texts, expected_first_text, scores): + """ + Test if the component ranks documents correctly. + """ + ranker = TransformersSimilarityRanker(model="cross-encoder/ms-marco-MiniLM-L-6-v2", batch_size=2) + ranker.warm_up() + docs_before = [Document(content=text) for text in docs_before_texts] + output = ranker.run(query=query, documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 3 + assert docs_after[0].content == expected_first_text + + sorted_scores = sorted(scores, reverse=True) + assert docs_after[0].score == pytest.approx(sorted_scores[0], abs=1e-6) + assert docs_after[1].score == pytest.approx(sorted_scores[1], abs=1e-6) + assert docs_after[2].score == pytest.approx(sorted_scores[2], abs=1e-6) + + # Returns an empty list if no documents are provided + @pytest.mark.integration + def test_returns_empty_list_if_no_documents_are_provided(self): + sampler = TransformersSimilarityRanker() + sampler.warm_up() + output = sampler.run(query="City in Germany", documents=[]) + assert not output["documents"] + + # Raises ComponentError if model is not warmed up + @pytest.mark.integration + def test_raises_component_error_if_model_not_warmed_up(self): + sampler = TransformersSimilarityRanker() + with pytest.raises(RuntimeError): + sampler.run(query="query", documents=[Document(content="document")]) + + @pytest.mark.integration + @pytest.mark.parametrize( + "query,docs_before_texts,expected_first_text", + [ + ("City in Bosnia and Herzegovina", ["Berlin", "Belgrade", "Sarajevo"], "Sarajevo"), + ("Machine learning", ["Python", "Bakery in Paris", "Tesla Giga Berlin"], "Python"), + ("Cubist movement", ["Nirvana", "Pablo Picasso", "Coffee"], "Pablo Picasso"), + ], + ) + def test_run_top_k(self, query, docs_before_texts, expected_first_text): + """ + Test if the component ranks documents correctly with a custom top_k. + """ + ranker = TransformersSimilarityRanker(model="cross-encoder/ms-marco-MiniLM-L-6-v2", top_k=2) + ranker.warm_up() + docs_before = [Document(content=text) for text in docs_before_texts] + output = ranker.run(query=query, documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 2 + assert docs_after[0].content == expected_first_text + + sorted_scores = sorted([doc.score for doc in docs_after], reverse=True) + assert [doc.score for doc in docs_after] == sorted_scores + + @pytest.mark.integration + def test_run_single_document(self): + """ + Test if the component runs with a single document. + """ + ranker = TransformersSimilarityRanker(model="cross-encoder/ms-marco-MiniLM-L-6-v2", device=None) + ranker.warm_up() + docs_before = [Document(content="Berlin")] + output = ranker.run(query="City in Germany", documents=docs_before) + docs_after = output["documents"] + + assert len(docs_after) == 1 diff --git a/testbed/deepset-ai__haystack/test/components/readers/test_extractive.py b/testbed/deepset-ai__haystack/test/components/readers/test_extractive.py new file mode 100644 index 0000000000000000000000000000000000000000..9c42c44254eae3a4797f4d44bb86062fcbd05125 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/readers/test_extractive.py @@ -0,0 +1,840 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +from math import ceil, exp +from typing import List +from unittest.mock import Mock, patch + +import pytest +import torch +from _pytest.monkeypatch import MonkeyPatch +from transformers import pipeline + +from haystack import Document, ExtractedAnswer +from haystack.components.readers import ExtractiveReader +from haystack.utils import Secret +from haystack.utils.device import ComponentDevice, DeviceMap + + +@pytest.fixture() +def initialized_token(monkeypatch: MonkeyPatch) -> Secret: + monkeypatch.setenv("HF_API_TOKEN", "secret-token") + + return Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + + +@pytest.fixture +def mock_tokenizer(): + def mock_tokenize( + texts: List[str], + text_pairs: List[str], + padding: bool, + truncation: bool, + max_length: int, + return_tensors: str, + return_overflowing_tokens: bool, + stride: int, + ): + assert padding + assert truncation + assert return_tensors == "pt" + assert return_overflowing_tokens + + tokens = Mock() + + num_splits = [ceil(len(text + pair) / max_length) for text, pair in zip(texts, text_pairs)] + tokens.overflow_to_sample_mapping = [i for i, num in enumerate(num_splits) for _ in range(num)] + num_samples = sum(num_splits) + tokens.encodings = [Mock() for _ in range(num_samples)] + sequence_ids = [0] * 16 + [1] * 16 + [None] * (max_length - 32) + for encoding in tokens.encodings: + encoding.sequence_ids = sequence_ids + encoding.token_to_chars = lambda i: (i - 16, i - 15) + tokens.input_ids = torch.zeros(num_samples, max_length, dtype=torch.int) + attention_mask = torch.zeros(num_samples, max_length, dtype=torch.int) + attention_mask[:32] = 1 + tokens.attention_mask = attention_mask + return tokens + + with patch("haystack.components.readers.extractive.AutoTokenizer.from_pretrained") as tokenizer: + tokenizer.return_value = mock_tokenize + yield tokenizer + + +@pytest.fixture() +def mock_reader(mock_tokenizer): + class MockModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.hf_device_map = {"": "cpu:0"} + + def forward(self, input_ids, attention_mask, *args, **kwargs): + assert input_ids.device == torch.device("cpu") + assert attention_mask.device == torch.device("cpu") + start = torch.zeros(input_ids.shape[:2]) + end = torch.zeros(input_ids.shape[:2]) + start[:, 27] = 1 + end[:, 31] = 1 + end[:, 32] = 1 + prediction = Mock() + prediction.start_logits = start + prediction.end_logits = end + return prediction + + with patch("haystack.components.readers.extractive.AutoModelForQuestionAnswering.from_pretrained") as model: + model.return_value = MockModel() + reader = ExtractiveReader(model="mock-model", device=ComponentDevice.from_str("cpu")) + reader.warm_up() + return reader + + +example_queries = ["Who is the chancellor of Germany?", "Who is the head of the department?"] +example_documents = [ + [ + Document(content="Angela Merkel was the chancellor of Germany."), + Document(content="Olaf Scholz is the chancellor of Germany"), + Document(content="Jerry is the head of the department.", meta={"page_number": 3}), + ] +] * 2 + + +def test_to_dict(initialized_token: Secret): + component = ExtractiveReader("my-model", token=initialized_token, model_kwargs={"torch_dtype": torch.float16}) + data = component.to_dict() + + assert data == { + "type": "haystack.components.readers.extractive.ExtractiveReader", + "init_parameters": { + "model": "my-model", + "device": None, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "top_k": 20, + "score_threshold": None, + "max_seq_length": 384, + "stride": 128, + "max_batch_size": None, + "answers_per_seq": None, + "no_answer": True, + "calibration_factor": 0.1, + "model_kwargs": { + "torch_dtype": "torch.float16", + "device_map": ComponentDevice.resolve_device(None).to_hf(), + }, # torch_dtype is correctly serialized + }, + } + + +def test_to_dict_no_token(): + component = ExtractiveReader("my-model", token=None, model_kwargs={"torch_dtype": torch.float16}) + data = component.to_dict() + + assert data == { + "type": "haystack.components.readers.extractive.ExtractiveReader", + "init_parameters": { + "model": "my-model", + "device": None, + "token": None, + "top_k": 20, + "score_threshold": None, + "max_seq_length": 384, + "stride": 128, + "max_batch_size": None, + "answers_per_seq": None, + "no_answer": True, + "calibration_factor": 0.1, + "model_kwargs": { + "torch_dtype": "torch.float16", + "device_map": ComponentDevice.resolve_device(None).to_hf(), + }, # torch_dtype is correctly serialized + }, + } + + +def test_to_dict_empty_model_kwargs(initialized_token: Secret): + component = ExtractiveReader("my-model", token=initialized_token) + data = component.to_dict() + + assert data == { + "type": "haystack.components.readers.extractive.ExtractiveReader", + "init_parameters": { + "model": "my-model", + "device": None, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "top_k": 20, + "score_threshold": None, + "max_seq_length": 384, + "stride": 128, + "max_batch_size": None, + "answers_per_seq": None, + "no_answer": True, + "calibration_factor": 0.1, + "model_kwargs": {"device_map": ComponentDevice.resolve_device(None).to_hf()}, + }, + } + + +@pytest.mark.parametrize( + "device_map,expected", + [ + ("auto", "auto"), + ("cpu:0", ComponentDevice.from_str("cpu:0").to_hf()), + ({"": "cpu:0"}, ComponentDevice.from_multiple(DeviceMap.from_hf({"": "cpu:0"})).to_hf()), + ], +) +def test_to_dict_device_map(device_map, expected): + component = ExtractiveReader("my-model", model_kwargs={"device_map": device_map}) + data = component.to_dict() + + assert data == { + "type": "haystack.components.readers.extractive.ExtractiveReader", + "init_parameters": { + "model": "my-model", + "device": None, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "top_k": 20, + "score_threshold": None, + "max_seq_length": 384, + "stride": 128, + "max_batch_size": None, + "answers_per_seq": None, + "no_answer": True, + "calibration_factor": 0.1, + "model_kwargs": {"device_map": expected}, + }, + } + + +def test_from_dict(): + data = { + "type": "haystack.components.readers.extractive.ExtractiveReader", + "init_parameters": { + "model": "my-model", + "device": None, + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "top_k": 20, + "score_threshold": None, + "max_seq_length": 384, + "stride": 128, + "max_batch_size": None, + "answers_per_seq": None, + "no_answer": True, + "calibration_factor": 0.1, + "model_kwargs": {"torch_dtype": "torch.float16"}, + }, + } + + component = ExtractiveReader.from_dict(data) + assert component.model_name_or_path == "my-model" + assert component.device is None + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.top_k == 20 + assert component.score_threshold is None + assert component.max_seq_length == 384 + assert component.stride == 128 + assert component.max_batch_size is None + assert component.answers_per_seq is None + assert component.no_answer + assert component.calibration_factor == 0.1 + # torch_dtype is correctly deserialized + assert component.model_kwargs == { + "torch_dtype": torch.float16, + "device_map": ComponentDevice.resolve_device(None).to_hf(), + } + + +def test_from_dict_no_default_parameters(): + data = {"type": "haystack.components.readers.extractive.ExtractiveReader", "init_parameters": {}} + + component = ExtractiveReader.from_dict(data) + assert component.model_name_or_path == "deepset/roberta-base-squad2-distilled" + assert component.device is None + assert component.token == Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False) + assert component.top_k == 20 + assert component.score_threshold is None + assert component.max_seq_length == 384 + assert component.stride == 128 + assert component.max_batch_size is None + assert component.answers_per_seq is None + assert component.no_answer + assert component.calibration_factor == 0.1 + assert component.overlap_threshold == 0.01 + assert component.model_kwargs == {"device_map": ComponentDevice.resolve_device(None).to_hf()} + + +def test_from_dict_no_token(): + data = { + "type": "haystack.components.readers.extractive.ExtractiveReader", + "init_parameters": { + "model": "my-model", + "device": None, + "token": None, + "top_k": 20, + "score_threshold": None, + "max_seq_length": 384, + "stride": 128, + "max_batch_size": None, + "answers_per_seq": None, + "no_answer": True, + "calibration_factor": 0.1, + "model_kwargs": {"torch_dtype": "torch.float16"}, + }, + } + + component = ExtractiveReader.from_dict(data) + assert component.token is None + + +def test_run_no_docs(mock_reader: ExtractiveReader): + mock_reader.warm_up() + assert mock_reader.run(query="hello", documents=[]) == {"answers": []} + + +def test_output(mock_reader: ExtractiveReader): + answers = mock_reader.run(example_queries[0], example_documents[0], top_k=3)["answers"] + doc_ids = set() + no_answer_prob = 1 + for doc, answer in zip(example_documents[0], answers[:3]): + assert answer.document_offset is not None + assert answer.document_offset.start == 11 + assert answer.document_offset.end == 16 + assert doc.content is not None + assert answer.data == doc.content[11:16] + assert answer.score == pytest.approx(1 / (1 + exp(-2 * mock_reader.calibration_factor))) + no_answer_prob *= 1 - answer.score + doc_ids.add(doc.id) + assert len(doc_ids) == 3 + assert answers[-1].score == pytest.approx(no_answer_prob) + + +def test_flatten_documents(mock_reader: ExtractiveReader): + queries, docs, query_ids = mock_reader._flatten_documents(example_queries, example_documents) + i = 0 + for j, query in enumerate(example_queries): + for doc in example_documents[j]: + assert queries[i] == query + assert docs[i] == doc + assert query_ids[i] == j + i += 1 + assert len(docs) == len(queries) == len(query_ids) == i + + +def test_preprocess(mock_reader: ExtractiveReader): + _, _, seq_ids, _, query_ids, doc_ids = mock_reader._preprocess( + example_queries * 3, example_documents[0], 384, [1, 1, 1], 0 + ) + expected_seq_ids = torch.full((3, 384), -1, dtype=torch.int) + expected_seq_ids[:, :16] = 0 + expected_seq_ids[:, 16:32] = 1 + assert torch.equal(seq_ids, expected_seq_ids) + assert query_ids == [1, 1, 1] + assert doc_ids == [0, 1, 2] + + +def test_preprocess_splitting(mock_reader: ExtractiveReader): + _, _, seq_ids, _, query_ids, doc_ids = mock_reader._preprocess( + example_queries * 4, example_documents[0] + [Document(content="a" * 64)], 96, [1, 1, 1, 1], 0 + ) + assert seq_ids.shape[0] == 5 + assert query_ids == [1, 1, 1, 1, 1] + assert doc_ids == [0, 1, 2, 3, 3] + + +def test_postprocess(mock_reader: ExtractiveReader): + start = torch.zeros((2, 8)) + start[0, 3] = 4 + start[0, 1] = 5 # test attention_mask + start[0, 4] = 3 + start[1, 2] = 1 + + end = torch.zeros((2, 8)) + end[0, 1] = 5 # test attention_mask + end[0, 2] = 4 # test that end can't be before start + end[0, 3] = 3 + end[0, 4] = 2 + end[1, :] = -10 + end[1, 4] = -1 + + sequence_ids = torch.ones((2, 8)) + attention_mask = torch.ones((2, 8)) + attention_mask[0, :2] = 0 + encoding = Mock() + encoding.token_to_chars = lambda i: (int(i), int(i) + 1) + + start_candidates, end_candidates, probs = mock_reader._postprocess( + start, end, sequence_ids, attention_mask, 3, [encoding, encoding] + ) + + assert len(start_candidates) == len(end_candidates) == len(probs) == 2 + assert len(start_candidates[0]) == len(end_candidates[0]) == len(probs[0]) == 3 + assert start_candidates[0][0] == 3 + assert end_candidates[0][0] == 4 + assert start_candidates[0][1] == 3 + assert end_candidates[0][1] == 5 + assert start_candidates[0][2] == 4 + assert end_candidates[0][2] == 5 + assert probs[0][0] == pytest.approx(1 / (1 + exp(-7 * mock_reader.calibration_factor))) + assert probs[0][1] == pytest.approx(1 / (1 + exp(-6 * mock_reader.calibration_factor))) + assert probs[0][2] == pytest.approx(1 / (1 + exp(-5 * mock_reader.calibration_factor))) + assert start_candidates[1][0] == 2 + assert end_candidates[1][0] == 5 + assert probs[1][0] == pytest.approx(1 / 2) + + +def test_nest_answers(mock_reader: ExtractiveReader): + start = list(range(5)) + end = [i + 5 for i in start] + start = [start] * 6 # type: ignore + end = [end] * 6 # type: ignore + probabilities = torch.arange(5).unsqueeze(0) / 5 + torch.arange(6).unsqueeze(-1) / 25 + query_ids = [0] * 3 + [1] * 3 + document_ids = list(range(3)) * 2 + nested_answers = mock_reader._nest_answers( # type: ignore + start=start, + end=end, + probabilities=probabilities, + flattened_documents=example_documents[0], + queries=example_queries, + answers_per_seq=5, + top_k=3, + score_threshold=None, + query_ids=query_ids, + document_ids=document_ids, + no_answer=True, + overlap_threshold=None, + ) + expected_no_answers = [0.2 * 0.16 * 0.12, 0] + for query, answers, expected_no_answer, probabilities in zip( + example_queries, nested_answers, expected_no_answers, [probabilities[:3, -1], probabilities[3:, -1]] + ): + assert len(answers) == 4 + for doc, answer, score in zip(example_documents[0], reversed(answers[:3]), probabilities): + assert answer.query == query + assert answer.document == doc + assert answer.score == pytest.approx(score) + if "page_number" in doc.meta: + assert answer.meta["answer_page_number"] == doc.meta["page_number"] + no_answer = answers[-1] + assert no_answer.query == query + assert no_answer.document is None + assert no_answer.score == pytest.approx(expected_no_answer) + + +def test_add_answer_page_number_returns_same_answer(mock_reader: ExtractiveReader, caplog): + # answer.document_offset is None + document = Document(content="I thought a lot about this. The answer is 42.", meta={"page_number": 5}) + answer = ExtractedAnswer( + data="42", + query="What is the answer?", + document=document, + score=1.0, + document_offset=None, + meta={"meta_key": "meta_value"}, + ) + assert mock_reader._add_answer_page_number(answer=answer) == answer + + # answer.document is None + answer = ExtractedAnswer( + data="42", + query="What is the answer?", + document=None, + score=1.0, + document_offset=ExtractedAnswer.Span(42, 44), + meta={"meta_key": "meta_value"}, + ) + assert mock_reader._add_answer_page_number(answer=answer) == answer + + # answer.document.meta is None + document = Document(content="I thought a lot about this. The answer is 42.") + answer = ExtractedAnswer( + data="42", + query="What is the answer?", + document=document, + score=1.0, + document_offset=ExtractedAnswer.Span(42, 44), + meta={"meta_key": "meta_value"}, + ) + assert mock_reader._add_answer_page_number(answer=answer) == answer + + # answer.document.meta["page_number"] is not int + document = Document(content="I thought a lot about this. The answer is 42.", meta={"page_number": "5"}) + answer = ExtractedAnswer( + data="42", + query="What is the answer?", + document=document, + score=1.0, + document_offset=ExtractedAnswer.Span(42, 44), + meta={"meta_key": "meta_value"}, + ) + with caplog.at_level(logging.WARNING): + assert mock_reader._add_answer_page_number(answer=answer) == answer + assert "page_number must be int" in caplog.text + + +def test_add_answer_page_number_with_form_feed(mock_reader: ExtractiveReader): + document = Document( + content="I thought a lot about this. \f And this document is long. \f The answer is 42.", + meta={"page_number": 5}, + ) + answer = ExtractedAnswer( + data="42", + query="What is the answer?", + document=document, + context="The answer is 42.", + score=1.0, + document_offset=ExtractedAnswer.Span(73, 75), + context_offset=ExtractedAnswer.Span(14, 16), + meta={"meta_key": "meta_value"}, + ) + answer_with_page_number = mock_reader._add_answer_page_number(answer=answer) + assert answer_with_page_number.meta["answer_page_number"] == 7 + + +@patch("haystack.components.readers.extractive.AutoTokenizer.from_pretrained") +@patch("haystack.components.readers.extractive.AutoModelForQuestionAnswering.from_pretrained") +def test_warm_up_use_hf_token(mocked_automodel, mocked_autotokenizer, initialized_token: Secret): + reader = ExtractiveReader("deepset/roberta-base-squad2", device=ComponentDevice.from_str("cpu")) + + class MockedModel: + def __init__(self): + self.hf_device_map = {"": "cpu"} + + mocked_automodel.return_value = MockedModel() + reader.warm_up() + + mocked_automodel.assert_called_once_with("deepset/roberta-base-squad2", token="secret-token", device_map="cpu") + mocked_autotokenizer.assert_called_once_with("deepset/roberta-base-squad2", token="secret-token") + + +@patch("haystack.components.readers.extractive.AutoTokenizer.from_pretrained") +@patch("haystack.components.readers.extractive.AutoModelForQuestionAnswering.from_pretrained") +def test_device_map_auto(mocked_automodel, _mocked_autotokenizer, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + reader = ExtractiveReader("deepset/roberta-base-squad2", model_kwargs={"device_map": "auto"}) + auto_device = ComponentDevice.resolve_device(None) + + class MockedModel: + def __init__(self): + self.hf_device_map = {"": auto_device.to_hf()} + + mocked_automodel.return_value = MockedModel() + reader.warm_up() + + mocked_automodel.assert_called_once_with("deepset/roberta-base-squad2", token=None, device_map="auto") + assert reader.device == ComponentDevice.from_multiple(DeviceMap.from_hf({"": auto_device.to_hf()})) + + +@patch("haystack.components.readers.extractive.AutoTokenizer.from_pretrained") +@patch("haystack.components.readers.extractive.AutoModelForQuestionAnswering.from_pretrained") +def test_device_map_str(mocked_automodel, _mocked_autotokenizer, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + reader = ExtractiveReader("deepset/roberta-base-squad2", model_kwargs={"device_map": "cpu:0"}) + + class MockedModel: + def __init__(self): + self.hf_device_map = {"": "cpu:0"} + + mocked_automodel.return_value = MockedModel() + reader.warm_up() + + mocked_automodel.assert_called_once_with("deepset/roberta-base-squad2", token=None, device_map="cpu:0") + assert reader.device == ComponentDevice.from_multiple(DeviceMap.from_hf({"": "cpu:0"})) + + +@patch("haystack.components.readers.extractive.AutoTokenizer.from_pretrained") +@patch("haystack.components.readers.extractive.AutoModelForQuestionAnswering.from_pretrained") +def test_device_map_dict(mocked_automodel, _mocked_autotokenizer, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + reader = ExtractiveReader( + "deepset/roberta-base-squad2", model_kwargs={"device_map": {"layer_1": 1, "classifier": "cpu"}} + ) + + class MockedModel: + def __init__(self): + self.hf_device_map = {"layer_1": 1, "classifier": "cpu"} + + mocked_automodel.return_value = MockedModel() + reader.warm_up() + + mocked_automodel.assert_called_once_with( + "deepset/roberta-base-squad2", token=None, device_map={"layer_1": 1, "classifier": "cpu"} + ) + assert reader.device == ComponentDevice.from_multiple(DeviceMap.from_hf({"layer_1": 1, "classifier": "cpu"})) + + +def test_device_map_and_device_warning(caplog): + with caplog.at_level(logging.WARNING): + _ = ExtractiveReader( + "deepset/roberta-base-squad2", model_kwargs={"device_map": "cpu"}, device=ComponentDevice.from_str("cuda") + ) + assert ( + "The parameters `device` and `device_map` from `model_kwargs` are both provided. Ignoring `device` and using `device_map`." + in caplog.text + ) + + +class TestDeduplication: + @pytest.fixture + def doc1(self): + return Document(content="I want to go to the river in Maine.") + + @pytest.fixture + def doc2(self): + return Document(content="I want to go skiing in Colorado.") + + @pytest.fixture + def candidate_answer(self, doc1): + answer1 = "the river" + return ExtractedAnswer( + query="test", + data=answer1, + document=doc1, + document_offset=ExtractedAnswer.Span(doc1.content.find(answer1), doc1.content.find(answer1) + len(answer1)), + score=0.1, + meta={}, + ) + + def test_calculate_overlap(self, mock_reader: ExtractiveReader, doc1: Document): + answer1 = "the river" + answer2 = "river in Maine" + overlap_in_characters = mock_reader._calculate_overlap( + answer1_start=doc1.content.find(answer1), + answer1_end=doc1.content.find(answer1) + len(answer1), + answer2_start=doc1.content.find(answer2), + answer2_end=doc1.content.find(answer2) + len(answer2), + ) + assert overlap_in_characters == 5 + + def test_should_keep_false( + self, mock_reader: ExtractiveReader, doc1: Document, doc2: Document, candidate_answer: ExtractedAnswer + ): + answer2 = "river in Maine" + answer3 = "skiing in Colorado" + keep = mock_reader._should_keep( + candidate_answer=candidate_answer, + current_answers=[ + ExtractedAnswer( + query="test", + data=answer2, + document=doc1, + document_offset=ExtractedAnswer.Span( + doc1.content.find(answer2), doc1.content.find(answer2) + len(answer2) + ), + score=0.1, + meta={}, + ), + ExtractedAnswer( + query="test", + data=answer3, + document=doc2, + document_offset=ExtractedAnswer.Span( + doc2.content.find(answer3), doc2.content.find(answer3) + len(answer3) + ), + score=0.1, + meta={}, + ), + ], + overlap_threshold=0.01, + ) + assert keep is False + + def test_should_keep_true( + self, mock_reader: ExtractiveReader, doc1: Document, doc2: Document, candidate_answer: ExtractedAnswer + ): + answer2 = "Maine" + answer3 = "skiing in Colorado" + keep = mock_reader._should_keep( + candidate_answer=candidate_answer, + current_answers=[ + ExtractedAnswer( + query="test", + data=answer2, + document=doc1, + document_offset=ExtractedAnswer.Span( + doc1.content.find(answer2), doc1.content.find(answer2) + len(answer2) + ), + score=0.1, + meta={}, + ), + ExtractedAnswer( + query="test", + data=answer3, + document=doc2, + document_offset=ExtractedAnswer.Span( + doc2.content.find(answer3), doc2.content.find(answer3) + len(answer3) + ), + score=0.1, + meta={}, + ), + ], + overlap_threshold=0.01, + ) + assert keep is True + + def test_should_keep_missing_document_current_answer( + self, mock_reader: ExtractiveReader, doc1: Document, candidate_answer: ExtractedAnswer + ): + answer2 = "river in Maine" + keep = mock_reader._should_keep( + candidate_answer=candidate_answer, + current_answers=[ + ExtractedAnswer( + query="test", + data=answer2, + document=None, + document_offset=ExtractedAnswer.Span( + doc1.content.find(answer2), doc1.content.find(answer2) + len(answer2) + ), + score=0.1, + meta={}, + ) + ], + overlap_threshold=0.01, + ) + assert keep is True + + def test_should_keep_missing_document_candidate_answer( + self, mock_reader: ExtractiveReader, doc1: Document, candidate_answer: ExtractedAnswer + ): + answer2 = "river in Maine" + keep = mock_reader._should_keep( + candidate_answer=ExtractedAnswer( + query="test", + data=answer2, + document=None, + document_offset=ExtractedAnswer.Span( + doc1.content.find(answer2), doc1.content.find(answer2) + len(answer2) + ), + score=0.1, + meta={}, + ), + current_answers=[ + ExtractedAnswer( + query="test", + data=answer2, + document=doc1, + document_offset=ExtractedAnswer.Span( + doc1.content.find(answer2), doc1.content.find(answer2) + len(answer2) + ), + score=0.1, + meta={}, + ) + ], + overlap_threshold=0.01, + ) + assert keep is True + + def test_should_keep_missing_span( + self, mock_reader: ExtractiveReader, doc1: Document, candidate_answer: ExtractedAnswer + ): + answer2 = "river in Maine" + keep = mock_reader._should_keep( + candidate_answer=candidate_answer, + current_answers=[ + ExtractedAnswer(query="test", data=answer2, document=doc1, document_offset=None, score=0.1, meta={}) + ], + overlap_threshold=0.01, + ) + assert keep is True + + def test_deduplicate_by_overlap_none_overlap( + self, mock_reader: ExtractiveReader, candidate_answer: ExtractedAnswer + ): + result = mock_reader.deduplicate_by_overlap( + answers=[candidate_answer, candidate_answer], overlap_threshold=None + ) + assert len(result) == 2 + + def test_deduplicate_by_overlap( + self, mock_reader: ExtractiveReader, candidate_answer: ExtractedAnswer, doc1: Document + ): + answer2 = "Maine" + extracted_answer2 = ExtractedAnswer( + query="test", + data=answer2, + document=doc1, + document_offset=ExtractedAnswer.Span(doc1.content.find(answer2), doc1.content.find(answer2) + len(answer2)), + score=0.1, + meta={}, + ) + result = mock_reader.deduplicate_by_overlap( + answers=[candidate_answer, candidate_answer, extracted_answer2], overlap_threshold=0.01 + ) + assert len(result) == 2 + + +@pytest.mark.integration +def test_t5(): + reader = ExtractiveReader("sjrhuschlee/flan-t5-base-squad2") + reader.warm_up() + answers = reader.run(example_queries[0], example_documents[0], top_k=2)[ + "answers" + ] # remove indices when batching support is reintroduced + assert answers[0].data == "Olaf Scholz" + assert answers[0].score == pytest.approx(0.8085031509399414, abs=1e-5) + assert answers[1].data == "Angela Merkel" + assert answers[1].score == pytest.approx(0.8021242618560791, abs=1e-5) + assert answers[2].data is None + assert answers[2].score == pytest.approx(0.0378925803599941, abs=1e-5) + assert len(answers) == 3 + # Uncomment assertions below when batching is reintroduced + # assert answers[0][2].score == pytest.approx(0.051331606147570596) + # assert answers[1][0].data == "Jerry" + # assert answers[1][0].score == pytest.approx(0.7413333654403687) + # assert answers[1][1].data == "Olaf Scholz" + # assert answers[1][1].score == pytest.approx(0.7266613841056824) + # assert answers[1][2].data is None + # assert answers[1][2].score == pytest.approx(0.0707035798685709) + + +@pytest.mark.integration +def test_roberta(): + reader = ExtractiveReader("deepset/tinyroberta-squad2") + reader.warm_up() + answers = reader.run(example_queries[0], example_documents[0], top_k=2)[ + "answers" + ] # remove indices when batching is reintroduced + assert answers[0].data == "Olaf Scholz" + assert answers[0].score == pytest.approx(0.8614975214004517) + assert answers[1].data == "Angela Merkel" + assert answers[1].score == pytest.approx(0.857952892780304) + assert answers[2].data is None + assert answers[2].score == pytest.approx(0.019673851661650588, abs=1e-5) + assert len(answers) == 3 + # uncomment assertions below when there is batching in v2 + # assert answers[0][0].data == "Olaf Scholz" + # assert answers[0][0].score == pytest.approx(0.8614975214004517) + # assert answers[0][1].data == "Angela Merkel" + # assert answers[0][1].score == pytest.approx(0.857952892780304) + # assert answers[0][2].data is None + # assert answers[0][2].score == pytest.approx(0.0196738764278237) + # assert answers[1][0].data == "Jerry" + # assert answers[1][0].score == pytest.approx(0.7048940658569336) + # assert answers[1][1].data == "Olaf Scholz" + # assert answers[1][1].score == pytest.approx(0.6604189872741699) + # assert answers[1][2].data is None + # assert answers[1][2].score == pytest.approx(0.1002123719777046) + + +@pytest.mark.integration +def test_matches_hf_pipeline(): + reader = ExtractiveReader( + "deepset/tinyroberta-squad2", device=ComponentDevice.from_str("cpu"), overlap_threshold=None + ) + reader.warm_up() + answers = reader.run(example_queries[0], [[example_documents[0][0]]][0], top_k=20, no_answer=False)[ + "answers" + ] # [0] Remove first two indices when batching support is reintroduced + pipe = pipeline("question-answering", model=reader.model, tokenizer=reader.tokenizer, align_to_words=False) + answers_hf = pipe( + question=example_queries[0], + context=example_documents[0][0].content, + max_answer_len=1_000, + handle_impossible_answer=False, + top_k=20, + ) # We need to disable HF postprocessing features to make the results comparable. This is related to https://github.com/huggingface/transformers/issues/26286 + assert len(answers) == len(answers_hf) == 20 + for answer, answer_hf in zip(answers, answers_hf): + assert answer.document_offset.start == answer_hf["start"] + assert answer.document_offset.end == answer_hf["end"] + assert answer.data == answer_hf["answer"] diff --git a/testbed/deepset-ai__haystack/test/components/retrievers/__init__.py b/testbed/deepset-ai__haystack/test/components/retrievers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/retrievers/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/retrievers/test_filter_retriever.py b/testbed/deepset-ai__haystack/test/components/retrievers/test_filter_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..bef09e7a7701fbc059dc297b0576169f45894b75 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/retrievers/test_filter_retriever.py @@ -0,0 +1,145 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Dict, Any, List + +import pytest + +from haystack import Pipeline, DeserializationError +from haystack.testing.factory import document_store_class +from haystack.components.retrievers.filter_retriever import FilterRetriever +from haystack.dataclasses import Document +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +@pytest.fixture() +def sample_docs(): + en_docs = [ + Document(content="Javascript is a popular programming language", meta={"lang": "en"}), + Document(content="Python is a popular programming language", meta={"lang": "en"}), + Document(content="A chromosome is a package of DNA ", meta={"lang": "en"}), + ] + de_docs = [ + Document(content="python ist eine beliebte Programmiersprache", meta={"lang": "de"}), + Document(content="javascript ist eine beliebte Programmiersprache", meta={"lang": "de"}), + ] + all_docs = en_docs + de_docs + return {"en_docs": en_docs, "de_docs": de_docs, "all_docs": all_docs} + + +@pytest.fixture() +def sample_document_store(sample_docs): + doc_store = InMemoryDocumentStore() + doc_store.write_documents(sample_docs["all_docs"]) + return doc_store + + +class TestFilterRetriever: + @classmethod + def _documents_equal(cls, docs1: List[Document], docs2: List[Document]) -> bool: + # # Order doesn't matter; we sort before comparing + docs1.sort(key=lambda x: x.id) + docs2.sort(key=lambda x: x.id) + return docs1 == docs2 + + def test_init_default(self): + retriever = FilterRetriever(InMemoryDocumentStore()) + assert retriever.filters is None + + def test_init_with_parameters(self): + retriever = FilterRetriever(InMemoryDocumentStore(), filters={"lang": "en"}) + assert retriever.filters == {"lang": "en"} + + def test_to_dict(self): + FilterDocStore = document_store_class("MyFakeStore", bases=(InMemoryDocumentStore,)) + document_store = FilterDocStore() + document_store.to_dict = lambda: {"type": "FilterDocStore", "init_parameters": {}} + component = FilterRetriever(document_store=document_store) + + data = component.to_dict() + assert data == { + "type": "haystack.components.retrievers.filter_retriever.FilterRetriever", + "init_parameters": {"document_store": {"type": "FilterDocStore", "init_parameters": {}}, "filters": None}, + } + + def test_to_dict_with_custom_init_parameters(self): + ds = InMemoryDocumentStore(index="test_to_dict_with_custom_init_parameters") + serialized_ds = ds.to_dict() + + component = FilterRetriever( + document_store=InMemoryDocumentStore(index="test_to_dict_with_custom_init_parameters"), + filters={"lang": "en"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.retrievers.filter_retriever.FilterRetriever", + "init_parameters": {"document_store": serialized_ds, "filters": {"lang": "en"}}, + } + + def test_from_dict(self): + valid_data = { + "type": "haystack.components.retrievers.filter_retriever.FilterRetriever", + "init_parameters": { + "document_store": { + "type": "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore", + "init_parameters": {}, + }, + "filters": {"lang": "en"}, + }, + } + component = FilterRetriever.from_dict(valid_data) + assert isinstance(component.document_store, InMemoryDocumentStore) + assert component.filters == {"lang": "en"} + + def test_from_dict_without_docstore(self): + data = {"type": "InMemoryBM25Retriever", "init_parameters": {}} + with pytest.raises(DeserializationError, match="Missing 'document_store' in serialization data"): + FilterRetriever.from_dict(data) + + def test_retriever_init_filter(self, sample_document_store, sample_docs): + retriever = FilterRetriever(sample_document_store, filters={"field": "lang", "operator": "==", "value": "en"}) + result = retriever.run() + + assert "documents" in result + assert len(result["documents"]) == 3 + assert TestFilterRetriever._documents_equal(result["documents"], sample_docs["en_docs"]) + + def test_retriever_runtime_filter(self, sample_document_store, sample_docs): + retriever = FilterRetriever(sample_document_store) + result = retriever.run(filters={"field": "lang", "operator": "==", "value": "en"}) + + assert "documents" in result + assert len(result["documents"]) == 3 + assert TestFilterRetriever._documents_equal(result["documents"], sample_docs["en_docs"]) + + def test_retriever_init_filter_run_filter_override(self, sample_document_store, sample_docs): + retriever = FilterRetriever(sample_document_store, filters={"field": "lang", "operator": "==", "value": "en"}) + result = retriever.run(filters={"field": "lang", "operator": "==", "value": "de"}) + + assert "documents" in result + assert len(result["documents"]) == 2 + assert TestFilterRetriever._documents_equal(result["documents"], sample_docs["de_docs"]) + + @pytest.mark.integration + def test_run_with_pipeline(self, sample_document_store, sample_docs): + retriever = FilterRetriever(sample_document_store, filters={"field": "lang", "operator": "==", "value": "de"}) + + pipeline = Pipeline() + pipeline.add_component("retriever", retriever) + result: Dict[str, Any] = pipeline.run(data={"retriever": {}}) + + assert result + assert "retriever" in result + results_docs = result["retriever"]["documents"] + assert results_docs + assert TestFilterRetriever._documents_equal(results_docs, sample_docs["de_docs"]) + + result: Dict[str, Any] = pipeline.run( + data={"retriever": {"filters": {"field": "lang", "operator": "==", "value": "en"}}} + ) + + assert result + assert "retriever" in result + results_docs = result["retriever"]["documents"] + assert results_docs + assert TestFilterRetriever._documents_equal(results_docs, sample_docs["en_docs"]) diff --git a/testbed/deepset-ai__haystack/test/components/retrievers/test_in_memory_bm25_retriever.py b/testbed/deepset-ai__haystack/test/components/retrievers/test_in_memory_bm25_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..ed1ba1887cf2a6cc726b332d39c4d0e69f47fcb8 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/retrievers/test_in_memory_bm25_retriever.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Dict, Any + +import pytest + +from haystack import Pipeline, DeserializationError +from haystack.document_stores.types import FilterPolicy +from haystack.testing.factory import document_store_class +from haystack.components.retrievers.in_memory import InMemoryBM25Retriever +from haystack.dataclasses import Document +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +@pytest.fixture() +def mock_docs(): + return [ + Document(content="Javascript is a popular programming language"), + Document(content="Java is a popular programming language"), + Document(content="Python is a popular programming language"), + Document(content="Ruby is a popular programming language"), + Document(content="PHP is a popular programming language"), + ] + + +class TestMemoryBM25Retriever: + def test_init_default(self): + retriever = InMemoryBM25Retriever(InMemoryDocumentStore()) + assert retriever.filters is None + assert retriever.top_k == 10 + assert retriever.scale_score is False + + def test_init_with_parameters(self): + retriever = InMemoryBM25Retriever( + InMemoryDocumentStore(), filters={"name": "test.txt"}, top_k=5, scale_score=True + ) + assert retriever.filters == {"name": "test.txt"} + assert retriever.top_k == 5 + assert retriever.scale_score + + def test_init_with_invalid_top_k_parameter(self): + with pytest.raises(ValueError): + InMemoryBM25Retriever(InMemoryDocumentStore(), top_k=-2) + + def test_to_dict(self): + MyFakeStore = document_store_class("MyFakeStore", bases=(InMemoryDocumentStore,)) + document_store = MyFakeStore() + document_store.to_dict = lambda: {"type": "MyFakeStore", "init_parameters": {}} + component = InMemoryBM25Retriever(document_store=document_store) + + data = component.to_dict() + assert data == { + "type": "haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever", + "init_parameters": { + "document_store": {"type": "MyFakeStore", "init_parameters": {}}, + "filters": None, + "top_k": 10, + "scale_score": False, + "filter_policy": "replace", + }, + } + + def test_to_dict_with_custom_init_parameters(self): + ds = InMemoryDocumentStore(index="test_to_dict_with_custom_init_parameters") + serialized_ds = ds.to_dict() + + component = InMemoryBM25Retriever( + document_store=InMemoryDocumentStore(index="test_to_dict_with_custom_init_parameters"), + filters={"name": "test.txt"}, + top_k=5, + scale_score=True, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever", + "init_parameters": { + "document_store": serialized_ds, + "filters": {"name": "test.txt"}, + "top_k": 5, + "scale_score": True, + "filter_policy": "replace", + }, + } + + # + + def test_from_dict(self): + data = { + "type": "haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever", + "init_parameters": { + "document_store": { + "type": "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore", + "init_parameters": {}, + }, + "filters": {"name": "test.txt"}, + "top_k": 5, + }, + } + component = InMemoryBM25Retriever.from_dict(data) + assert isinstance(component.document_store, InMemoryDocumentStore) + assert component.filters == {"name": "test.txt"} + assert component.top_k == 5 + assert component.scale_score is False + assert component.filter_policy == FilterPolicy.REPLACE + + def test_from_dict_without_docstore(self): + data = {"type": "InMemoryBM25Retriever", "init_parameters": {}} + with pytest.raises(DeserializationError, match="Missing 'document_store' in serialization data"): + InMemoryBM25Retriever.from_dict(data) + + def test_from_dict_without_docstore_type(self): + data = {"type": "InMemoryBM25Retriever", "init_parameters": {"document_store": {"init_parameters": {}}}} + with pytest.raises(DeserializationError, match="Missing 'type' in document store's serialization data"): + InMemoryBM25Retriever.from_dict(data) + + def test_from_dict_nonexisting_docstore(self): + data = { + "type": "haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever", + "init_parameters": {"document_store": {"type": "Nonexisting.Docstore", "init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + InMemoryBM25Retriever.from_dict(data) + + def test_retriever_valid_run(self, mock_docs): + ds = InMemoryDocumentStore() + ds.write_documents(mock_docs) + + retriever = InMemoryBM25Retriever(ds, top_k=5) + result = retriever.run(query="PHP") + + assert "documents" in result + assert len(result["documents"]) == 5 + assert result["documents"][0].content == "PHP is a popular programming language" + + def test_invalid_run_wrong_store_type(self): + SomeOtherDocumentStore = document_store_class("SomeOtherDocumentStore") + with pytest.raises(ValueError, match="document_store must be an instance of InMemoryDocumentStore"): + InMemoryBM25Retriever(SomeOtherDocumentStore()) + + @pytest.mark.integration + @pytest.mark.parametrize( + "query, query_result", + [ + ("Javascript", "Javascript is a popular programming language"), + ("Java", "Java is a popular programming language"), + ], + ) + def test_run_with_pipeline(self, mock_docs, query: str, query_result: str): + ds = InMemoryDocumentStore() + ds.write_documents(mock_docs) + retriever = InMemoryBM25Retriever(ds) + + pipeline = Pipeline() + pipeline.add_component("retriever", retriever) + result: Dict[str, Any] = pipeline.run(data={"retriever": {"query": query}}) + + assert result + assert "retriever" in result + results_docs = result["retriever"]["documents"] + assert results_docs + assert results_docs[0].content == query_result + + @pytest.mark.integration + @pytest.mark.parametrize( + "query, query_result, top_k", + [ + ("Javascript", "Javascript is a popular programming language", 1), + ("Java", "Java is a popular programming language", 2), + ("Ruby", "Ruby is a popular programming language", 3), + ], + ) + def test_run_with_pipeline_and_top_k(self, mock_docs, query: str, query_result: str, top_k: int): + ds = InMemoryDocumentStore() + ds.write_documents(mock_docs) + retriever = InMemoryBM25Retriever(ds) + + pipeline = Pipeline() + pipeline.add_component("retriever", retriever) + result: Dict[str, Any] = pipeline.run(data={"retriever": {"query": query, "top_k": top_k}}) + + assert result + assert "retriever" in result + results_docs = result["retriever"]["documents"] + assert results_docs + assert len(results_docs) == top_k + assert results_docs[0].content == query_result diff --git a/testbed/deepset-ai__haystack/test/components/retrievers/test_in_memory_embedding_retriever.py b/testbed/deepset-ai__haystack/test/components/retrievers/test_in_memory_embedding_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..366fd17b320921e3100a00d74ea6b83bbaaafc06 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/retrievers/test_in_memory_embedding_retriever.py @@ -0,0 +1,167 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Dict, Any + +import pytest + +from haystack import Pipeline, DeserializationError +from haystack.document_stores.types import FilterPolicy +from haystack.testing.factory import document_store_class +from haystack.components.retrievers.in_memory.embedding_retriever import InMemoryEmbeddingRetriever +from haystack.dataclasses import Document +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +class TestMemoryEmbeddingRetriever: + def test_init_default(self): + retriever = InMemoryEmbeddingRetriever(InMemoryDocumentStore()) + assert retriever.filters is None + assert retriever.top_k == 10 + assert retriever.scale_score is False + + def test_init_with_parameters(self): + retriever = InMemoryEmbeddingRetriever( + InMemoryDocumentStore(), filters={"name": "test.txt"}, top_k=5, scale_score=True + ) + assert retriever.filters == {"name": "test.txt"} + assert retriever.top_k == 5 + assert retriever.scale_score + + def test_init_with_invalid_top_k_parameter(self): + with pytest.raises(ValueError): + InMemoryEmbeddingRetriever(InMemoryDocumentStore(), top_k=-2) + + def test_to_dict(self): + MyFakeStore = document_store_class("MyFakeStore", bases=(InMemoryDocumentStore,)) + document_store = MyFakeStore() + document_store.to_dict = lambda: {"type": "test_module.MyFakeStore", "init_parameters": {}} + component = InMemoryEmbeddingRetriever(document_store=document_store) + + data = component.to_dict() + assert data == { + "type": "haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever", + "init_parameters": { + "document_store": {"type": "test_module.MyFakeStore", "init_parameters": {}}, + "filters": None, + "top_k": 10, + "scale_score": False, + "return_embedding": False, + "filter_policy": "replace", + }, + } + + def test_to_dict_with_custom_init_parameters(self): + MyFakeStore = document_store_class("MyFakeStore", bases=(InMemoryDocumentStore,)) + document_store = MyFakeStore() + document_store.to_dict = lambda: {"type": "test_module.MyFakeStore", "init_parameters": {}} + component = InMemoryEmbeddingRetriever( + document_store=document_store, + filters={"name": "test.txt"}, + top_k=5, + scale_score=True, + return_embedding=True, + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever", + "init_parameters": { + "document_store": {"type": "test_module.MyFakeStore", "init_parameters": {}}, + "filters": {"name": "test.txt"}, + "top_k": 5, + "scale_score": True, + "return_embedding": True, + "filter_policy": "replace", + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever", + "init_parameters": { + "document_store": { + "type": "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore", + "init_parameters": {}, + }, + "filters": {"name": "test.txt"}, + "top_k": 5, + "filter_policy": "merge", + }, + } + component = InMemoryEmbeddingRetriever.from_dict(data) + assert isinstance(component.document_store, InMemoryDocumentStore) + assert component.filters == {"name": "test.txt"} + assert component.top_k == 5 + assert component.scale_score is False + assert component.filter_policy == FilterPolicy.MERGE + + def test_from_dict_without_docstore(self): + data = { + "type": "haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever", + "init_parameters": {}, + } + with pytest.raises(DeserializationError, match="Missing 'document_store' in serialization data"): + InMemoryEmbeddingRetriever.from_dict(data) + + def test_from_dict_without_docstore_type(self): + data = { + "type": "haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever", + "init_parameters": {"document_store": {"init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + InMemoryEmbeddingRetriever.from_dict(data) + + def test_from_dict_nonexisting_docstore(self): + data = { + "type": "haystack.components.retrievers.in_memory.embedding_retriever.InMemoryEmbeddingRetriever", + "init_parameters": {"document_store": {"type": "Nonexisting.Docstore", "init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + InMemoryEmbeddingRetriever.from_dict(data) + + def test_valid_run(self): + top_k = 3 + ds = InMemoryDocumentStore(embedding_similarity_function="cosine") + docs = [ + Document(content="my document", embedding=[0.1, 0.2, 0.3, 0.4]), + Document(content="another document", embedding=[1.0, 1.0, 1.0, 1.0]), + Document(content="third document", embedding=[0.5, 0.7, 0.5, 0.7]), + ] + ds.write_documents(docs) + + retriever = InMemoryEmbeddingRetriever(ds, top_k=top_k) + result = retriever.run(query_embedding=[0.1, 0.1, 0.1, 0.1], return_embedding=True) + + assert "documents" in result + assert len(result["documents"]) == top_k + assert result["documents"][0].embedding == [1.0, 1.0, 1.0, 1.0] + + def test_invalid_run_wrong_store_type(self): + SomeOtherDocumentStore = document_store_class("SomeOtherDocumentStore") + with pytest.raises(ValueError, match="document_store must be an instance of InMemoryDocumentStore"): + InMemoryEmbeddingRetriever(SomeOtherDocumentStore()) + + @pytest.mark.integration + def test_run_with_pipeline(self): + ds = InMemoryDocumentStore(embedding_similarity_function="cosine") + top_k = 2 + docs = [ + Document(content="my document", embedding=[0.1, 0.2, 0.3, 0.4]), + Document(content="another document", embedding=[1.0, 1.0, 1.0, 1.0]), + Document(content="third document", embedding=[0.5, 0.7, 0.5, 0.7]), + ] + ds.write_documents(docs) + retriever = InMemoryEmbeddingRetriever(ds, top_k=top_k) + + pipeline = Pipeline() + pipeline.add_component("retriever", retriever) + result: Dict[str, Any] = pipeline.run( + data={"retriever": {"query_embedding": [0.1, 0.1, 0.1, 0.1], "return_embedding": True}} + ) + + assert result + assert "retriever" in result + results_docs = result["retriever"]["documents"] + assert results_docs + assert len(results_docs) == top_k + assert results_docs[0].embedding == [1.0, 1.0, 1.0, 1.0] diff --git a/testbed/deepset-ai__haystack/test/components/retrievers/test_sentence_window_retriever.py b/testbed/deepset-ai__haystack/test/components/retrievers/test_sentence_window_retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..786d278dd6234bf7b9c44d2aafb135c30b2aad02 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/retrievers/test_sentence_window_retriever.py @@ -0,0 +1,189 @@ +import pytest + +from haystack import DeserializationError, Document, Pipeline +from haystack.components.preprocessors import DocumentSplitter +from haystack.components.retrievers import InMemoryBM25Retriever +from haystack.components.retrievers.sentence_window_retriever import SentenceWindowRetriever +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +class TestSentenceWindowRetriever: + def test_init_default(self): + retriever = SentenceWindowRetriever(InMemoryDocumentStore()) + assert retriever.window_size == 3 + + def test_init_with_parameters(self): + retriever = SentenceWindowRetriever(InMemoryDocumentStore(), window_size=5) + assert retriever.window_size == 5 + + def test_init_with_invalid_window_size_parameter(self): + with pytest.raises(ValueError): + SentenceWindowRetriever(InMemoryDocumentStore(), window_size=-2) + + def test_merge_documents(self): + docs = [ + { + "id": "doc_0", + "content": "This is a text with some words. There is a ", + "source_id": "c5d7c632affc486d0cfe7b3c0f4dc1d3896ea720da2b538d6d10b104a3df5f99", + "page_number": 1, + "split_id": 0, + "split_idx_start": 0, + "_split_overlap": [{"doc_id": "doc_1", "range": (0, 23)}], + }, + { + "id": "doc_1", + "content": "some words. There is a second sentence. And there is ", + "source_id": "c5d7c632affc486d0cfe7b3c0f4dc1d3896ea720da2b538d6d10b104a3df5f99", + "page_number": 1, + "split_id": 1, + "split_idx_start": 20, + "_split_overlap": [{"doc_id": "doc_0", "range": (20, 43)}, {"doc_id": "doc_2", "range": (0, 29)}], + }, + { + "id": "doc_2", + "content": "second sentence. And there is also a third sentence", + "source_id": "c5d7c632affc486d0cfe7b3c0f4dc1d3896ea720da2b538d6d10b104a3df5f99", + "page_number": 1, + "split_id": 2, + "split_idx_start": 43, + "_split_overlap": [{"doc_id": "doc_1", "range": (23, 52)}], + }, + ] + merged_text = SentenceWindowRetriever.merge_documents_text([Document.from_dict(doc) for doc in docs]) + expected = "This is a text with some words. There is a second sentence. And there is also a third sentence" + assert merged_text == expected + + def test_to_dict(self): + window_retriever = SentenceWindowRetriever(InMemoryDocumentStore()) + data = window_retriever.to_dict() + + assert data["type"] == "haystack.components.retrievers.sentence_window_retriever.SentenceWindowRetriever" + assert data["init_parameters"]["window_size"] == 3 + assert ( + data["init_parameters"]["document_store"]["type"] + == "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore" + ) + + def test_from_dict(self): + data = { + "type": "haystack.components.retrievers.sentence_window_retriever.SentenceWindowRetriever", + "init_parameters": { + "document_store": { + "type": "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore", + "init_parameters": {}, + }, + "window_size": 5, + }, + } + component = SentenceWindowRetriever.from_dict(data) + assert isinstance(component.document_store, InMemoryDocumentStore) + assert component.window_size == 5 + + def test_from_dict_without_docstore(self): + data = {"type": "SentenceWindowRetriever", "init_parameters": {}} + with pytest.raises(DeserializationError, match="Missing 'document_store' in serialization data"): + SentenceWindowRetriever.from_dict(data) + + def test_from_dict_without_docstore_type(self): + data = {"type": "SentenceWindowRetriever", "init_parameters": {"document_store": {"init_parameters": {}}}} + with pytest.raises(DeserializationError): + SentenceWindowRetriever.from_dict(data) + + def test_from_dict_non_existing_docstore(self): + data = { + "type": "SentenceWindowRetriever", + "init_parameters": {"document_store": {"type": "Nonexisting.Docstore", "init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + SentenceWindowRetriever.from_dict(data) + + def test_document_without_split_id(self): + docs = [ + Document(content="This is a text with some words. There is a ", meta={"id": "doc_0"}), + Document(content="some words. There is a second sentence. And there is ", meta={"id": "doc_1"}), + ] + with pytest.raises(ValueError): + retriever = SentenceWindowRetriever(document_store=InMemoryDocumentStore(), window_size=3) + retriever.run(retrieved_documents=docs) + + def test_document_without_source_id(self): + docs = [ + Document(content="This is a text with some words. There is a ", meta={"id": "doc_0", "split_id": 0}), + Document( + content="some words. There is a second sentence. And there is ", meta={"id": "doc_1", "split_id": 1} + ), + ] + with pytest.raises(ValueError): + retriever = SentenceWindowRetriever(document_store=InMemoryDocumentStore(), window_size=3) + retriever.run(retrieved_documents=docs) + + def test_run_invalid_window_size(self): + docs = [Document(content="This is a text with some words. There is a ", meta={"id": "doc_0", "split_id": 0})] + with pytest.raises(ValueError): + retriever = SentenceWindowRetriever(document_store=InMemoryDocumentStore(), window_size=0) + retriever.run(retrieved_documents=docs) + + def test_constructor_parameter_does_not_change(self): + retriever = SentenceWindowRetriever(InMemoryDocumentStore(), window_size=5) + assert retriever.window_size == 5 + + doc = { + "id": "doc_0", + "content": "This is a text with some words. There is a ", + "source_id": "c5d7c632affc486d0cfe7b3c0f4dc1d3896ea720da2b538d6d10b104a3df5f99", + "page_number": 1, + "split_id": 0, + "split_idx_start": 0, + "_split_overlap": [{"doc_id": "doc_1", "range": (0, 23)}], + } + + retriever.run(retrieved_documents=[Document.from_dict(doc)], window_size=1) + assert retriever.window_size == 5 + + @pytest.mark.integration + def test_run_with_pipeline(self): + splitter = DocumentSplitter(split_length=1, split_overlap=0, split_by="sentence") + text = ( + "This is a text with some words. There is a second sentence. And there is also a third sentence. " + "It also contains a fourth sentence. And a fifth sentence. And a sixth sentence. And a seventh sentence" + ) + doc = Document(content=text) + docs = splitter.run([doc]) + doc_store = InMemoryDocumentStore() + doc_store.write_documents(docs["documents"]) + + pipe = Pipeline() + pipe.add_component("bm25_retriever", InMemoryBM25Retriever(doc_store, top_k=1)) + pipe.add_component( + "sentence_window_retriever", SentenceWindowRetriever(document_store=doc_store, window_size=2) + ) + pipe.connect("bm25_retriever", "sentence_window_retriever") + result = pipe.run({"bm25_retriever": {"query": "third"}}) + + assert result["sentence_window_retriever"]["context_windows"] == [ + "This is a text with some words. There is a second sentence. And there is also a third sentence. " + "It also contains a fourth sentence. And a fifth sentence." + ] + assert len(result["sentence_window_retriever"]["context_documents"][0]) == 5 + + result = pipe.run({"bm25_retriever": {"query": "third"}, "sentence_window_retriever": {"window_size": 1}}) + assert result["sentence_window_retriever"]["context_windows"] == [ + " There is a second sentence. And there is also a third sentence. It also contains a fourth sentence." + ] + assert len(result["sentence_window_retriever"]["context_documents"][0]) == 3 + + @pytest.mark.integration + def test_serialization_deserialization_in_pipeline(self): + doc_store = InMemoryDocumentStore() + pipe = Pipeline() + pipe.add_component("bm25_retriever", InMemoryBM25Retriever(doc_store, top_k=1)) + pipe.add_component( + "sentence_window_retriever", SentenceWindowRetriever(document_store=doc_store, window_size=2) + ) + pipe.connect("bm25_retriever", "sentence_window_retriever") + + serialized = pipe.to_dict() + deserialized = Pipeline.from_dict(serialized) + + assert deserialized == pipe diff --git a/testbed/deepset-ai__haystack/test/components/routers/__init__.py b/testbed/deepset-ai__haystack/test/components/routers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/routers/test_conditional_router.py b/testbed/deepset-ai__haystack/test/components/routers/test_conditional_router.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea3f86d92c663a0ab850c1711cf22fa069b21b5 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/test_conditional_router.py @@ -0,0 +1,399 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import copy +from typing import List +from unittest import mock + +import pytest + +from haystack.components.routers import ConditionalRouter +from haystack.components.routers.conditional_router import NoRouteSelectedException +from haystack.dataclasses import ChatMessage + + +def custom_filter_to_sede(value): + """splits by hyphen and returns the first part""" + return int(value.split("-")[0]) + + +class TestRouter: + def test_missing_mandatory_fields(self): + """ + Router raises a ValueError if each route does not contain 'condition', 'output', and 'output_type' keys + """ + routes = [ + {"condition": "{{streams|length < 2}}", "output": "{{query}}"}, + {"condition": "{{streams|length < 2}}", "output_type": str}, + ] + with pytest.raises(ValueError): + ConditionalRouter(routes) + + def test_invalid_condition_field(self): + """ + ConditionalRouter init raises a ValueError if one of the routes contains invalid condition + """ + # invalid condition field + routes = [{"condition": "{{streams|length < 2", "output": "query", "output_type": str, "output_name": "test"}] + with pytest.raises(ValueError, match="Invalid template"): + ConditionalRouter(routes) + + def test_no_vars_in_output_route_but_with_output_name(self): + """ + Router can't accept a route with no variables used in the output field + """ + routes = [ + { + "condition": "{{streams|length > 2}}", + "output": "This is a constant", + "output_name": "enough_streams", + "output_type": str, + } + ] + router = ConditionalRouter(routes) + kwargs = {"streams": [1, 2, 3], "query": "Haystack"} + result = router.run(**kwargs) + assert result == {"enough_streams": "This is a constant"} + + def test_mandatory_and_optional_fields_with_extra_fields(self): + """ + Router accepts a list of routes with mandatory and optional fields but not if some new field is added + """ + + routes = [ + { + "condition": "{{streams|length < 2}}", + "output": "{{query}}", + "output_type": str, + "output_name": "test", + "bla": "bla", + }, + {"condition": "{{streams|length < 2}}", "output": "{{query}}", "output_type": str}, + ] + + with pytest.raises(ValueError): + ConditionalRouter(routes) + + def test_router_initialized(self): + routes = [ + {"condition": "{{streams|length < 2}}", "output": "{{query}}", "output_type": str, "output_name": "query"}, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + router = ConditionalRouter(routes) + + assert router.routes == routes + assert set(router.__haystack_input__._sockets_dict.keys()) == {"query", "streams"} + assert set(router.__haystack_output__._sockets_dict.keys()) == {"query", "streams"} + + def test_router_evaluate_condition_expressions(self): + router = ConditionalRouter( + [ + { + "condition": "{{streams|length < 2}}", + "output": "{{query}}", + "output_type": str, + "output_name": "query", + }, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + ) + # first route should be selected + kwargs = {"streams": [1, 2, 3], "query": "test"} + result = router.run(**kwargs) + assert result == {"streams": [1, 2, 3]} + + # second route should be selected + kwargs = {"streams": [1], "query": "test"} + result = router.run(**kwargs) + assert result == {"query": "test"} + + def test_router_evaluate_condition_expressions_using_output_slot(self): + routes = [ + { + "condition": "{{streams|length > 2}}", + "output": "{{streams}}", + "output_name": "enough_streams", + "output_type": List[int], + }, + { + "condition": "{{streams|length <= 2}}", + "output": "{{streams}}", + "output_name": "insufficient_streams", + "output_type": List[int], + }, + ] + router = ConditionalRouter(routes) + # enough_streams output slot will be selected with [1, 2, 3] list being outputted + kwargs = {"streams": [1, 2, 3], "query": "Haystack"} + result = router.run(**kwargs) + assert result == {"enough_streams": [1, 2, 3]} + + def test_complex_condition(self): + routes = [ + { + "condition": "{{messages[-1].meta.finish_reason == 'function_call'}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + { + "condition": "{{True}}", + "output": "{{query}}", + "output_type": str, + "output_name": "query", + }, # catch-all condition + ] + router = ConditionalRouter(routes) + message = mock.MagicMock() + message.meta.finish_reason = "function_call" + result = router.run(messages=[message], streams=[1, 2, 3], query="my query") + assert result == {"streams": [1, 2, 3]} + + def test_router_no_route(self): + # should raise an exception + router = ConditionalRouter( + [ + { + "condition": "{{streams|length < 2}}", + "output": "{{query}}", + "output_type": str, + "output_name": "query", + }, + { + "condition": "{{streams|length >= 5}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + ) + + kwargs = {"streams": [1, 2, 3], "query": "test"} + with pytest.raises(NoRouteSelectedException): + router.run(**kwargs) + + def test_router_raises_value_error_if_route_not_dictionary(self): + """ + Router raises a ValueError if each route is not a dictionary + """ + routes = [ + {"condition": "{{streams|length < 2}}", "output": "{{query}}", "output_type": str, "output_name": "query"}, + ["{{streams|length >= 2}}", "streams", List[int]], + ] + + with pytest.raises(ValueError): + ConditionalRouter(routes) + + def test_router_raises_value_error_if_route_missing_keys(self): + """ + Router raises a ValueError if each route does not contain 'condition', 'output', and 'output_type' keys + """ + routes = [ + {"condition": "{{streams|length < 2}}", "output": "{{query}}"}, + {"condition": "{{streams|length < 2}}", "output_type": str}, + ] + + with pytest.raises(ValueError): + ConditionalRouter(routes) + + def test_router_de_serialization(self): + routes = [ + {"condition": "{{streams|length < 2}}", "output": "{{query}}", "output_type": str, "output_name": "query"}, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + router = ConditionalRouter(routes) + router_dict = router.to_dict() + + # assert that the router dict is correct, with all keys and values being strings + for route in router_dict["init_parameters"]["routes"]: + for key in route.keys(): + assert isinstance(key, str) + assert isinstance(route[key], str) + + new_router = ConditionalRouter.from_dict(router_dict) + assert router.routes == new_router.routes + + # now use both routers with the same input + kwargs = {"streams": [1, 2, 3], "query": "Haystack"} + result1 = router.run(**kwargs) + result2 = new_router.run(**kwargs) + + # check that the result is the same and correct + assert result1 == result2 and result1 == {"streams": [1, 2, 3]} + + def test_router_de_serialization_with_none_argument(self): + new_router = ConditionalRouter.from_dict( + { + "type": "haystack.components.routers.conditional_router.ConditionalRouter", + "init_parameters": { + "routes": [ + { + "condition": "{{streams|length < 2}}", + "output": "{{query}}", + "output_type": "str", + "output_name": "query", + }, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": "typing.List[int]", + "output_name": "streams", + }, + ], + "custom_filters": None, + "unsafe": False, + }, + } + ) + + # now use both routers with the same input + kwargs = {"streams": [1, 2, 3], "query": "Haystack"} + result2 = new_router.run(**kwargs) + assert result2 == {"streams": [1, 2, 3]} + + def test_router_serialization_idempotence(self): + routes = [ + { + "condition": "{{streams|length < 2}}", + "output": "{{message}}", + "output_type": ChatMessage, + "output_name": "message", + }, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + router = ConditionalRouter(routes) + # invoke to_dict twice and check that the result is the same + router_dict_first_invocation = copy.deepcopy(router.to_dict()) + router_dict_second_invocation = router.to_dict() + assert router_dict_first_invocation == router_dict_second_invocation + + def test_custom_filter(self): + routes = [ + { + "condition": "{{phone_num|get_area_code == 123}}", + "output": "Phone number has a 123 area code", + "output_name": "good_phone_num", + "output_type": str, + }, + { + "condition": "{{phone_num|get_area_code != 123}}", + "output": "Phone number does not have 123 area code", + "output_name": "bad_phone_num", + "output_type": str, + }, + ] + + router = ConditionalRouter(routes, custom_filters={"get_area_code": custom_filter_to_sede}) + kwargs = {"phone_num": "123-456-7890"} + result = router.run(**kwargs) + assert result == {"good_phone_num": "Phone number has a 123 area code"} + kwargs = {"phone_num": "321-456-7890"} + result = router.run(**kwargs) + assert result == {"bad_phone_num": "Phone number does not have 123 area code"} + + def test_sede_with_custom_filter(self): + routes = [ + { + "condition": "{{ test|custom_filter_to_sede == 123 }}", + "output": "123", + "output_name": "test", + "output_type": int, + } + ] + custom_filters = {"custom_filter_to_sede": custom_filter_to_sede} + router = ConditionalRouter(routes, custom_filters=custom_filters) + kwargs = {"test": "123-456-789"} + result = router.run(**kwargs) + assert result == {"test": 123} + serialized_router = router.to_dict() + deserialized_router = ConditionalRouter.from_dict(serialized_router) + assert deserialized_router.custom_filters == router.custom_filters + assert deserialized_router.custom_filters["custom_filter_to_sede"]("123-456-789") == 123 + assert result == deserialized_router.run(**kwargs) + + def test_unsafe(self): + routes = [ + { + "condition": "{{streams|length < 2}}", + "output": "{{message}}", + "output_type": ChatMessage, + "output_name": "message", + }, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + router = ConditionalRouter(routes, unsafe=True) + streams = [1] + message = ChatMessage.from_user(content="This is a message") + res = router.run(streams=streams, message=message) + assert res == {"message": message} + + def test_validate_output_type_without_unsafe(self): + routes = [ + { + "condition": "{{streams|length < 2}}", + "output": "{{message}}", + "output_type": ChatMessage, + "output_name": "message", + }, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + router = ConditionalRouter(routes, validate_output_type=True) + streams = [1] + message = ChatMessage.from_user(content="This is a message") + with pytest.raises(ValueError, match="Route 'message' type doesn't match expected type"): + router.run(streams=streams, message=message) + + def test_validate_output_type_with_unsafe(self): + routes = [ + { + "condition": "{{streams|length < 2}}", + "output": "{{message}}", + "output_type": ChatMessage, + "output_name": "message", + }, + { + "condition": "{{streams|length >= 2}}", + "output": "{{streams}}", + "output_type": List[int], + "output_name": "streams", + }, + ] + router = ConditionalRouter(routes, unsafe=True, validate_output_type=True) + streams = [1] + message = ChatMessage.from_user(content="This is a message") + res = router.run(streams=streams, message=message) + assert isinstance(res["message"], ChatMessage) + + streams = ["1", "2", "3", "4"] + with pytest.raises(ValueError, match="Route 'streams' type doesn't match expected type"): + router.run(streams=streams, message=message) diff --git a/testbed/deepset-ai__haystack/test/components/routers/test_file_router.py b/testbed/deepset-ai__haystack/test/components/routers/test_file_router.py new file mode 100644 index 0000000000000000000000000000000000000000..3d99bf4d612bec98bcba5fc7dfcedba72c5cccee --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/test_file_router.py @@ -0,0 +1,395 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import io +import sys +from unittest.mock import mock_open, patch + +import pytest + +from haystack.components.routers.file_type_router import FileTypeRouter +from haystack.components.converters import TextFileToDocument, PyPDFToDocument +from haystack.dataclasses import ByteStream +from haystack import Pipeline + + +@pytest.mark.skipif( + sys.platform in ["win32", "cygwin"], + reason="Can't run on Windows Github CI, need access to registry to get mime types", +) +class TestFileTypeRouter: + def test_init(self): + """ + Test that the component initializes correctly. + """ + router = FileTypeRouter(mime_types=["text/plain", "audio/x-wav", "image/jpeg"]) + assert router.mime_types == ["text/plain", "audio/x-wav", "image/jpeg"] + assert router._additional_mimetypes is None + + router = FileTypeRouter( + mime_types=["text/plain"], + additional_mimetypes={"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}, + ) + assert router.mime_types == ["text/plain"] + assert router._additional_mimetypes == { + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx" + } + + def test_init_fail_wo_mime_types(self): + """ + Test that the component raises an error if no mime types are provided. + """ + with pytest.raises(ValueError): + FileTypeRouter(mime_types=[]) + + def test_to_dict(self): + router = FileTypeRouter( + mime_types=["text/plain", "audio/x-wav", "image/jpeg"], + additional_mimetypes={"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}, + ) + expected_dict = { + "type": "haystack.components.routers.file_type_router.FileTypeRouter", + "init_parameters": { + "mime_types": ["text/plain", "audio/x-wav", "image/jpeg"], + "additional_mimetypes": { + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx" + }, + }, + } + assert router.to_dict() == expected_dict + + def test_from_dict(self): + router_dict = { + "type": "haystack.components.routers.file_type_router.FileTypeRouter", + "init_parameters": { + "mime_types": ["text/plain", "audio/x-wav", "image/jpeg"], + "additional_mimetypes": { + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx" + }, + }, + } + loaded_router = FileTypeRouter.from_dict(router_dict) + + expected_router = FileTypeRouter( + mime_types=["text/plain", "audio/x-wav", "image/jpeg"], + additional_mimetypes={"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}, + ) + + assert loaded_router.mime_types == expected_router.mime_types + assert loaded_router._additional_mimetypes == expected_router._additional_mimetypes + + def test_run(self, test_files_path): + """ + Test if the component runs correctly in the simplest happy path. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "txt" / "doc_2.txt", + test_files_path / "audio" / "the context for this answer is here.wav", + test_files_path / "images" / "apple.jpg", + ] + + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav", r"image/jpeg"]) + output = router.run(sources=file_paths) + assert output + assert len(output[r"text/plain"]) == 2 + assert len(output[r"audio/x-wav"]) == 1 + assert len(output[r"image/jpeg"]) == 1 + assert not output.get("unclassified") + + def test_run_with_single_meta(self, test_files_path): + """ + Test if the component runs correctly when a single metadata dictionary is provided. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "txt" / "doc_2.txt", + test_files_path / "audio" / "the context for this answer is here.wav", + ] + + meta = {"meta_field": "meta_value"} + + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav"]) + output = router.run(sources=file_paths, meta=meta) + assert output + + assert len(output[r"text/plain"]) == 2 + assert len(output[r"audio/x-wav"]) == 1 + assert not output.get("unclassified") + + for elements in output.values(): + for el in elements: + assert isinstance(el, ByteStream) + assert el.meta["meta_field"] == "meta_value" + + def test_run_with_meta_list(self, test_files_path): + """ + Test if the component runs correctly when a list of metadata dictionaries is provided. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "images" / "apple.jpg", + test_files_path / "audio" / "the context for this answer is here.wav", + ] + + meta = [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}] + + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav", r"image/jpeg"]) + output = router.run(sources=file_paths, meta=meta) + assert output + + assert len(output[r"text/plain"]) == 1 + assert len(output[r"audio/x-wav"]) == 1 + assert len(output[r"image/jpeg"]) == 1 + assert not output.get("unclassified") + + for i, elements in enumerate(output.values()): + for el in elements: + assert isinstance(el, ByteStream) + + expected_meta_key, expected_meta_value = list(meta[i].items())[0] + assert el.meta[expected_meta_key] == expected_meta_value + + def test_run_with_meta_and_bytestreams(self): + """ + Test if the component runs correctly with ByteStream inputs and meta. + The original meta is preserved and the new meta is added. + """ + + bs = ByteStream.from_string("Haystack!", mime_type="text/plain", meta={"foo": "bar"}) + + meta = {"another_key": "another_value"} + + router = FileTypeRouter(mime_types=[r"text/plain"]) + + output = router.run(sources=[bs], meta=meta) + + assert output + assert len(output[r"text/plain"]) == 1 + assert not output.get("unclassified") + + assert isinstance(output[r"text/plain"][0], ByteStream) + assert output[r"text/plain"][0].meta["foo"] == "bar" + assert output[r"text/plain"][0].meta["another_key"] == "another_value" + + def test_run_fails_if_meta_length_does_not_match_sources(self, test_files_path): + """ + Test that the component raises an error if the length of the metadata list does not match the number of sources. + """ + file_paths = [test_files_path / "txt" / "doc_1.txt"] + + meta = [{"key1": "value1"}, {"key2": "value2"}, {"key3": "value3"}] + + router = FileTypeRouter(mime_types=[r"text/plain"]) + + with pytest.raises(ValueError): + router.run(sources=file_paths, meta=meta) + + def test_run_with_bytestreams(self, test_files_path): + """ + Test if the component runs correctly with ByteStream inputs. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "txt" / "doc_2.txt", + test_files_path / "audio" / "the context for this answer is here.wav", + test_files_path / "images" / "apple.jpg", + ] + mime_types = [r"text/plain", r"text/plain", r"audio/x-wav", r"image/jpeg"] + # Convert file paths to ByteStream objects and set metadata + byte_streams = [] + for path, mime_type in zip(file_paths, mime_types): + stream = ByteStream(path.read_bytes()) + stream.mime_type = mime_type + byte_streams.append(stream) + + # add unclassified ByteStream + bs = ByteStream(b"unclassified content") + bs.meta["content_type"] = "unknown_type" + byte_streams.append(bs) + + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav", r"image/jpeg"]) + output = router.run(sources=byte_streams) + assert output + assert len(output[r"text/plain"]) == 2 + assert len(output[r"audio/x-wav"]) == 1 + assert len(output[r"image/jpeg"]) == 1 + assert len(output.get("unclassified")) == 1 + + def test_run_with_bytestreams_and_file_paths(self, test_files_path): + """ + Test if the component raises an error for unsupported data source types. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "audio" / "the context for this answer is here.wav", + test_files_path / "txt" / "doc_2.txt", + test_files_path / "images" / "apple.jpg", + test_files_path / "markdown" / "sample.md", + ] + mime_types = [r"text/plain", r"audio/x-wav", r"text/plain", r"image/jpeg", r"text/markdown"] + byte_stream_sources = [] + for path, mime_type in zip(file_paths, mime_types): + stream = ByteStream(path.read_bytes()) + stream.mime_type = mime_type + byte_stream_sources.append(stream) + + mixed_sources = file_paths[:2] + byte_stream_sources[2:] + + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav", r"image/jpeg", r"text/markdown"]) + output = router.run(sources=mixed_sources) + assert len(output[r"text/plain"]) == 2 + assert len(output[r"audio/x-wav"]) == 1 + assert len(output[r"image/jpeg"]) == 1 + assert len(output[r"text/markdown"]) == 1 + + def test_no_files(self): + """ + Test that the component runs correctly when no files are provided. + """ + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav", r"image/jpeg"]) + output = router.run(sources=[]) + assert not output + + def test_unlisted_extensions(self, test_files_path): + """ + Test that the component correctly handles files with non specified mime types. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "audio" / "ignored.mp3", + test_files_path / "audio" / "this is the content of the document.wav", + ] + router = FileTypeRouter(mime_types=[r"text/plain"]) + output = router.run(sources=file_paths) + assert len(output[r"text/plain"]) == 1 + assert "mp3" not in output + assert len(output.get("unclassified")) == 2 + + def test_no_extension(self, test_files_path): + """ + Test that the component ignores files with no extension. + """ + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "txt" / "doc_2", + test_files_path / "txt" / "doc_2.txt", + ] + router = FileTypeRouter(mime_types=[r"text/plain"]) + output = router.run(sources=file_paths) + assert len(output[r"text/plain"]) == 2 + assert len(output.get("unclassified")) == 1 + + def test_unsupported_source_type(self): + """ + Test if the component raises an error for unsupported data source types. + """ + router = FileTypeRouter(mime_types=[r"text/plain", r"audio/x-wav", r"image/jpeg"]) + with pytest.raises(ValueError, match="Unsupported data source type:"): + router.run(sources=[{"unsupported": "type"}]) + + def test_invalid_regex_pattern(self): + """ + Test that the component raises a ValueError for invalid regex patterns. + """ + with pytest.raises(ValueError, match="Invalid regex pattern"): + FileTypeRouter(mime_types=["[Invalid-Regex"]) + + def test_regex_mime_type_matching(self, test_files_path): + """ + Test if the component correctly matches mime types using regex. + """ + router = FileTypeRouter(mime_types=[r"text\/.*", r"audio\/.*", r"image\/.*"]) + file_paths = [ + test_files_path / "txt" / "doc_1.txt", + test_files_path / "audio" / "the context for this answer is here.wav", + test_files_path / "images" / "apple.jpg", + ] + output = router.run(sources=file_paths) + assert len(output[r"text\/.*"]) == 1, "Failed to match text file with regex" + assert len(output[r"audio\/.*"]) == 1, "Failed to match audio file with regex" + assert len(output[r"image\/.*"]) == 1, "Failed to match image file with regex" + + @patch("pathlib.Path.open", new_callable=mock_open, read_data=b"Mock file content.") + def test_exact_mime_type_matching(self, mock_file): + """ + Test if the component correctly matches mime types exactly, without regex patterns. + """ + txt_stream = ByteStream(io.BytesIO(b"Text file content").read()) + txt_stream.mime_type = "text/plain" + jpg_stream = ByteStream(io.BytesIO(b"JPEG file content").read()) + jpg_stream.mime_type = "image/jpeg" + mp3_stream = ByteStream(io.BytesIO(b"MP3 file content").read()) + mp3_stream.mime_type = "audio/mpeg" + + byte_streams = [txt_stream, jpg_stream, mp3_stream] + + router = FileTypeRouter(mime_types=["text/plain", "image/jpeg"]) + + output = router.run(sources=byte_streams) + + assert len(output["text/plain"]) == 1, "Failed to match 'text/plain' MIME type exactly" + assert txt_stream in output["text/plain"], "'doc_1.txt' ByteStream not correctly classified as 'text/plain'" + + assert len(output["image/jpeg"]) == 1, "Failed to match 'image/jpeg' MIME type exactly" + assert jpg_stream in output["image/jpeg"], "'apple.jpg' ByteStream not correctly classified as 'image/jpeg'" + + assert len(output.get("unclassified")) == 1, "Failed to handle unclassified file types" + assert mp3_stream in output["unclassified"], "'sound.mp3' ByteStream should be unclassified but is not" + + def test_serde_in_pipeline(self): + """ + Test if a pipeline containing the component can be serialized and deserialized without errors. + """ + + file_type_router = FileTypeRouter(mime_types=["text/plain", "application/pdf"]) + + pipeline = Pipeline() + pipeline.add_component(instance=file_type_router, name="file_type_router") + + pipeline_dict = pipeline.to_dict() + + assert pipeline_dict == { + "metadata": {}, + "max_runs_per_component": 100, + "components": { + "file_type_router": { + "type": "haystack.components.routers.file_type_router.FileTypeRouter", + "init_parameters": {"mime_types": ["text/plain", "application/pdf"], "additional_mimetypes": None}, + } + }, + "connections": [], + } + + pipeline_yaml = pipeline.dumps() + + new_pipeline = Pipeline.loads(pipeline_yaml) + assert new_pipeline == pipeline + + @pytest.mark.integration + def test_pipeline_with_converters(self, test_files_path): + """ + Test if the component runs correctly in a pipeline with converters and passes metadata correctly. + """ + file_type_router = FileTypeRouter( + mime_types=["text/plain", "application/pdf"], + additional_mimetypes={"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"}, + ) + + pipe = Pipeline() + pipe.add_component(instance=file_type_router, name="file_type_router") + pipe.add_component(instance=TextFileToDocument(), name="text_file_converter") + pipe.add_component(instance=PyPDFToDocument(), name="pypdf_converter") + pipe.connect("file_type_router.text/plain", "text_file_converter.sources") + pipe.connect("file_type_router.application/pdf", "pypdf_converter.sources") + + print(pipe.to_dict()) + + file_paths = [test_files_path / "txt" / "doc_1.txt", test_files_path / "pdf" / "sample_pdf_1.pdf"] + + meta = [{"meta_field_1": "meta_value_1"}, {"meta_field_2": "meta_value_2"}] + + output = pipe.run(data={"file_type_router": {"sources": file_paths, "meta": meta}}) + + assert output["text_file_converter"]["documents"][0].meta["meta_field_1"] == "meta_value_1" + assert output["pypdf_converter"]["documents"][0].meta["meta_field_2"] == "meta_value_2" diff --git a/testbed/deepset-ai__haystack/test/components/routers/test_metadata_router.py b/testbed/deepset-ai__haystack/test/components/routers/test_metadata_router.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e8ce9875983cf6923423f4331a855ca7618446 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/test_metadata_router.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document +from haystack.components.routers.metadata_router import MetadataRouter + + +class TestMetadataRouter: + def test_run(self): + rules = { + "edge_1": { + "operator": "AND", + "conditions": [ + {"field": "meta.created_at", "operator": ">=", "value": "2023-01-01"}, + {"field": "meta.created_at", "operator": "<", "value": "2023-04-01"}, + ], + }, + "edge_2": { + "operator": "AND", + "conditions": [ + {"field": "meta.created_at", "operator": ">=", "value": "2023-04-01"}, + {"field": "meta.created_at", "operator": "<", "value": "2023-07-01"}, + ], + }, + } + router = MetadataRouter(rules=rules) + documents = [ + Document(meta={"created_at": "2023-02-01"}), + Document(meta={"created_at": "2023-05-01"}), + Document(meta={"created_at": "2023-08-01"}), + ] + output = router.run(documents=documents) + assert output["edge_1"][0].meta["created_at"] == "2023-02-01" + assert output["edge_2"][0].meta["created_at"] == "2023-05-01" + assert output["unmatched"][0].meta["created_at"] == "2023-08-01" diff --git a/testbed/deepset-ai__haystack/test/components/routers/test_text_language_router.py b/testbed/deepset-ai__haystack/test/components/routers/test_text_language_router.py new file mode 100644 index 0000000000000000000000000000000000000000..c72e55323836f48e0259ed1ff7581dfc8d0a3e60 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/test_text_language_router.py @@ -0,0 +1,56 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import logging +import pytest +from _pytest.logging import LogCaptureFixture + +from haystack import Document +from haystack.components.routers import TextLanguageRouter + + +class TestTextLanguageRouter: + def test_non_string_input(self): + with pytest.raises(TypeError, match="TextLanguageRouter expects a string as input."): + classifier = TextLanguageRouter() + classifier.run(text=Document(content="This is an english sentence.")) + + def test_list_of_string(self): + with pytest.raises(TypeError, match="TextLanguageRouter expects a string as input."): + classifier = TextLanguageRouter() + classifier.run(text=["This is an english sentence."]) + + def test_empty_string(self): + classifier = TextLanguageRouter() + result = classifier.run(text="") + assert result == {"unmatched": ""} + + def test_detect_language(self): + classifier = TextLanguageRouter() + detected_language = classifier._detect_language("This is an english sentence.") + assert detected_language == "en" + + def test_route_to_en(self): + classifier = TextLanguageRouter() + english_sentence = "This is an english sentence." + result = classifier.run(text=english_sentence) + assert result == {"en": english_sentence} + + def test_route_to_unmatched(self): + classifier = TextLanguageRouter() + german_sentence = "Ein deutscher Satz ohne Verb." + result = classifier.run(text=german_sentence) + assert result == {"unmatched": german_sentence} + + def test_warning_if_no_language_detected(self, caplog: LogCaptureFixture): + with caplog.at_level(logging.WARNING): + classifier = TextLanguageRouter() + classifier.run(text=".") + assert "Langdetect cannot detect the language of text. Error: No features in text." in caplog.text + + def test_warning_if_no_language_detected_if_debug(self, caplog: LogCaptureFixture): + with caplog.at_level(logging.DEBUG): + classifier = TextLanguageRouter() + classifier.run(text=".") + assert "Langdetect cannot detect the language of text. Error: No features in text." in caplog.text + assert "Langdetect cannot detect the language of text: ." in caplog.text diff --git a/testbed/deepset-ai__haystack/test/components/routers/test_transformers_text_router.py b/testbed/deepset-ai__haystack/test/components/routers/test_transformers_text_router.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0dca8d63e2aa4545f7adbeaed823fa3db0a997 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/test_transformers_text_router.py @@ -0,0 +1,205 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import patch, MagicMock + +import pytest + +from haystack.components.routers.transformers_text_router import TransformersTextRouter +from haystack.utils import ComponentDevice, Secret + + +class TestTransformersTextRouter: + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + def test_to_dict(self, mock_auto_config_from_pretrained): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection") + router_dict = router.to_dict() + assert router_dict == { + "type": "haystack.components.routers.transformers_text_router.TransformersTextRouter", + "init_parameters": { + "labels": ["en", "de"], + "model": "papluca/xlm-roberta-base-language-detection", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "text-classification", + }, + }, + } + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + def test_to_dict_with_cpu_device(self, mock_auto_config_from_pretrained): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + router = TransformersTextRouter( + model="papluca/xlm-roberta-base-language-detection", device=ComponentDevice.from_str("cpu") + ) + router_dict = router.to_dict() + assert router_dict == { + "type": "haystack.components.routers.transformers_text_router.TransformersTextRouter", + "init_parameters": { + "labels": ["en", "de"], + "model": "papluca/xlm-roberta-base-language-detection", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.from_str("cpu").to_hf(), + "task": "text-classification", + }, + }, + } + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + def test_from_dict(self, mock_auto_config_from_pretrained, monkeypatch): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + monkeypatch.delenv("HF_API_TOKEN", raising=False) + data = { + "type": "haystack.components.routers.transformers_text_router.TransformersTextRouter", + "init_parameters": { + "model": "papluca/xlm-roberta-base-language-detection", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + }, + }, + } + + component = TransformersTextRouter.from_dict(data) + assert component.labels == ["en", "de"] + assert component.pipeline is None + assert component.token == Secret.from_dict( + {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + ) + assert component.huggingface_pipeline_kwargs == { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "text-classification", + "token": None, + } + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + def test_from_dict_no_default_parameters(self, mock_auto_config_from_pretrained, monkeypatch): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + monkeypatch.delenv("HF_API_TOKEN", raising=False) + data = { + "type": "haystack.components.routers.transformers_text_router.TransformersTextRouter", + "init_parameters": {"model": "papluca/xlm-roberta-base-language-detection"}, + } + component = TransformersTextRouter.from_dict(data) + assert component.labels == ["en", "de"] + assert component.pipeline is None + assert component.token == Secret.from_dict( + {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + ) + assert component.huggingface_pipeline_kwargs == { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "text-classification", + "token": None, + } + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + def test_from_dict_with_cpu_device(self, mock_auto_config_from_pretrained, monkeypatch): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + monkeypatch.delenv("HF_API_TOKEN", raising=False) + data = { + "type": "haystack.components.routers.transformers_text_router.TransformersTextRouter", + "init_parameters": { + "model": "papluca/xlm-roberta-base-language-detection", + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.from_str("cpu").to_hf(), + "task": "zero-shot-classification", + }, + }, + } + + component = TransformersTextRouter.from_dict(data) + assert component.labels == ["en", "de"] + assert component.pipeline is None + assert component.token == Secret.from_dict( + {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + ) + assert component.huggingface_pipeline_kwargs == { + "model": "papluca/xlm-roberta-base-language-detection", + "device": ComponentDevice.from_str("cpu").to_hf(), + "task": "text-classification", + "token": None, + } + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + @patch("haystack.components.routers.transformers_text_router.pipeline") + def test_warm_up(self, hf_pipeline_mock, mock_auto_config_from_pretrained): + hf_pipeline_mock.return_value = MagicMock(model=MagicMock(config=MagicMock(label2id={"en": 0, "de": 1}))) + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection") + router.warm_up() + assert router.pipeline is not None + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + def test_run_fails_without_warm_up(self, mock_auto_config_from_pretrained): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection") + with pytest.raises(RuntimeError): + router.run(text="test") + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + @patch("haystack.components.routers.transformers_text_router.pipeline") + def test_run_fails_with_non_string_input(self, hf_pipeline_mock, mock_auto_config_from_pretrained): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + hf_pipeline_mock.return_value = MagicMock(model=MagicMock(config=MagicMock(label2id={"en": 0, "de": 1}))) + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection") + router.warm_up() + with pytest.raises(TypeError): + router.run(text=["wrong_input"]) + + @patch("haystack.components.routers.transformers_text_router.AutoConfig.from_pretrained") + @patch("haystack.components.routers.transformers_text_router.pipeline") + def test_run_unit(self, hf_pipeline_mock, mock_auto_config_from_pretrained): + mock_auto_config_from_pretrained.return_value = MagicMock(label2id={"en": 0, "de": 1}) + hf_pipeline_mock.return_value = [{"label": "en", "score": 0.9}] + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection") + router.pipeline = hf_pipeline_mock + out = router.run("What is the color of the sky?") + assert router.pipeline is not None + assert out == {"en": "What is the color of the sky?"} + + @pytest.mark.integration + def test_run(self): + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection") + router.warm_up() + out = router.run("What is the color of the sky?") + assert set(router.labels) == { + "ar", + "bg", + "de", + "el", + "en", + "es", + "fr", + "hi", + "it", + "ja", + "nl", + "pl", + "pt", + "ru", + "sw", + "th", + "tr", + "ur", + "vi", + "zh", + } + assert router.pipeline is not None + assert out == {"en": "What is the color of the sky?"} + + @pytest.mark.integration + def test_wrong_labels(self): + router = TransformersTextRouter(model="papluca/xlm-roberta-base-language-detection", labels=["en", "de"]) + with pytest.raises(ValueError): + router.warm_up() diff --git a/testbed/deepset-ai__haystack/test/components/routers/test_zero_shot_text_router.py b/testbed/deepset-ai__haystack/test/components/routers/test_zero_shot_text_router.py new file mode 100644 index 0000000000000000000000000000000000000000..8e9759f361d2403bf36630237f1c87d9b1286255 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/routers/test_zero_shot_text_router.py @@ -0,0 +1,112 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from unittest.mock import patch + +import pytest + +from haystack.components.routers.zero_shot_text_router import TransformersZeroShotTextRouter +from haystack.utils import ComponentDevice, Secret + + +class TestTransformersZeroShotTextRouter: + def test_to_dict(self): + router = TransformersZeroShotTextRouter(labels=["query", "passage"]) + router_dict = router.to_dict() + assert router_dict == { + "type": "haystack.components.routers.zero_shot_text_router.TransformersZeroShotTextRouter", + "init_parameters": { + "labels": ["query", "passage"], + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + }, + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + data = { + "type": "haystack.components.routers.zero_shot_text_router.TransformersZeroShotTextRouter", + "init_parameters": { + "labels": ["query", "passage"], + "token": {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"}, + "huggingface_pipeline_kwargs": { + "model": "MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + }, + }, + } + + component = TransformersZeroShotTextRouter.from_dict(data) + assert component.labels == ["query", "passage"] + assert component.pipeline is None + assert component.token == Secret.from_dict( + {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + ) + assert component.huggingface_pipeline_kwargs == { + "model": "MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + "token": None, + } + + def test_from_dict_no_default_parameters(self, monkeypatch): + monkeypatch.delenv("HF_API_TOKEN", raising=False) + data = { + "type": "haystack.components.routers.zero_shot_text_router.TransformersZeroShotTextRouter", + "init_parameters": {"labels": ["query", "passage"]}, + } + component = TransformersZeroShotTextRouter.from_dict(data) + assert component.labels == ["query", "passage"] + assert component.pipeline is None + assert component.token == Secret.from_dict( + {"env_vars": ["HF_API_TOKEN", "HF_TOKEN"], "strict": False, "type": "env_var"} + ) + assert component.huggingface_pipeline_kwargs == { + "model": "MoritzLaurer/deberta-v3-base-zeroshot-v1.1-all-33", + "device": ComponentDevice.resolve_device(None).to_hf(), + "task": "zero-shot-classification", + "token": None, + } + + @patch("haystack.components.routers.zero_shot_text_router.pipeline") + def test_warm_up(self, hf_pipeline_mock): + router = TransformersZeroShotTextRouter(labels=["query", "passage"]) + router.warm_up() + assert router.pipeline is not None + + def test_run_fails_without_warm_up(self): + router = TransformersZeroShotTextRouter(labels=["query", "passage"]) + with pytest.raises(RuntimeError): + router.run(text="test") + + @patch("haystack.components.routers.zero_shot_text_router.pipeline") + def test_run_fails_with_non_string_input(self, hf_pipeline_mock): + hf_pipeline_mock.return_value = " " + router = TransformersZeroShotTextRouter(labels=["query", "passage"]) + router.warm_up() + with pytest.raises(TypeError): + router.run(text=["wrong_input"]) + + @patch("haystack.components.routers.zero_shot_text_router.pipeline") + def test_run_unit(self, hf_pipeline_mock): + hf_pipeline_mock.return_value = [ + {"sequence": "What is the color of the sky?", "labels": ["query", "passage"], "scores": [0.9, 0.1]} + ] + router = TransformersZeroShotTextRouter(labels=["query", "passage"]) + router.pipeline = hf_pipeline_mock + out = router.run("What is the color of the sky?") + assert router.pipeline is not None + assert out == {"query": "What is the color of the sky?"} + + @pytest.mark.integration + def test_run(self): + router = TransformersZeroShotTextRouter(labels=["query", "passage"]) + router.warm_up() + out = router.run("What is the color of the sky?") + assert router.pipeline is not None + assert out == {"query": "What is the color of the sky?"} diff --git a/testbed/deepset-ai__haystack/test/components/samplers/__init__.py b/testbed/deepset-ai__haystack/test/components/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/samplers/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/samplers/test_top_p.py b/testbed/deepset-ai__haystack/test/components/samplers/test_top_p.py new file mode 100644 index 0000000000000000000000000000000000000000..49317fb8317a918ec4456fbf905a780b23790670 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/samplers/test_top_p.py @@ -0,0 +1,131 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import random +from typing import List + +import pytest +from haystack import Document +from haystack.components.samplers.top_p import TopPSampler + + +@pytest.fixture +def documents_with_score_field() -> List[Document]: + return [ + Document(content="Sarajevo", meta={"similarity_score": 0.7}), + Document(content="Belgrade", meta={"similarity_score": 0.01}), + Document(content="Berlin", meta={"similarity_score": 0.001}), + ] + + +@pytest.fixture +def documents_with_score() -> List[Document]: + return [ + Document(content="Sarajevo", score=0.7), + Document(content="Belgrade", score=0.01), + Document(content="Berlin", score=0.001), + ] + + +class TestTopPSampler: + def test_init_raises_value_error(self) -> None: + with pytest.raises(ValueError): + TopPSampler(top_p=2.0) + + def test_run_raises_value_error(self, documents_with_score: List[Document]) -> None: + sampler = TopPSampler(top_p=0.95) + with pytest.raises(ValueError): + sampler.run(documents=documents_with_score, top_p=2.0) + + def test_run_score_field(self, documents_with_score_field: List[Document]) -> None: + sampler = TopPSampler(top_p=0.95, score_field="similarity_score") + docs = documents_with_score_field + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 2 + assert docs[0].content == "Sarajevo" + assert docs[1].content == "Belgrade" + + def test_run_score_field_missing_scores(self, caplog: pytest.LogCaptureFixture) -> None: + sampler = TopPSampler(top_p=1.0, score_field="similarity_score") + docs = [ + Document(content="Sarajevo", meta={"similarity_score": 0.7}), + Document(content="Belgrade", meta={"similarity_score": 0.01}), + Document(content="Berlin", meta={"similarity_score": None}), + ] + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 2 + assert docs[0].content == "Sarajevo" + assert docs[1].content == "Belgrade" + assert "Score field" in caplog.text + + def test_run(self, documents_with_score: List[Document]) -> None: + sampler = TopPSampler(top_p=0.99) + docs = documents_with_score + random.shuffle(docs) + sorted_scores = sorted([doc.score for doc in docs], reverse=True) + + # top_p = 0.99 will get the top 1 document + output = sampler.run(documents=docs) + docs_filtered = output["documents"] + assert len(docs_filtered) == 2 + assert docs_filtered[0].content == "Sarajevo" + assert docs_filtered[1].content == "Belgrade" + + assert [doc.score for doc in docs_filtered] == sorted_scores[:2] + + def test_run_top_p_1(self, documents_with_score: List[Document]) -> None: + sampler = TopPSampler(top_p=1.0) + docs = documents_with_score + random.shuffle(docs) + output = sampler.run(documents=docs) + docs_filtered = output["documents"] + assert len(docs_filtered) == len(docs) + assert docs_filtered[0].content == "Sarajevo" + assert [doc.score for doc in docs_filtered] == sorted([doc.score for doc in docs], reverse=True) + + def test_run_top_p_0(self, caplog: pytest.LogCaptureFixture, documents_with_score: List[Document]) -> None: + sampler = TopPSampler(top_p=0.0) + docs = documents_with_score + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 1 + assert docs[0].content == "Sarajevo" + assert "Top-p sampling with p=" in caplog.text + + def test_run_returns_empty_list_no_documents(self) -> None: + sampler = TopPSampler() + output = sampler.run(documents=[]) + assert output["documents"] == [] + + def test_run_no_score_field(self, caplog: pytest.LogCaptureFixture, documents_with_score: List[Document]) -> None: + sampler = TopPSampler(top_p=0.95, score_field="similarity_score") + docs = documents_with_score + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 3 + assert docs[0].content == "Sarajevo" + assert "Score field 'similarity_score' not found" in caplog.text + + def test_run_missing_scores(self, caplog: pytest.LogCaptureFixture) -> None: + sampler = TopPSampler(top_p=0.95) + docs = [ + Document(content="Sarajevo", score=0.7), + Document(content="Belgrade", score=0.01), + Document(content="Berlin", score=None), + ] + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 1 + assert docs[0].content == "Sarajevo" + assert "Ensure all documents have a valid score value" in caplog.text + + def test_run_min_top_k(self, documents_with_score: List[Document]) -> None: + sampler = TopPSampler(min_top_k=2, top_p=0.2) + docs = documents_with_score + output = sampler.run(documents=docs) + docs = output["documents"] + assert len(docs) == 2 + assert docs[0].content == "Sarajevo" + assert docs[1].content == "Belgrade" diff --git a/testbed/deepset-ai__haystack/test/components/validators/test_json_schema.py b/testbed/deepset-ai__haystack/test/components/validators/test_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..39e9c785871f53419505d69a1e600fdc4288d607 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/validators/test_json_schema.py @@ -0,0 +1,205 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import json +from typing import List + +import pytest + +from haystack import Pipeline, component +from haystack.components.validators import JsonSchemaValidator +from haystack.dataclasses import ChatMessage + + +@pytest.fixture +def genuine_fc_message(): + return """[{"id": "call_NJr1NBz2Th7iUWJpRIJZoJIA", "function": {"arguments": "{\\n \\"basehead\\": \\"main...amzn_chat\\",\\n \\"owner\\": \\"deepset-ai\\",\\n \\"repo\\": \\"haystack-core-integrations\\"\\n }", "name": "compare_branches"}, "type": "function"}]""" + + +@pytest.fixture +def json_schema_github_compare(): + json_schema = { + "type": "object", + "properties": { + "id": {"type": "string", "description": "A unique identifier for the call"}, + "function": { + "type": "object", + "properties": { + "arguments": { + "type": "object", + "properties": { + "basehead": { + "type": "string", + "pattern": "^[^\\.]+(\\.{3}).+$", + "description": "Branch names must be in the format 'base_branch...head_branch'", + }, + "owner": {"type": "string", "description": "Owner of the repository"}, + "repo": {"type": "string", "description": "Name of the repository"}, + }, + "required": ["basehead", "owner", "repo"], + "description": "Parameters for the function call", + }, + "name": {"type": "string", "description": "Name of the function to be called"}, + }, + "required": ["arguments", "name"], + "description": "Details of the function being called", + }, + "type": {"type": "string", "description": "Type of the call (e.g., 'function')"}, + }, + "required": ["function", "type"], + "description": "Structure representing a function call", + } + return json_schema + + +@pytest.fixture +def json_schema_github_compare_openai(): + json_schema = { + "name": "compare_branches", + "description": "Compares two branches in a GitHub repository", + "parameters": { + "type": "object", + "properties": { + "basehead": { + "type": "string", + "pattern": "^[^\\.]+(\\.{3}).+$", + "description": "Branch names must be in the format 'base_branch...head_branch'", + }, + "owner": {"type": "string", "description": "Owner of the repository"}, + "repo": {"type": "string", "description": "Name of the repository"}, + }, + "required": ["basehead", "owner", "repo"], + "description": "Parameters for the function call", + }, + } + return json_schema + + +class TestJsonSchemaValidator: + # Validates a message against a provided JSON schema successfully. + def test_validates_message_against_json_schema(self, json_schema_github_compare, genuine_fc_message): + validator = JsonSchemaValidator() + message = ChatMessage.from_assistant(genuine_fc_message) + + result = validator.run([message], json_schema_github_compare) + + assert "validated" in result + assert len(result["validated"]) == 1 + assert result["validated"][0] == message + + # Validates recursive_json_to_object method + def test_recursive_json_to_object(self, genuine_fc_message): + arguments_is_string = json.loads(genuine_fc_message) + assert isinstance(arguments_is_string[0]["function"]["arguments"], str) + + # but ensure_json_objects converts the string to a json object + validator = JsonSchemaValidator() + result = validator._recursive_json_to_object({"key": genuine_fc_message}) + + # we need this recursive json conversion to validate the message + assert result["key"][0]["function"]["arguments"]["basehead"] == "main...amzn_chat" + + # Validates multiple messages against a provided JSON schema successfully. + def test_validates_multiple_messages_against_json_schema(self, json_schema_github_compare, genuine_fc_message): + validator = JsonSchemaValidator() + + messages = [ + ChatMessage.from_user("I'm not being validated, but the message after me is!"), + ChatMessage.from_assistant(genuine_fc_message), + ] + + result = validator.run(messages, json_schema_github_compare) + assert "validated" in result + assert len(result["validated"]) == 1 + assert result["validated"][0] == messages[1] + + # Validates a message against an OpenAI function calling schema successfully. + def test_validates_message_against_openai_function_calling_schema( + self, json_schema_github_compare_openai, genuine_fc_message + ): + validator = JsonSchemaValidator() + + message = ChatMessage.from_assistant(genuine_fc_message) + result = validator.run([message], json_schema_github_compare_openai) + + assert "validated" in result + assert len(result["validated"]) == 1 + assert result["validated"][0] == message + + # Validates multiple messages against an OpenAI function calling schema successfully. + def test_validates_multiple_messages_against_openai_function_calling_schema( + self, json_schema_github_compare_openai, genuine_fc_message + ): + validator = JsonSchemaValidator() + + messages = [ + ChatMessage.from_system("Common use case is that this is for example system message"), + ChatMessage.from_assistant(genuine_fc_message), + ] + + result = validator.run(messages, json_schema_github_compare_openai) + + assert "validated" in result + assert len(result["validated"]) == 1 + assert result["validated"][0] == messages[1] + + # Constructs a custom error recovery message when validation fails. + def test_construct_custom_error_recovery_message(self): + validator = JsonSchemaValidator() + + new_error_template = ( + "Error details:\n- Message: {error_message}\n" + "- Error Path in JSON: {error_path}\n" + "- Schema Path: {error_schema_path}\n" + "Please match the following schema:\n" + "{json_schema}\n" + "Failing Json: {failing_json}\n" + ) + + recovery_message = validator._construct_error_recovery_message( + new_error_template, "Error message", "Error path", "Error schema path", {"type": "object"}, "Failing Json" + ) + + expected_recovery_message = ( + "Error details:\n- Message: Error message\n" + "- Error Path in JSON: Error path\n" + "- Schema Path: Error schema path\n" + "Please match the following schema:\n" + "{'type': 'object'}\n" + "Failing Json: Failing Json\n" + ) + assert recovery_message == expected_recovery_message + + def test_schema_validator_in_pipeline_validated(self, json_schema_github_compare, genuine_fc_message): + @component + class ChatMessageProducer: + @component.output_types(messages=List[ChatMessage]) + def run(self): + return {"messages": [ChatMessage.from_assistant(genuine_fc_message)]} + + pipe = Pipeline() + pipe.add_component(name="schema_validator", instance=JsonSchemaValidator()) + pipe.add_component(name="message_producer", instance=ChatMessageProducer()) + pipe.connect("message_producer", "schema_validator") + result = pipe.run(data={"schema_validator": {"json_schema": json_schema_github_compare}}) + assert "validated" in result["schema_validator"] + assert len(result["schema_validator"]["validated"]) == 1 + assert result["schema_validator"]["validated"][0].content == genuine_fc_message + + def test_schema_validator_in_pipeline_validation_error(self, json_schema_github_compare): + @component + class ChatMessageProducer: + @component.output_types(messages=List[ChatMessage]) + def run(self): + # example json string that is not valid + simple_invalid_json = '{"key": "value"}' + return {"messages": [ChatMessage.from_assistant(simple_invalid_json)]} # invalid message + + pipe = Pipeline() + pipe.add_component(name="schema_validator", instance=JsonSchemaValidator()) + pipe.add_component(name="message_producer", instance=ChatMessageProducer()) + pipe.connect("message_producer", "schema_validator") + result = pipe.run(data={"schema_validator": {"json_schema": json_schema_github_compare}}) + assert "validation_error" in result["schema_validator"] + assert len(result["schema_validator"]["validation_error"]) == 1 + assert "Error details" in result["schema_validator"]["validation_error"][0].content diff --git a/testbed/deepset-ai__haystack/test/components/websearch/__init__.py b/testbed/deepset-ai__haystack/test/components/websearch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/websearch/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/websearch/test_searchapi.py b/testbed/deepset-ai__haystack/test/components/websearch/test_searchapi.py new file mode 100644 index 0000000000000000000000000000000000000000..3eee31c2705fee17c6677d81b23c48084612ce6a --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/websearch/test_searchapi.py @@ -0,0 +1,444 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os +from unittest.mock import Mock, patch + +import pytest +from requests import HTTPError, RequestException, Timeout + +from haystack import Document +from haystack.components.websearch.searchapi import SearchApiError, SearchApiWebSearch +from haystack.utils.auth import Secret + +EXAMPLE_SEARCHAPI_RESPONSE = { + "search_metadata": { + "id": "search_Y16dWXw4JOrIwNjjvqoKNGlE", + "status": "Success", + "created_at": "2023-11-22T16:10:56Z", + "request_time_taken": 1.98, + "parsing_time_taken": 0.16, + "total_time_taken": 2.15, + "request_url": "https://www.google.com/search?q=Who+is+CEO+of+Microsoft%3F&oq=Who+is+CEO+of+Microsoft%3F&gl=us&hl=en&ie=UTF-8", + "html_url": "https://www.searchapi.io/api/v1/searches/search_Y16dWXw4JOrIwNjjvqoKNGlE.html", + "json_url": "https://www.searchapi.io/api/v1/searches/search_Y16dWXw4JOrIwNjjvqoKNGlE", + }, + "search_parameters": { + "engine": "google", + "q": "Who is CEO of Microsoft?", + "device": "desktop", + "google_domain": "google.com", + "hl": "en", + "gl": "us", + }, + "search_information": { + "query_displayed": "Who is CEO of Microsoft?", + "total_results": 429000000, + "time_taken_displayed": 0.48, + }, + "answer_box": { + "type": "organic_result", + "title": "Microsoft Corporation/CEO", + "answer": "Satya Nadella", + "answer_date": "Feb 4, 2014–", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Satya+Nadella&stick=H4sIAAAAAAAAAONgVuLSz9U3KDQxqMjKesRoyi3w8sc9YSmdSWtOXmNU4-IKzsgvd80rySypFJLgYoOy-KR4uJC08Sxi5Q1OLKlMVPBLTEnNyUkEALvb1RBWAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQzIcDKAB6BAgyEAE", + "snippet": "Microsoft CEO Satya Nadella speaks during the OpenAI DevDay event on November 06, 2023 in San Francisco, California.", + "date": "1 day ago", + "organic_result": { + "title": "Microsoft CEO Satya Nadella's response to the OpenAI board ...", + "link": "https://fortune.com/2023/11/21/microsoft-ceo-satya-nadella-openai-ceo-sam-altman-move-fast-fix-things/#:~:text=Microsoft%20CEO%20Satya%20Nadella%20speaks,2023%20in%20San%20Francisco%2C%20California.", + "source": "Fortune", + "domain": "fortune.com", + "displayed_link": "https://fortune.com › 2023/11/21 › microsoft-ceo-satya-...", + }, + "people_also_search_for": [ + { + "title": "Sundar Pichai", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Sundar+Pichai&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1HiArEs01OKzU20-AJSi4rz84IzU1LLEyuLF7HyBpfmpSQWKQRkJmckZgIAJfaYezgAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEAQ", + }, + { + "title": "Steve Ballmer", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Steve+Ballmer&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1ECs8yTssu0-AJSi4rz84IzU1LLEyuLF7HyBpeklqUqOCXm5OSmFgEA31ogfDYAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEAY", + }, + { + "title": "Anupama Nadella", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Anupama+Nadella&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1Hi1U_XNzRMMjPMzTHMMtHiC0gtKs7PC85MSS1PrCxexMrvmFdakJibqOCXmJKak5MIAEx0yhM9AAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEAg", + }, + { + "title": "Zain Nadella", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Zain+Nadella&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1Hi1U_XNzRMMjMyKCgsj9fiC0gtKs7PC85MSS1PrCxexMoTlZiZp-CXmJKak5MIANDRqOs6AAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEAo", + }, + { + "title": "Bill Gates", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Bill+Gates&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1ECswzN80q0-AJSi4rz84IzU1LLEyuLF7FyOWXm5Ci4J5akFgMAF5_u-TMAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEAw", + }, + { + "title": "Shantanu Narayen", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Shantanu+Narayen&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1HiArGMzC0ts5O0-AJSi4rz84IzU1LLEyuLF7EKBGck5pUk5pUq-CUWJVam5gEA2xdRszsAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEA4", + }, + { + "title": "Paul Allen", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Paul+Allen&stick=H4sIAAAAAAAAAONgFuLQz9U3MCkuM1ECs0xLsnO1-AJSi4rz84IzU1LLEyuLF7FyBSSW5ig45uSk5gEA_4-yKDMAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQxA16BAgnEBA", + }, + ], + }, + "knowledge_graph": { + "kgmid": "/m/0q40xjj", + "knowledge_graph_type": "People", + "title": "Satya Nadella", + "type": "CEO of Microsoft", + "description": "Satya Narayana Nadella is an Indian-American business executive. He is the executive chairman and CEO of Microsoft, succeeding Steve Ballmer in 2014 as CEO and John W. Thompson in 2021 as chairman.", + "source": {"name": "Wikipedia", "link": "https://en.wikipedia.org/wiki/Satya_Nadella"}, + "born": "August 19, 1967 (age 56 years), Hyderabad, India", + "born_links": [ + { + "text": "Hyderabad, India", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Hyderabad&si=ALGXSlZS0YT-iRe81F2cKC9lM9KWTK4y0m5Atx8g9YliNNw2meVELJr66A46Jmr2L7YaEMWXarsN12T-Vg9bXBeu7mCHCG-SpT-gWQmluIDs5SvdST1r6rBUhcAOclNosjy4RgkGlWnecyHsBen2Ttz-NbCqTmTwwPK9ro0lfOFPb0CUDvLAkTbBXx4xNX7WWUJ19n0EWeuA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAHoECGUQAg", + } + ], + "awards": "Padma Bhushan, CNN-IBN Indian of the Year Global Indian", + "awards_links": [ + { + "text": "Padma Bhushan", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Padma+Bhushan&si=ALGXSlYh1-GEPndq7qMo--O-TPixQtNN4JMroSxgItz5kq0stCyOa5BGWGIYt20KbMd-zdQdvwREsU7qSkWcyv0yzHS195H46le5meMq90to5z-nIHo4evgG3koKwps5uC-gu8Huemxmq6P1usjVEj5YR9okGopoUaOxuuyZP-isnQAmC6otzjnjf1O9jMuQObZmAnl2HH7coBXCHbIx1QvAHw1KZOYyJKPnYhWaYgqfQo7yF5BOVVLXvtr_8FhnFIxxl7f_V2B6&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAHoECF8QAg", + }, + { + "text": "CNN-IBN Indian of the Year Global Indian", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=CNN-IBN+Indian+of+the+Year+Global+Indian&si=ALGXSlZZLz93Q5j8HVkpXyxpTaoqXw8cocmoi-DFAGsSj5diF8YzT48GvLer52UWWyGCjf3yeWD9YQzPqUV-LEVPLmirdkrJ_7HPexciHWOKnyaMVi0vXdKPSwvc8pE4fD3qmgVyw7qAFoNmy-T-U6OlosYKKVbf9CZnaOonmPhLRRFHGEEmKVtb_0FdKkXeUE2RIDgUJ1n1LWZoTeporPHOj4JfKSJADc-hymzzDEb5-uW3KxQtTdv_GJNMOoleFxqH9cvObQvW0_NvpfHZcThW9b_9g1BXjLfozVqh6hjRTbb40p5vu5e9Oi4sNqxtACf4Xoys_QX5&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAXoECF8QAw", + }, + ], + "nominations": "CNN-IBN Indian of the Year Global Indian", + "nominations_links": [ + { + "text": "CNN-IBN Indian of the Year Global Indian", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=CNN-IBN+Indian+of+the+Year+Global+Indian&si=ALGXSlZZLz93Q5j8HVkpXyxpTaoqXw8cocmoi-DFAGsSj5diF8YzT48GvLer52UWWyGCjf3yeWD9YQzPqUV-LEVPLmirdkrJ_7HPexciHWOKnyaMVlh5LgokSYRM8a-Dib-kzfIaD6Uw_x_3lxo6j3NNKQbuBs4v4kkSCjL68joimLMo16eCX83PFrnvSsVKsgu6aFRoBYQt5p5NRofNfBXtVt2jzFVAWh23VsBHyyAxOuC2aQmgvKp-FGYymourIbHCdJ3rcx-Z&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAHoECGIQAg", + } + ], + "books": "Hit Refresh: The Quest to Rediscover Microsoft's Soul and Imagine a Better Future for Everyone", + "books_links": [ + { + "text": "Hit Refresh: The Quest to Rediscover Microsoft's Soul and Imagine a Better Future for Everyone", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Hit+Refresh&si=ALGXSlZZLz93Q5j8HVkpXyxpTaoqXw8cocmoi-DFAGsSj5diFzM3kSV8cu0gYZuy4n6At7XJ8qKh8mnRaXfDbxUaZoS_kPW87tGFHpw6B9zAS2a52vwJDx-fkzytheyPXaMQENZSl3bwqC9Nz3bqn7-Pglqh0Bik5Ow9AdVr2XI8mdVktN4SkCIaPE4qQfjAurt8rjUVyQzu3OFQx04nfPH3Gv7vP8aKqg%3D%3D&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAHoECGEQAg", + } + ], + "children": "Zain Nadella, Divya Nadella, Tara Nadella", + "children_links": [ + { + "text": "Zain Nadella", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Zain+Nadella&si=ALGXSlZZLz93Q5j8HVkpXyxpTaoqXw8cocmoi-DFAGsSj5diFxtguEvrMR1GmF2uy_-DLcVXwF5gosIuQudQPkad9bBUZxVKOG9PFdHXdEGQHrfXekG0E0x_raEKuDnHD6kk8_HfD3LZ57PWZ3Zyz0uhKPE15DfvA42IpAByWbms0fsgRw5IFCWwB5XMd3WM5U8KKsgeb_DmdoooQ_k3RrxO57jTcm5ZwgDlpBpGq0wj2Ksc2A65RQvA8NPJtpEqDcvEpJ4xWQ_tM_rHduCXRfsv9XFr84DzwA%3D%3D&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAHoECGQQAg", + }, + { + "text": "Divya Nadella", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Divya+Nadella&si=ALGXSlZZLz93Q5j8HVkpXyxpTaoqXw8cocmoi-DFAGsSj5diFwYr_pFPi4_6apkHPz96V-E6wDawAGH_i6kZL7ZB-ETzV3LLESN1a8BgFguu3LOpz1qAQypmcVosQxCFWSJVexciDel34yrgWJmUu5bY2zzEmu1h95LQ35yUDkf6Mqcn-TiwyLu7OzGYkw6D9P4kNkS2D3gNPnRZb6vQJbqdayQg-wgn-LG2BmwR-RntneXFgSSZgotziGaY96UzeZ0zgRWYp6LAKlRqlTbeDeCbDDY2_VIWjQ%3D%3D&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAXoECGQQAw", + }, + { + "text": "Tara Nadella", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Tara+Nadella&si=ALGXSlZZLz93Q5j8HVkpXyxpTaoqXw8cocmoi-DFAGsSj5diF465A_RPTnaELE1D-l5XgaKmBEpoAyayrOAdoXqBSLZ8Qu5UB1hBz6xLN4I1DdUSzqN0G0e9_8lfDbD_Qnx2uLJL_3XUNJ3gPrjCNvCyYeR9a9wkCnMBLchfUhVji9EHiobO4WgdWkxKd44YXHxfMBIYEek8OfbdUx9tplETPYtu7X1HRtGzqp8lXsQ6Vacj-aT7K6Xw0psbP4NXwHRQ71MYjLS-A5_VpSnitGScPsP-1m41Kg%3D%3D&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAnoECGQQBA", + }, + ], + "education": "University of Wisconsin-Milwaukee (1990), MORE", + "education_links": [ + { + "text": "University of Wisconsin-Milwaukee", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=University+of+Wisconsin+Milwaukee&si=ALGXSlYh1-GEPndq7qMo--O-TPixQtNN4JMroSxgItz5kq0stDerMl6ZWDVLeoc_9LMxC6poOvWKyPlaxlQHHC7l9sV2e_sYZ2w92bas10emnFKqvF8PcMhCIIHCiTbdtg6nHIA-ihu0l0dNJtl3ZXuRejodvwikfjAsz-cGgFCLkxoi_eMM95SSZ77VXB0gP7fPTA6q__pIRK7T6ZfiSyM2xTbDt3YUvrWFmx5LBSJwRd2K1f0DK6sGaIa3ozdQOGvGXZkTOTLEG_a2ssbGBTX4MyU4cHmLsvW-Gfpq-makl3esSS7fQTc%3D&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQmxMoAHoECGAQAg", + }, + { + "text": "MORE", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=satya+nadella+education&stick=H4sIAAAAAAAAAOPgE-LSz9U3KDQxqMjK0pLOTrbSL0jNL8hJBVJFxfl5VqkppcmJJZn5eYtYxYsTSyoTFfISU1JzchIV4DIAcrWm-UUAAAA&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ44YBKAF6BAhgEAM", + }, + ], + "full_name": "Satya Narayana Nadella", + "profiles": [ + {"name": "LinkedIn", "link": "https://www.linkedin.com/in/satyanadella"}, + {"name": "Twitter", "link": "https://twitter.com/satyanadella"}, + ], + }, + "organic_results": [ + { + "position": 1, + "title": "Satya Nadella - Stories", + "link": "https://news.microsoft.com/exec/satya-nadella/", + "source": "Microsoft", + "domain": "news.microsoft.com", + "displayed_link": "https://news.microsoft.com › exec › satya-nadella", + "snippet": "Satya Nadella is Chairman and Chief Executive Officer of Microsoft. Before being named CEO in February 2014, Nadella held leadership roles in both ...", + "snippet_highlighted_words": ["Satya Nadella"], + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:jTiZ69Cck7EJ:https://news.microsoft.com/exec/satya-nadella/&hl=en&gl=us", + }, + { + "position": 2, + "title": "Satya Nadella", + "link": "https://en.wikipedia.org/wiki/Satya_Nadella", + "source": "Wikipedia", + "domain": "en.wikipedia.org", + "displayed_link": "https://en.wikipedia.org › wiki › Satya_Nadella", + "snippet": "Satya Narayana Nadella is an Indian-American business executive. He is the executive chairman and CEO of Microsoft, succeeding Steve Ballmer in 2014 as CEO ...", + "snippet_highlighted_words": ["Satya Narayana Nadella"], + "sitelinks": { + "inline": [ + { + "title": "Manipal Institute of Technology", + "link": "https://en.wikipedia.org/wiki/Manipal_Institute_of_Technology", + }, + { + "title": "University of Wisconsin", + "link": "https://en.wikipedia.org/wiki/University_of_Wisconsin%E2%80%93Milwaukee", + }, + {"title": "S. Somasegar", "link": "https://en.wikipedia.org/wiki/S._Somasegar"}, + ] + }, + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:Tgw93hG0PnoJ:https://en.wikipedia.org/wiki/Satya_Nadella&hl=en&gl=us", + }, + { + "position": 3, + "title": "Satya Nadella", + "link": "https://www.linkedin.com/in/satyanadella", + "source": "LinkedIn · Satya Nadella", + "domain": "www.linkedin.com", + "displayed_link": "10.5M+ followers", + "snippet": "As chairman and CEO of Microsoft, I define my mission and that of my company as empowering… | Learn more about Satya Nadella's work experience, education, ...", + "snippet_highlighted_words": ["Satya Nadella's"], + }, + { + "position": 4, + "title": "Who is Satya Nadella, Family, Salary, Education, Net Worth ...", + "link": "https://www.business-standard.com/about/who-is-satya-nadella", + "source": "Business Standard", + "domain": "www.business-standard.com", + "displayed_link": "https://www.business-standard.com › about › who-is-s...", + "snippet": "Satya Narayana Nadella is the chief executive officer (CEO) of Microsoft. Under him, Microsoft has more cloud computing revenue than Google, more subscribers ...", + "snippet_highlighted_words": ["Satya Narayana Nadella"], + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:yQ0bmLSmP8gJ:https://www.business-standard.com/about/who-is-satya-nadella&hl=en&gl=us", + }, + { + "position": 5, + "title": "Satya Nadella (@satyanadella) / X", + "link": "https://twitter.com/satyanadella", + "source": "Twitter · satyanadella", + "domain": "twitter.com", + "displayed_link": "3.1M+ followers", + "snippet": "Chairman and CEO of Microsoft Corporation.", + "snippet_highlighted_words": ["CEO of Microsoft"], + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:dEJiGKzwLfkJ:https://twitter.com/satyanadella&hl=en&gl=us", + }, + { + "position": 6, + "title": "Satya Nadella | Biography & Facts", + "link": "https://www.britannica.com/biography/Satya-Nadella", + "source": "Britannica", + "domain": "www.britannica.com", + "displayed_link": "https://www.britannica.com › biography › Satya-Nadella", + "snippet": "Satya Nadella (born August 19, 1967, Hyderabad, India) Indian-born business executive who was CEO of the computer software company Microsoft (2014– ).", + "snippet_highlighted_words": ["Satya Nadella"], + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:a0S8ke4I9qgJ:https://www.britannica.com/biography/Satya-Nadella&hl=en&gl=us", + }, + { + "position": 7, + "title": "Satya Nadella", + "link": "https://www.forbes.com/profile/satya-nadella/", + "source": "Forbes", + "domain": "www.forbes.com", + "displayed_link": "https://www.forbes.com › profile › satya-nadella", + "snippet": "Satya Nadella replaced billionaire Steve Ballmer as Microsoft CEO in 2014. Prior to that, Nadella was Microsoft EVP of the cloud and enterprise group.", + "snippet_highlighted_words": ["Satya Nadella"], + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:q_CXTYNnHSMJ:https://www.forbes.com/profile/satya-nadella/&hl=en&gl=us", + }, + { + "position": 8, + "title": "5 Facts You Didn't Know About Microsoft CEO Satya Nadella", + "link": "https://in.benzinga.com/content/35911756/5-facts-you-didnt-know-about-microsoft-ceo-satya-nadella", + "source": "Benzinga", + "domain": "in.benzinga.com", + "displayed_link": "https://in.benzinga.com › content › 5-facts-you-didnt-...", + "snippet": "Satya Nadella's journey at Microsoft underscores the importance of diverse experiences in shaping effective and empathetic leadership in the ...", + "snippet_highlighted_words": ["Satya Nadella's"], + "date": "8 hours ago", + "cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:hCbtJUTgvEQJ:https://in.benzinga.com/content/35911756/5-facts-you-didnt-know-about-microsoft-ceo-satya-nadella&hl=en&gl=us", + }, + { + "position": 9, + "title": "Microsoft CEO Satya Nadella: Q&A - The Wall Street Journal", + "link": "https://www.wsj.com/video/microsoft-ceo-satya-nadella-qa/41D02815-935C-421D-8021-5E1BFD3DDE84", + "source": "Wall Street Journal", + "domain": "www.wsj.com", + "displayed_link": "https://www.wsj.com › video › microsoft-ceo-satya-nadel...", + "snippet": "Microsoft CEO Satya Nadella talks about his biggest accomplishment, how to make successful acquisitions and how the tech industry could improve its image ...", + "snippet_highlighted_words": ["Microsoft CEO"], + "video": {"source": "The Wall Street Journal", "channel": "The Wall Street Journal", "date": "Feb 1, 2019"}, + }, + ], + "related_questions": [ + { + "question": "Who is the real CEO of Microsoft?", + "answer": "Satya Nadella is Chairman and Chief Executive Officer of Microsoft.", + "answer_highlight": "Satya Nadella", + "source": { + "title": "Satya Nadella - Stories - Microsoft News", + "link": "https://news.microsoft.com/exec/satya-nadella/#:~:text=Satya%20Nadella%20is%20Chairman%20and%20Chief%20Executive%20Officer%20of%20Microsoft.", + "source": "Microsoft", + "domain": "news.microsoft.com", + "displayed_link": "https://news.microsoft.com › exec › satya-nadella", + }, + "search": { + "title": "Search for: Who is the real CEO of Microsoft?", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Who+is+the+real+CEO+of+Microsoft%3F&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQzmd6BAgeEAY", + }, + }, + { + "question": "Who is the CEO of Microsoft 2023?", + "answer": "Microsoft Corp. chief executive officer Satya Nadella signaled that he'd be open to Sam Altman going back to OpenAI, rather than joining his company as part of a surprise move announced over the weekend.", + "date": "2 days ago", + "source": { + "title": "Microsoft CEO Satya Nadella signals willingness to have Sam Altman ...", + "link": "https://economictimes.indiatimes.com/tech/technology/microsoft-ceo-satya-nadella-signals-willingness-to-have-sam-altman-rejoin-openai/articleshow/105370026.cms#:~:text=Microsoft%20Corp.%20chief%20executive%20officer,move%20announced%20over%20the%20weekend.", + "source": "indiatimes.com", + "domain": "economictimes.indiatimes.com", + "displayed_link": "https://economictimes.indiatimes.com › tech › articleshow", + }, + "search": { + "title": "Search for: Who is the CEO of Microsoft 2023?", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Who+is+the+CEO+of+Microsoft+2023%3F&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQzmd6BAgcEAY", + }, + }, + { + "question": "How many degrees does Satya Nadella have?", + "answer": "He earned a bachelor's degree in electrical engineering from Mangalore University, a master's degree in computer science from the University of Wisconsin – Milwaukee and a master's degree in business administration from the University of Chicago.", + "source": { + "title": "Satya Nadella - Institutional - BlackRock", + "link": "https://www.blackrock.com/institutions/en-zz/biographies/satya-nadella#:~:text=He%20earned%20a%20bachelor's%20degree,from%20the%20University%20of%20Chicago.", + "source": "blackrock.com", + "domain": "www.blackrock.com", + "displayed_link": "https://www.blackrock.com › en-zz › biographies › satya...", + }, + "search": { + "title": "Search for: How many degrees does Satya Nadella have?", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=How+many+degrees+does+Satya+Nadella+have%3F&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQzmd6BAgdEAY", + }, + }, + { + "question": "How old is Satya Nadella?", + "answer_highlight": "56 years (August 19, 1967)", + "entity": {"subject": "Satya Nadella", "attribute": "Age", "value": "56 years (August 19, 1967)"}, + "search": { + "title": "Search for: How old is Satya Nadella?", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=How+old+is+Satya+Nadella%3F&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQzmd6BAgREAY", + }, + }, + ], + "related_searches": [ + { + "query": "Who is ceo of microsoft wife", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Who+is+ceo+of+microsoft+wife&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhWEAE", + }, + { + "query": "Who is ceo of microsoft and microsoft", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Who+is+ceo+of+microsoft+and+microsoft&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhVEAE", + }, + { + "query": "Who is ceo of microsoft wikipedia", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Who+is+ceo+of+microsoft+wikipedia&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhUEAE", + }, + { + "query": "microsoft founder", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Microsoft+founder&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhSEAE", + }, + { + "query": "Who is ceo of microsoft 2020", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Who+is+ceo+of+microsoft+2020&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhTEAE", + }, + { + "query": "satya nadella net worth", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=Satya+Nadella+net+worth&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhREAE", + }, + { + "query": "ceo of microsoft salary", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=CEO+of+Microsoft+salary&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhQEAE", + }, + { + "query": "ceo of apple", + "link": "https://www.google.com/search?sca_esv=584620230&gl=us&hl=en&q=CEO+of+Apple&sa=X&ved=2ahUKEwi89re3_9eCAxU4IUQIHfHeB6MQ1QJ6BAhXEAE", + }, + ], +} + + +@pytest.fixture +def mock_searchapi_search_result(): + with patch("haystack.components.websearch.searchapi.requests.get") as mock_get: + mock_get.return_value = Mock(status_code=200, json=lambda: EXAMPLE_SEARCHAPI_RESPONSE) + yield mock_get + + +class TestSearchApiSearchAPI: + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("SEARCHAPI_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + SearchApiWebSearch() + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("SEARCHAPI_API_KEY", "test-api-key") + component = SearchApiWebSearch( + top_k=10, allowed_domains=["testdomain.com"], search_params={"param": "test params"} + ) + data = component.to_dict() + assert data == { + "type": "haystack.components.websearch.searchapi.SearchApiWebSearch", + "init_parameters": { + "api_key": {"env_vars": ["SEARCHAPI_API_KEY"], "strict": True, "type": "env_var"}, + "top_k": 10, + "allowed_domains": ["testdomain.com"], + "search_params": {"param": "test params", "engine": "google"}, + }, + } + + @pytest.mark.parametrize("top_k", [1, 5, 7]) + def test_web_search_top_k(self, mock_searchapi_search_result, top_k: int): + ws = SearchApiWebSearch(api_key=Secret.from_token("test-api-key"), top_k=top_k) + results = ws.run(query="Who is CEO of Microsoft?") + documents = results["documents"] + links = results["links"] + assert len(documents) == len(links) == top_k + assert all(isinstance(doc, Document) for doc in documents) + assert all(isinstance(link, str) for link in links) + assert all(link.startswith("http") for link in links) + + @patch("requests.get") + def test_timeout_error(self, mock_get): + mock_get.side_effect = Timeout + ws = SearchApiWebSearch(api_key=Secret.from_token("test-api-key")) + + with pytest.raises(TimeoutError): + ws.run(query="Who is CEO of Microsoft?") + + @patch("requests.get") + def test_request_exception(self, mock_get): + mock_get.side_effect = RequestException + ws = SearchApiWebSearch(api_key=Secret.from_token("test-api-key")) + + with pytest.raises(SearchApiError): + ws.run(query="Who is CEO of Microsoft?") + + @patch("requests.get") + def test_bad_response_code(self, mock_get): + mock_response = mock_get.return_value + mock_response.status_code = 404 + mock_response.raise_for_status.side_effect = HTTPError + ws = SearchApiWebSearch(api_key=Secret.from_token("test-api-key")) + + with pytest.raises(SearchApiError): + ws.run(query="Who is CEO of Microsoft?") + + @pytest.mark.skipif( + not os.environ.get("SEARCHAPI_API_KEY", None), + reason="Export an env var called SEARCHAPI_API_KEY containing the SearchApi API key to run this test.", + ) + @pytest.mark.integration + def test_web_search(self): + ws = SearchApiWebSearch(top_k=10) + results = ws.run(query="Who is CEO of Microsoft?") + documents = results["documents"] + links = results["links"] + assert len(documents) == len(links) == 10 + assert all(isinstance(doc, Document) for doc in results) + assert all(isinstance(link, str) for link in links) + assert all(link.startswith("http") for link in links) diff --git a/testbed/deepset-ai__haystack/test/components/websearch/test_serperdev.py b/testbed/deepset-ai__haystack/test/components/websearch/test_serperdev.py new file mode 100644 index 0000000000000000000000000000000000000000..a2fe33344c58e7278906efafd4d7d8907323f800 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/websearch/test_serperdev.py @@ -0,0 +1,199 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import json +import os +from unittest.mock import Mock, patch +from haystack.utils.auth import Secret + +import pytest +from requests import Timeout, RequestException, HTTPError + +from haystack import Document +from haystack.components.websearch.serper_dev import SerperDevWebSearch, SerperDevError + + +EXAMPLE_SERPERDEV_RESPONSE = { + "searchParameters": { + "q": "Who is the boyfriend of Olivia Wilde?", + "gl": "us", + "hl": "en", + "autocorrect": True, + "type": "search", + }, + "organic": [ + { + "title": "Olivia Wilde embraces Jason Sudeikis amid custody battle, Harry Styles split - Page Six", + "link": "https://pagesix.com/2023/01/29/olivia-wilde-hugs-it-out-with-jason-sudeikis-after-harry-styles-split/", + "snippet": "Looks like Olivia Wilde and Jason Sudeikis are starting 2023 on good terms. Amid their highly publicized custody battle – and the actress' ...", + "date": "Jan 29, 2023", + "position": 1, + }, + { + "title": "Olivia Wilde Is 'Quietly Dating' Again Following Harry Styles Split: 'He Makes Her Happy'", + "link": "https://www.yahoo.com/now/olivia-wilde-quietly-dating-again-183844364.html", + "snippet": "Olivia Wilde is “quietly dating again” following her November 2022 split from Harry Styles, a source exclusively tells Life & Style.", + "date": "Feb 10, 2023", + "position": 2, + }, + { + "title": "Olivia Wilde and Harry Styles' Relationship Timeline: The Way They Were - Us Weekly", + "link": "https://www.usmagazine.com/celebrity-news/pictures/olivia-wilde-and-harry-styles-relationship-timeline/", + "snippet": "Olivia Wilde started dating Harry Styles after ending her years-long engagement to Jason Sudeikis — see their relationship timeline.", + "date": "Mar 10, 2023", + "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgTcalNFvptTbYBiDXX55s8yCGfn6F1qbed9DAN16LvynTr9GayK5SPmY&s", + "position": 3, + }, + { + "title": "Olivia Wilde Is 'Ready to Date Again' After Harry Styles Split - Us Weekly", + "link": "https://www.usmagazine.com/celebrity-news/news/olivia-wilde-is-ready-to-date-again-after-harry-styles-split/", + "snippet": "Ready for love! Olivia Wilde is officially back on the dating scene following her split from her ex-boyfriend, Harry Styles.", + "date": "Mar 1, 2023", + "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRCRAeRy5sVE631ZctzbzuOF70xkIOHaTvh2K7dYvdiVBwALiKrIjpscok&s", + "position": 4, + }, + { + "title": "Harry Styles and Olivia Wilde's Definitive Relationship Timeline - Harper's Bazaar", + "link": "https://www.harpersbazaar.com/celebrity/latest/a35172115/harry-styles-olivia-wilde-relationship-timeline/", + "snippet": "November 2020: News breaks about Olivia splitting from fiancé Jason Sudeikis. ... In mid-November, news breaks of Olivia Wilde's split from Jason ...", + "date": "Feb 23, 2023", + "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRRqw3fvZOIGHEepxCc7yFAWYsS_v_1H6X-4nxyFJxdfRuFQw_BrI6JVzI&s", + "position": 5, + }, + { + "title": "Harry Styles and Olivia Wilde's Relationship Timeline - People", + "link": "https://people.com/music/harry-styles-olivia-wilde-relationship-timeline/", + "snippet": "Harry Styles and Olivia Wilde first met on the set of Don't Worry Darling and stepped out as a couple in January 2021. Relive all their biggest relationship ...", + "position": 6, + }, + { + "title": "Jason Sudeikis and Olivia Wilde's Relationship Timeline - People", + "link": "https://people.com/movies/jason-sudeikis-olivia-wilde-relationship-timeline/", + "snippet": "Jason Sudeikis and Olivia Wilde ended their engagement of seven years in 2020. Here's a complete timeline of their relationship.", + "date": "Mar 24, 2023", + "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSleZoXusQyJJe2WMgIuck_cVaJ8AE0_hU2QxsXzYvKANi55UQlv82yAVI&s", + "position": 7, + }, + { + "title": "Olivia Wilde's anger at ex-boyfriend Harry Styles: She resents him and thinks he was using her | Marca", + "link": "https://www.marca.com/en/lifestyle/celebrities/2023/02/23/63f779a4e2704e8d988b4624.html", + "snippet": "The two started dating after Wilde split up with actor Jason Sudeikisin 2020. However, their relationship came to an end last November.", + "date": "Feb 23, 2023", + "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBgJF2mSnIWCvPrqUqM4WTI9xPNWPyLvHuune85swpB1yE_G8cy_7KRh0&s", + "position": 8, + }, + { + "title": "Olivia Wilde's dating history: Who has the actress dated? | The US Sun", + "link": "https://www.the-sun.com/entertainment/5221040/olivia-wildes-dating-history/", + "snippet": "AMERICAN actress Olivia Wilde started dating Harry Styles in January 2021 after breaking off her engagement the year prior.", + "date": "Nov 19, 2022", + "imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTpm8BToVFHJoH6yRggg0fLocLT9mt6lwsnRxFFDNdDGhDydzQiSKZ9__g&s", + "position": 9, + }, + ], + "relatedSearches": [ + {"query": "Harry Styles girlfriends in order"}, + {"query": "Harry Styles and Olivia Wilde engaged"}, + {"query": "Harry Styles and Olivia Wilde wedding"}, + {"query": "Who is Harry Styles married to"}, + {"query": "Jason Sudeikis Olivia Wilde relationship"}, + {"query": "Olivia Wilde and Jason Sudeikis kids"}, + {"query": "Olivia Wilde children"}, + {"query": "Harry Styles and Olivia Wilde age difference"}, + {"query": "Jason Sudeikis Olivia Wilde, Harry Styles"}, + ], +} + + +@pytest.fixture +def mock_serper_dev_search_result(): + with patch("haystack.components.websearch.serper_dev.requests") as mock_run: + mock_run.post.return_value = Mock(status_code=200, json=lambda: EXAMPLE_SERPERDEV_RESPONSE) + yield mock_run + + +@pytest.fixture +def mock_serper_dev_search_result_no_snippet(): + resp = {**EXAMPLE_SERPERDEV_RESPONSE} + del resp["organic"][0]["snippet"] + with patch("haystack.components.websearch.serper_dev.requests") as mock_run: + mock_run.post.return_value = Mock(status_code=200, json=lambda: resp) + yield mock_run + + +class TestSerperDevSearchAPI: + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("SERPERDEV_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + SerperDevWebSearch() + + def test_to_dict(self, monkeypatch): + monkeypatch.setenv("SERPERDEV_API_KEY", "test-api-key") + component = SerperDevWebSearch(top_k=10, allowed_domains=["test.com"], search_params={"param": "test"}) + data = component.to_dict() + assert data == { + "type": "haystack.components.websearch.serper_dev.SerperDevWebSearch", + "init_parameters": { + "api_key": {"env_vars": ["SERPERDEV_API_KEY"], "strict": True, "type": "env_var"}, + "top_k": 10, + "allowed_domains": ["test.com"], + "search_params": {"param": "test"}, + }, + } + + @pytest.mark.parametrize("top_k", [1, 5, 7]) + def test_web_search_top_k(self, mock_serper_dev_search_result, top_k: int): + ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), top_k=top_k) + results = ws.run(query="Who is the boyfriend of Olivia Wilde?") + documents = results["documents"] + links = results["links"] + assert len(documents) == len(links) == top_k + assert all(isinstance(doc, Document) for doc in documents) + assert all(isinstance(link, str) for link in links) + assert all(link.startswith("http") for link in links) + + def test_no_snippet(self, mock_serper_dev_search_result_no_snippet): + ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), top_k=1) + ws.run(query="Who is the boyfriend of Olivia Wilde?") + + @patch("requests.post") + def test_timeout_error(self, mock_post): + mock_post.side_effect = Timeout + ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key")) + + with pytest.raises(TimeoutError): + ws.run(query="Who is the boyfriend of Olivia Wilde?") + + @patch("requests.post") + def test_request_exception(self, mock_post): + mock_post.side_effect = RequestException + ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key")) + + with pytest.raises(SerperDevError): + ws.run(query="Who is the boyfriend of Olivia Wilde?") + + @patch("requests.post") + def test_bad_response_code(self, mock_post): + mock_response = mock_post.return_value + mock_response.status_code = 404 + mock_response.raise_for_status.side_effect = HTTPError + ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key")) + + with pytest.raises(SerperDevError): + ws.run(query="Who is the boyfriend of Olivia Wilde?") + + @pytest.mark.skipif( + not os.environ.get("SERPERDEV_API_KEY", None), + reason="Export an env var called SERPERDEV_API_KEY containing the SerperDev API key to run this test.", + ) + @pytest.mark.integration + def test_web_search(self): + ws = SerperDevWebSearch(top_k=10) + results = ws.run(query="Who is the boyfriend of Olivia Wilde?") + documents = results["documents"] + links = results["links"] + assert len(documents) == len(links) == 10 + assert all(isinstance(doc, Document) for doc in results) + assert all(isinstance(link, str) for link in links) + assert all(link.startswith("http") for link in links) diff --git a/testbed/deepset-ai__haystack/test/components/writers/__init__.py b/testbed/deepset-ai__haystack/test/components/writers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1764a6e039233b694403c434fa97c13e847f6ba --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/writers/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/testbed/deepset-ai__haystack/test/components/writers/test_document_writer.py b/testbed/deepset-ai__haystack/test/components/writers/test_document_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..44a4f40d268d7e925c525cd2d36498f8b1624cdb --- /dev/null +++ b/testbed/deepset-ai__haystack/test/components/writers/test_document_writer.py @@ -0,0 +1,94 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack import Document, DeserializationError +from haystack.testing.factory import document_store_class +from haystack.components.writers.document_writer import DocumentWriter +from haystack.document_stores.types import DuplicatePolicy +from haystack.document_stores.in_memory import InMemoryDocumentStore + + +class TestDocumentWriter: + def test_to_dict(self): + mocked_docstore_class = document_store_class("MockedDocumentStore") + component = DocumentWriter(document_store=mocked_docstore_class()) + data = component.to_dict() + assert data == { + "type": "haystack.components.writers.document_writer.DocumentWriter", + "init_parameters": { + "document_store": {"type": "haystack.testing.factory.MockedDocumentStore", "init_parameters": {}}, + "policy": "NONE", + }, + } + + def test_to_dict_with_custom_init_parameters(self): + mocked_docstore_class = document_store_class("MockedDocumentStore") + component = DocumentWriter(document_store=mocked_docstore_class(), policy=DuplicatePolicy.SKIP) + data = component.to_dict() + assert data == { + "type": "haystack.components.writers.document_writer.DocumentWriter", + "init_parameters": { + "document_store": {"type": "haystack.testing.factory.MockedDocumentStore", "init_parameters": {}}, + "policy": "SKIP", + }, + } + + def test_from_dict(self): + data = { + "type": "haystack.components.writers.document_writer.DocumentWriter", + "init_parameters": { + "document_store": { + "type": "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore", + "init_parameters": {}, + }, + "policy": "SKIP", + }, + } + component = DocumentWriter.from_dict(data) + assert isinstance(component.document_store, InMemoryDocumentStore) + assert component.policy == DuplicatePolicy.SKIP + + def test_from_dict_without_docstore(self): + data = {"type": "DocumentWriter", "init_parameters": {}} + with pytest.raises(DeserializationError, match="Missing 'document_store' in serialization data"): + DocumentWriter.from_dict(data) + + def test_from_dict_without_docstore_type(self): + data = {"type": "DocumentWriter", "init_parameters": {"document_store": {"init_parameters": {}}}} + with pytest.raises(DeserializationError): + DocumentWriter.from_dict(data) + + def test_from_dict_nonexisting_docstore(self): + data = { + "type": "DocumentWriter", + "init_parameters": {"document_store": {"type": "Nonexisting.DocumentStore", "init_parameters": {}}}, + } + with pytest.raises(DeserializationError): + DocumentWriter.from_dict(data) + + def test_run(self): + document_store = InMemoryDocumentStore() + writer = DocumentWriter(document_store) + documents = [ + Document(content="This is the text of a document."), + Document(content="This is the text of another document."), + ] + + result = writer.run(documents=documents) + assert result["documents_written"] == 2 + + def test_run_skip_policy(self): + document_store = InMemoryDocumentStore() + writer = DocumentWriter(document_store, policy=DuplicatePolicy.SKIP) + documents = [ + Document(content="This is the text of a document."), + Document(content="This is the text of another document."), + ] + + result = writer.run(documents=documents) + assert result["documents_written"] == 2 + + result = writer.run(documents=documents) + assert result["documents_written"] == 0 diff --git a/testbed/deepset-ai__haystack/test/core/component/test_sockets.py b/testbed/deepset-ai__haystack/test/core/component/test_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..14f3b7f1f40c27b785ab3f1c98c06f799259bf8a --- /dev/null +++ b/testbed/deepset-ai__haystack/test/core/component/test_sockets.py @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import pytest + +from haystack.core.component.sockets import InputSocket, Sockets +from haystack.core.pipeline import Pipeline +from haystack.testing.factory import component_class + + +class TestSockets: + def test_init(self): + comp = component_class("SomeComponent", input_types={"input_1": int, "input_2": int})() + sockets = {"input_1": InputSocket("input_1", int), "input_2": InputSocket("input_2", int)} + io = Sockets(component=comp, sockets_dict=sockets, sockets_io_type=InputSocket) + assert io._component == comp + assert "input_1" in io.__dict__ + assert io.__dict__["input_1"] == comp.__haystack_input__._sockets_dict["input_1"] + assert "input_2" in io.__dict__ + assert io.__dict__["input_2"] == comp.__haystack_input__._sockets_dict["input_2"] + + def test_init_with_empty_sockets(self): + comp = component_class("SomeComponent")() + io = Sockets(component=comp, sockets_dict={}, sockets_io_type=InputSocket) + + assert io._component == comp + assert io._sockets_dict == {} + + def test_getattribute(self): + comp = component_class("SomeComponent", input_types={"input_1": int, "input_2": int})() + io = Sockets(component=comp, sockets_dict=comp.__haystack_input__._sockets_dict, sockets_io_type=InputSocket) + + assert io.input_1 == comp.__haystack_input__._sockets_dict["input_1"] + assert io.input_2 == comp.__haystack_input__._sockets_dict["input_2"] + + def test_getattribute_non_existing_socket(self): + comp = component_class("SomeComponent", input_types={"input_1": int, "input_2": int})() + io = Sockets(component=comp, sockets_dict=comp.__haystack_input__._sockets_dict, sockets_io_type=InputSocket) + + with pytest.raises(AttributeError): + io.input_3 + + def test_repr(self): + comp = component_class("SomeComponent", input_types={"input_1": int, "input_2": int})() + io = Sockets(component=comp, sockets_dict=comp.__haystack_input__._sockets_dict, sockets_io_type=InputSocket) + res = repr(io) + assert res == "Inputs:\n - input_1: int\n - input_2: int" + + def test_get(self): + comp = component_class("SomeComponent", input_types={"input_1": int, "input_2": int})() + io = Sockets(component=comp, sockets_dict=comp.__haystack_input__._sockets_dict, sockets_io_type=InputSocket) + + assert io.get("input_1") == comp.__haystack_input__._sockets_dict["input_1"] + assert io.get("input_2") == comp.__haystack_input__._sockets_dict["input_2"] + assert io.get("invalid") == None + assert io.get("invalid", InputSocket("input_2", int)) == InputSocket("input_2", int) + + def test_contains(self): + comp = component_class("SomeComponent", input_types={"input_1": int, "input_2": int})() + io = Sockets(component=comp, sockets_dict=comp.__haystack_input__._sockets_dict, sockets_io_type=InputSocket) + + assert "input_1" in io + assert "input_2" in io + assert "invalid" not in io diff --git a/testbed/deepset-ai__haystack/test/core/pipeline/features/README.md b/testbed/deepset-ai__haystack/test/core/pipeline/features/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4d3c362cce667fa3f64e897811e2456574bdde17 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/core/pipeline/features/README.md @@ -0,0 +1,135 @@ +# `Pipeline.run()` behavioural tests + +This module contains all behavioural tests for `Pipeline.run()`. + +`pipeline_run.feature` contains the definition of the tests using a subset of the [Gherkin language](https://cucumber.io/docs/gherkin/). It's not the full language because we're using `pytest-bdd` and it doesn't implement it in full, but it's good enough for our use case. For more info see the [project `README.md`](https://github.com/pytest-dev/pytest-bdd). + +There are two cases covered by these tests: + +1. `Pipeline.run()` returns some output +2. `Pipeline.run()` raises an exception + +### Correct Pipeline + +In the first case to add a new test you need add a new entry in the `Examples` of the `Running a correct Pipeline` scenario outline and create the corresponding step that creates the `Pipeline` you need to test. + +For example to add a test for a linear `Pipeline` I add a new `that is linear` kind in `pipeline_run.feature`. + +```gherkin + Scenario Outline: Running a correct Pipeline + Given a pipeline + When I run the Pipeline + Then it should return the expected result + + Examples: + | kind | + | that has no components | + | that is linear | +``` + +Then define a new `pipeline_that_is_linear` function in `test_run.py`. +The function must be decorated with `@given` and return a tuple containing the `Pipeline` instance and a list of `PipelineRunData` instances. +`PipelineRunData` is a dataclass that stores all the information necessary to verify the `Pipeline` ran as expected. +The `@given` arguments must be the full step name, `"a pipeline that is linear"` in this case, and `target_fixture` must be set to `"pipeline_data"`. + +```python +@given("a pipeline that is linear", target_fixture="pipeline_data") +def pipeline_that_is_linear(): + pipeline = Pipeline() + pipeline.add_component("first_addition", AddFixedValue(add=2)) + pipeline.add_component("second_addition", AddFixedValue()) + pipeline.add_component("double", Double()) + pipeline.connect("first_addition", "double") + pipeline.connect("double", "second_addition") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"first_addition": {"value": 1}}, + expected_outputs={"second_addition": {"result": 7}}, + expected_run_order=["first_addition", "double", "second_addition"], + ) + ], + ) +``` + +Some kinds of `Pipeline`s require multiple runs to verify they work correctly, for example those with multiple branches. +For this reason we can return a list of `PipelineRunData`, we'll run the `Pipeline` for each instance. +For example, we could test two different runs of the same pipeline like this: + +```python +@given("a pipeline that is linear", target_fixture="pipeline_data") +def pipeline_that_is_linear(): + pipeline = Pipeline() + pipeline.add_component("first_addition", AddFixedValue(add=2)) + pipeline.add_component("second_addition", AddFixedValue()) + pipeline.add_component("double", Double()) + pipeline.connect("first_addition", "double") + pipeline.connect("double", "second_addition") + + return ( + pipeline, + [ + PipelineRunData( + inputs={"first_addition": {"value": 1}}, + include_outputs_from=set(), + expected_outputs={"second_addition": {"result": 7}}, + expected_run_order=["first_addition", "double", "second_addition"], + ), + PipelineRunData( + inputs={"first_addition": {"value": 100}}, + include_outputs_from=set(), + expected_outputs={"first_addition": {"value": 206}}, + expected_run_order=["first_addition", "double", "second_addition"], + ), + ], + ) +``` + +### Bad Pipeline + +The second case is similar to the first one. +In this case we test that a `Pipeline` with an infinite loop raises `PipelineMaxLoops`. + +```gherkin + Scenario Outline: Running a bad Pipeline + Given a pipeline + When I run the Pipeline + Then it must have raised + + Examples: + | kind | exception | + | that has an infinite loop | PipelineMaxLoops | +``` + +In a similar way as first case we need to defined a new `pipeline_that_has_an_infinite_loop` function in `test_run.py`, with some small differences. +The only difference from the first case is the last value returned by the function, we just omit the expected outputs and the expected run order. + +```python +@given("a pipeline that has an infinite loop", target_fixture="pipeline_data") +def pipeline_that_has_an_infinite_loop(): + def custom_init(self): + component.set_input_type(self, "x", int) + component.set_input_type(self, "y", int, 1) + component.set_output_types(self, a=int, b=int) + + FakeComponent = component_class("FakeComponent", output={"a": 1, "b": 1}, extra_fields={"__init__": custom_init}) + pipe.add_component("first", FakeComponent()) + pipe.add_component("second", FakeComponent()) + pipe.connect("first.a", "second.x") + pipe.connect("second.b", "first.y") + return pipe, [PipelineRunData({"first": {"x": 1}})] +``` + +## Why? + +As the time of writing, tests that invoke `Pipeline.run()` are scattered between different files with very little clarity on what they are intended to test - the only indicators are the name of each test itself and the name of their parent module. This makes it difficult to understand which behaviours are being tested, if they are tested redundantly or if they work correctly. + +The introduction of the Gherkin file allows for a single "source of truth" that enumerates (ideally, in an exhaustive manner) all the behaviours of the pipeline execution logic that we wish to test. This intermediate mapping of behaviours to actual test cases is meant to provide an overview of the latter and reduce the cognitive overhead of understanding them. When writing new tests, we now "tag" them with a specific behavioural parameter that's specified in a Gherkin scenario. + +This tag and behavioural parameter mapping is meant to be 1 to 1, meaning each "Given" step must map to one and only one function. If multiple function are marked with `@given("step name")` the last declaration will override all the previous ones. So it's important to verify that there are no other existing steps with the same name when adding a new one. + +While one could functionally do the same with well-defined test names and detailed comments on what is being tested, it would still lack the overview that the above approach provides. It's also extensible in that new scenarios with different behaviours can be introduced easily (e.g: for `async` pipeline execution logic). + +Apart from the above, the newly introduced harness ensures that all behavioural pipeline tests return a structured result, which simplifies checking of side-effects. diff --git a/testbed/deepset-ai__haystack/test/core/sample_components/test_add_value.py b/testbed/deepset-ai__haystack/test/core/sample_components/test_add_value.py new file mode 100644 index 0000000000000000000000000000000000000000..229950de60f2060fe7939801273be9eba4b18463 --- /dev/null +++ b/testbed/deepset-ai__haystack/test/core/sample_components/test_add_value.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from haystack.testing.sample_components import AddFixedValue +from haystack.core.serialization import component_to_dict, component_from_dict + + +def test_run(): + component = AddFixedValue() + results = component.run(value=50, add=10) + assert results == {"result": 60}